blob: 557869f7f741c52ddcffc80d0488a55d52f70778 [file] [log] [blame]
Chris Lattner2188e402010-01-04 07:37:31 +00001//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitICmp and visitFCmp functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Matt Arsenault55e73122015-01-06 15:50:59 +000015#include "llvm/ADT/APSInt.h"
Silviu Barangaf29dfd32016-01-15 15:52:05 +000016#include "llvm/ADT/SetVector.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000017#include "llvm/ADT/Statistic.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000018#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000019#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/MemoryBuiltins.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000025#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000027#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000028#include "llvm/Support/Debug.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000029
Chris Lattner2188e402010-01-04 07:37:31 +000030using namespace llvm;
31using namespace PatternMatch;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "instcombine"
34
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000035// How many times is a select replaced by one of its operands?
36STATISTIC(NumSel, "Number of select opts");
37
38// Initialization Routines
39
Chris Lattner98457102011-02-10 05:23:05 +000040static ConstantInt *getOne(Constant *C) {
41 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
42}
43
Chris Lattner2188e402010-01-04 07:37:31 +000044static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
45 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
46}
47
48static bool HasAddOverflow(ConstantInt *Result,
49 ConstantInt *In1, ConstantInt *In2,
50 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000051 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000052 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000053
54 if (In2->isNegative())
55 return Result->getValue().sgt(In1->getValue());
56 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000057}
58
Sanjay Patel5f0217f2016-06-05 16:46:18 +000059/// Compute Result = In1+In2, returning true if the result overflowed for this
60/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000061static bool AddWithOverflow(Constant *&Result, Constant *In1,
62 Constant *In2, bool IsSigned = false) {
63 Result = ConstantExpr::getAdd(In1, In2);
64
Chris Lattner229907c2011-07-18 04:54:35 +000065 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000066 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
67 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
68 if (HasAddOverflow(ExtractElement(Result, Idx),
69 ExtractElement(In1, Idx),
70 ExtractElement(In2, Idx),
71 IsSigned))
72 return true;
73 }
74 return false;
75 }
76
77 return HasAddOverflow(cast<ConstantInt>(Result),
78 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
79 IsSigned);
80}
81
82static bool HasSubOverflow(ConstantInt *Result,
83 ConstantInt *In1, ConstantInt *In2,
84 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000085 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000086 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000087
Chris Lattnerb1a15122011-07-15 06:08:15 +000088 if (In2->isNegative())
89 return Result->getValue().slt(In1->getValue());
90
91 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000092}
93
Sanjay Patel5f0217f2016-06-05 16:46:18 +000094/// Compute Result = In1-In2, returning true if the result overflowed for this
95/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000096static bool SubWithOverflow(Constant *&Result, Constant *In1,
97 Constant *In2, bool IsSigned = false) {
98 Result = ConstantExpr::getSub(In1, In2);
99
Chris Lattner229907c2011-07-18 04:54:35 +0000100 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +0000101 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
102 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
103 if (HasSubOverflow(ExtractElement(Result, Idx),
104 ExtractElement(In1, Idx),
105 ExtractElement(In2, Idx),
106 IsSigned))
107 return true;
108 }
109 return false;
110 }
111
112 return HasSubOverflow(cast<ConstantInt>(Result),
113 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
114 IsSigned);
115}
116
Balaram Makam569eaec2016-05-04 21:32:14 +0000117/// Given an icmp instruction, return true if any use of this comparison is a
118/// branch on sign bit comparison.
119static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) {
120 for (auto *U : I.users())
121 if (isa<BranchInst>(U))
122 return isSignBit;
123 return false;
124}
125
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000126/// Given an exploded icmp instruction, return true if the comparison only
127/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
128/// result of the comparison is true when the input value is signed.
Sanjay Patel79263662016-08-21 15:07:45 +0000129static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000130 bool &TrueIfSigned) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000131 switch (Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000132 case ICmpInst::ICMP_SLT: // True if LHS s< 0
133 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000134 return RHS == 0;
Chris Lattner2188e402010-01-04 07:37:31 +0000135 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
136 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000137 return RHS.isAllOnesValue();
Chris Lattner2188e402010-01-04 07:37:31 +0000138 case ICmpInst::ICMP_SGT: // True if LHS s> -1
139 TrueIfSigned = false;
Sanjay Patel79263662016-08-21 15:07:45 +0000140 return RHS.isAllOnesValue();
Chris Lattner2188e402010-01-04 07:37:31 +0000141 case ICmpInst::ICMP_UGT:
142 // True if LHS u> RHS and RHS == high-bit-mask - 1
143 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000144 return RHS.isMaxSignedValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000145 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000146 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
147 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000148 return RHS.isSignBit();
Chris Lattner2188e402010-01-04 07:37:31 +0000149 default:
150 return false;
151 }
152}
153
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000154/// Returns true if the exploded icmp can be expressed as a signed comparison
155/// to zero and updates the predicate accordingly.
156/// The signedness of the comparison is preserved.
Sanjay Patel5b112842016-08-18 14:59:14 +0000157/// TODO: Refactor with decomposeBitTestICmp()?
158static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000159 if (!ICmpInst::isSigned(Pred))
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000160 return false;
161
Sanjay Patel5b112842016-08-18 14:59:14 +0000162 if (C == 0)
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000163 return ICmpInst::isRelational(Pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000164
Sanjay Patel5b112842016-08-18 14:59:14 +0000165 if (C == 1) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000166 if (Pred == ICmpInst::ICMP_SLT) {
167 Pred = ICmpInst::ICMP_SLE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000168 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000169 }
Sanjay Patel5b112842016-08-18 14:59:14 +0000170 } else if (C.isAllOnesValue()) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000171 if (Pred == ICmpInst::ICMP_SGT) {
172 Pred = ICmpInst::ICMP_SGE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000173 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000174 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000175 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000176
177 return false;
178}
179
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000180/// Given a signed integer type and a set of known zero and one bits, compute
181/// the maximum and minimum values that could have the specified known zero and
182/// known one bits, returning them in Min/Max.
183static void ComputeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
184 const APInt &KnownOne,
185 APInt &Min, APInt &Max) {
Chris Lattner2188e402010-01-04 07:37:31 +0000186 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
187 KnownZero.getBitWidth() == Min.getBitWidth() &&
188 KnownZero.getBitWidth() == Max.getBitWidth() &&
189 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
190 APInt UnknownBits = ~(KnownZero|KnownOne);
191
192 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
193 // bit if it is unknown.
194 Min = KnownOne;
195 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000196
Chris Lattner2188e402010-01-04 07:37:31 +0000197 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000198 Min.setBit(Min.getBitWidth()-1);
199 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000200 }
201}
202
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000203/// Given an unsigned integer type and a set of known zero and one bits, compute
204/// the maximum and minimum values that could have the specified known zero and
205/// known one bits, returning them in Min/Max.
Chris Lattner2188e402010-01-04 07:37:31 +0000206static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
207 const APInt &KnownOne,
208 APInt &Min, APInt &Max) {
209 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
210 KnownZero.getBitWidth() == Min.getBitWidth() &&
211 KnownZero.getBitWidth() == Max.getBitWidth() &&
212 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
213 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000214
Chris Lattner2188e402010-01-04 07:37:31 +0000215 // The minimum value is when the unknown bits are all zeros.
216 Min = KnownOne;
217 // The maximum value is when the unknown bits are all ones.
218 Max = KnownOne|UnknownBits;
219}
220
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000221/// This is called when we see this pattern:
Chris Lattner2188e402010-01-04 07:37:31 +0000222/// cmp pred (load (gep GV, ...)), cmpcst
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000223/// where GV is a global variable with a constant initializer. Try to simplify
224/// this into some simple computation that does not need the load. For example
Chris Lattner2188e402010-01-04 07:37:31 +0000225/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
226///
227/// If AndCst is non-null, then the loaded value is masked with that constant
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000228/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Sanjay Patel43395062016-07-21 18:07:40 +0000229Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
230 GlobalVariable *GV,
231 CmpInst &ICI,
232 ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000233 Constant *Init = GV->getInitializer();
234 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000235 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000236
Chris Lattnerfe741762012-01-31 02:55:06 +0000237 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000238 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000239
Chris Lattner2188e402010-01-04 07:37:31 +0000240 // There are many forms of this optimization we can handle, for now, just do
241 // the simple index into a single-dimensional array.
242 //
243 // Require: GEP GV, 0, i {{, constant indices}}
244 if (GEP->getNumOperands() < 3 ||
245 !isa<ConstantInt>(GEP->getOperand(1)) ||
246 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
247 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000248 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000249
250 // Check that indices after the variable are constants and in-range for the
251 // type they index. Collect the indices. This is typically for arrays of
252 // structs.
253 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000254
Chris Lattnerfe741762012-01-31 02:55:06 +0000255 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000256 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
257 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000258 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000259
Chris Lattner2188e402010-01-04 07:37:31 +0000260 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000261 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000262
Chris Lattner229907c2011-07-18 04:54:35 +0000263 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000264 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000265 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000266 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000267 EltTy = ATy->getElementType();
268 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000269 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000270 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000271
Chris Lattner2188e402010-01-04 07:37:31 +0000272 LaterIndices.push_back(IdxVal);
273 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000274
Chris Lattner2188e402010-01-04 07:37:31 +0000275 enum { Overdefined = -3, Undefined = -2 };
276
277 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000278
Chris Lattner2188e402010-01-04 07:37:31 +0000279 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
280 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
281 // and 87 is the second (and last) index. FirstTrueElement is -2 when
282 // undefined, otherwise set to the first true element. SecondTrueElement is
283 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
284 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
285
286 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
287 // form "i != 47 & i != 87". Same state transitions as for true elements.
288 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000289
Chris Lattner2188e402010-01-04 07:37:31 +0000290 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
291 /// define a state machine that triggers for ranges of values that the index
292 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
293 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
294 /// index in the range (inclusive). We use -2 for undefined here because we
295 /// use relative comparisons and don't want 0-1 to match -1.
296 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000297
Chris Lattner2188e402010-01-04 07:37:31 +0000298 // MagicBitvector - This is a magic bitvector where we set a bit if the
299 // comparison is true for element 'i'. If there are 64 elements or less in
300 // the array, this will fully represent all the comparison results.
301 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000302
Chris Lattner2188e402010-01-04 07:37:31 +0000303 // Scan the array and see if one of our patterns matches.
304 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000305 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
306 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000307 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000308
Chris Lattner2188e402010-01-04 07:37:31 +0000309 // If this is indexing an array of structures, get the structure element.
310 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000311 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000312
Chris Lattner2188e402010-01-04 07:37:31 +0000313 // If the element is masked, handle it.
314 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000315
Chris Lattner2188e402010-01-04 07:37:31 +0000316 // Find out if the comparison would be true or false for the i'th element.
317 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Justin Bogner99798402016-08-05 01:06:44 +0000318 CompareRHS, DL, &TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000319 // If the result is undef for this element, ignore it.
320 if (isa<UndefValue>(C)) {
321 // Extend range state machines to cover this element in case there is an
322 // undef in the middle of the range.
323 if (TrueRangeEnd == (int)i-1)
324 TrueRangeEnd = i;
325 if (FalseRangeEnd == (int)i-1)
326 FalseRangeEnd = i;
327 continue;
328 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000329
Chris Lattner2188e402010-01-04 07:37:31 +0000330 // If we can't compute the result for any of the elements, we have to give
331 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000332 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000333
Chris Lattner2188e402010-01-04 07:37:31 +0000334 // Otherwise, we know if the comparison is true or false for this element,
335 // update our state machines.
336 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000337
Chris Lattner2188e402010-01-04 07:37:31 +0000338 // State machine for single/double/range index comparison.
339 if (IsTrueForElt) {
340 // Update the TrueElement state machine.
341 if (FirstTrueElement == Undefined)
342 FirstTrueElement = TrueRangeEnd = i; // First true element.
343 else {
344 // Update double-compare state machine.
345 if (SecondTrueElement == Undefined)
346 SecondTrueElement = i;
347 else
348 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000349
Chris Lattner2188e402010-01-04 07:37:31 +0000350 // Update range state machine.
351 if (TrueRangeEnd == (int)i-1)
352 TrueRangeEnd = i;
353 else
354 TrueRangeEnd = Overdefined;
355 }
356 } else {
357 // Update the FalseElement state machine.
358 if (FirstFalseElement == Undefined)
359 FirstFalseElement = FalseRangeEnd = i; // First false element.
360 else {
361 // Update double-compare state machine.
362 if (SecondFalseElement == Undefined)
363 SecondFalseElement = i;
364 else
365 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000366
Chris Lattner2188e402010-01-04 07:37:31 +0000367 // Update range state machine.
368 if (FalseRangeEnd == (int)i-1)
369 FalseRangeEnd = i;
370 else
371 FalseRangeEnd = Overdefined;
372 }
373 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000374
Chris Lattner2188e402010-01-04 07:37:31 +0000375 // If this element is in range, update our magic bitvector.
376 if (i < 64 && IsTrueForElt)
377 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000378
Chris Lattner2188e402010-01-04 07:37:31 +0000379 // If all of our states become overdefined, bail out early. Since the
380 // predicate is expensive, only check it every 8 elements. This is only
381 // really useful for really huge arrays.
382 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
383 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
384 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000385 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000386 }
387
388 // Now that we've scanned the entire array, emit our new comparison(s). We
389 // order the state machines in complexity of the generated code.
390 Value *Idx = GEP->getOperand(2);
391
Matt Arsenault5aeae182013-08-19 21:40:31 +0000392 // If the index is larger than the pointer size of the target, truncate the
393 // index down like the GEP would do implicitly. We don't have to do this for
394 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000395 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000396 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000397 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
398 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
399 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
400 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000401
Chris Lattner2188e402010-01-04 07:37:31 +0000402 // If the comparison is only true for one or two elements, emit direct
403 // comparisons.
404 if (SecondTrueElement != Overdefined) {
405 // None true -> false.
406 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000407 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000408
Chris Lattner2188e402010-01-04 07:37:31 +0000409 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000410
Chris Lattner2188e402010-01-04 07:37:31 +0000411 // True for one element -> 'i == 47'.
412 if (SecondTrueElement == Undefined)
413 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000414
Chris Lattner2188e402010-01-04 07:37:31 +0000415 // True for two elements -> 'i == 47 | i == 72'.
416 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
417 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
418 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
419 return BinaryOperator::CreateOr(C1, C2);
420 }
421
422 // If the comparison is only false for one or two elements, emit direct
423 // comparisons.
424 if (SecondFalseElement != Overdefined) {
425 // None false -> true.
426 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000427 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000428
Chris Lattner2188e402010-01-04 07:37:31 +0000429 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
430
431 // False for one element -> 'i != 47'.
432 if (SecondFalseElement == Undefined)
433 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000434
Chris Lattner2188e402010-01-04 07:37:31 +0000435 // False for two elements -> 'i != 47 & i != 72'.
436 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
437 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
438 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
439 return BinaryOperator::CreateAnd(C1, C2);
440 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000441
Chris Lattner2188e402010-01-04 07:37:31 +0000442 // If the comparison can be replaced with a range comparison for the elements
443 // where it is true, emit the range check.
444 if (TrueRangeEnd != Overdefined) {
445 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000446
Chris Lattner2188e402010-01-04 07:37:31 +0000447 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
448 if (FirstTrueElement) {
449 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
450 Idx = Builder->CreateAdd(Idx, Offs);
451 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000452
Chris Lattner2188e402010-01-04 07:37:31 +0000453 Value *End = ConstantInt::get(Idx->getType(),
454 TrueRangeEnd-FirstTrueElement+1);
455 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
456 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000457
Chris Lattner2188e402010-01-04 07:37:31 +0000458 // False range check.
459 if (FalseRangeEnd != Overdefined) {
460 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
461 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
462 if (FirstFalseElement) {
463 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
464 Idx = Builder->CreateAdd(Idx, Offs);
465 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000466
Chris Lattner2188e402010-01-04 07:37:31 +0000467 Value *End = ConstantInt::get(Idx->getType(),
468 FalseRangeEnd-FirstFalseElement);
469 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
470 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000471
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000472 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000473 // of this load, replace it with computation that does:
474 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000475 {
Craig Topperf40110f2014-04-25 05:29:35 +0000476 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000477
478 // Look for an appropriate type:
479 // - The type of Idx if the magic fits
480 // - The smallest fitting legal type if we have a DataLayout
481 // - Default to i32
482 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
483 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000484 else
485 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000486
Craig Topperf40110f2014-04-25 05:29:35 +0000487 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000488 Value *V = Builder->CreateIntCast(Idx, Ty, false);
489 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
490 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
491 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
492 }
Chris Lattner2188e402010-01-04 07:37:31 +0000493 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000494
Craig Topperf40110f2014-04-25 05:29:35 +0000495 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000496}
497
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000498/// Return a value that can be used to compare the *offset* implied by a GEP to
499/// zero. For example, if we have &A[i], we want to return 'i' for
500/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
501/// are involved. The above expression would also be legal to codegen as
502/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
503/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000504/// to generate the first by knowing that pointer arithmetic doesn't overflow.
505///
506/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000507///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000508static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
509 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000510 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000511
Chris Lattner2188e402010-01-04 07:37:31 +0000512 // Check to see if this gep only has a single variable index. If so, and if
513 // any constant indices are a multiple of its scale, then we can compute this
514 // in terms of the scale of the variable index. For example, if the GEP
515 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
516 // because the expression will cross zero at the same point.
517 unsigned i, e = GEP->getNumOperands();
518 int64_t Offset = 0;
519 for (i = 1; i != e; ++i, ++GTI) {
520 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
521 // Compute the aggregate offset of constant indices.
522 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000523
Chris Lattner2188e402010-01-04 07:37:31 +0000524 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000525 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000526 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000527 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000528 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000529 Offset += Size*CI->getSExtValue();
530 }
531 } else {
532 // Found our variable index.
533 break;
534 }
535 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000536
Chris Lattner2188e402010-01-04 07:37:31 +0000537 // If there are no variable indices, we must have a constant offset, just
538 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000539 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000540
Chris Lattner2188e402010-01-04 07:37:31 +0000541 Value *VariableIdx = GEP->getOperand(i);
542 // Determine the scale factor of the variable element. For example, this is
543 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000544 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000545
Chris Lattner2188e402010-01-04 07:37:31 +0000546 // Verify that there are no other variable indices. If so, emit the hard way.
547 for (++i, ++GTI; i != e; ++i, ++GTI) {
548 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000549 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000550
Chris Lattner2188e402010-01-04 07:37:31 +0000551 // Compute the aggregate offset of constant indices.
552 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000553
Chris Lattner2188e402010-01-04 07:37:31 +0000554 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000555 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000556 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000557 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000558 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000559 Offset += Size*CI->getSExtValue();
560 }
561 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000562
Chris Lattner2188e402010-01-04 07:37:31 +0000563 // Okay, we know we have a single variable index, which must be a
564 // pointer/array/vector index. If there is no offset, life is simple, return
565 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000566 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000567 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000568 if (Offset == 0) {
569 // Cast to intptrty in case a truncation occurs. If an extension is needed,
570 // we don't need to bother extending: the extension won't affect where the
571 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000572 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000573 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
574 }
Chris Lattner2188e402010-01-04 07:37:31 +0000575 return VariableIdx;
576 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000577
Chris Lattner2188e402010-01-04 07:37:31 +0000578 // Otherwise, there is an index. The computation we will do will be modulo
579 // the pointer size, so get it.
580 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000581
Chris Lattner2188e402010-01-04 07:37:31 +0000582 Offset &= PtrSizeMask;
583 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000584
Chris Lattner2188e402010-01-04 07:37:31 +0000585 // To do this transformation, any constant index must be a multiple of the
586 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
587 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
588 // multiple of the variable scale.
589 int64_t NewOffs = Offset / (int64_t)VariableScale;
590 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000591 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000592
Chris Lattner2188e402010-01-04 07:37:31 +0000593 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000594 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000595 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
596 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000597 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000598 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000599}
600
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000601/// Returns true if we can rewrite Start as a GEP with pointer Base
602/// and some integer offset. The nodes that need to be re-written
603/// for this transformation will be added to Explored.
604static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
605 const DataLayout &DL,
606 SetVector<Value *> &Explored) {
607 SmallVector<Value *, 16> WorkList(1, Start);
608 Explored.insert(Base);
609
610 // The following traversal gives us an order which can be used
611 // when doing the final transformation. Since in the final
612 // transformation we create the PHI replacement instructions first,
613 // we don't have to get them in any particular order.
614 //
615 // However, for other instructions we will have to traverse the
616 // operands of an instruction first, which means that we have to
617 // do a post-order traversal.
618 while (!WorkList.empty()) {
619 SetVector<PHINode *> PHIs;
620
621 while (!WorkList.empty()) {
622 if (Explored.size() >= 100)
623 return false;
624
625 Value *V = WorkList.back();
626
627 if (Explored.count(V) != 0) {
628 WorkList.pop_back();
629 continue;
630 }
631
632 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
633 !isa<GEPOperator>(V) && !isa<PHINode>(V))
634 // We've found some value that we can't explore which is different from
635 // the base. Therefore we can't do this transformation.
636 return false;
637
638 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
639 auto *CI = dyn_cast<CastInst>(V);
640 if (!CI->isNoopCast(DL))
641 return false;
642
643 if (Explored.count(CI->getOperand(0)) == 0)
644 WorkList.push_back(CI->getOperand(0));
645 }
646
647 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
648 // We're limiting the GEP to having one index. This will preserve
649 // the original pointer type. We could handle more cases in the
650 // future.
651 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
652 GEP->getType() != Start->getType())
653 return false;
654
655 if (Explored.count(GEP->getOperand(0)) == 0)
656 WorkList.push_back(GEP->getOperand(0));
657 }
658
659 if (WorkList.back() == V) {
660 WorkList.pop_back();
661 // We've finished visiting this node, mark it as such.
662 Explored.insert(V);
663 }
664
665 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000666 // We cannot transform PHIs on unsplittable basic blocks.
667 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
668 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000669 Explored.insert(PN);
670 PHIs.insert(PN);
671 }
672 }
673
674 // Explore the PHI nodes further.
675 for (auto *PN : PHIs)
676 for (Value *Op : PN->incoming_values())
677 if (Explored.count(Op) == 0)
678 WorkList.push_back(Op);
679 }
680
681 // Make sure that we can do this. Since we can't insert GEPs in a basic
682 // block before a PHI node, we can't easily do this transformation if
683 // we have PHI node users of transformed instructions.
684 for (Value *Val : Explored) {
685 for (Value *Use : Val->uses()) {
686
687 auto *PHI = dyn_cast<PHINode>(Use);
688 auto *Inst = dyn_cast<Instruction>(Val);
689
690 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
691 Explored.count(PHI) == 0)
692 continue;
693
694 if (PHI->getParent() == Inst->getParent())
695 return false;
696 }
697 }
698 return true;
699}
700
701// Sets the appropriate insert point on Builder where we can add
702// a replacement Instruction for V (if that is possible).
703static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
704 bool Before = true) {
705 if (auto *PHI = dyn_cast<PHINode>(V)) {
706 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
707 return;
708 }
709 if (auto *I = dyn_cast<Instruction>(V)) {
710 if (!Before)
711 I = &*std::next(I->getIterator());
712 Builder.SetInsertPoint(I);
713 return;
714 }
715 if (auto *A = dyn_cast<Argument>(V)) {
716 // Set the insertion point in the entry block.
717 BasicBlock &Entry = A->getParent()->getEntryBlock();
718 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
719 return;
720 }
721 // Otherwise, this is a constant and we don't need to set a new
722 // insertion point.
723 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
724}
725
726/// Returns a re-written value of Start as an indexed GEP using Base as a
727/// pointer.
728static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
729 const DataLayout &DL,
730 SetVector<Value *> &Explored) {
731 // Perform all the substitutions. This is a bit tricky because we can
732 // have cycles in our use-def chains.
733 // 1. Create the PHI nodes without any incoming values.
734 // 2. Create all the other values.
735 // 3. Add the edges for the PHI nodes.
736 // 4. Emit GEPs to get the original pointers.
737 // 5. Remove the original instructions.
738 Type *IndexType = IntegerType::get(
739 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
740
741 DenseMap<Value *, Value *> NewInsts;
742 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
743
744 // Create the new PHI nodes, without adding any incoming values.
745 for (Value *Val : Explored) {
746 if (Val == Base)
747 continue;
748 // Create empty phi nodes. This avoids cyclic dependencies when creating
749 // the remaining instructions.
750 if (auto *PHI = dyn_cast<PHINode>(Val))
751 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
752 PHI->getName() + ".idx", PHI);
753 }
754 IRBuilder<> Builder(Base->getContext());
755
756 // Create all the other instructions.
757 for (Value *Val : Explored) {
758
759 if (NewInsts.find(Val) != NewInsts.end())
760 continue;
761
762 if (auto *CI = dyn_cast<CastInst>(Val)) {
763 NewInsts[CI] = NewInsts[CI->getOperand(0)];
764 continue;
765 }
766 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
767 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
768 : GEP->getOperand(1);
769 setInsertionPoint(Builder, GEP);
770 // Indices might need to be sign extended. GEPs will magically do
771 // this, but we need to do it ourselves here.
772 if (Index->getType()->getScalarSizeInBits() !=
773 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
774 Index = Builder.CreateSExtOrTrunc(
775 Index, NewInsts[GEP->getOperand(0)]->getType(),
776 GEP->getOperand(0)->getName() + ".sext");
777 }
778
779 auto *Op = NewInsts[GEP->getOperand(0)];
780 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
781 NewInsts[GEP] = Index;
782 else
783 NewInsts[GEP] = Builder.CreateNSWAdd(
784 Op, Index, GEP->getOperand(0)->getName() + ".add");
785 continue;
786 }
787 if (isa<PHINode>(Val))
788 continue;
789
790 llvm_unreachable("Unexpected instruction type");
791 }
792
793 // Add the incoming values to the PHI nodes.
794 for (Value *Val : Explored) {
795 if (Val == Base)
796 continue;
797 // All the instructions have been created, we can now add edges to the
798 // phi nodes.
799 if (auto *PHI = dyn_cast<PHINode>(Val)) {
800 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
801 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
802 Value *NewIncoming = PHI->getIncomingValue(I);
803
804 if (NewInsts.find(NewIncoming) != NewInsts.end())
805 NewIncoming = NewInsts[NewIncoming];
806
807 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
808 }
809 }
810 }
811
812 for (Value *Val : Explored) {
813 if (Val == Base)
814 continue;
815
816 // Depending on the type, for external users we have to emit
817 // a GEP or a GEP + ptrtoint.
818 setInsertionPoint(Builder, Val, false);
819
820 // If required, create an inttoptr instruction for Base.
821 Value *NewBase = Base;
822 if (!Base->getType()->isPointerTy())
823 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
824 Start->getName() + "to.ptr");
825
826 Value *GEP = Builder.CreateInBoundsGEP(
827 Start->getType()->getPointerElementType(), NewBase,
828 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
829
830 if (!Val->getType()->isPointerTy()) {
831 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
832 Val->getName() + ".conv");
833 GEP = Cast;
834 }
835 Val->replaceAllUsesWith(GEP);
836 }
837
838 return NewInsts[Start];
839}
840
841/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
842/// the input Value as a constant indexed GEP. Returns a pair containing
843/// the GEPs Pointer and Index.
844static std::pair<Value *, Value *>
845getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
846 Type *IndexType = IntegerType::get(V->getContext(),
847 DL.getPointerTypeSizeInBits(V->getType()));
848
849 Constant *Index = ConstantInt::getNullValue(IndexType);
850 while (true) {
851 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
852 // We accept only inbouds GEPs here to exclude the possibility of
853 // overflow.
854 if (!GEP->isInBounds())
855 break;
856 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
857 GEP->getType() == V->getType()) {
858 V = GEP->getOperand(0);
859 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
860 Index = ConstantExpr::getAdd(
861 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
862 continue;
863 }
864 break;
865 }
866 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
867 if (!CI->isNoopCast(DL))
868 break;
869 V = CI->getOperand(0);
870 continue;
871 }
872 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
873 if (!CI->isNoopCast(DL))
874 break;
875 V = CI->getOperand(0);
876 continue;
877 }
878 break;
879 }
880 return {V, Index};
881}
882
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000883/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
884/// We can look through PHIs, GEPs and casts in order to determine a common base
885/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000886static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
887 ICmpInst::Predicate Cond,
888 const DataLayout &DL) {
889 if (!GEPLHS->hasAllConstantIndices())
890 return nullptr;
891
892 Value *PtrBase, *Index;
893 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
894
895 // The set of nodes that will take part in this transformation.
896 SetVector<Value *> Nodes;
897
898 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
899 return nullptr;
900
901 // We know we can re-write this as
902 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
903 // Since we've only looked through inbouds GEPs we know that we
904 // can't have overflow on either side. We can therefore re-write
905 // this as:
906 // OFFSET1 cmp OFFSET2
907 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
908
909 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
910 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
911 // offset. Since Index is the offset of LHS to the base pointer, we will now
912 // compare the offsets instead of comparing the pointers.
913 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
914}
915
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000916/// Fold comparisons between a GEP instruction and something else. At this point
917/// we know that the GEP is on the LHS of the comparison.
Sanjay Patel43395062016-07-21 18:07:40 +0000918Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000919 ICmpInst::Predicate Cond,
920 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000921 // Don't transform signed compares of GEPs into index compares. Even if the
922 // GEP is inbounds, the final add of the base pointer can have signed overflow
923 // and would change the result of the icmp.
924 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000925 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000926 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000927 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000928
Matt Arsenault44f60d02014-06-09 19:20:29 +0000929 // Look through bitcasts and addrspacecasts. We do not however want to remove
930 // 0 GEPs.
931 if (!isa<GetElementPtrInst>(RHS))
932 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000933
934 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000936 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
937 // This transformation (ignoring the base and scales) is valid because we
938 // know pointers can't overflow since the gep is inbounds. See if we can
939 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000940 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000941
Chris Lattner2188e402010-01-04 07:37:31 +0000942 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000943 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000944 Offset = EmitGEPOffset(GEPLHS);
945 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
946 Constant::getNullValue(Offset->getType()));
947 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
948 // If the base pointers are different, but the indices are the same, just
949 // compare the base pointer.
950 if (PtrBase != GEPRHS->getOperand(0)) {
951 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
952 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
953 GEPRHS->getOperand(0)->getType();
954 if (IndicesTheSame)
955 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
956 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
957 IndicesTheSame = false;
958 break;
959 }
960
961 // If all indices are the same, just compare the base pointers.
962 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000963 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000964
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000965 // If we're comparing GEPs with two base pointers that only differ in type
966 // and both GEPs have only constant indices or just one use, then fold
967 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000968 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000969 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
970 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
971 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000972 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000973 Value *LOffset = EmitGEPOffset(GEPLHS);
974 Value *ROffset = EmitGEPOffset(GEPRHS);
975
976 // If we looked through an addrspacecast between different sized address
977 // spaces, the LHS and RHS pointers are different sized
978 // integers. Truncate to the smaller one.
979 Type *LHSIndexTy = LOffset->getType();
980 Type *RHSIndexTy = ROffset->getType();
981 if (LHSIndexTy != RHSIndexTy) {
982 if (LHSIndexTy->getPrimitiveSizeInBits() <
983 RHSIndexTy->getPrimitiveSizeInBits()) {
984 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
985 } else
986 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
987 }
988
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000989 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000990 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000991 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000992 }
993
Chris Lattner2188e402010-01-04 07:37:31 +0000994 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000995 // different. Try convert this to an indexed compare by looking through
996 // PHIs/casts.
997 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +0000998 }
999
1000 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001001 if (GEPLHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001002 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +00001003 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +00001004
1005 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001006 if (GEPRHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001007 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner2188e402010-01-04 07:37:31 +00001008
Stuart Hastings66a82b92011-05-14 05:55:10 +00001009 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001010 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1011 // If the GEPs only differ by one index, compare it.
1012 unsigned NumDifferences = 0; // Keep track of # differences.
1013 unsigned DiffOperand = 0; // The operand that differs.
1014 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1015 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1016 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1017 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1018 // Irreconcilable differences.
1019 NumDifferences = 2;
1020 break;
1021 } else {
1022 if (NumDifferences++) break;
1023 DiffOperand = i;
1024 }
1025 }
1026
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001027 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001028 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001029 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001030
Stuart Hastings66a82b92011-05-14 05:55:10 +00001031 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001032 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1033 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1034 // Make sure we do a signed comparison here.
1035 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1036 }
1037 }
1038
1039 // Only lower this if the icmp is the only user of the GEP or if we expect
1040 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001041 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001042 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1043 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1044 Value *L = EmitGEPOffset(GEPLHS);
1045 Value *R = EmitGEPOffset(GEPRHS);
1046 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1047 }
1048 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001049
1050 // Try convert this to an indexed compare by looking through PHIs/casts as a
1051 // last resort.
1052 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001053}
1054
Pete Cooper980a9352016-08-12 17:13:28 +00001055Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1056 const AllocaInst *Alloca,
1057 const Value *Other) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001058 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1059
1060 // It would be tempting to fold away comparisons between allocas and any
1061 // pointer not based on that alloca (e.g. an argument). However, even
1062 // though such pointers cannot alias, they can still compare equal.
1063 //
1064 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1065 // doesn't escape we can argue that it's impossible to guess its value, and we
1066 // can therefore act as if any such guesses are wrong.
1067 //
1068 // The code below checks that the alloca doesn't escape, and that it's only
1069 // used in a comparison once (the current instruction). The
1070 // single-comparison-use condition ensures that we're trivially folding all
1071 // comparisons against the alloca consistently, and avoids the risk of
1072 // erroneously folding a comparison of the pointer with itself.
1073
1074 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1075
Pete Cooper980a9352016-08-12 17:13:28 +00001076 SmallVector<const Use *, 32> Worklist;
1077 for (const Use &U : Alloca->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001078 if (Worklist.size() >= MaxIter)
1079 return nullptr;
1080 Worklist.push_back(&U);
1081 }
1082
1083 unsigned NumCmps = 0;
1084 while (!Worklist.empty()) {
1085 assert(Worklist.size() <= MaxIter);
Pete Cooper980a9352016-08-12 17:13:28 +00001086 const Use *U = Worklist.pop_back_val();
1087 const Value *V = U->getUser();
Hans Wennborgf1f36512015-10-07 00:20:07 +00001088 --MaxIter;
1089
1090 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1091 isa<SelectInst>(V)) {
1092 // Track the uses.
1093 } else if (isa<LoadInst>(V)) {
1094 // Loading from the pointer doesn't escape it.
1095 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001096 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001097 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1098 if (SI->getValueOperand() == U->get())
1099 return nullptr;
1100 continue;
1101 } else if (isa<ICmpInst>(V)) {
1102 if (NumCmps++)
1103 return nullptr; // Found more than one cmp.
1104 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001105 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001106 switch (Intrin->getIntrinsicID()) {
1107 // These intrinsics don't escape or compare the pointer. Memset is safe
1108 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1109 // we don't allow stores, so src cannot point to V.
1110 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1111 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1112 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1113 continue;
1114 default:
1115 return nullptr;
1116 }
1117 } else {
1118 return nullptr;
1119 }
Pete Cooper980a9352016-08-12 17:13:28 +00001120 for (const Use &U : V->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001121 if (Worklist.size() >= MaxIter)
1122 return nullptr;
1123 Worklist.push_back(&U);
1124 }
1125 }
1126
1127 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001128 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001129 ICI,
1130 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1131}
1132
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001133/// Fold "icmp pred (X+CI), X".
Sanjay Patel43395062016-07-21 18:07:40 +00001134Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI,
1135 Value *X, ConstantInt *CI,
1136 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001137 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001138 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001139 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001140
Chris Lattner8c92b572010-01-08 17:48:19 +00001141 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001142 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1143 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1144 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001145 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001146 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001147 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1148 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001149
Chris Lattner2188e402010-01-04 07:37:31 +00001150 // (X+1) >u X --> X <u (0-1) --> X != 255
1151 // (X+2) >u X --> X <u (0-2) --> X <u 254
1152 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001153 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001154 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001155
Chris Lattner2188e402010-01-04 07:37:31 +00001156 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1157 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1158 APInt::getSignedMaxValue(BitWidth));
1159
1160 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1161 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1162 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1163 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1164 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1165 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001166 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001167 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001168
Chris Lattner2188e402010-01-04 07:37:31 +00001169 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1170 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1171 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1172 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1173 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1174 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001175
Chris Lattner2188e402010-01-04 07:37:31 +00001176 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001177 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001178 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1179}
1180
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001181/// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001182/// (icmp eq/ne A, Log2(const2/const1)) ->
1183/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
Sanjay Patel43395062016-07-21 18:07:40 +00001184Instruction *InstCombiner::foldICmpCstShrConst(ICmpInst &I, Value *Op, Value *A,
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001185 ConstantInt *CI1,
1186 ConstantInt *CI2) {
1187 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1188
1189 auto getConstant = [&I, this](bool IsTrue) {
1190 if (I.getPredicate() == I.ICMP_NE)
1191 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001192 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001193 };
1194
1195 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1196 if (I.getPredicate() == I.ICMP_NE)
1197 Pred = CmpInst::getInversePredicate(Pred);
1198 return new ICmpInst(Pred, LHS, RHS);
1199 };
1200
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001201 const APInt &AP1 = CI1->getValue();
1202 const APInt &AP2 = CI2->getValue();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001203
David Majnemer2abb8182014-10-25 07:13:13 +00001204 // Don't bother doing any work for cases which InstSimplify handles.
1205 if (AP2 == 0)
1206 return nullptr;
1207 bool IsAShr = isa<AShrOperator>(Op);
1208 if (IsAShr) {
1209 if (AP2.isAllOnesValue())
1210 return nullptr;
1211 if (AP2.isNegative() != AP1.isNegative())
1212 return nullptr;
1213 if (AP2.sgt(AP1))
1214 return nullptr;
1215 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001216
David Majnemerd2056022014-10-21 19:51:55 +00001217 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001218 // 'A' must be large enough to shift out the highest set bit.
1219 return getICmp(I.ICMP_UGT, A,
1220 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001221
David Majnemerd2056022014-10-21 19:51:55 +00001222 if (AP1 == AP2)
1223 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001224
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001225 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001226 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001227 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001228 else
David Majnemere5977eb2015-09-19 00:48:26 +00001229 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001230
David Majnemerd2056022014-10-21 19:51:55 +00001231 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001232 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1233 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001234 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001235 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1236 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001237 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001238 } else if (AP1 == AP2.lshr(Shift)) {
1239 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1240 }
David Majnemerd2056022014-10-21 19:51:55 +00001241 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001242 // Shifting const2 will never be equal to const1.
1243 return getConstant(false);
1244}
Chris Lattner2188e402010-01-04 07:37:31 +00001245
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001246/// Handle "(icmp eq/ne (shl const2, A), const1)" ->
David Majnemer59939ac2014-10-19 08:23:08 +00001247/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
Sanjay Patel43395062016-07-21 18:07:40 +00001248Instruction *InstCombiner::foldICmpCstShlConst(ICmpInst &I, Value *Op, Value *A,
1249 ConstantInt *CI1,
1250 ConstantInt *CI2) {
David Majnemer59939ac2014-10-19 08:23:08 +00001251 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1252
1253 auto getConstant = [&I, this](bool IsTrue) {
1254 if (I.getPredicate() == I.ICMP_NE)
1255 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001256 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001257 };
1258
1259 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1260 if (I.getPredicate() == I.ICMP_NE)
1261 Pred = CmpInst::getInversePredicate(Pred);
1262 return new ICmpInst(Pred, LHS, RHS);
1263 };
1264
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001265 const APInt &AP1 = CI1->getValue();
1266 const APInt &AP2 = CI2->getValue();
David Majnemer59939ac2014-10-19 08:23:08 +00001267
David Majnemer2abb8182014-10-25 07:13:13 +00001268 // Don't bother doing any work for cases which InstSimplify handles.
1269 if (AP2 == 0)
1270 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001271
1272 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1273
1274 if (!AP1 && AP2TrailingZeros != 0)
1275 return getICmp(I.ICMP_UGE, A,
1276 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1277
1278 if (AP1 == AP2)
1279 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1280
1281 // Get the distance between the lowest bits that are set.
1282 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1283
1284 if (Shift > 0 && AP2.shl(Shift) == AP1)
1285 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1286
1287 // Shifting const2 will never be equal to const1.
1288 return getConstant(false);
1289}
1290
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001291/// Fold icmp (trunc X, Y), C.
1292Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp,
1293 Instruction *Trunc,
1294 const APInt *C) {
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001295 ICmpInst::Predicate Pred = Cmp.getPredicate();
1296 Value *X = Trunc->getOperand(0);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001297 if (*C == 1 && C->getBitWidth() > 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001298 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1299 Value *V = nullptr;
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001300 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001301 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1302 ConstantInt::get(V->getType(), 1));
1303 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001304
1305 if (Cmp.isEquality() && Trunc->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001306 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1307 // of the high bits truncated out of x are known.
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001308 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1309 SrcBits = X->getType()->getScalarSizeInBits();
Sanjay Patela3f4f082016-08-16 17:54:36 +00001310 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001311 computeKnownBits(X, KnownZero, KnownOne, 0, &Cmp);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001312
1313 // If all the high bits are known, we can do this xform.
1314 if ((KnownZero | KnownOne).countLeadingOnes() >= SrcBits - DstBits) {
1315 // Pull in the high bits from known-ones set.
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001316 APInt NewRHS = C->zext(SrcBits);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001317 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001318 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001319 }
1320 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001321
Sanjay Patela3f4f082016-08-16 17:54:36 +00001322 return nullptr;
1323}
1324
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001325/// Fold icmp (xor X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001326Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp,
1327 BinaryOperator *Xor,
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001328 const APInt *C) {
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001329 Value *X = Xor->getOperand(0);
1330 Value *Y = Xor->getOperand(1);
Sanjay Pateldaffec912016-08-17 19:45:18 +00001331 const APInt *XorC;
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001332 if (!match(Y, m_APInt(XorC)))
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001333 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001334
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001335 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1336 // fold the xor.
1337 ICmpInst::Predicate Pred = Cmp.getPredicate();
1338 if ((Pred == ICmpInst::ICMP_SLT && *C == 0) ||
1339 (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001340
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001341 // If the sign bit of the XorCst is not set, there is no change to
1342 // the operation, just stop using the Xor.
Sanjay Pateldaffec912016-08-17 19:45:18 +00001343 if (!XorC->isNegative()) {
1344 Cmp.setOperand(0, X);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001345 Worklist.Add(Xor);
1346 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001347 }
1348
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001349 // Was the old condition true if the operand is positive?
1350 bool isTrueIfPositive = Pred == ICmpInst::ICMP_SGT;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001351
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001352 // If so, the new one isn't.
1353 isTrueIfPositive ^= true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001354
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001355 Constant *CmpConstant = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001356 if (isTrueIfPositive)
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001357 return new ICmpInst(ICmpInst::ICMP_SGT, X, SubOne(CmpConstant));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001358 else
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001359 return new ICmpInst(ICmpInst::ICMP_SLT, X, AddOne(CmpConstant));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001360 }
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001361
1362 if (Xor->hasOneUse()) {
Sanjay Pateldaffec912016-08-17 19:45:18 +00001363 // (icmp u/s (xor X SignBit), C) -> (icmp s/u X, (xor C SignBit))
1364 if (!Cmp.isEquality() && XorC->isSignBit()) {
1365 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1366 : Cmp.getSignedPredicate();
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001367 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001368 }
1369
Sanjay Pateldaffec912016-08-17 19:45:18 +00001370 // (icmp u/s (xor X ~SignBit), C) -> (icmp s/u X, (xor C ~SignBit))
1371 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1372 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1373 : Cmp.getSignedPredicate();
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001374 Pred = Cmp.getSwappedPredicate(Pred);
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001375 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001376 }
1377 }
1378
1379 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1380 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001381 if (Pred == ICmpInst::ICMP_UGT && *XorC == ~(*C) && (*C + 1).isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001382 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001383
1384 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1385 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001386 if (Pred == ICmpInst::ICMP_ULT && *XorC == -(*C) && C->isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001387 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001388
Sanjay Patela3f4f082016-08-16 17:54:36 +00001389 return nullptr;
1390}
1391
Sanjay Pateld3c7bb282016-08-26 16:42:33 +00001392/// Fold icmp (and X, C2), C.
1393Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp,
1394 BinaryOperator *And,
1395 const APInt *C) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001396 // FIXME: This check restricts all folds under here to scalar types.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001397 ConstantInt *RHS = dyn_cast<ConstantInt>(Cmp.getOperand(1));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001398 if (!RHS)
1399 return nullptr;
1400
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001401 if (And->hasOneUse() && isa<ConstantInt>(And->getOperand(1)) &&
1402 And->getOperand(0)->hasOneUse()) {
1403 ConstantInt *AndCst = cast<ConstantInt>(And->getOperand(1));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001404
1405 // If the LHS is an AND of a truncating cast, we can widen the
1406 // and/compare to be the input width without changing the value
1407 // produced, eliminating a cast.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001408 if (TruncInst *Cast = dyn_cast<TruncInst>(And->getOperand(0))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001409 // We can do this transformation if either the AND constant does not
1410 // have its sign bit set or if it is an equality comparison.
1411 // Extending a relational comparison when we're checking the sign
1412 // bit would not work.
Sanjay Pateld3c7bb282016-08-26 16:42:33 +00001413 if (Cmp.isEquality() || (!AndCst->isNegative() && C->isNonNegative())) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001414 Value *NewAnd =
1415 Builder->CreateAnd(Cast->getOperand(0),
1416 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001417 NewAnd->takeName(And);
1418 return new ICmpInst(Cmp.getPredicate(), NewAnd,
Sanjay Patela3f4f082016-08-16 17:54:36 +00001419 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1420 }
1421 }
1422
1423 // If the LHS is an AND of a zext, and we have an equality compare, we can
1424 // shrink the and/compare to the smaller type, eliminating the cast.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001425 if (ZExtInst *Cast = dyn_cast<ZExtInst>(And->getOperand(0))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001426 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1427 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1428 // should fold the icmp to true/false in that case.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001429 if (Cmp.isEquality() && C->getActiveBits() <= Ty->getBitWidth()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001430 Value *NewAnd = Builder->CreateAnd(Cast->getOperand(0),
1431 ConstantExpr::getTrunc(AndCst, Ty));
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001432 NewAnd->takeName(And);
1433 return new ICmpInst(Cmp.getPredicate(), NewAnd,
Sanjay Patela3f4f082016-08-16 17:54:36 +00001434 ConstantExpr::getTrunc(RHS, Ty));
1435 }
1436 }
1437
1438 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1439 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1440 // happens a LOT in code produced by the C front-end, for bitfield
1441 // access.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001442 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001443 if (Shift && !Shift->isShift())
1444 Shift = nullptr;
1445
1446 ConstantInt *ShAmt;
1447 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
1448
1449 // This seemingly simple opportunity to fold away a shift turns out to
1450 // be rather complicated. See PR17827
1451 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
1452 if (ShAmt) {
1453 bool CanFold = false;
1454 unsigned ShiftOpcode = Shift->getOpcode();
1455 if (ShiftOpcode == Instruction::AShr) {
1456 // There may be some constraints that make this possible,
1457 // but nothing simple has been discovered yet.
1458 CanFold = false;
1459 } else if (ShiftOpcode == Instruction::Shl) {
1460 // For a left shift, we can fold if the comparison is not signed.
1461 // We can also fold a signed comparison if the mask value and
1462 // comparison value are not negative. These constraints may not be
1463 // obvious, but we can prove that they are correct using an SMT
1464 // solver.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001465 if (!Cmp.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001466 CanFold = true;
1467 } else if (ShiftOpcode == Instruction::LShr) {
1468 // For a logical right shift, we can fold if the comparison is not
1469 // signed. We can also fold a signed comparison if the shifted mask
1470 // value and the shifted comparison value are not negative.
1471 // These constraints may not be obvious, but we can prove that they
1472 // are correct using an SMT solver.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001473 if (!Cmp.isSigned())
Sanjay Patela3f4f082016-08-16 17:54:36 +00001474 CanFold = true;
1475 else {
1476 ConstantInt *ShiftedAndCst =
1477 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1478 ConstantInt *ShiftedRHSCst =
1479 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1480
1481 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1482 CanFold = true;
1483 }
1484 }
1485
1486 if (CanFold) {
1487 Constant *NewCst;
1488 if (ShiftOpcode == Instruction::Shl)
1489 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1490 else
1491 NewCst = ConstantExpr::getShl(RHS, ShAmt);
1492
1493 // Check to see if we are shifting out any of the bits being
1494 // compared.
1495 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
1496 // If we shifted bits out, the fold is not going to work out.
1497 // As a special case, check to see if this means that the
1498 // result is always true or false now.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001499 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1500 return replaceInstUsesWith(Cmp, Builder->getFalse());
1501 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1502 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patela3f4f082016-08-16 17:54:36 +00001503 } else {
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001504 Cmp.setOperand(1, NewCst);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001505 Constant *NewAndCst;
1506 if (ShiftOpcode == Instruction::Shl)
1507 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
1508 else
1509 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001510 And->setOperand(1, NewAndCst);
1511 And->setOperand(0, Shift->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001512 Worklist.Add(Shift); // Shift is dead.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001513 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001514 }
1515 }
1516 }
1517
1518 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1519 // preferable because it allows the C<<Y expression to be hoisted out
1520 // of a loop if Y is invariant and X is not.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001521 if (Shift && Shift->hasOneUse() && *C == 0 && Cmp.isEquality() &&
Sanjay Patela3f4f082016-08-16 17:54:36 +00001522 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1523 // Compute C << Y.
1524 Value *NS;
1525 if (Shift->getOpcode() == Instruction::LShr) {
1526 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
1527 } else {
1528 // Insert a logical shift.
1529 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
1530 }
1531
1532 // Compute X & (C << Y).
1533 Value *NewAnd =
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001534 Builder->CreateAnd(Shift->getOperand(0), NS, And->getName());
Sanjay Patela3f4f082016-08-16 17:54:36 +00001535
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001536 Cmp.setOperand(0, NewAnd);
1537 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001538 }
1539
1540 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1541 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1542 //
1543 // iff pred isn't signed
1544 {
1545 Value *X, *Y, *LShr;
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001546 if (!Cmp.isSigned() && *C == 0) {
1547 if (match(And->getOperand(1), m_One())) {
1548 Constant *One = cast<Constant>(And->getOperand(1));
1549 Value *Or = And->getOperand(0);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001550 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1551 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1552 unsigned UsesRemoved = 0;
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001553 if (And->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00001554 ++UsesRemoved;
1555 if (Or->hasOneUse())
1556 ++UsesRemoved;
1557 if (LShr->hasOneUse())
1558 ++UsesRemoved;
1559 Value *NewOr = nullptr;
1560 // Compute X & ((1 << Y) | 1)
1561 if (auto *C = dyn_cast<Constant>(Y)) {
1562 if (UsesRemoved >= 1)
1563 NewOr =
1564 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1565 } else {
1566 if (UsesRemoved >= 3)
1567 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1568 LShr->getName(),
1569 /*HasNUW=*/true),
1570 One, Or->getName());
1571 }
1572 if (NewOr) {
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001573 Value *NewAnd = Builder->CreateAnd(X, NewOr, And->getName());
1574 Cmp.setOperand(0, NewAnd);
1575 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001576 }
1577 }
1578 }
1579 }
1580 }
1581
1582 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1583 // bit set in (X & AndCst) will produce a result greater than RHSV.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001584 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001585 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1586 if ((NTZ < AndCst->getBitWidth()) &&
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001587 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(*C))
1588 return new ICmpInst(ICmpInst::ICMP_NE, And,
Sanjay Patela3f4f082016-08-16 17:54:36 +00001589 Constant::getNullValue(RHS->getType()));
1590 }
1591 }
Sanjay Pateld3c7bb282016-08-26 16:42:33 +00001592 return nullptr;
1593}
1594
1595/// Fold icmp (and X, Y), C.
1596Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp,
1597 BinaryOperator *And,
1598 const APInt *C) {
1599 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1600 return I;
1601
1602 // FIXME: This check restricts all folds under here to scalar types.
1603 ConstantInt *RHS = dyn_cast<ConstantInt>(Cmp.getOperand(1));
1604 if (!RHS)
1605 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001606
1607 // Try to optimize things like "A[i]&42 == 0" to index computations.
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001608 if (LoadInst *LI = dyn_cast<LoadInst>(And->getOperand(0))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001609 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1610 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1611 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001612 !LI->isVolatile() && isa<ConstantInt>(And->getOperand(1))) {
1613 ConstantInt *C = cast<ConstantInt>(And->getOperand(1));
1614 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001615 return Res;
1616 }
1617 }
1618
1619 // X & -C == -C -> X > u ~C
1620 // X & -C != -C -> X <= u ~C
1621 // iff C is a power of 2
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001622 if (Cmp.isEquality() && RHS == And->getOperand(1) && (-(*C)).isPowerOf2())
1623 return new ICmpInst(Cmp.getPredicate() == ICmpInst::ICMP_EQ
Sanjay Patela3f4f082016-08-16 17:54:36 +00001624 ? ICmpInst::ICMP_UGT
1625 : ICmpInst::ICMP_ULE,
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001626 And->getOperand(0), SubOne(RHS));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001627
1628 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1629 // iff C is a power of 2
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001630 if (Cmp.isEquality() && And->hasOneUse() && match(RHS, m_Zero())) {
1631 if (auto *CI = dyn_cast<ConstantInt>(And->getOperand(1))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001632 const APInt &AI = CI->getValue();
1633 int32_t ExactLogBase2 = AI.exactLogBase2();
1634 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
Sanjay Patel311e0fa2016-08-26 16:14:06 +00001635 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1);
1636 Value *Trunc = Builder->CreateTrunc(And->getOperand(0), NTy);
1637 return new ICmpInst(Cmp.getPredicate() == ICmpInst::ICMP_EQ
Sanjay Patela3f4f082016-08-16 17:54:36 +00001638 ? ICmpInst::ICMP_SGE
1639 : ICmpInst::ICMP_SLT,
1640 Trunc, Constant::getNullValue(NTy));
1641 }
1642 }
1643 }
1644 return nullptr;
1645}
1646
Sanjay Patel943e92e2016-08-17 16:30:43 +00001647/// Fold icmp (or X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001648Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
Sanjay Patel943e92e2016-08-17 16:30:43 +00001649 const APInt *C) {
Sanjay Patel943e92e2016-08-17 16:30:43 +00001650 ICmpInst::Predicate Pred = Cmp.getPredicate();
1651 if (*C == 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001652 // icmp slt signum(V) 1 --> icmp slt V, 1
1653 Value *V = nullptr;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001654 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001655 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1656 ConstantInt::get(V->getType(), 1));
1657 }
1658
Sanjay Patel943e92e2016-08-17 16:30:43 +00001659 if (!Cmp.isEquality() || *C != 0 || !Or->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00001660 return nullptr;
1661
1662 Value *P, *Q;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001663 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001664 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1665 // -> and (icmp eq P, null), (icmp eq Q, null).
Reid Klecknera871d382016-08-19 16:53:18 +00001666 Value *CmpP =
1667 Builder->CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1668 Value *CmpQ =
1669 Builder->CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
Sanjay Patel943e92e2016-08-17 16:30:43 +00001670 auto LogicOpc = Pred == ICmpInst::Predicate::ICMP_EQ ? Instruction::And
1671 : Instruction::Or;
1672 return BinaryOperator::Create(LogicOpc, CmpP, CmpQ);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001673 }
Sanjay Patel943e92e2016-08-17 16:30:43 +00001674
Sanjay Patela3f4f082016-08-16 17:54:36 +00001675 return nullptr;
1676}
1677
Sanjay Patel63478072016-08-18 15:44:44 +00001678/// Fold icmp (mul X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001679Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp,
1680 BinaryOperator *Mul,
Sanjay Patel63478072016-08-18 15:44:44 +00001681 const APInt *C) {
1682 const APInt *MulC;
1683 if (!match(Mul->getOperand(1), m_APInt(MulC)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001684 return nullptr;
1685
Sanjay Patel63478072016-08-18 15:44:44 +00001686 // If this is a test of the sign bit and the multiply is sign-preserving with
1687 // a constant operand, use the multiply LHS operand instead.
1688 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patelc9196c42016-08-22 21:24:29 +00001689 if (isSignTest(Pred, *C) && Mul->hasNoSignedWrap()) {
Sanjay Patel63478072016-08-18 15:44:44 +00001690 if (MulC->isNegative())
1691 Pred = ICmpInst::getSwappedPredicate(Pred);
1692 return new ICmpInst(Pred, Mul->getOperand(0),
1693 Constant::getNullValue(Mul->getType()));
1694 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001695
1696 return nullptr;
1697}
1698
Sanjay Patel98cd99d2016-08-18 21:28:30 +00001699/// Fold icmp (shl 1, Y), C.
1700static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
1701 const APInt *C) {
1702 Value *Y;
1703 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
1704 return nullptr;
1705
1706 Type *ShiftType = Shl->getType();
1707 uint32_t TypeBits = C->getBitWidth();
1708 bool CIsPowerOf2 = C->isPowerOf2();
1709 ICmpInst::Predicate Pred = Cmp.getPredicate();
1710 if (Cmp.isUnsigned()) {
1711 // (1 << Y) pred C -> Y pred Log2(C)
1712 if (!CIsPowerOf2) {
1713 // (1 << Y) < 30 -> Y <= 4
1714 // (1 << Y) <= 30 -> Y <= 4
1715 // (1 << Y) >= 30 -> Y > 4
1716 // (1 << Y) > 30 -> Y > 4
1717 if (Pred == ICmpInst::ICMP_ULT)
1718 Pred = ICmpInst::ICMP_ULE;
1719 else if (Pred == ICmpInst::ICMP_UGE)
1720 Pred = ICmpInst::ICMP_UGT;
1721 }
1722
1723 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31
1724 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31
1725 unsigned CLog2 = C->logBase2();
1726 if (CLog2 == TypeBits - 1) {
1727 if (Pred == ICmpInst::ICMP_UGE)
1728 Pred = ICmpInst::ICMP_EQ;
1729 else if (Pred == ICmpInst::ICMP_ULT)
1730 Pred = ICmpInst::ICMP_NE;
1731 }
1732 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
1733 } else if (Cmp.isSigned()) {
1734 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
1735 if (C->isAllOnesValue()) {
1736 // (1 << Y) <= -1 -> Y == 31
1737 if (Pred == ICmpInst::ICMP_SLE)
1738 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1739
1740 // (1 << Y) > -1 -> Y != 31
1741 if (Pred == ICmpInst::ICMP_SGT)
1742 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1743 } else if (!(*C)) {
1744 // (1 << Y) < 0 -> Y == 31
1745 // (1 << Y) <= 0 -> Y == 31
1746 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1747 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1748
1749 // (1 << Y) >= 0 -> Y != 31
1750 // (1 << Y) > 0 -> Y != 31
1751 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1752 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1753 }
1754 } else if (Cmp.isEquality() && CIsPowerOf2) {
1755 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C->logBase2()));
1756 }
1757
1758 return nullptr;
1759}
1760
Sanjay Patel38b75062016-08-19 17:20:37 +00001761/// Fold icmp (shl X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001762Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp,
1763 BinaryOperator *Shl,
Sanjay Patel38b75062016-08-19 17:20:37 +00001764 const APInt *C) {
Sanjay Patelfa7de602016-08-19 22:33:26 +00001765 const APInt *ShiftAmt;
1766 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patel38b75062016-08-19 17:20:37 +00001767 return foldICmpShlOne(Cmp, Shl, C);
Sanjay Patela867afe2016-08-19 16:12:16 +00001768
Sanjay Patel38b75062016-08-19 17:20:37 +00001769 // Check that the shift amount is in range. If not, don't perform undefined
1770 // shifts. When the shift is visited it will be simplified.
1771 unsigned TypeBits = C->getBitWidth();
Sanjay Patelfa7de602016-08-19 22:33:26 +00001772 if (ShiftAmt->uge(TypeBits))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001773 return nullptr;
1774
Sanjay Patele38e79c2016-08-19 17:34:05 +00001775 ICmpInst::Predicate Pred = Cmp.getPredicate();
1776 Value *X = Shl->getOperand(0);
Sanjay Patel38b75062016-08-19 17:20:37 +00001777 if (Cmp.isEquality()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001778 // If the shift is NUW, then it is just shifting out zeros, no need for an
1779 // AND.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001780 Constant *LShrC = ConstantInt::get(Shl->getType(), C->lshr(*ShiftAmt));
Sanjay Patelc9196c42016-08-22 21:24:29 +00001781 if (Shl->hasNoUnsignedWrap())
Sanjay Patelfa7de602016-08-19 22:33:26 +00001782 return new ICmpInst(Pred, X, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001783
1784 // If the shift is NSW and we compare to 0, then it is just shifting out
1785 // sign bits, no need for an AND either.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001786 if (Shl->hasNoSignedWrap() && *C == 0)
Sanjay Patelfa7de602016-08-19 22:33:26 +00001787 return new ICmpInst(Pred, X, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001788
Sanjay Patel38b75062016-08-19 17:20:37 +00001789 if (Shl->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001790 // Otherwise strength reduce the shift into an and.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001791 Constant *Mask = ConstantInt::get(Shl->getType(),
1792 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001793
Sanjay Patele38e79c2016-08-19 17:34:05 +00001794 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patelfa7de602016-08-19 22:33:26 +00001795 return new ICmpInst(Pred, And, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001796 }
1797 }
1798
1799 // If this is a signed comparison to 0 and the shift is sign preserving,
Sanjay Patele38e79c2016-08-19 17:34:05 +00001800 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
1801 // do that if we're sure to not continue on in this function.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001802 if (Shl->hasNoSignedWrap() && isSignTest(Pred, *C))
Sanjay Patel7e09f132016-08-21 16:28:22 +00001803 return new ICmpInst(Pred, X, Constant::getNullValue(X->getType()));
1804
Sanjay Patela3f4f082016-08-16 17:54:36 +00001805 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1806 bool TrueIfSigned = false;
Sanjay Patel79263662016-08-21 15:07:45 +00001807 if (Shl->hasOneUse() && isSignBitCheck(Pred, *C, TrueIfSigned)) {
Sanjay Patel7ffcde72016-08-21 16:35:34 +00001808 // (X << 31) <s 0 --> (X & 1) != 0
Sanjay Patela3f4f082016-08-16 17:54:36 +00001809 Constant *Mask = ConstantInt::get(
Sanjay Patele38e79c2016-08-19 17:34:05 +00001810 X->getType(),
Sanjay Patelfa7de602016-08-19 22:33:26 +00001811 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
Sanjay Patele38e79c2016-08-19 17:34:05 +00001812 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patela3f4f082016-08-16 17:54:36 +00001813 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1814 And, Constant::getNullValue(And->getType()));
1815 }
1816
Sanjay Patel643d21a2016-08-21 17:10:07 +00001817 // Transform (icmp pred iM (shl iM %v, N), C)
1818 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
1819 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
1820 // This enables us to get rid of the shift in favor of a trunc which can be
Sanjay Patela3f4f082016-08-16 17:54:36 +00001821 // free on the target. It has the additional benefit of comparing to a
1822 // smaller constant, which will be target friendly.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001823 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
Sanjay Patel38b75062016-08-19 17:20:37 +00001824 if (Shl->hasOneUse() && Amt != 0 && C->countTrailingZeros() >= Amt) {
Sanjay Patel643d21a2016-08-21 17:10:07 +00001825 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
1826 if (X->getType()->isVectorTy())
1827 TruncTy = VectorType::get(TruncTy, X->getType()->getVectorNumElements());
1828 Constant *NewC =
1829 ConstantInt::get(TruncTy, C->ashr(*ShiftAmt).trunc(TypeBits - Amt));
1830 return new ICmpInst(Pred, Builder->CreateTrunc(X, TruncTy), NewC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001831 }
1832
1833 return nullptr;
1834}
1835
Sanjay Patela3920492016-08-22 20:45:06 +00001836/// Fold icmp ({al}shr X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001837Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp,
1838 BinaryOperator *Shr,
1839 const APInt *C) {
Sanjay Patela3920492016-08-22 20:45:06 +00001840 // An exact shr only shifts out zero bits, so:
1841 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
Sanjay Pateld64e9882016-08-23 22:05:55 +00001842 Value *X = Shr->getOperand(0);
Sanjay Patelc9196c42016-08-22 21:24:29 +00001843 CmpInst::Predicate Pred = Cmp.getPredicate();
1844 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() && *C == 0)
Sanjay Pateld64e9882016-08-23 22:05:55 +00001845 return new ICmpInst(Pred, X, Cmp.getOperand(1));
Sanjay Patela3920492016-08-22 20:45:06 +00001846
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001847 const APInt *ShiftAmt;
1848 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001849 return nullptr;
1850
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001851 // Check that the shift amount is in range. If not, don't perform undefined
1852 // shifts. When the shift is visited it will be simplified.
1853 unsigned TypeBits = C->getBitWidth();
1854 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001855 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
1856 return nullptr;
1857
Sanjay Pateld64e9882016-08-23 22:05:55 +00001858 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001859 if (!Cmp.isEquality()) {
1860 // If we have an unsigned comparison and an ashr, we can't simplify this.
1861 // Similarly for signed comparisons with lshr.
Sanjay Pateld64e9882016-08-23 22:05:55 +00001862 if (Cmp.isSigned() != IsAShr)
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001863 return nullptr;
1864
1865 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1866 // by a power of 2. Since we already have logic to simplify these,
1867 // transform to div and then simplify the resultant comparison.
Sanjay Pateld64e9882016-08-23 22:05:55 +00001868 if (IsAShr && (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001869 return nullptr;
1870
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001871 // FIXME: This check restricts this fold to scalar types.
1872 ConstantInt *ShAmt = dyn_cast<ConstantInt>(Shr->getOperand(1));
1873 if (!ShAmt)
1874 return nullptr;
1875
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001876 // Revisit the shift (to delete it).
1877 Worklist.Add(Shr);
1878
1879 Constant *DivCst = ConstantInt::get(
1880 Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
1881
Sanjay Pateld64e9882016-08-23 22:05:55 +00001882 Value *Tmp = IsAShr ? Builder->CreateSDiv(X, DivCst, "", Shr->isExact())
1883 : Builder->CreateUDiv(X, DivCst, "", Shr->isExact());
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001884
1885 Cmp.setOperand(0, Tmp);
1886
1887 // If the builder folded the binop, just return it.
1888 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1889 if (!TheDiv)
1890 return &Cmp;
1891
1892 // Otherwise, fold this div/compare.
1893 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1894 TheDiv->getOpcode() == Instruction::UDiv);
1895
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001896 Instruction *Res = foldICmpDivConstant(Cmp, TheDiv, C);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001897 assert(Res && "This div/cst should have folded!");
Sanjay Patela3920492016-08-22 20:45:06 +00001898 return Res;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001899 }
1900
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001901 // Handle equality comparisons of shift-by-constant.
1902
Sanjay Patel8e297742016-08-24 13:55:55 +00001903 // If the comparison constant changes with the shift, the comparison cannot
1904 // succeed (bits of the comparison constant cannot match the shifted value).
1905 // This should be known by InstSimplify and already be folded to true/false.
1906 assert(((IsAShr && C->shl(ShAmtVal).ashr(ShAmtVal) == *C) ||
1907 (!IsAShr && C->shl(ShAmtVal).lshr(ShAmtVal) == *C)) &&
1908 "Expected icmp+shr simplify did not occur.");
1909
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001910 // Check if the bits shifted out are known to be zero. If so, we can compare
1911 // against the unshifted value:
1912 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001913 Constant *ShiftedCmpRHS = ConstantInt::get(Shr->getType(), *C << ShAmtVal);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001914 if (Shr->hasOneUse()) {
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001915 if (Shr->isExact())
1916 return new ICmpInst(Pred, X, ShiftedCmpRHS);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001917
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001918 // Otherwise strength reduce the shift into an 'and'.
1919 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1920 Constant *Mask = ConstantInt::get(Shr->getType(), Val);
Sanjay Pateld64e9882016-08-23 22:05:55 +00001921 Value *And = Builder->CreateAnd(X, Mask, Shr->getName() + ".mask");
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001922 return new ICmpInst(Pred, And, ShiftedCmpRHS);
1923 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001924
1925 return nullptr;
1926}
1927
Sanjay Patel12a41052016-08-18 17:37:26 +00001928/// Fold icmp (udiv X, Y), C.
1929Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp,
Sanjay Patelc9196c42016-08-22 21:24:29 +00001930 BinaryOperator *UDiv,
Sanjay Patel12a41052016-08-18 17:37:26 +00001931 const APInt *C) {
Sanjay Patelfa5ca2b2016-08-18 17:55:59 +00001932 const APInt *C2;
1933 if (!match(UDiv->getOperand(0), m_APInt(C2)))
1934 return nullptr;
1935
1936 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
1937
1938 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
1939 Value *Y = UDiv->getOperand(1);
1940 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
1941 assert(!C->isMaxValue() &&
1942 "icmp ugt X, UINT_MAX should have been simplified already.");
1943 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
1944 ConstantInt::get(Y->getType(), C2->udiv(*C + 1)));
1945 }
1946
1947 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
1948 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) {
1949 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
1950 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
1951 ConstantInt::get(Y->getType(), C2->udiv(*C)));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001952 }
1953
1954 return nullptr;
1955}
1956
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001957/// Fold icmp ({su}div X, Y), C.
1958Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp,
1959 BinaryOperator *Div,
1960 const APInt *C) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001961 // FIXME: This check restricts all folds under here to scalar types.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001962 ConstantInt *RHS = dyn_cast<ConstantInt>(Cmp.getOperand(1));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001963 if (!RHS)
1964 return nullptr;
1965
1966 // Fold: icmp pred ([us]div X, C1), C2 -> range test
1967 // Fold this div into the comparison, producing a range check.
1968 // Determine, based on the divide type, what the range is being
1969 // checked. If there is an overflow on the low or high side, remember
1970 // it, otherwise compute the range [low, hi) bounding the new value.
1971 // See: InsertRangeTest above for the kinds of replacements possible.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001972 ConstantInt *DivRHS = dyn_cast<ConstantInt>(Div->getOperand(1));
Sanjay Patel16554142016-08-24 23:03:36 +00001973 if (!DivRHS)
1974 return nullptr;
1975
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001976 ConstantInt *CmpRHS = cast<ConstantInt>(Cmp.getOperand(1));
Sanjay Patel16554142016-08-24 23:03:36 +00001977
1978 // FIXME: If the operand types don't match the type of the divide
1979 // then don't attempt this transform. The code below doesn't have the
1980 // logic to deal with a signed divide and an unsigned compare (and
1981 // vice versa). This is because (x /s C1) <s C2 produces different
1982 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
1983 // (x /u C1) <u C2. Simply casting the operands and result won't
1984 // work. :( The if statement below tests that condition and bails
1985 // if it finds it.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001986 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
1987 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
Sanjay Patel16554142016-08-24 23:03:36 +00001988 return nullptr;
1989 if (DivRHS->isZero())
1990 return nullptr; // The ProdOV computation fails on divide by zero.
1991 if (DivIsSigned && DivRHS->isAllOnesValue())
1992 return nullptr; // The overflow computation also screws up here
1993 if (DivRHS->isOne()) {
1994 // This eliminates some funny cases with INT_MIN.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001995 Cmp.setOperand(0, Div->getOperand(0)); // X/1 == X.
1996 return &Cmp;
Sanjay Patel16554142016-08-24 23:03:36 +00001997 }
1998
1999 // Compute Prod = CI * DivRHS. We are essentially solving an equation
2000 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
2001 // C2 (CI). By solving for X we can turn this into a range check
2002 // instead of computing a divide.
2003 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
2004
2005 // Determine if the product overflows by seeing if the product is
2006 // not equal to the divide. Make sure we do the same kind of divide
2007 // as in the LHS instruction that we're folding.
2008 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
2009 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
2010
2011 // Get the ICmp opcode
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002012 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patel16554142016-08-24 23:03:36 +00002013
2014 // If the division is known to be exact, then there is no remainder from the
2015 // divide, so the covered range size is unit, otherwise it is the divisor.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002016 ConstantInt *RangeSize = Div->isExact() ? getOne(Prod) : DivRHS;
Sanjay Patel16554142016-08-24 23:03:36 +00002017
2018 // Figure out the interval that is being checked. For example, a comparison
2019 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2020 // Compute this interval based on the constants involved and the signedness of
2021 // the compare/divide. This computes a half-open interval, keeping track of
2022 // whether either value in the interval overflows. After analysis each
2023 // overflow variable is set to 0 if it's corresponding bound variable is valid
2024 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2025 int LoOverflow = 0, HiOverflow = 0;
2026 Constant *LoBound = nullptr, *HiBound = nullptr;
2027
2028 if (!DivIsSigned) { // udiv
2029 // e.g. X/5 op 3 --> [15, 20)
2030 LoBound = Prod;
2031 HiOverflow = LoOverflow = ProdOV;
2032 if (!HiOverflow) {
2033 // If this is not an exact divide, then many values in the range collapse
2034 // to the same result value.
2035 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
2036 }
2037 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002038 if (*C == 0) { // (X / pos) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00002039 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2040 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
2041 HiBound = RangeSize;
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002042 } else if (C->isStrictlyPositive()) { // (X / pos) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00002043 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2044 HiOverflow = LoOverflow = ProdOV;
2045 if (!HiOverflow)
2046 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
2047 } else { // (X / pos) op neg
2048 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2049 HiBound = AddOne(Prod);
2050 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2051 if (!LoOverflow) {
2052 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
2053 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2054 }
2055 }
2056 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002057 if (Div->isExact())
Sanjay Patel16554142016-08-24 23:03:36 +00002058 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002059 if (*C == 0) { // (X / neg) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00002060 // e.g. X/-5 op 0 --> [-4, 5)
2061 LoBound = AddOne(RangeSize);
2062 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
2063 if (HiBound == DivRHS) { // -INTMIN = INTMIN
2064 HiOverflow = 1; // [INTMIN+1, overflow)
2065 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
2066 }
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002067 } else if (C->isStrictlyPositive()) { // (X / neg) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00002068 // e.g. X/-5 op 3 --> [-19, -14)
2069 HiBound = AddOne(Prod);
2070 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2071 if (!LoOverflow)
2072 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
2073 } else { // (X / neg) op neg
2074 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2075 LoOverflow = HiOverflow = ProdOV;
2076 if (!HiOverflow)
2077 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
2078 }
2079
2080 // Dividing by a negative swaps the condition. LT <-> GT
2081 Pred = ICmpInst::getSwappedPredicate(Pred);
2082 }
2083
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002084 Value *X = Div->getOperand(0);
Sanjay Patel16554142016-08-24 23:03:36 +00002085 switch (Pred) {
2086 default: llvm_unreachable("Unhandled icmp opcode!");
2087 case ICmpInst::ICMP_EQ:
2088 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002089 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002090 if (HiOverflow)
2091 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2092 ICmpInst::ICMP_UGE, X, LoBound);
2093 if (LoOverflow)
2094 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2095 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002096 return replaceInstUsesWith(Cmp, InsertRangeTest(X, LoBound, HiBound,
Sanjay Patel16554142016-08-24 23:03:36 +00002097 DivIsSigned, true));
2098 case ICmpInst::ICMP_NE:
2099 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002100 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002101 if (HiOverflow)
2102 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2103 ICmpInst::ICMP_ULT, X, LoBound);
2104 if (LoOverflow)
2105 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2106 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002107 return replaceInstUsesWith(Cmp, InsertRangeTest(X, LoBound, HiBound,
Sanjay Patel16554142016-08-24 23:03:36 +00002108 DivIsSigned, false));
2109 case ICmpInst::ICMP_ULT:
2110 case ICmpInst::ICMP_SLT:
2111 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002112 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002113 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002114 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002115 return new ICmpInst(Pred, X, LoBound);
2116 case ICmpInst::ICMP_UGT:
2117 case ICmpInst::ICMP_SGT:
2118 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002119 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002120 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002121 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002122 if (Pred == ICmpInst::ICMP_UGT)
2123 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
2124 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
2125 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002126
2127 return nullptr;
2128}
2129
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002130/// Fold icmp (sub X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002131Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp,
2132 BinaryOperator *Sub,
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002133 const APInt *C) {
Sanjay Patele47df1a2016-08-16 21:53:19 +00002134 const APInt *C2;
2135 if (!match(Sub->getOperand(0), m_APInt(C2)) || !Sub->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00002136 return nullptr;
2137
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002138 // C-X <u C2 -> (X|(C2-1)) == C
2139 // iff C & (C2-1) == C2-1
Sanjay Patela3f4f082016-08-16 17:54:36 +00002140 // C2 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002141 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2142 (*C2 & (*C - 1)) == (*C - 1))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002143 return new ICmpInst(ICmpInst::ICMP_EQ,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002144 Builder->CreateOr(Sub->getOperand(1), *C - 1),
2145 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002146
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002147 // C-X >u C2 -> (X|C2) != C
2148 // iff C & C2 == C2
Sanjay Patela3f4f082016-08-16 17:54:36 +00002149 // C2+1 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002150 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2151 (*C2 & *C) == *C)
Sanjay Patela3f4f082016-08-16 17:54:36 +00002152 return new ICmpInst(ICmpInst::ICMP_NE,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002153 Builder->CreateOr(Sub->getOperand(1), *C),
2154 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002155
2156 return nullptr;
2157}
2158
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002159/// Fold icmp (add X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002160Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp,
2161 BinaryOperator *Add,
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002162 const APInt *C) {
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002163 Value *Y = Add->getOperand(1);
2164 const APInt *C2;
2165 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002166 return nullptr;
2167
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002168 // Fold icmp pred (add X, C2), C.
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002169 Value *X = Add->getOperand(0);
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002170 Type *Ty = Add->getType();
2171 auto CR = Cmp.makeConstantRange(Cmp.getPredicate(), *C).subtract(*C2);
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002172 const APInt &Upper = CR.getUpper();
2173 const APInt &Lower = CR.getLower();
2174 if (Cmp.isSigned()) {
2175 if (Lower.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002176 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002177 if (Upper.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002178 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002179 } else {
2180 if (Lower.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002181 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002182 if (Upper.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002183 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002184 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002185
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002186 if (!Add->hasOneUse())
2187 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002188
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002189 // X+C <u C2 -> (X & -C2) == C
2190 // iff C & (C2-1) == 0
2191 // C2 is a power of 2
2192 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2193 (*C2 & (*C - 1)) == 0)
2194 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)),
2195 ConstantExpr::getNeg(cast<Constant>(Y)));
2196
2197 // X+C >u C2 -> (X & ~C2) != C
2198 // iff C & C2 == 0
2199 // C2+1 is a power of 2
2200 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2201 (*C2 & *C) == 0)
2202 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)),
2203 ConstantExpr::getNeg(cast<Constant>(Y)));
2204
Sanjay Patela3f4f082016-08-16 17:54:36 +00002205 return nullptr;
2206}
2207
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00002208/// Try to fold integer comparisons with a constant operand: icmp Pred X, C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002209Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) {
2210 const APInt *C;
2211 if (!match(Cmp.getOperand(1), m_APInt(C)))
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00002212 return nullptr;
2213
Sanjay Patelc9196c42016-08-22 21:24:29 +00002214 BinaryOperator *BO;
2215 if (match(Cmp.getOperand(0), m_BinOp(BO))) {
2216 switch (BO->getOpcode()) {
2217 case Instruction::Xor:
2218 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
2219 return I;
2220 break;
2221 case Instruction::And:
2222 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
2223 return I;
2224 break;
2225 case Instruction::Or:
2226 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
2227 return I;
2228 break;
2229 case Instruction::Mul:
2230 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
2231 return I;
2232 break;
2233 case Instruction::Shl:
2234 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
2235 return I;
2236 break;
2237 case Instruction::LShr:
2238 case Instruction::AShr:
2239 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
2240 return I;
2241 break;
2242 case Instruction::UDiv:
2243 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
2244 return I;
2245 LLVM_FALLTHROUGH;
2246 case Instruction::SDiv:
2247 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
2248 return I;
2249 break;
2250 case Instruction::Sub:
2251 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
2252 return I;
2253 break;
2254 case Instruction::Add:
2255 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
2256 return I;
2257 break;
2258 default:
2259 break;
2260 }
Chris Lattner2188e402010-01-04 07:37:31 +00002261 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002262
Sanjay Patelc9196c42016-08-22 21:24:29 +00002263 Instruction *LHSI;
2264 if (match(Cmp.getOperand(0), m_Instruction(LHSI)) &&
2265 LHSI->getOpcode() == Instruction::Trunc)
2266 if (Instruction *I = foldICmpTruncConstant(Cmp, LHSI, C))
2267 return I;
2268
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002269 return nullptr;
2270}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002271
Sanjay Patelab50a932016-08-02 22:38:33 +00002272/// Simplify icmp_eq and icmp_ne instructions with binary operator LHS and
2273/// integer constant RHS.
2274Instruction *InstCombiner::foldICmpEqualityWithConstant(ICmpInst &ICI) {
Sanjay Patelab50a932016-08-02 22:38:33 +00002275 BinaryOperator *BO;
Sanjay Patel43aeb002016-08-03 18:59:03 +00002276 const APInt *RHSV;
2277 // FIXME: Some of these folds could work with arbitrary constants, but this
2278 // match is limited to scalars and vector splat constants.
Sanjay Patelab50a932016-08-02 22:38:33 +00002279 if (!ICI.isEquality() || !match(ICI.getOperand(0), m_BinOp(BO)) ||
Sanjay Patel43aeb002016-08-03 18:59:03 +00002280 !match(ICI.getOperand(1), m_APInt(RHSV)))
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002281 return nullptr;
2282
Sanjay Patel43aeb002016-08-03 18:59:03 +00002283 Constant *RHS = cast<Constant>(ICI.getOperand(1));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002284 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002285 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002286
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002287 switch (BO->getOpcode()) {
2288 case Instruction::SRem:
2289 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002290 if (*RHSV == 0 && BO->hasOneUse()) {
2291 const APInt *BOC;
2292 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002293 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002294 return new ICmpInst(ICI.getPredicate(), NewRem,
2295 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002296 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002297 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002298 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002299 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002300 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002301 const APInt *BOC;
2302 if (match(BOp1, m_APInt(BOC))) {
2303 if (BO->hasOneUse()) {
2304 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
2305 return new ICmpInst(ICI.getPredicate(), BOp0, SubC);
2306 }
Sanjay Patel43aeb002016-08-03 18:59:03 +00002307 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002308 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2309 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002310 if (Value *NegVal = dyn_castNegVal(BOp1))
2311 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
2312 if (Value *NegVal = dyn_castNegVal(BOp0))
2313 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
2314 if (BO->hasOneUse()) {
2315 Value *Neg = Builder->CreateNeg(BOp1);
2316 Neg->takeName(BO);
2317 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
2318 }
2319 }
2320 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002321 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002322 case Instruction::Xor:
2323 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002324 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002325 // For the xor case, we can xor two constants together, eliminating
2326 // the explicit xor.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002327 return new ICmpInst(ICI.getPredicate(), BOp0,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002328 ConstantExpr::getXor(RHS, BOC));
Sanjay Patel43aeb002016-08-03 18:59:03 +00002329 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002330 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002331 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002332 }
2333 }
2334 break;
2335 case Instruction::Sub:
2336 if (BO->hasOneUse()) {
Sanjay Patel9d591d12016-08-04 15:19:25 +00002337 const APInt *BOC;
2338 if (match(BOp0, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002339 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
Sanjay Patel9d591d12016-08-04 15:19:25 +00002340 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
2341 return new ICmpInst(ICI.getPredicate(), BOp1, SubC);
Sanjay Patel43aeb002016-08-03 18:59:03 +00002342 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002343 // Replace ((sub A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002344 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002345 }
2346 }
2347 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002348 case Instruction::Or: {
2349 const APInt *BOC;
2350 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002351 // Comparing if all bits outside of a constant mask are set?
2352 // Replace (X | C) == -1 with (X & ~C) == ~C.
2353 // This removes the -1 constant.
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002354 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2355 Value *And = Builder->CreateAnd(BOp0, NotBOC);
2356 return new ICmpInst(ICI.getPredicate(), And, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002357 }
2358 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002359 }
Sanjay Pateld938e882016-08-04 20:05:02 +00002360 case Instruction::And: {
2361 const APInt *BOC;
2362 if (match(BOp1, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002363 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Pateld938e882016-08-04 20:05:02 +00002364 if (RHSV == BOC && RHSV->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002365 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002366 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002367
2368 // Don't perform the following transforms if the AND has multiple uses
2369 if (!BO->hasOneUse())
2370 break;
2371
2372 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Sanjay Pateld938e882016-08-04 20:05:02 +00002373 if (BOC->isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002374 Constant *Zero = Constant::getNullValue(BOp0->getType());
2375 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002376 isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002377 return new ICmpInst(Pred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002378 }
2379
2380 // ((X & ~7) == 0) --> X < 8
Sanjay Pateld938e882016-08-04 20:05:02 +00002381 if (*RHSV == 0 && (~(*BOC) + 1).isPowerOf2()) {
2382 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1));
Sanjay Patel51a767c2016-08-03 17:23:08 +00002383 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002384 isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Sanjay Pateld938e882016-08-04 20:05:02 +00002385 return new ICmpInst(Pred, BOp0, NegBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002386 }
2387 }
2388 break;
Sanjay Pateld938e882016-08-04 20:05:02 +00002389 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002390 case Instruction::Mul:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002391 if (*RHSV == 0 && BO->hasNoSignedWrap()) {
Sanjay Patel3bade132016-08-04 22:19:27 +00002392 const APInt *BOC;
2393 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) {
2394 // The trivial case (mul X, 0) is handled by InstSimplify.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002395 // General case : (mul X, C) != 0 iff X != 0
2396 // (mul X, C) == 0 iff X == 0
Sanjay Patel3bade132016-08-04 22:19:27 +00002397 return new ICmpInst(ICI.getPredicate(), BOp0,
2398 Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002399 }
2400 }
2401 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002402 case Instruction::UDiv:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002403 if (*RHSV == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002404 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
2405 ICmpInst::Predicate Pred =
2406 isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002407 return new ICmpInst(Pred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002408 }
2409 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002410 default:
2411 break;
2412 }
2413 return nullptr;
2414}
2415
Sanjay Patel1271bf92016-07-23 13:06:49 +00002416Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &ICI) {
2417 IntrinsicInst *II = dyn_cast<IntrinsicInst>(ICI.getOperand(0));
2418 const APInt *Op1C;
2419 if (!II || !ICI.isEquality() || !match(ICI.getOperand(1), m_APInt(Op1C)))
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002420 return nullptr;
2421
2422 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002423 switch (II->getIntrinsicID()) {
2424 case Intrinsic::bswap:
2425 Worklist.Add(II);
2426 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002427 ICI.setOperand(1, Builder->getInt(Op1C->byteSwap()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002428 return &ICI;
2429 case Intrinsic::ctlz:
2430 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002431 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel1271bf92016-07-23 13:06:49 +00002432 if (*Op1C == Op1C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002433 Worklist.Add(II);
2434 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002435 ICI.setOperand(1, ConstantInt::getNullValue(II->getType()));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002436 return &ICI;
Chris Lattner2188e402010-01-04 07:37:31 +00002437 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002438 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002439 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002440 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002441 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
2442 bool IsZero = *Op1C == 0;
2443 if (IsZero || *Op1C == Op1C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002444 Worklist.Add(II);
2445 ICI.setOperand(0, II->getArgOperand(0));
Amaury Sechet6bea6742016-08-04 05:27:20 +00002446 auto *NewOp = IsZero
2447 ? ConstantInt::getNullValue(II->getType())
2448 : ConstantInt::getAllOnesValue(II->getType());
2449 ICI.setOperand(1, NewOp);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002450 return &ICI;
2451 }
Amaury Sechet6bea6742016-08-04 05:27:20 +00002452 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002453 break;
2454 default:
2455 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002456 }
Craig Topperf40110f2014-04-25 05:29:35 +00002457 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002458}
2459
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002460/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
2461/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00002462Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002463 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00002464 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002465 Type *SrcTy = LHSCIOp->getType();
2466 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002467 Value *RHSCIOp;
2468
Jim Grosbach129c52a2011-09-30 18:09:53 +00002469 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002470 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002471 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2472 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002473 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002474 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00002475 Value *RHSCIOp = RHSC->getOperand(0);
2476 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2477 LHSCIOp->getType()->getPointerAddressSpace()) {
2478 RHSOp = RHSC->getOperand(0);
2479 // If the pointer types don't match, insert a bitcast.
2480 if (LHSCIOp->getType() != RHSOp->getType())
2481 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2482 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002483 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002484 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002485 }
Chris Lattner2188e402010-01-04 07:37:31 +00002486
2487 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002488 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002489 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002490
Chris Lattner2188e402010-01-04 07:37:31 +00002491 // The code below only handles extension cast instructions, so far.
2492 // Enforce this.
2493 if (LHSCI->getOpcode() != Instruction::ZExt &&
2494 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002495 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002496
2497 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002498 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00002499
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002500 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002501 // Not an extension from the same type?
2502 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002503 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002504 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002505
Chris Lattner2188e402010-01-04 07:37:31 +00002506 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2507 // and the other is a zext), then we can't handle this.
2508 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002509 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002510
2511 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002512 if (ICmp.isEquality())
2513 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002514
2515 // A signed comparison of sign extended values simplifies into a
2516 // signed comparison.
2517 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002518 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002519
2520 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002521 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002522 }
2523
Sanjay Patel4c204232016-06-04 20:39:22 +00002524 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002525 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
2526 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00002527 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002528
2529 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002530 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002531 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002532 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002533
2534 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002535 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00002536 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002537 if (ICmp.isEquality())
2538 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002539
2540 // A signed comparison of sign extended values simplifies into a
2541 // signed comparison.
2542 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002543 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002544
2545 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002546 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002547 }
2548
Sanjay Patel6a333c32016-06-06 16:56:57 +00002549 // The re-extended constant changed, partly changed (in the case of a vector),
2550 // or could not be determined to be equal (in the case of a constant
2551 // expression), so the constant cannot be represented in the shorter type.
2552 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002553 // All the cases that fold to true or false will have already been handled
2554 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002555
Sanjay Patel6a333c32016-06-06 16:56:57 +00002556 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00002557 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002558
2559 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2560 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002561
2562 // We're performing an unsigned comp with a sign extended value.
2563 // This is true if the input is >= 0. [aka >s -1]
2564 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002565 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002566
2567 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002568 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2569 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002570
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002571 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002572 return BinaryOperator::CreateNot(Result);
2573}
2574
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002575/// The caller has matched a pattern of the form:
Chris Lattneree61c1d2010-12-19 17:52:50 +00002576/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002577/// If this is of the form:
2578/// sum = a + b
2579/// if (sum+128 >u 255)
2580/// Then replace it with llvm.sadd.with.overflow.i8.
2581///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002582static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2583 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002584 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002585 // The transformation we're trying to do here is to transform this into an
2586 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2587 // with a narrower add, and discard the add-with-constant that is part of the
2588 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002589
Chris Lattnerf29562d2010-12-19 17:59:02 +00002590 // In order to eliminate the add-with-constant, the compare can be its only
2591 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002592 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002593 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002594
Chris Lattnerc56c8452010-12-19 18:22:06 +00002595 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002596 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002597 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002598 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002599
Chris Lattnerc56c8452010-12-19 18:22:06 +00002600 // The width of the new add formed is 1 more than the bias.
2601 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002602
Chris Lattnerc56c8452010-12-19 18:22:06 +00002603 // Check to see that CI1 is an all-ones value with NewWidth bits.
2604 if (CI1->getBitWidth() == NewWidth ||
2605 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002606 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002607
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002608 // This is only really a signed overflow check if the inputs have been
2609 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2610 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2611 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002612 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2613 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002614 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002615
Jim Grosbach129c52a2011-09-30 18:09:53 +00002616 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002617 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2618 // and truncates that discard the high bits of the add. Verify that this is
2619 // the case.
2620 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002621 for (User *U : OrigAdd->users()) {
2622 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002623
Chris Lattnerc56c8452010-12-19 18:22:06 +00002624 // Only accept truncates for now. We would really like a nice recursive
2625 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2626 // chain to see which bits of a value are actually demanded. If the
2627 // original add had another add which was then immediately truncated, we
2628 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002629 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002630 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2631 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002632 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002633
Chris Lattneree61c1d2010-12-19 17:52:50 +00002634 // If the pattern matches, truncate the inputs to the narrower type and
2635 // use the sadd_with_overflow intrinsic to efficiently compute both the
2636 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002637 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002638 Value *F = Intrinsic::getDeclaration(I.getModule(),
2639 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002640
Chris Lattnerce2995a2010-12-19 18:38:44 +00002641 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002642
Chris Lattner79874562010-12-19 18:35:09 +00002643 // Put the new code above the original add, in case there are any uses of the
2644 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002645 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002646
Chris Lattner79874562010-12-19 18:35:09 +00002647 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2648 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002649 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002650 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2651 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002652
Chris Lattneree61c1d2010-12-19 17:52:50 +00002653 // The inner add was the result of the narrow add, zero extended to the
2654 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002655 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002656
Chris Lattner79874562010-12-19 18:35:09 +00002657 // The original icmp gets replaced with the overflow value.
2658 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002659}
Chris Lattner2188e402010-01-04 07:37:31 +00002660
Sanjoy Dasb0984472015-04-08 04:27:22 +00002661bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2662 Value *RHS, Instruction &OrigI,
2663 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002664 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2665 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002666
2667 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2668 Result = OpResult;
2669 Overflow = OverflowVal;
2670 if (ReuseName)
2671 Result->takeName(&OrigI);
2672 return true;
2673 };
2674
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002675 // If the overflow check was an add followed by a compare, the insertion point
2676 // may be pointing to the compare. We want to insert the new instructions
2677 // before the add in case there are uses of the add between the add and the
2678 // compare.
2679 Builder->SetInsertPoint(&OrigI);
2680
Sanjoy Dasb0984472015-04-08 04:27:22 +00002681 switch (OCF) {
2682 case OCF_INVALID:
2683 llvm_unreachable("bad overflow check kind!");
2684
2685 case OCF_UNSIGNED_ADD: {
2686 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2687 if (OR == OverflowResult::NeverOverflows)
2688 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2689 true);
2690
2691 if (OR == OverflowResult::AlwaysOverflows)
2692 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002693
2694 // Fall through uadd into sadd
2695 LLVM_FALLTHROUGH;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002696 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002697 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002698 // X + 0 -> {X, false}
2699 if (match(RHS, m_Zero()))
2700 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002701
2702 // We can strength reduce this signed add into a regular add if we can prove
2703 // that it will never overflow.
2704 if (OCF == OCF_SIGNED_ADD)
2705 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2706 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2707 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002708 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002709 }
2710
2711 case OCF_UNSIGNED_SUB:
2712 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002713 // X - 0 -> {X, false}
2714 if (match(RHS, m_Zero()))
2715 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002716
2717 if (OCF == OCF_SIGNED_SUB) {
2718 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2719 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2720 true);
2721 } else {
2722 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2723 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2724 true);
2725 }
2726 break;
2727 }
2728
2729 case OCF_UNSIGNED_MUL: {
2730 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2731 if (OR == OverflowResult::NeverOverflows)
2732 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2733 true);
2734 if (OR == OverflowResult::AlwaysOverflows)
2735 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002736 LLVM_FALLTHROUGH;
2737 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002738 case OCF_SIGNED_MUL:
2739 // X * undef -> undef
2740 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002741 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002742
David Majnemer27e89ba2015-05-21 23:04:21 +00002743 // X * 0 -> {0, false}
2744 if (match(RHS, m_Zero()))
2745 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002746
David Majnemer27e89ba2015-05-21 23:04:21 +00002747 // X * 1 -> {X, false}
2748 if (match(RHS, m_One()))
2749 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002750
2751 if (OCF == OCF_SIGNED_MUL)
2752 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2753 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2754 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002755 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002756 }
2757
2758 return false;
2759}
2760
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002761/// \brief Recognize and process idiom involving test for multiplication
2762/// overflow.
2763///
2764/// The caller has matched a pattern of the form:
2765/// I = cmp u (mul(zext A, zext B), V
2766/// The function checks if this is a test for overflow and if so replaces
2767/// multiplication with call to 'mul.with.overflow' intrinsic.
2768///
2769/// \param I Compare instruction.
2770/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2771/// the compare instruction. Must be of integer type.
2772/// \param OtherVal The other argument of compare instruction.
2773/// \returns Instruction which must replace the compare instruction, NULL if no
2774/// replacement required.
2775static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2776 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002777 // Don't bother doing this transformation for pointers, don't do it for
2778 // vectors.
2779 if (!isa<IntegerType>(MulVal->getType()))
2780 return nullptr;
2781
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002782 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2783 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002784 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2785 if (!MulInstr)
2786 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002787 assert(MulInstr->getOpcode() == Instruction::Mul);
2788
David Majnemer634ca232014-11-01 23:46:05 +00002789 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2790 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002791 assert(LHS->getOpcode() == Instruction::ZExt);
2792 assert(RHS->getOpcode() == Instruction::ZExt);
2793 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2794
2795 // Calculate type and width of the result produced by mul.with.overflow.
2796 Type *TyA = A->getType(), *TyB = B->getType();
2797 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2798 WidthB = TyB->getPrimitiveSizeInBits();
2799 unsigned MulWidth;
2800 Type *MulType;
2801 if (WidthB > WidthA) {
2802 MulWidth = WidthB;
2803 MulType = TyB;
2804 } else {
2805 MulWidth = WidthA;
2806 MulType = TyA;
2807 }
2808
2809 // In order to replace the original mul with a narrower mul.with.overflow,
2810 // all uses must ignore upper bits of the product. The number of used low
2811 // bits must be not greater than the width of mul.with.overflow.
2812 if (MulVal->hasNUsesOrMore(2))
2813 for (User *U : MulVal->users()) {
2814 if (U == &I)
2815 continue;
2816 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2817 // Check if truncation ignores bits above MulWidth.
2818 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2819 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002820 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002821 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2822 // Check if AND ignores bits above MulWidth.
2823 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002824 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002825 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2826 const APInt &CVal = CI->getValue();
2827 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002828 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002829 }
2830 } else {
2831 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002832 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002833 }
2834 }
2835
2836 // Recognize patterns
2837 switch (I.getPredicate()) {
2838 case ICmpInst::ICMP_EQ:
2839 case ICmpInst::ICMP_NE:
2840 // Recognize pattern:
2841 // mulval = mul(zext A, zext B)
2842 // cmp eq/neq mulval, zext trunc mulval
2843 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2844 if (Zext->hasOneUse()) {
2845 Value *ZextArg = Zext->getOperand(0);
2846 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2847 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2848 break; //Recognized
2849 }
2850
2851 // Recognize pattern:
2852 // mulval = mul(zext A, zext B)
2853 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2854 ConstantInt *CI;
2855 Value *ValToMask;
2856 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2857 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002858 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002859 const APInt &CVal = CI->getValue() + 1;
2860 if (CVal.isPowerOf2()) {
2861 unsigned MaskWidth = CVal.logBase2();
2862 if (MaskWidth == MulWidth)
2863 break; // Recognized
2864 }
2865 }
Craig Topperf40110f2014-04-25 05:29:35 +00002866 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002867
2868 case ICmpInst::ICMP_UGT:
2869 // Recognize pattern:
2870 // mulval = mul(zext A, zext B)
2871 // cmp ugt mulval, max
2872 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2873 APInt MaxVal = APInt::getMaxValue(MulWidth);
2874 MaxVal = MaxVal.zext(CI->getBitWidth());
2875 if (MaxVal.eq(CI->getValue()))
2876 break; // Recognized
2877 }
Craig Topperf40110f2014-04-25 05:29:35 +00002878 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002879
2880 case ICmpInst::ICMP_UGE:
2881 // Recognize pattern:
2882 // mulval = mul(zext A, zext B)
2883 // cmp uge mulval, max+1
2884 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2885 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2886 if (MaxVal.eq(CI->getValue()))
2887 break; // Recognized
2888 }
Craig Topperf40110f2014-04-25 05:29:35 +00002889 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002890
2891 case ICmpInst::ICMP_ULE:
2892 // Recognize pattern:
2893 // mulval = mul(zext A, zext B)
2894 // cmp ule mulval, max
2895 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2896 APInt MaxVal = APInt::getMaxValue(MulWidth);
2897 MaxVal = MaxVal.zext(CI->getBitWidth());
2898 if (MaxVal.eq(CI->getValue()))
2899 break; // Recognized
2900 }
Craig Topperf40110f2014-04-25 05:29:35 +00002901 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002902
2903 case ICmpInst::ICMP_ULT:
2904 // Recognize pattern:
2905 // mulval = mul(zext A, zext B)
2906 // cmp ule mulval, max + 1
2907 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002908 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002909 if (MaxVal.eq(CI->getValue()))
2910 break; // Recognized
2911 }
Craig Topperf40110f2014-04-25 05:29:35 +00002912 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002913
2914 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002915 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002916 }
2917
2918 InstCombiner::BuilderTy *Builder = IC.Builder;
2919 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002920
2921 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2922 Value *MulA = A, *MulB = B;
2923 if (WidthA < MulWidth)
2924 MulA = Builder->CreateZExt(A, MulType);
2925 if (WidthB < MulWidth)
2926 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002927 Value *F = Intrinsic::getDeclaration(I.getModule(),
2928 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002929 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002930 IC.Worklist.Add(MulInstr);
2931
2932 // If there are uses of mul result other than the comparison, we know that
2933 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002934 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002935 if (MulVal->hasNUsesOrMore(2)) {
2936 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2937 for (User *U : MulVal->users()) {
2938 if (U == &I || U == OtherVal)
2939 continue;
2940 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2941 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002942 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002943 else
2944 TI->setOperand(0, Mul);
2945 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2946 assert(BO->getOpcode() == Instruction::And);
2947 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2948 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2949 APInt ShortMask = CI->getValue().trunc(MulWidth);
2950 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2951 Instruction *Zext =
2952 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2953 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002954 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002955 } else {
2956 llvm_unreachable("Unexpected Binary operation");
2957 }
2958 IC.Worklist.Add(cast<Instruction>(U));
2959 }
2960 }
2961 if (isa<Instruction>(OtherVal))
2962 IC.Worklist.Add(cast<Instruction>(OtherVal));
2963
2964 // The original icmp gets replaced with the overflow value, maybe inverted
2965 // depending on predicate.
2966 bool Inverse = false;
2967 switch (I.getPredicate()) {
2968 case ICmpInst::ICMP_NE:
2969 break;
2970 case ICmpInst::ICMP_EQ:
2971 Inverse = true;
2972 break;
2973 case ICmpInst::ICMP_UGT:
2974 case ICmpInst::ICMP_UGE:
2975 if (I.getOperand(0) == MulVal)
2976 break;
2977 Inverse = true;
2978 break;
2979 case ICmpInst::ICMP_ULT:
2980 case ICmpInst::ICMP_ULE:
2981 if (I.getOperand(1) == MulVal)
2982 break;
2983 Inverse = true;
2984 break;
2985 default:
2986 llvm_unreachable("Unexpected predicate");
2987 }
2988 if (Inverse) {
2989 Value *Res = Builder->CreateExtractValue(Call, 1);
2990 return BinaryOperator::CreateNot(Res);
2991 }
2992
2993 return ExtractValueInst::Create(Call, 1);
2994}
2995
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002996/// When performing a comparison against a constant, it is possible that not all
2997/// the bits in the LHS are demanded. This helper method computes the mask that
2998/// IS demanded.
Owen Andersond490c2d2011-01-11 00:36:45 +00002999static APInt DemandedBitsLHSMask(ICmpInst &I,
3000 unsigned BitWidth, bool isSignCheck) {
3001 if (isSignCheck)
3002 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003003
Owen Andersond490c2d2011-01-11 00:36:45 +00003004 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3005 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00003006 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003007
Owen Andersond490c2d2011-01-11 00:36:45 +00003008 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003009 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00003010 // correspond to the trailing ones of the comparand. The value of these
3011 // bits doesn't impact the outcome of the comparison, because any value
3012 // greater than the RHS must differ in a bit higher than these due to carry.
3013 case ICmpInst::ICMP_UGT: {
3014 unsigned trailingOnes = RHS.countTrailingOnes();
3015 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
3016 return ~lowBitsSet;
3017 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003018
Owen Andersond490c2d2011-01-11 00:36:45 +00003019 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
3020 // Any value less than the RHS must differ in a higher bit because of carries.
3021 case ICmpInst::ICMP_ULT: {
3022 unsigned trailingZeros = RHS.countTrailingZeros();
3023 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
3024 return ~lowBitsSet;
3025 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003026
Owen Andersond490c2d2011-01-11 00:36:45 +00003027 default:
3028 return APInt::getAllOnesValue(BitWidth);
3029 }
Owen Andersond490c2d2011-01-11 00:36:45 +00003030}
Chris Lattner2188e402010-01-04 07:37:31 +00003031
Quentin Colombet5ab55552013-09-09 20:56:48 +00003032/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
3033/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00003034/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00003035/// as subtract operands and their positions in those instructions.
3036/// The rational is that several architectures use the same instruction for
3037/// both subtract and cmp, thus it is better if the order of those operands
3038/// match.
3039/// \return true if Op0 and Op1 should be swapped.
3040static bool swapMayExposeCSEOpportunities(const Value * Op0,
3041 const Value * Op1) {
3042 // Filter out pointer value as those cannot appears directly in subtract.
3043 // FIXME: we may want to go through inttoptrs or bitcasts.
3044 if (Op0->getType()->isPointerTy())
3045 return false;
3046 // Count every uses of both Op0 and Op1 in a subtract.
3047 // Each time Op0 is the first operand, count -1: swapping is bad, the
3048 // subtract has already the same layout as the compare.
3049 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00003050 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003051 // At the end, if the benefit is greater than 0, Op0 should come second to
3052 // expose more CSE opportunities.
3053 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003054 for (const User *U : Op0->users()) {
3055 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003056 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
3057 continue;
3058 // If Op0 is the first argument, this is not beneficial to swap the
3059 // arguments.
3060 int LocalSwapBenefits = -1;
3061 unsigned Op1Idx = 1;
3062 if (BinOp->getOperand(Op1Idx) == Op0) {
3063 Op1Idx = 0;
3064 LocalSwapBenefits = 1;
3065 }
3066 if (BinOp->getOperand(Op1Idx) != Op1)
3067 continue;
3068 GlobalSwapBenefits += LocalSwapBenefits;
3069 }
3070 return GlobalSwapBenefits > 0;
3071}
3072
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003073/// \brief Check that one use is in the same block as the definition and all
3074/// other uses are in blocks dominated by a given block
3075///
3076/// \param DI Definition
3077/// \param UI Use
3078/// \param DB Block that must dominate all uses of \p DI outside
3079/// the parent block
3080/// \return true when \p UI is the only use of \p DI in the parent block
3081/// and all other uses of \p DI are in blocks dominated by \p DB.
3082///
3083bool InstCombiner::dominatesAllUses(const Instruction *DI,
3084 const Instruction *UI,
3085 const BasicBlock *DB) const {
3086 assert(DI && UI && "Instruction not defined\n");
3087 // ignore incomplete definitions
3088 if (!DI->getParent())
3089 return false;
3090 // DI and UI must be in the same block
3091 if (DI->getParent() != UI->getParent())
3092 return false;
3093 // Protect from self-referencing blocks
3094 if (DI->getParent() == DB)
3095 return false;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003096 for (const User *U : DI->users()) {
3097 auto *Usr = cast<Instruction>(U);
Justin Bogner99798402016-08-05 01:06:44 +00003098 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003099 return false;
3100 }
3101 return true;
3102}
3103
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003104/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003105static bool isChainSelectCmpBranch(const SelectInst *SI) {
3106 const BasicBlock *BB = SI->getParent();
3107 if (!BB)
3108 return false;
3109 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3110 if (!BI || BI->getNumSuccessors() != 2)
3111 return false;
3112 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3113 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3114 return false;
3115 return true;
3116}
3117
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003118/// \brief True when a select result is replaced by one of its operands
3119/// in select-icmp sequence. This will eventually result in the elimination
3120/// of the select.
3121///
3122/// \param SI Select instruction
3123/// \param Icmp Compare instruction
3124/// \param SIOpd Operand that replaces the select
3125///
3126/// Notes:
3127/// - The replacement is global and requires dominator information
3128/// - The caller is responsible for the actual replacement
3129///
3130/// Example:
3131///
3132/// entry:
3133/// %4 = select i1 %3, %C* %0, %C* null
3134/// %5 = icmp eq %C* %4, null
3135/// br i1 %5, label %9, label %7
3136/// ...
3137/// ; <label>:7 ; preds = %entry
3138/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3139/// ...
3140///
3141/// can be transformed to
3142///
3143/// %5 = icmp eq %C* %0, null
3144/// %6 = select i1 %3, i1 %5, i1 true
3145/// br i1 %6, label %9, label %7
3146/// ...
3147/// ; <label>:7 ; preds = %entry
3148/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3149///
3150/// Similar when the first operand of the select is a constant or/and
3151/// the compare is for not equal rather than equal.
3152///
3153/// NOTE: The function is only called when the select and compare constants
3154/// are equal, the optimization can work only for EQ predicates. This is not a
3155/// major restriction since a NE compare should be 'normalized' to an equal
3156/// compare, which usually happens in the combiner and test case
3157/// select-cmp-br.ll
3158/// checks for it.
3159bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3160 const ICmpInst *Icmp,
3161 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003162 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003163 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3164 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3165 // The check for the unique predecessor is not the best that can be
3166 // done. But it protects efficiently against cases like when SI's
3167 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3168 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3169 // replaced can be reached on either path. So the uniqueness check
3170 // guarantees that the path all uses of SI (outside SI's parent) are on
3171 // is disjoint from all other paths out of SI. But that information
3172 // is more expensive to compute, and the trade-off here is in favor
3173 // of compile-time.
3174 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3175 NumSel++;
3176 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3177 return true;
3178 }
3179 }
3180 return false;
3181}
3182
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003183/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3184/// it into the appropriate icmp lt or icmp gt instruction. This transform
3185/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00003186static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3187 ICmpInst::Predicate Pred = I.getPredicate();
3188 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3189 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3190 return nullptr;
3191
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003192 Value *Op0 = I.getOperand(0);
3193 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003194 auto *Op1C = dyn_cast<Constant>(Op1);
3195 if (!Op1C)
3196 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003197
Sanjay Patele9b2c322016-05-17 00:57:57 +00003198 // Check if the constant operand can be safely incremented/decremented without
3199 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3200 // the edge cases for us, so we just assert on them. For vectors, we must
3201 // handle the edge cases.
3202 Type *Op1Type = Op1->getType();
3203 bool IsSigned = I.isSigned();
3204 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00003205 auto *CI = dyn_cast<ConstantInt>(Op1C);
3206 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00003207 // A <= MAX -> TRUE ; A >= MIN -> TRUE
3208 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3209 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00003210 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00003211 // are for scalar, we could remove the min/max checks. However, to do that,
3212 // we would have to use insertelement/shufflevector to replace edge values.
3213 unsigned NumElts = Op1Type->getVectorNumElements();
3214 for (unsigned i = 0; i != NumElts; ++i) {
3215 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00003216 if (!Elt)
3217 return nullptr;
3218
Sanjay Patele9b2c322016-05-17 00:57:57 +00003219 if (isa<UndefValue>(Elt))
3220 continue;
3221 // Bail out if we can't determine if this constant is min/max or if we
3222 // know that this constant is min/max.
3223 auto *CI = dyn_cast<ConstantInt>(Elt);
3224 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3225 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003226 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00003227 } else {
3228 // ConstantExpr?
3229 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003230 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003231
Sanjay Patele9b2c322016-05-17 00:57:57 +00003232 // Increment or decrement the constant and set the new comparison predicate:
3233 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00003234 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003235 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3236 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3237 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003238}
3239
Chris Lattner2188e402010-01-04 07:37:31 +00003240Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3241 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003242 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003243 unsigned Op0Cplxity = getComplexity(Op0);
3244 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003245
Chris Lattner2188e402010-01-04 07:37:31 +00003246 /// Orders the operands of the compare so that they are listed from most
3247 /// complex to least complex. This puts constants before unary operators,
3248 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003249 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00003250 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003251 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003252 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003253 Changed = true;
3254 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003255
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003256 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00003257 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003258 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003259
Pete Cooperbc5c5242011-12-01 03:58:40 +00003260 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003261 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00003262 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003263 Value *Cond, *SelectTrue, *SelectFalse;
3264 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003265 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003266 if (Value *V = dyn_castNegVal(SelectTrue)) {
3267 if (V == SelectFalse)
3268 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3269 }
3270 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3271 if (V == SelectTrue)
3272 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003273 }
3274 }
3275 }
3276
Chris Lattner229907c2011-07-18 04:54:35 +00003277 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003278
3279 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00003280 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003281 switch (I.getPredicate()) {
3282 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003283 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3284 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003285 return BinaryOperator::CreateNot(Xor);
3286 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003287 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00003288 return BinaryOperator::CreateXor(Op0, Op1);
3289
3290 case ICmpInst::ICMP_UGT:
3291 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003292 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003293 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3294 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003295 return BinaryOperator::CreateAnd(Not, Op1);
3296 }
3297 case ICmpInst::ICMP_SGT:
3298 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003299 LLVM_FALLTHROUGH;
Chris Lattner2188e402010-01-04 07:37:31 +00003300 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003301 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003302 return BinaryOperator::CreateAnd(Not, Op0);
3303 }
3304 case ICmpInst::ICMP_UGE:
3305 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003306 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003307 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3308 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003309 return BinaryOperator::CreateOr(Not, Op1);
3310 }
3311 case ICmpInst::ICMP_SGE:
3312 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003313 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003314 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3315 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003316 return BinaryOperator::CreateOr(Not, Op0);
3317 }
3318 }
3319 }
3320
Sanjay Patele9b2c322016-05-17 00:57:57 +00003321 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003322 return NewICmp;
3323
Chris Lattner2188e402010-01-04 07:37:31 +00003324 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003325 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00003326 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003327 else // Get pointer size.
3328 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003329
Chris Lattner2188e402010-01-04 07:37:31 +00003330 bool isSignBit = false;
3331
3332 // See if we are doing a comparison with a constant.
3333 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003334 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003335
Owen Anderson1294ea72010-12-17 18:08:00 +00003336 // Match the following pattern, which is a common idiom when writing
3337 // overflow-safe integer arithmetic function. The source performs an
3338 // addition in wider type, and explicitly checks for overflow using
3339 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3340 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003341 //
3342 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003343 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003344 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003345 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003346 // sum = a + b
3347 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003348 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003349 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003350 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003351 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003352 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003353 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003354 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003355
Philip Reamesec8a8b52016-03-09 21:05:07 +00003356 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3357 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3358 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3359 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3360 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003361 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003362 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003363 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003364 return new ICmpInst(I.getPredicate(), A, CI);
3365 }
3366 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00003367
Philip Reamesec8a8b52016-03-09 21:05:07 +00003368
David Majnemera0afb552015-01-14 19:26:56 +00003369 // The following transforms are only 'worth it' if the only user of the
3370 // subtraction is the icmp.
3371 if (Op0->hasOneUse()) {
3372 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3373 if (I.isEquality() && CI->isZero() &&
3374 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3375 return new ICmpInst(I.getPredicate(), A, B);
3376
3377 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3378 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3379 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3380 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3381
3382 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3383 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3384 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3385 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3386
3387 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3388 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3389 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3390 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3391
3392 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3393 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3394 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3395 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003396 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003397
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003398 if (I.isEquality()) {
3399 ConstantInt *CI2;
3400 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3401 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003402 // (icmp eq/ne (ashr/lshr const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003403 if (Instruction *Inst = foldICmpCstShrConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003404 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003405 }
David Majnemer59939ac2014-10-19 08:23:08 +00003406 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3407 // (icmp eq/ne (shl const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003408 if (Instruction *Inst = foldICmpCstShlConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003409 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003410 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003411 }
3412
Chris Lattner2188e402010-01-04 07:37:31 +00003413 // If this comparison is a normal comparison, it demands all
3414 // bits, if it is a sign bit comparison, it only demands the sign bit.
3415 bool UnusedBit;
Sanjay Patel79263662016-08-21 15:07:45 +00003416 isSignBit = isSignBitCheck(I.getPredicate(), CI->getValue(), UnusedBit);
Balaram Makam569eaec2016-05-04 21:32:14 +00003417
3418 // Canonicalize icmp instructions based on dominating conditions.
3419 BasicBlock *Parent = I.getParent();
3420 BasicBlock *Dom = Parent->getSinglePredecessor();
3421 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3422 ICmpInst::Predicate Pred;
3423 BasicBlock *TrueBB, *FalseBB;
3424 ConstantInt *CI2;
3425 if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3426 TrueBB, FalseBB)) &&
3427 TrueBB != FalseBB) {
3428 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3429 CI->getValue());
3430 ConstantRange DominatingCR =
3431 (Parent == TrueBB)
3432 ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3433 : ConstantRange::makeExactICmpRegion(
3434 CmpInst::getInversePredicate(Pred), CI2->getValue());
3435 ConstantRange Intersection = DominatingCR.intersectWith(CR);
3436 ConstantRange Difference = DominatingCR.difference(CR);
3437 if (Intersection.isEmptySet())
3438 return replaceInstUsesWith(I, Builder->getFalse());
3439 if (Difference.isEmptySet())
3440 return replaceInstUsesWith(I, Builder->getTrue());
3441 // Canonicalizing a sign bit comparison that gets used in a branch,
3442 // pessimizes codegen by generating branch on zero instruction instead
3443 // of a test and branch. So we avoid canonicalizing in such situations
3444 // because test and branch instruction has better branch displacement
3445 // than compare and branch instruction.
3446 if (!isBranchOnSignBitCheck(I, isSignBit) && !I.isEquality()) {
3447 if (auto *AI = Intersection.getSingleElement())
3448 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3449 if (auto *AD = Difference.getSingleElement())
3450 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3451 }
3452 }
Chris Lattner2188e402010-01-04 07:37:31 +00003453 }
3454
3455 // See if we can fold the comparison based on range information we can get
3456 // by checking whether bits are known to be zero or one in the input.
3457 if (BitWidth != 0) {
3458 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3459 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3460
3461 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00003462 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00003463 Op0KnownZero, Op0KnownOne, 0))
3464 return &I;
3465 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003466 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3467 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00003468 return &I;
3469
3470 // Given the known and unknown bits, compute a range that the LHS could be
3471 // in. Compute the Min, Max and RHS values based on the known bits. For the
3472 // EQ and NE we use unsigned values.
3473 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3474 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3475 if (I.isSigned()) {
3476 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3477 Op0Min, Op0Max);
3478 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3479 Op1Min, Op1Max);
3480 } else {
3481 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3482 Op0Min, Op0Max);
3483 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3484 Op1Min, Op1Max);
3485 }
3486
3487 // If Min and Max are known to be the same, then SimplifyDemandedBits
3488 // figured out that the LHS is a constant. Just constant fold this now so
3489 // that code below can assume that Min != Max.
3490 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3491 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00003492 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003493 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3494 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00003495 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00003496
3497 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00003498 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00003499 switch (I.getPredicate()) {
3500 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00003501 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00003502 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003503 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003504
Chris Lattnerf7e89612010-11-21 06:44:42 +00003505 // If all bits are known zero except for one, then we know at most one
3506 // bit is set. If the comparison is against zero, then this is a check
3507 // to see if *that* bit is set.
3508 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003509 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003510 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003511 Value *LHS = nullptr;
3512 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003513 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3514 LHSC->getValue() != Op0KnownZeroInverted)
3515 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003516
Chris Lattnerf7e89612010-11-21 06:44:42 +00003517 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00003518 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003519 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00003520 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003521 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003522 APInt ValToCheck = Op0KnownZeroInverted;
3523 if (ValToCheck.isPowerOf2()) {
3524 unsigned CmpVal = ValToCheck.countTrailingZeros();
3525 return new ICmpInst(ICmpInst::ICMP_NE, X,
3526 ConstantInt::get(X->getType(), CmpVal));
3527 } else if ((++ValToCheck).isPowerOf2()) {
3528 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3529 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3530 ConstantInt::get(X->getType(), CmpVal));
3531 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003532 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003533
Chris Lattnerf7e89612010-11-21 06:44:42 +00003534 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00003535 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003536 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003537 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003538 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003539 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003540 ConstantInt::get(X->getType(),
3541 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003542 }
Chris Lattner2188e402010-01-04 07:37:31 +00003543 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003544 }
3545 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003546 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003547 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003548
Chris Lattnerf7e89612010-11-21 06:44:42 +00003549 // If all bits are known zero except for one, then we know at most one
3550 // bit is set. If the comparison is against zero, then this is a check
3551 // to see if *that* bit is set.
3552 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003553 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003554 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003555 Value *LHS = nullptr;
3556 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003557 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3558 LHSC->getValue() != Op0KnownZeroInverted)
3559 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003560
Chris Lattnerf7e89612010-11-21 06:44:42 +00003561 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00003562 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003563 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003564 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003565 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003566 APInt ValToCheck = Op0KnownZeroInverted;
3567 if (ValToCheck.isPowerOf2()) {
3568 unsigned CmpVal = ValToCheck.countTrailingZeros();
3569 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3570 ConstantInt::get(X->getType(), CmpVal));
3571 } else if ((++ValToCheck).isPowerOf2()) {
3572 unsigned CmpVal = ValToCheck.countTrailingZeros();
3573 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3574 ConstantInt::get(X->getType(), CmpVal));
3575 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003576 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003577
Chris Lattnerf7e89612010-11-21 06:44:42 +00003578 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00003579 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003580 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003581 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003582 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003583 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003584 ConstantInt::get(X->getType(),
3585 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003586 }
Chris Lattner2188e402010-01-04 07:37:31 +00003587 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003588 }
Chris Lattner2188e402010-01-04 07:37:31 +00003589 case ICmpInst::ICMP_ULT:
3590 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003591 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003592 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003593 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003594 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3595 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3596 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3597 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3598 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003599 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003600
3601 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3602 if (CI->isMinValue(true))
3603 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3604 Constant::getAllOnesValue(Op0->getType()));
3605 }
3606 break;
Sanjay Patel57b12d32016-08-19 15:40:44 +00003607 case ICmpInst::ICMP_UGT: {
Chris Lattner2188e402010-01-04 07:37:31 +00003608 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003609 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Sanjay Patel57b12d32016-08-19 15:40:44 +00003610
Chris Lattner2188e402010-01-04 07:37:31 +00003611 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003612 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003613
3614 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3615 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Sanjay Patel57b12d32016-08-19 15:40:44 +00003616
3617 const APInt *CmpC;
3618 if (match(Op1, m_APInt(CmpC))) {
3619 // A >u C -> A == C+1 if max(a)-1 == C
3620 if (*CmpC == Op0Max - 1)
Chris Lattner2188e402010-01-04 07:37:31 +00003621 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Sanjay Patel57b12d32016-08-19 15:40:44 +00003622 ConstantInt::get(Op1->getType(), *CmpC + 1));
Chris Lattner2188e402010-01-04 07:37:31 +00003623
3624 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
Sanjay Patel57b12d32016-08-19 15:40:44 +00003625 if (CmpC->isMaxSignedValue())
Chris Lattner2188e402010-01-04 07:37:31 +00003626 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3627 Constant::getNullValue(Op0->getType()));
3628 }
3629 break;
Sanjay Patel57b12d32016-08-19 15:40:44 +00003630 }
Chris Lattner2188e402010-01-04 07:37:31 +00003631 case ICmpInst::ICMP_SLT:
3632 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003633 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003634 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003635 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003636 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3637 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3638 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3639 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3640 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003641 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003642 }
3643 break;
3644 case ICmpInst::ICMP_SGT:
3645 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003646 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003647 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003648 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003649
3650 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3651 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3652 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3653 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3654 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003655 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003656 }
3657 break;
3658 case ICmpInst::ICMP_SGE:
3659 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3660 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003661 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003662 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003663 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003664 break;
3665 case ICmpInst::ICMP_SLE:
3666 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3667 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003668 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003669 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003670 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003671 break;
3672 case ICmpInst::ICMP_UGE:
3673 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3674 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003675 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003676 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003677 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003678 break;
3679 case ICmpInst::ICMP_ULE:
3680 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3681 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003682 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003683 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003684 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003685 break;
3686 }
3687
3688 // Turn a signed comparison into an unsigned one if both operands
3689 // are known to have the same sign.
3690 if (I.isSigned() &&
3691 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3692 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3693 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3694 }
3695
3696 // Test if the ICmpInst instruction is used exclusively by a select as
3697 // part of a minimum or maximum operation. If so, refrain from doing
3698 // any other folding. This helps out other analyses which understand
3699 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3700 // and CodeGen. And in this case, at least one of the comparison
3701 // operands has at least one user besides the compare (the select),
3702 // which would often largely negate the benefit of folding anyway.
3703 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003704 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003705 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3706 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003707 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003708
3709 // See if we are doing a comparison between a constant and an instruction that
3710 // can be folded into the comparison.
Sanjay Patel1271bf92016-07-23 13:06:49 +00003711
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00003712 if (Instruction *Res = foldICmpWithConstant(I))
3713 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00003714
Sanjay Patelab50a932016-08-02 22:38:33 +00003715 if (Instruction *Res = foldICmpEqualityWithConstant(I))
3716 return Res;
3717
Sanjay Patel1271bf92016-07-23 13:06:49 +00003718 if (Instruction *Res = foldICmpIntrinsicWithConstant(I))
3719 return Res;
3720
Chris Lattner2188e402010-01-04 07:37:31 +00003721 // Handle icmp with constant (but not simple integer constant) RHS
3722 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3723 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3724 switch (LHSI->getOpcode()) {
3725 case Instruction::GetElementPtr:
3726 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3727 if (RHSC->isNullValue() &&
3728 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3729 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3730 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3731 break;
3732 case Instruction::PHI:
3733 // Only fold icmp into the PHI if the phi and icmp are in the same
3734 // block. If in the same block, we're encouraging jump threading. If
3735 // not, we are just pessimizing the code by making an i1 phi.
3736 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003737 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003738 return NV;
3739 break;
3740 case Instruction::Select: {
3741 // If either operand of the select is a constant, we can fold the
3742 // comparison into the select arms, which will cause one to be
3743 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003744 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003745 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003746 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003747 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003748 CI = dyn_cast<ConstantInt>(Op1);
3749 }
3750 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003751 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003752 CI = dyn_cast<ConstantInt>(Op2);
3753 }
Chris Lattner2188e402010-01-04 07:37:31 +00003754
3755 // We only want to perform this transformation if it will not lead to
3756 // additional code. This is true if either both sides of the select
3757 // fold to a constant (in which case the icmp is replaced with a select
3758 // which will usually simplify) or this is the only user of the
3759 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003760 // select+icmp) or all uses of the select can be replaced based on
3761 // dominance information ("Global cases").
3762 bool Transform = false;
3763 if (Op1 && Op2)
3764 Transform = true;
3765 else if (Op1 || Op2) {
3766 // Local case
3767 if (LHSI->hasOneUse())
3768 Transform = true;
3769 // Global cases
3770 else if (CI && !CI->isZero())
3771 // When Op1 is constant try replacing select with second operand.
3772 // Otherwise Op2 is constant and try replacing select with first
3773 // operand.
3774 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3775 Op1 ? 2 : 1);
3776 }
3777 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003778 if (!Op1)
3779 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3780 RHSC, I.getName());
3781 if (!Op2)
3782 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3783 RHSC, I.getName());
3784 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3785 }
3786 break;
3787 }
Chris Lattner2188e402010-01-04 07:37:31 +00003788 case Instruction::IntToPtr:
3789 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003790 if (RHSC->isNullValue() &&
3791 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003792 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3793 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3794 break;
3795
3796 case Instruction::Load:
3797 // Try to optimize things like "A[i] > 4" to index computations.
3798 if (GetElementPtrInst *GEP =
3799 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3800 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3801 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3802 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00003803 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Chris Lattner2188e402010-01-04 07:37:31 +00003804 return Res;
3805 }
3806 break;
3807 }
3808 }
3809
3810 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3811 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00003812 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00003813 return NI;
3814 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003815 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00003816 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3817 return NI;
3818
Hans Wennborgf1f36512015-10-07 00:20:07 +00003819 // Try to optimize equality comparisons against alloca-based pointers.
3820 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3821 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3822 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003823 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003824 return New;
3825 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003826 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003827 return New;
3828 }
3829
Chris Lattner2188e402010-01-04 07:37:31 +00003830 // Test to see if the operands of the icmp are casted versions of other
3831 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3832 // now.
3833 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003834 if (Op0->getType()->isPointerTy() &&
3835 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003836 // We keep moving the cast from the left operand over to the right
3837 // operand, where it can often be eliminated completely.
3838 Op0 = CI->getOperand(0);
3839
3840 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3841 // so eliminate it as well.
3842 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3843 Op1 = CI2->getOperand(0);
3844
3845 // If Op1 is a constant, we can fold the cast into the constant.
3846 if (Op0->getType() != Op1->getType()) {
3847 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3848 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3849 } else {
3850 // Otherwise, cast the RHS right before the icmp
3851 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3852 }
3853 }
3854 return new ICmpInst(I.getPredicate(), Op0, Op1);
3855 }
3856 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003857
Chris Lattner2188e402010-01-04 07:37:31 +00003858 if (isa<CastInst>(Op0)) {
3859 // Handle the special case of: icmp (cast bool to X), <cst>
3860 // This comes up when you have code like
3861 // int X = A < B;
3862 // if (X) ...
3863 // For generality, we handle any zero-extension of any operand comparison
3864 // with a constant or another cast from the same type.
3865 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003866 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003867 return R;
3868 }
Chris Lattner2188e402010-01-04 07:37:31 +00003869
Duncan Sandse5220012011-02-17 07:46:37 +00003870 // Special logic for binary operators.
3871 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3872 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3873 if (BO0 || BO1) {
3874 CmpInst::Predicate Pred = I.getPredicate();
3875 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3876 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3877 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3878 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3879 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3880 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3881 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3882 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3883 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3884
3885 // Analyze the case when either Op0 or Op1 is an add instruction.
3886 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
Craig Topperf40110f2014-04-25 05:29:35 +00003887 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003888 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3889 A = BO0->getOperand(0);
3890 B = BO0->getOperand(1);
3891 }
3892 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3893 C = BO1->getOperand(0);
3894 D = BO1->getOperand(1);
3895 }
Duncan Sandse5220012011-02-17 07:46:37 +00003896
David Majnemer549f4f22014-11-01 09:09:51 +00003897 // icmp (X+cst) < 0 --> X < -cst
3898 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3899 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3900 if (!RHSC->isMinValue(/*isSigned=*/true))
3901 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3902
Duncan Sandse5220012011-02-17 07:46:37 +00003903 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3904 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3905 return new ICmpInst(Pred, A == Op1 ? B : A,
3906 Constant::getNullValue(Op1->getType()));
3907
3908 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3909 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3910 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3911 C == Op0 ? D : C);
3912
Duncan Sands84653b32011-02-18 16:25:37 +00003913 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003914 if (A && C && (A == C || A == D || B == C || B == D) &&
3915 NoOp0WrapProblem && NoOp1WrapProblem &&
3916 // Try not to increase register pressure.
3917 BO0->hasOneUse() && BO1->hasOneUse()) {
3918 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003919 Value *Y, *Z;
3920 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003921 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003922 Y = B;
3923 Z = D;
3924 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003925 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003926 Y = B;
3927 Z = C;
3928 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003929 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003930 Y = A;
3931 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003932 } else {
3933 assert(B == D);
3934 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003935 Y = A;
3936 Z = C;
3937 }
Duncan Sandse5220012011-02-17 07:46:37 +00003938 return new ICmpInst(Pred, Y, Z);
3939 }
3940
David Majnemerb81cd632013-04-11 20:05:46 +00003941 // icmp slt (X + -1), Y -> icmp sle X, Y
3942 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3943 match(B, m_AllOnes()))
3944 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3945
3946 // icmp sge (X + -1), Y -> icmp sgt X, Y
3947 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3948 match(B, m_AllOnes()))
3949 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3950
3951 // icmp sle (X + 1), Y -> icmp slt X, Y
3952 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3953 match(B, m_One()))
3954 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3955
3956 // icmp sgt (X + 1), Y -> icmp sge X, Y
3957 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3958 match(B, m_One()))
3959 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3960
Michael Liaoc65d3862015-10-19 22:08:14 +00003961 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3962 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3963 match(D, m_AllOnes()))
3964 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3965
3966 // icmp sle X, (Y + -1) -> icmp slt X, Y
3967 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3968 match(D, m_AllOnes()))
3969 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3970
3971 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3972 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3973 match(D, m_One()))
3974 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3975
3976 // icmp slt X, (Y + 1) -> icmp sle X, Y
3977 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3978 match(D, m_One()))
3979 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3980
David Majnemerb81cd632013-04-11 20:05:46 +00003981 // if C1 has greater magnitude than C2:
3982 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3983 // s.t. C3 = C1 - C2
3984 //
3985 // if C2 has greater magnitude than C1:
3986 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3987 // s.t. C3 = C2 - C1
3988 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3989 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3990 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3991 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3992 const APInt &AP1 = C1->getValue();
3993 const APInt &AP2 = C2->getValue();
3994 if (AP1.isNegative() == AP2.isNegative()) {
3995 APInt AP1Abs = C1->getValue().abs();
3996 APInt AP2Abs = C2->getValue().abs();
3997 if (AP1Abs.uge(AP2Abs)) {
3998 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3999 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
4000 return new ICmpInst(Pred, NewAdd, C);
4001 } else {
4002 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
4003 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
4004 return new ICmpInst(Pred, A, NewAdd);
4005 }
4006 }
4007 }
4008
4009
Duncan Sandse5220012011-02-17 07:46:37 +00004010 // Analyze the case when either Op0 or Op1 is a sub instruction.
4011 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
Richard Trieu7a083812016-02-18 22:09:30 +00004012 A = nullptr;
4013 B = nullptr;
4014 C = nullptr;
4015 D = nullptr;
4016 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
4017 A = BO0->getOperand(0);
4018 B = BO0->getOperand(1);
4019 }
4020 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
4021 C = BO1->getOperand(0);
4022 D = BO1->getOperand(1);
4023 }
Duncan Sandse5220012011-02-17 07:46:37 +00004024
Duncan Sands84653b32011-02-18 16:25:37 +00004025 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
4026 if (A == Op1 && NoOp0WrapProblem)
4027 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
4028
4029 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
4030 if (C == Op0 && NoOp1WrapProblem)
4031 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
4032
4033 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00004034 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
4035 // Try not to increase register pressure.
4036 BO0->hasOneUse() && BO1->hasOneUse())
4037 return new ICmpInst(Pred, A, C);
4038
Duncan Sands84653b32011-02-18 16:25:37 +00004039 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
4040 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
4041 // Try not to increase register pressure.
4042 BO0->hasOneUse() && BO1->hasOneUse())
4043 return new ICmpInst(Pred, D, B);
4044
David Majnemer186c9422014-05-15 00:02:20 +00004045 // icmp (0-X) < cst --> x > -cst
4046 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
4047 Value *X;
4048 if (match(BO0, m_Neg(m_Value(X))))
4049 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
4050 if (!RHSC->isMinValue(/*isSigned=*/true))
4051 return new ICmpInst(I.getSwappedPredicate(), X,
4052 ConstantExpr::getNeg(RHSC));
4053 }
4054
Craig Topperf40110f2014-04-25 05:29:35 +00004055 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004056 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00004057 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
4058 Op1 == BO0->getOperand(1))
4059 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004060 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00004061 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4062 Op0 == BO1->getOperand(1))
4063 SRem = BO1;
4064 if (SRem) {
4065 // We don't check hasOneUse to avoid increasing register pressure because
4066 // the value we use is the same value this instruction was already using.
4067 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4068 default: break;
4069 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00004070 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004071 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00004072 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004073 case ICmpInst::ICMP_SGT:
4074 case ICmpInst::ICMP_SGE:
4075 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4076 Constant::getAllOnesValue(SRem->getType()));
4077 case ICmpInst::ICMP_SLT:
4078 case ICmpInst::ICMP_SLE:
4079 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4080 Constant::getNullValue(SRem->getType()));
4081 }
4082 }
4083
Duncan Sandse5220012011-02-17 07:46:37 +00004084 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4085 BO0->hasOneUse() && BO1->hasOneUse() &&
4086 BO0->getOperand(1) == BO1->getOperand(1)) {
4087 switch (BO0->getOpcode()) {
4088 default: break;
4089 case Instruction::Add:
4090 case Instruction::Sub:
4091 case Instruction::Xor:
4092 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4093 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4094 BO1->getOperand(0));
4095 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4096 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4097 if (CI->getValue().isSignBit()) {
4098 ICmpInst::Predicate Pred = I.isSigned()
4099 ? I.getUnsignedPredicate()
4100 : I.getSignedPredicate();
4101 return new ICmpInst(Pred, BO0->getOperand(0),
4102 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00004103 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004104
David Majnemerf8853ae2016-02-01 17:37:56 +00004105 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00004106 ICmpInst::Predicate Pred = I.isSigned()
4107 ? I.getUnsignedPredicate()
4108 : I.getSignedPredicate();
4109 Pred = I.getSwappedPredicate(Pred);
4110 return new ICmpInst(Pred, BO0->getOperand(0),
4111 BO1->getOperand(0));
4112 }
Chris Lattner2188e402010-01-04 07:37:31 +00004113 }
Duncan Sandse5220012011-02-17 07:46:37 +00004114 break;
4115 case Instruction::Mul:
4116 if (!I.isEquality())
4117 break;
4118
4119 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4120 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4121 // Mask = -1 >> count-trailing-zeros(Cst).
4122 if (!CI->isZero() && !CI->isOne()) {
4123 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004124 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00004125 APInt::getLowBitsSet(AP.getBitWidth(),
4126 AP.getBitWidth() -
4127 AP.countTrailingZeros()));
4128 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4129 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4130 return new ICmpInst(I.getPredicate(), And1, And2);
4131 }
4132 }
4133 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004134 case Instruction::UDiv:
4135 case Instruction::LShr:
4136 if (I.isSigned())
4137 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00004138 LLVM_FALLTHROUGH;
Nick Lewycky9719a712011-03-05 05:19:11 +00004139 case Instruction::SDiv:
4140 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004141 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004142 break;
4143 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4144 BO1->getOperand(0));
4145 case Instruction::Shl: {
4146 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4147 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4148 if (!NUW && !NSW)
4149 break;
4150 if (!NSW && I.isSigned())
4151 break;
4152 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4153 BO1->getOperand(0));
4154 }
Chris Lattner2188e402010-01-04 07:37:31 +00004155 }
4156 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004157
4158 if (BO0) {
4159 // Transform A & (L - 1) `ult` L --> L != 0
4160 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4161 auto BitwiseAnd =
4162 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4163
4164 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4165 auto *Zero = Constant::getNullValue(BO0->getType());
4166 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4167 }
4168 }
Chris Lattner2188e402010-01-04 07:37:31 +00004169 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004170
Chris Lattner2188e402010-01-04 07:37:31 +00004171 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004172 // Transform (A & ~B) == 0 --> (A & B) != 0
4173 // and (A & ~B) != 0 --> (A & B) == 0
4174 // if A is a power of 2.
4175 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004176 match(Op1, m_Zero()) &&
Justin Bogner99798402016-08-05 01:06:44 +00004177 isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004178 return new ICmpInst(I.getInversePredicate(),
4179 Builder->CreateAnd(A, B),
4180 Op1);
4181
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004182 // ~x < ~y --> y < x
4183 // ~x < cst --> ~cst < x
4184 if (match(Op0, m_Not(m_Value(A)))) {
4185 if (match(Op1, m_Not(m_Value(B))))
4186 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004187 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004188 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4189 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004190
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004191 Instruction *AddI = nullptr;
4192 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4193 m_Instruction(AddI))) &&
4194 isa<IntegerType>(A->getType())) {
4195 Value *Result;
4196 Constant *Overflow;
4197 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4198 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004199 replaceInstUsesWith(*AddI, Result);
4200 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004201 }
4202 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004203
4204 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4205 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4206 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4207 return R;
4208 }
4209 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4210 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4211 return R;
4212 }
Chris Lattner2188e402010-01-04 07:37:31 +00004213 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004214
Chris Lattner2188e402010-01-04 07:37:31 +00004215 if (I.isEquality()) {
4216 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004217
Chris Lattner2188e402010-01-04 07:37:31 +00004218 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4219 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4220 Value *OtherVal = A == Op1 ? B : A;
4221 return new ICmpInst(I.getPredicate(), OtherVal,
4222 Constant::getNullValue(A->getType()));
4223 }
4224
4225 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4226 // A^c1 == C^c2 --> A == C^(c1^c2)
4227 ConstantInt *C1, *C2;
4228 if (match(B, m_ConstantInt(C1)) &&
4229 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004230 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004231 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004232 return new ICmpInst(I.getPredicate(), A, Xor);
4233 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004234
Chris Lattner2188e402010-01-04 07:37:31 +00004235 // A^B == A^D -> B == D
4236 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4237 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4238 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4239 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4240 }
4241 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004242
Chris Lattner2188e402010-01-04 07:37:31 +00004243 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4244 (A == Op0 || B == Op0)) {
4245 // A == (A^B) -> B == 0
4246 Value *OtherVal = A == Op0 ? B : A;
4247 return new ICmpInst(I.getPredicate(), OtherVal,
4248 Constant::getNullValue(A->getType()));
4249 }
4250
Chris Lattner2188e402010-01-04 07:37:31 +00004251 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004252 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004253 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004254 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004255
Chris Lattner2188e402010-01-04 07:37:31 +00004256 if (A == C) {
4257 X = B; Y = D; Z = A;
4258 } else if (A == D) {
4259 X = B; Y = C; Z = A;
4260 } else if (B == C) {
4261 X = A; Y = D; Z = B;
4262 } else if (B == D) {
4263 X = A; Y = C; Z = B;
4264 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004265
Chris Lattner2188e402010-01-04 07:37:31 +00004266 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004267 Op1 = Builder->CreateXor(X, Y);
4268 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004269 I.setOperand(0, Op1);
4270 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4271 return &I;
4272 }
4273 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004274
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004275 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004276 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004277 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004278 if ((Op0->hasOneUse() &&
4279 match(Op0, m_ZExt(m_Value(A))) &&
4280 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4281 (Op1->hasOneUse() &&
4282 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4283 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004284 APInt Pow2 = Cst1->getValue() + 1;
4285 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4286 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4287 return new ICmpInst(I.getPredicate(), A,
4288 Builder->CreateTrunc(B, A->getType()));
4289 }
4290
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004291 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4292 // For lshr and ashr pairs.
4293 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4294 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4295 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4296 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4297 unsigned TypeBits = Cst1->getBitWidth();
4298 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4299 if (ShAmt < TypeBits && ShAmt != 0) {
4300 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4301 ? ICmpInst::ICMP_UGE
4302 : ICmpInst::ICMP_ULT;
4303 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4304 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4305 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4306 }
4307 }
4308
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004309 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4310 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4311 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4312 unsigned TypeBits = Cst1->getBitWidth();
4313 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4314 if (ShAmt < TypeBits && ShAmt != 0) {
4315 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4316 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4317 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4318 I.getName() + ".mask");
4319 return new ICmpInst(I.getPredicate(), And,
4320 Constant::getNullValue(Cst1->getType()));
4321 }
4322 }
4323
Chris Lattner1b06c712011-04-26 20:18:20 +00004324 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4325 // "icmp (and X, mask), cst"
4326 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004327 if (Op0->hasOneUse() &&
4328 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4329 m_ConstantInt(ShAmt))))) &&
4330 match(Op1, m_ConstantInt(Cst1)) &&
4331 // Only do this when A has multiple uses. This is most important to do
4332 // when it exposes other optimizations.
4333 !A->hasOneUse()) {
4334 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004335
Chris Lattner1b06c712011-04-26 20:18:20 +00004336 if (ShAmt < ASize) {
4337 APInt MaskV =
4338 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4339 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004340
Chris Lattner1b06c712011-04-26 20:18:20 +00004341 APInt CmpV = Cst1->getValue().zext(ASize);
4342 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004343
Chris Lattner1b06c712011-04-26 20:18:20 +00004344 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4345 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4346 }
4347 }
Chris Lattner2188e402010-01-04 07:37:31 +00004348 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004349
David Majnemerc1eca5a2014-11-06 23:23:30 +00004350 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4351 // an i1 which indicates whether or not we successfully did the swap.
4352 //
4353 // Replace comparisons between the old value and the expected value with the
4354 // indicator that 'cmpxchg' returns.
4355 //
4356 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4357 // spuriously fail. In those cases, the old value may equal the expected
4358 // value but it is possible for the swap to not occur.
4359 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4360 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4361 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4362 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4363 !ACXI->isWeak())
4364 return ExtractValueInst::Create(ACXI, 1);
4365
Chris Lattner2188e402010-01-04 07:37:31 +00004366 {
4367 Value *X; ConstantInt *Cst;
4368 // icmp X+Cst, X
4369 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004370 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004371
4372 // icmp X, X+Cst
4373 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004374 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004375 }
Craig Topperf40110f2014-04-25 05:29:35 +00004376 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004377}
4378
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004379/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004380Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004381 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004382 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004383 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004384
Chris Lattner2188e402010-01-04 07:37:31 +00004385 // Get the width of the mantissa. We don't want to hack on conversions that
4386 // might lose information from the integer, e.g. "i64 -> float"
4387 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004388 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004389
Matt Arsenault55e73122015-01-06 15:50:59 +00004390 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4391
Chris Lattner2188e402010-01-04 07:37:31 +00004392 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004393
Matt Arsenault55e73122015-01-06 15:50:59 +00004394 if (I.isEquality()) {
4395 FCmpInst::Predicate P = I.getPredicate();
4396 bool IsExact = false;
4397 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4398 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4399
4400 // If the floating point constant isn't an integer value, we know if we will
4401 // ever compare equal / not equal to it.
4402 if (!IsExact) {
4403 // TODO: Can never be -0.0 and other non-representable values
4404 APFloat RHSRoundInt(RHS);
4405 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4406 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4407 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004408 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004409
4410 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004411 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004412 }
4413 }
4414
4415 // TODO: If the constant is exactly representable, is it always OK to do
4416 // equality compares as integer?
4417 }
4418
Arch D. Robison8ed08542015-09-15 17:51:59 +00004419 // Check to see that the input is converted from an integer type that is small
4420 // enough that preserves all bits. TODO: check here for "known" sign bits.
4421 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4422 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004423
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004424 // Following test does NOT adjust InputSize downwards for signed inputs,
4425 // because the most negative value still requires all the mantissa bits
Arch D. Robison8ed08542015-09-15 17:51:59 +00004426 // to distinguish it from one less than that value.
4427 if ((int)InputSize > MantissaWidth) {
4428 // Conversion would lose accuracy. Check if loss can impact comparison.
4429 int Exp = ilogb(RHS);
4430 if (Exp == APFloat::IEK_Inf) {
4431 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004432 if (MaxExponent < (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004433 // Conversion could create infinity.
4434 return nullptr;
4435 } else {
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004436 // Note that if RHS is zero or NaN, then Exp is negative
Arch D. Robison8ed08542015-09-15 17:51:59 +00004437 // and first condition is trivially false.
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004438 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004439 // Conversion could affect comparison.
4440 return nullptr;
4441 }
4442 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004443
Chris Lattner2188e402010-01-04 07:37:31 +00004444 // Otherwise, we can potentially simplify the comparison. We know that it
4445 // will always come through as an integer value and we know the constant is
4446 // not a NAN (it would have been previously simplified).
4447 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004448
Chris Lattner2188e402010-01-04 07:37:31 +00004449 ICmpInst::Predicate Pred;
4450 switch (I.getPredicate()) {
4451 default: llvm_unreachable("Unexpected predicate!");
4452 case FCmpInst::FCMP_UEQ:
4453 case FCmpInst::FCMP_OEQ:
4454 Pred = ICmpInst::ICMP_EQ;
4455 break;
4456 case FCmpInst::FCMP_UGT:
4457 case FCmpInst::FCMP_OGT:
4458 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4459 break;
4460 case FCmpInst::FCMP_UGE:
4461 case FCmpInst::FCMP_OGE:
4462 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4463 break;
4464 case FCmpInst::FCMP_ULT:
4465 case FCmpInst::FCMP_OLT:
4466 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4467 break;
4468 case FCmpInst::FCMP_ULE:
4469 case FCmpInst::FCMP_OLE:
4470 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4471 break;
4472 case FCmpInst::FCMP_UNE:
4473 case FCmpInst::FCMP_ONE:
4474 Pred = ICmpInst::ICMP_NE;
4475 break;
4476 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004477 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004478 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004479 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004480 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004481
Chris Lattner2188e402010-01-04 07:37:31 +00004482 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004483
Chris Lattner2188e402010-01-04 07:37:31 +00004484 // See if the FP constant is too large for the integer. For example,
4485 // comparing an i8 to 300.0.
4486 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004487
Chris Lattner2188e402010-01-04 07:37:31 +00004488 if (!LHSUnsigned) {
4489 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4490 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004491 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004492 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4493 APFloat::rmNearestTiesToEven);
4494 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4495 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4496 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004497 return replaceInstUsesWith(I, Builder->getTrue());
4498 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004499 }
4500 } else {
4501 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4502 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004503 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004504 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4505 APFloat::rmNearestTiesToEven);
4506 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4507 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4508 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004509 return replaceInstUsesWith(I, Builder->getTrue());
4510 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004511 }
4512 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004513
Chris Lattner2188e402010-01-04 07:37:31 +00004514 if (!LHSUnsigned) {
4515 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004516 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004517 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4518 APFloat::rmNearestTiesToEven);
4519 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4520 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4521 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004522 return replaceInstUsesWith(I, Builder->getTrue());
4523 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004524 }
Devang Patel698452b2012-02-13 23:05:18 +00004525 } else {
4526 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004527 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004528 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4529 APFloat::rmNearestTiesToEven);
4530 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4531 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4532 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004533 return replaceInstUsesWith(I, Builder->getTrue());
4534 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004535 }
Chris Lattner2188e402010-01-04 07:37:31 +00004536 }
4537
4538 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4539 // [0, UMAX], but it may still be fractional. See if it is fractional by
4540 // casting the FP value to the integer value and back, checking for equality.
4541 // Don't do this for zero, because -0.0 is not fractional.
4542 Constant *RHSInt = LHSUnsigned
4543 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4544 : ConstantExpr::getFPToSI(RHSC, IntTy);
4545 if (!RHS.isZero()) {
4546 bool Equal = LHSUnsigned
4547 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4548 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4549 if (!Equal) {
4550 // If we had a comparison against a fractional value, we have to adjust
4551 // the compare predicate and sometimes the value. RHSC is rounded towards
4552 // zero at this point.
4553 switch (Pred) {
4554 default: llvm_unreachable("Unexpected integer comparison!");
4555 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004556 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004557 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004558 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004559 case ICmpInst::ICMP_ULE:
4560 // (float)int <= 4.4 --> int <= 4
4561 // (float)int <= -4.4 --> false
4562 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004563 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004564 break;
4565 case ICmpInst::ICMP_SLE:
4566 // (float)int <= 4.4 --> int <= 4
4567 // (float)int <= -4.4 --> int < -4
4568 if (RHS.isNegative())
4569 Pred = ICmpInst::ICMP_SLT;
4570 break;
4571 case ICmpInst::ICMP_ULT:
4572 // (float)int < -4.4 --> false
4573 // (float)int < 4.4 --> int <= 4
4574 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004575 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004576 Pred = ICmpInst::ICMP_ULE;
4577 break;
4578 case ICmpInst::ICMP_SLT:
4579 // (float)int < -4.4 --> int < -4
4580 // (float)int < 4.4 --> int <= 4
4581 if (!RHS.isNegative())
4582 Pred = ICmpInst::ICMP_SLE;
4583 break;
4584 case ICmpInst::ICMP_UGT:
4585 // (float)int > 4.4 --> int > 4
4586 // (float)int > -4.4 --> true
4587 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004588 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004589 break;
4590 case ICmpInst::ICMP_SGT:
4591 // (float)int > 4.4 --> int > 4
4592 // (float)int > -4.4 --> int >= -4
4593 if (RHS.isNegative())
4594 Pred = ICmpInst::ICMP_SGE;
4595 break;
4596 case ICmpInst::ICMP_UGE:
4597 // (float)int >= -4.4 --> true
4598 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004599 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004600 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004601 Pred = ICmpInst::ICMP_UGT;
4602 break;
4603 case ICmpInst::ICMP_SGE:
4604 // (float)int >= -4.4 --> int >= -4
4605 // (float)int >= 4.4 --> int > 4
4606 if (!RHS.isNegative())
4607 Pred = ICmpInst::ICMP_SGT;
4608 break;
4609 }
4610 }
4611 }
4612
4613 // Lower this FP comparison into an appropriate integer version of the
4614 // comparison.
4615 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4616}
4617
4618Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4619 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004620
Chris Lattner2188e402010-01-04 07:37:31 +00004621 /// Orders the operands of the compare so that they are listed from most
4622 /// complex to least complex. This puts constants before unary operators,
4623 /// before binary operators.
4624 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4625 I.swapOperands();
4626 Changed = true;
4627 }
4628
4629 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004630
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004631 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
Justin Bogner99798402016-08-05 01:06:44 +00004632 I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004633 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004634
4635 // Simplify 'fcmp pred X, X'
4636 if (Op0 == Op1) {
4637 switch (I.getPredicate()) {
4638 default: llvm_unreachable("Unknown predicate!");
4639 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4640 case FCmpInst::FCMP_ULT: // True if unordered or less than
4641 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4642 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4643 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4644 I.setPredicate(FCmpInst::FCMP_UNO);
4645 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4646 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004647
Chris Lattner2188e402010-01-04 07:37:31 +00004648 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4649 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4650 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4651 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4652 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4653 I.setPredicate(FCmpInst::FCMP_ORD);
4654 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4655 return &I;
4656 }
4657 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004658
James Molloy2b21a7c2015-05-20 18:41:25 +00004659 // Test if the FCmpInst instruction is used exclusively by a select as
4660 // part of a minimum or maximum operation. If so, refrain from doing
4661 // any other folding. This helps out other analyses which understand
4662 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4663 // and CodeGen. And in this case, at least one of the comparison
4664 // operands has at least one user besides the compare (the select),
4665 // which would often largely negate the benefit of folding anyway.
4666 if (I.hasOneUse())
4667 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4668 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4669 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4670 return nullptr;
4671
Chris Lattner2188e402010-01-04 07:37:31 +00004672 // Handle fcmp with constant RHS
4673 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4674 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4675 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004676 case Instruction::FPExt: {
4677 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4678 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4679 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4680 if (!RHSF)
4681 break;
4682
4683 const fltSemantics *Sem;
4684 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004685 if (LHSExt->getSrcTy()->isHalfTy())
4686 Sem = &APFloat::IEEEhalf;
4687 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004688 Sem = &APFloat::IEEEsingle;
4689 else if (LHSExt->getSrcTy()->isDoubleTy())
4690 Sem = &APFloat::IEEEdouble;
4691 else if (LHSExt->getSrcTy()->isFP128Ty())
4692 Sem = &APFloat::IEEEquad;
4693 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4694 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004695 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4696 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004697 else
4698 break;
4699
4700 bool Lossy;
4701 APFloat F = RHSF->getValueAPF();
4702 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4703
Jim Grosbach24ff8342011-09-30 18:45:50 +00004704 // Avoid lossy conversions and denormals. Zero is a special case
4705 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004706 APFloat Fabs = F;
4707 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004708 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004709 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4710 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004711
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004712 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4713 ConstantFP::get(RHSC->getContext(), F));
4714 break;
4715 }
Chris Lattner2188e402010-01-04 07:37:31 +00004716 case Instruction::PHI:
4717 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4718 // block. If in the same block, we're encouraging jump threading. If
4719 // not, we are just pessimizing the code by making an i1 phi.
4720 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004721 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004722 return NV;
4723 break;
4724 case Instruction::SIToFP:
4725 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004726 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004727 return NV;
4728 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004729 case Instruction::FSub: {
4730 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4731 Value *Op;
4732 if (match(LHSI, m_FNeg(m_Value(Op))))
4733 return new FCmpInst(I.getSwappedPredicate(), Op,
4734 ConstantExpr::getFNeg(RHSC));
4735 break;
4736 }
Dan Gohman94732022010-02-24 06:46:09 +00004737 case Instruction::Load:
4738 if (GetElementPtrInst *GEP =
4739 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4740 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4741 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4742 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004743 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004744 return Res;
4745 }
4746 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004747 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004748 if (!RHSC->isNullValue())
4749 break;
4750
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004751 CallInst *CI = cast<CallInst>(LHSI);
Justin Bogner99798402016-08-05 01:06:44 +00004752 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004753 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004754 break;
4755
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004756 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004757 switch (I.getPredicate()) {
4758 default:
4759 break;
4760 // fabs(x) < 0 --> false
4761 case FCmpInst::FCMP_OLT:
4762 llvm_unreachable("handled by SimplifyFCmpInst");
4763 // fabs(x) > 0 --> x != 0
4764 case FCmpInst::FCMP_OGT:
4765 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4766 // fabs(x) <= 0 --> x == 0
4767 case FCmpInst::FCMP_OLE:
4768 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4769 // fabs(x) >= 0 --> !isnan(x)
4770 case FCmpInst::FCMP_OGE:
4771 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4772 // fabs(x) == 0 --> x == 0
4773 // fabs(x) != 0 --> x != 0
4774 case FCmpInst::FCMP_OEQ:
4775 case FCmpInst::FCMP_UEQ:
4776 case FCmpInst::FCMP_ONE:
4777 case FCmpInst::FCMP_UNE:
4778 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004779 }
4780 }
Chris Lattner2188e402010-01-04 07:37:31 +00004781 }
Chris Lattner2188e402010-01-04 07:37:31 +00004782 }
4783
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004784 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004785 Value *X, *Y;
4786 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004787 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004788
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004789 // fcmp (fpext x), (fpext y) -> fcmp x, y
4790 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4791 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4792 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4793 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4794 RHSExt->getOperand(0));
4795
Craig Topperf40110f2014-04-25 05:29:35 +00004796 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004797}