Bug Summary

File:lib/Transforms/InstCombine/InstCombineCompares.cpp
Warning:line 5321, column 42
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name InstCombineCompares.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/lib/Transforms/InstCombine -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp

/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp

1//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visitICmp and visitFCmp functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/ConstantFolding.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/TargetLibraryInfo.h"
20#include "llvm/IR/ConstantRange.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/GetElementPtrTypeIterator.h"
23#include "llvm/IR/IntrinsicInst.h"
24#include "llvm/IR/PatternMatch.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/KnownBits.h"
27
28using namespace llvm;
29using namespace PatternMatch;
30
31#define DEBUG_TYPE"instcombine" "instcombine"
32
33// How many times is a select replaced by one of its operands?
34STATISTIC(NumSel, "Number of select opts")static llvm::Statistic NumSel = {"instcombine", "NumSel", "Number of select opts"
}
;
35
36
37/// Compute Result = In1+In2, returning true if the result overflowed for this
38/// type.
39static bool addWithOverflow(APInt &Result, const APInt &In1,
40 const APInt &In2, bool IsSigned = false) {
41 bool Overflow;
42 if (IsSigned)
43 Result = In1.sadd_ov(In2, Overflow);
44 else
45 Result = In1.uadd_ov(In2, Overflow);
46
47 return Overflow;
48}
49
50/// Compute Result = In1-In2, returning true if the result overflowed for this
51/// type.
52static bool subWithOverflow(APInt &Result, const APInt &In1,
53 const APInt &In2, bool IsSigned = false) {
54 bool Overflow;
55 if (IsSigned)
56 Result = In1.ssub_ov(In2, Overflow);
57 else
58 Result = In1.usub_ov(In2, Overflow);
59
60 return Overflow;
61}
62
63/// Given an icmp instruction, return true if any use of this comparison is a
64/// branch on sign bit comparison.
65static bool hasBranchUse(ICmpInst &I) {
66 for (auto *U : I.users())
67 if (isa<BranchInst>(U))
68 return true;
69 return false;
70}
71
72/// Returns true if the exploded icmp can be expressed as a signed comparison
73/// to zero and updates the predicate accordingly.
74/// The signedness of the comparison is preserved.
75/// TODO: Refactor with decomposeBitTestICmp()?
76static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
77 if (!ICmpInst::isSigned(Pred))
78 return false;
79
80 if (C.isNullValue())
81 return ICmpInst::isRelational(Pred);
82
83 if (C.isOneValue()) {
84 if (Pred == ICmpInst::ICMP_SLT) {
85 Pred = ICmpInst::ICMP_SLE;
86 return true;
87 }
88 } else if (C.isAllOnesValue()) {
89 if (Pred == ICmpInst::ICMP_SGT) {
90 Pred = ICmpInst::ICMP_SGE;
91 return true;
92 }
93 }
94
95 return false;
96}
97
98/// Given a signed integer type and a set of known zero and one bits, compute
99/// the maximum and minimum values that could have the specified known zero and
100/// known one bits, returning them in Min/Max.
101/// TODO: Move to method on KnownBits struct?
102static void computeSignedMinMaxValuesFromKnownBits(const KnownBits &Known,
103 APInt &Min, APInt &Max) {
104 assert(Known.getBitWidth() == Min.getBitWidth() &&((Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth
() == Max.getBitWidth() && "KnownZero, KnownOne and Min, Max must have equal bitwidth."
) ? static_cast<void> (0) : __assert_fail ("Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth() == Max.getBitWidth() && \"KnownZero, KnownOne and Min, Max must have equal bitwidth.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 106, __PRETTY_FUNCTION__))
105 Known.getBitWidth() == Max.getBitWidth() &&((Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth
() == Max.getBitWidth() && "KnownZero, KnownOne and Min, Max must have equal bitwidth."
) ? static_cast<void> (0) : __assert_fail ("Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth() == Max.getBitWidth() && \"KnownZero, KnownOne and Min, Max must have equal bitwidth.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 106, __PRETTY_FUNCTION__))
106 "KnownZero, KnownOne and Min, Max must have equal bitwidth.")((Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth
() == Max.getBitWidth() && "KnownZero, KnownOne and Min, Max must have equal bitwidth."
) ? static_cast<void> (0) : __assert_fail ("Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth() == Max.getBitWidth() && \"KnownZero, KnownOne and Min, Max must have equal bitwidth.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 106, __PRETTY_FUNCTION__))
;
107 APInt UnknownBits = ~(Known.Zero|Known.One);
108
109 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
110 // bit if it is unknown.
111 Min = Known.One;
112 Max = Known.One|UnknownBits;
113
114 if (UnknownBits.isNegative()) { // Sign bit is unknown
115 Min.setSignBit();
116 Max.clearSignBit();
117 }
118}
119
120/// Given an unsigned integer type and a set of known zero and one bits, compute
121/// the maximum and minimum values that could have the specified known zero and
122/// known one bits, returning them in Min/Max.
123/// TODO: Move to method on KnownBits struct?
124static void computeUnsignedMinMaxValuesFromKnownBits(const KnownBits &Known,
125 APInt &Min, APInt &Max) {
126 assert(Known.getBitWidth() == Min.getBitWidth() &&((Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth
() == Max.getBitWidth() && "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."
) ? static_cast<void> (0) : __assert_fail ("Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth() == Max.getBitWidth() && \"Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 128, __PRETTY_FUNCTION__))
127 Known.getBitWidth() == Max.getBitWidth() &&((Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth
() == Max.getBitWidth() && "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."
) ? static_cast<void> (0) : __assert_fail ("Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth() == Max.getBitWidth() && \"Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 128, __PRETTY_FUNCTION__))
128 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.")((Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth
() == Max.getBitWidth() && "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."
) ? static_cast<void> (0) : __assert_fail ("Known.getBitWidth() == Min.getBitWidth() && Known.getBitWidth() == Max.getBitWidth() && \"Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 128, __PRETTY_FUNCTION__))
;
129 APInt UnknownBits = ~(Known.Zero|Known.One);
130
131 // The minimum value is when the unknown bits are all zeros.
132 Min = Known.One;
133 // The maximum value is when the unknown bits are all ones.
134 Max = Known.One|UnknownBits;
135}
136
137/// This is called when we see this pattern:
138/// cmp pred (load (gep GV, ...)), cmpcst
139/// where GV is a global variable with a constant initializer. Try to simplify
140/// this into some simple computation that does not need the load. For example
141/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
142///
143/// If AndCst is non-null, then the loaded value is masked with that constant
144/// before doing the comparison. This handles cases like "A[i]&4 == 0".
145Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
146 GlobalVariable *GV,
147 CmpInst &ICI,
148 ConstantInt *AndCst) {
149 Constant *Init = GV->getInitializer();
150 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
151 return nullptr;
152
153 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
154 // Don't blow up on huge arrays.
155 if (ArrayElementCount > MaxArraySizeForCombine)
156 return nullptr;
157
158 // There are many forms of this optimization we can handle, for now, just do
159 // the simple index into a single-dimensional array.
160 //
161 // Require: GEP GV, 0, i {{, constant indices}}
162 if (GEP->getNumOperands() < 3 ||
163 !isa<ConstantInt>(GEP->getOperand(1)) ||
164 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
165 isa<Constant>(GEP->getOperand(2)))
166 return nullptr;
167
168 // Check that indices after the variable are constants and in-range for the
169 // type they index. Collect the indices. This is typically for arrays of
170 // structs.
171 SmallVector<unsigned, 4> LaterIndices;
172
173 Type *EltTy = Init->getType()->getArrayElementType();
174 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
175 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
176 if (!Idx) return nullptr; // Variable index.
177
178 uint64_t IdxVal = Idx->getZExtValue();
179 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
180
181 if (StructType *STy = dyn_cast<StructType>(EltTy))
182 EltTy = STy->getElementType(IdxVal);
183 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
184 if (IdxVal >= ATy->getNumElements()) return nullptr;
185 EltTy = ATy->getElementType();
186 } else {
187 return nullptr; // Unknown type.
188 }
189
190 LaterIndices.push_back(IdxVal);
191 }
192
193 enum { Overdefined = -3, Undefined = -2 };
194
195 // Variables for our state machines.
196
197 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
198 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
199 // and 87 is the second (and last) index. FirstTrueElement is -2 when
200 // undefined, otherwise set to the first true element. SecondTrueElement is
201 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
202 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
203
204 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
205 // form "i != 47 & i != 87". Same state transitions as for true elements.
206 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
207
208 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
209 /// define a state machine that triggers for ranges of values that the index
210 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
211 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
212 /// index in the range (inclusive). We use -2 for undefined here because we
213 /// use relative comparisons and don't want 0-1 to match -1.
214 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
215
216 // MagicBitvector - This is a magic bitvector where we set a bit if the
217 // comparison is true for element 'i'. If there are 64 elements or less in
218 // the array, this will fully represent all the comparison results.
219 uint64_t MagicBitvector = 0;
220
221 // Scan the array and see if one of our patterns matches.
222 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
223 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
224 Constant *Elt = Init->getAggregateElement(i);
225 if (!Elt) return nullptr;
226
227 // If this is indexing an array of structures, get the structure element.
228 if (!LaterIndices.empty())
229 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
230
231 // If the element is masked, handle it.
232 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
233
234 // Find out if the comparison would be true or false for the i'th element.
235 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
236 CompareRHS, DL, &TLI);
237 // If the result is undef for this element, ignore it.
238 if (isa<UndefValue>(C)) {
239 // Extend range state machines to cover this element in case there is an
240 // undef in the middle of the range.
241 if (TrueRangeEnd == (int)i-1)
242 TrueRangeEnd = i;
243 if (FalseRangeEnd == (int)i-1)
244 FalseRangeEnd = i;
245 continue;
246 }
247
248 // If we can't compute the result for any of the elements, we have to give
249 // up evaluating the entire conditional.
250 if (!isa<ConstantInt>(C)) return nullptr;
251
252 // Otherwise, we know if the comparison is true or false for this element,
253 // update our state machines.
254 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
255
256 // State machine for single/double/range index comparison.
257 if (IsTrueForElt) {
258 // Update the TrueElement state machine.
259 if (FirstTrueElement == Undefined)
260 FirstTrueElement = TrueRangeEnd = i; // First true element.
261 else {
262 // Update double-compare state machine.
263 if (SecondTrueElement == Undefined)
264 SecondTrueElement = i;
265 else
266 SecondTrueElement = Overdefined;
267
268 // Update range state machine.
269 if (TrueRangeEnd == (int)i-1)
270 TrueRangeEnd = i;
271 else
272 TrueRangeEnd = Overdefined;
273 }
274 } else {
275 // Update the FalseElement state machine.
276 if (FirstFalseElement == Undefined)
277 FirstFalseElement = FalseRangeEnd = i; // First false element.
278 else {
279 // Update double-compare state machine.
280 if (SecondFalseElement == Undefined)
281 SecondFalseElement = i;
282 else
283 SecondFalseElement = Overdefined;
284
285 // Update range state machine.
286 if (FalseRangeEnd == (int)i-1)
287 FalseRangeEnd = i;
288 else
289 FalseRangeEnd = Overdefined;
290 }
291 }
292
293 // If this element is in range, update our magic bitvector.
294 if (i < 64 && IsTrueForElt)
295 MagicBitvector |= 1ULL << i;
296
297 // If all of our states become overdefined, bail out early. Since the
298 // predicate is expensive, only check it every 8 elements. This is only
299 // really useful for really huge arrays.
300 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
301 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
302 FalseRangeEnd == Overdefined)
303 return nullptr;
304 }
305
306 // Now that we've scanned the entire array, emit our new comparison(s). We
307 // order the state machines in complexity of the generated code.
308 Value *Idx = GEP->getOperand(2);
309
310 // If the index is larger than the pointer size of the target, truncate the
311 // index down like the GEP would do implicitly. We don't have to do this for
312 // an inbounds GEP because the index can't be out of range.
313 if (!GEP->isInBounds()) {
314 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
315 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
316 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
317 Idx = Builder.CreateTrunc(Idx, IntPtrTy);
318 }
319
320 // If the comparison is only true for one or two elements, emit direct
321 // comparisons.
322 if (SecondTrueElement != Overdefined) {
323 // None true -> false.
324 if (FirstTrueElement == Undefined)
325 return replaceInstUsesWith(ICI, Builder.getFalse());
326
327 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
328
329 // True for one element -> 'i == 47'.
330 if (SecondTrueElement == Undefined)
331 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
332
333 // True for two elements -> 'i == 47 | i == 72'.
334 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
335 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
336 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
337 return BinaryOperator::CreateOr(C1, C2);
338 }
339
340 // If the comparison is only false for one or two elements, emit direct
341 // comparisons.
342 if (SecondFalseElement != Overdefined) {
343 // None false -> true.
344 if (FirstFalseElement == Undefined)
345 return replaceInstUsesWith(ICI, Builder.getTrue());
346
347 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
348
349 // False for one element -> 'i != 47'.
350 if (SecondFalseElement == Undefined)
351 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
352
353 // False for two elements -> 'i != 47 & i != 72'.
354 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
355 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
356 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
357 return BinaryOperator::CreateAnd(C1, C2);
358 }
359
360 // If the comparison can be replaced with a range comparison for the elements
361 // where it is true, emit the range check.
362 if (TrueRangeEnd != Overdefined) {
363 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare")((TrueRangeEnd != FirstTrueElement && "Should emit single compare"
) ? static_cast<void> (0) : __assert_fail ("TrueRangeEnd != FirstTrueElement && \"Should emit single compare\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 363, __PRETTY_FUNCTION__))
;
364
365 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
366 if (FirstTrueElement) {
367 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
368 Idx = Builder.CreateAdd(Idx, Offs);
369 }
370
371 Value *End = ConstantInt::get(Idx->getType(),
372 TrueRangeEnd-FirstTrueElement+1);
373 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
374 }
375
376 // False range check.
377 if (FalseRangeEnd != Overdefined) {
378 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare")((FalseRangeEnd != FirstFalseElement && "Should emit single compare"
) ? static_cast<void> (0) : __assert_fail ("FalseRangeEnd != FirstFalseElement && \"Should emit single compare\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 378, __PRETTY_FUNCTION__))
;
379 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
380 if (FirstFalseElement) {
381 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
382 Idx = Builder.CreateAdd(Idx, Offs);
383 }
384
385 Value *End = ConstantInt::get(Idx->getType(),
386 FalseRangeEnd-FirstFalseElement);
387 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
388 }
389
390 // If a magic bitvector captures the entire comparison state
391 // of this load, replace it with computation that does:
392 // ((magic_cst >> i) & 1) != 0
393 {
394 Type *Ty = nullptr;
395
396 // Look for an appropriate type:
397 // - The type of Idx if the magic fits
398 // - The smallest fitting legal type
399 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
400 Ty = Idx->getType();
401 else
402 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
403
404 if (Ty) {
405 Value *V = Builder.CreateIntCast(Idx, Ty, false);
406 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
407 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
408 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
409 }
410 }
411
412 return nullptr;
413}
414
415/// Return a value that can be used to compare the *offset* implied by a GEP to
416/// zero. For example, if we have &A[i], we want to return 'i' for
417/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
418/// are involved. The above expression would also be legal to codegen as
419/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
420/// This latter form is less amenable to optimization though, and we are allowed
421/// to generate the first by knowing that pointer arithmetic doesn't overflow.
422///
423/// If we can't emit an optimized form for this expression, this returns null.
424///
425static Value *evaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
426 const DataLayout &DL) {
427 gep_type_iterator GTI = gep_type_begin(GEP);
428
429 // Check to see if this gep only has a single variable index. If so, and if
430 // any constant indices are a multiple of its scale, then we can compute this
431 // in terms of the scale of the variable index. For example, if the GEP
432 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
433 // because the expression will cross zero at the same point.
434 unsigned i, e = GEP->getNumOperands();
435 int64_t Offset = 0;
436 for (i = 1; i != e; ++i, ++GTI) {
437 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
438 // Compute the aggregate offset of constant indices.
439 if (CI->isZero()) continue;
440
441 // Handle a struct index, which adds its field offset to the pointer.
442 if (StructType *STy = GTI.getStructTypeOrNull()) {
443 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
444 } else {
445 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
446 Offset += Size*CI->getSExtValue();
447 }
448 } else {
449 // Found our variable index.
450 break;
451 }
452 }
453
454 // If there are no variable indices, we must have a constant offset, just
455 // evaluate it the general way.
456 if (i == e) return nullptr;
457
458 Value *VariableIdx = GEP->getOperand(i);
459 // Determine the scale factor of the variable element. For example, this is
460 // 4 if the variable index is into an array of i32.
461 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
462
463 // Verify that there are no other variable indices. If so, emit the hard way.
464 for (++i, ++GTI; i != e; ++i, ++GTI) {
465 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
466 if (!CI) return nullptr;
467
468 // Compute the aggregate offset of constant indices.
469 if (CI->isZero()) continue;
470
471 // Handle a struct index, which adds its field offset to the pointer.
472 if (StructType *STy = GTI.getStructTypeOrNull()) {
473 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
474 } else {
475 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
476 Offset += Size*CI->getSExtValue();
477 }
478 }
479
480 // Okay, we know we have a single variable index, which must be a
481 // pointer/array/vector index. If there is no offset, life is simple, return
482 // the index.
483 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
484 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
485 if (Offset == 0) {
486 // Cast to intptrty in case a truncation occurs. If an extension is needed,
487 // we don't need to bother extending: the extension won't affect where the
488 // computation crosses zero.
489 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
490 VariableIdx = IC.Builder.CreateTrunc(VariableIdx, IntPtrTy);
491 }
492 return VariableIdx;
493 }
494
495 // Otherwise, there is an index. The computation we will do will be modulo
496 // the pointer size.
497 Offset = SignExtend64(Offset, IntPtrWidth);
498 VariableScale = SignExtend64(VariableScale, IntPtrWidth);
499
500 // To do this transformation, any constant index must be a multiple of the
501 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
502 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
503 // multiple of the variable scale.
504 int64_t NewOffs = Offset / (int64_t)VariableScale;
505 if (Offset != NewOffs*(int64_t)VariableScale)
506 return nullptr;
507
508 // Okay, we can do this evaluation. Start by converting the index to intptr.
509 if (VariableIdx->getType() != IntPtrTy)
510 VariableIdx = IC.Builder.CreateIntCast(VariableIdx, IntPtrTy,
511 true /*Signed*/);
512 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
513 return IC.Builder.CreateAdd(VariableIdx, OffsetVal, "offset");
514}
515
516/// Returns true if we can rewrite Start as a GEP with pointer Base
517/// and some integer offset. The nodes that need to be re-written
518/// for this transformation will be added to Explored.
519static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
520 const DataLayout &DL,
521 SetVector<Value *> &Explored) {
522 SmallVector<Value *, 16> WorkList(1, Start);
523 Explored.insert(Base);
524
525 // The following traversal gives us an order which can be used
526 // when doing the final transformation. Since in the final
527 // transformation we create the PHI replacement instructions first,
528 // we don't have to get them in any particular order.
529 //
530 // However, for other instructions we will have to traverse the
531 // operands of an instruction first, which means that we have to
532 // do a post-order traversal.
533 while (!WorkList.empty()) {
534 SetVector<PHINode *> PHIs;
535
536 while (!WorkList.empty()) {
537 if (Explored.size() >= 100)
538 return false;
539
540 Value *V = WorkList.back();
541
542 if (Explored.count(V) != 0) {
543 WorkList.pop_back();
544 continue;
545 }
546
547 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
548 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
549 // We've found some value that we can't explore which is different from
550 // the base. Therefore we can't do this transformation.
551 return false;
552
553 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
554 auto *CI = dyn_cast<CastInst>(V);
555 if (!CI->isNoopCast(DL))
556 return false;
557
558 if (Explored.count(CI->getOperand(0)) == 0)
559 WorkList.push_back(CI->getOperand(0));
560 }
561
562 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
563 // We're limiting the GEP to having one index. This will preserve
564 // the original pointer type. We could handle more cases in the
565 // future.
566 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
567 GEP->getType() != Start->getType())
568 return false;
569
570 if (Explored.count(GEP->getOperand(0)) == 0)
571 WorkList.push_back(GEP->getOperand(0));
572 }
573
574 if (WorkList.back() == V) {
575 WorkList.pop_back();
576 // We've finished visiting this node, mark it as such.
577 Explored.insert(V);
578 }
579
580 if (auto *PN = dyn_cast<PHINode>(V)) {
581 // We cannot transform PHIs on unsplittable basic blocks.
582 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
583 return false;
584 Explored.insert(PN);
585 PHIs.insert(PN);
586 }
587 }
588
589 // Explore the PHI nodes further.
590 for (auto *PN : PHIs)
591 for (Value *Op : PN->incoming_values())
592 if (Explored.count(Op) == 0)
593 WorkList.push_back(Op);
594 }
595
596 // Make sure that we can do this. Since we can't insert GEPs in a basic
597 // block before a PHI node, we can't easily do this transformation if
598 // we have PHI node users of transformed instructions.
599 for (Value *Val : Explored) {
600 for (Value *Use : Val->uses()) {
601
602 auto *PHI = dyn_cast<PHINode>(Use);
603 auto *Inst = dyn_cast<Instruction>(Val);
604
605 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
606 Explored.count(PHI) == 0)
607 continue;
608
609 if (PHI->getParent() == Inst->getParent())
610 return false;
611 }
612 }
613 return true;
614}
615
616// Sets the appropriate insert point on Builder where we can add
617// a replacement Instruction for V (if that is possible).
618static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
619 bool Before = true) {
620 if (auto *PHI = dyn_cast<PHINode>(V)) {
621 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
622 return;
623 }
624 if (auto *I = dyn_cast<Instruction>(V)) {
625 if (!Before)
626 I = &*std::next(I->getIterator());
627 Builder.SetInsertPoint(I);
628 return;
629 }
630 if (auto *A = dyn_cast<Argument>(V)) {
631 // Set the insertion point in the entry block.
632 BasicBlock &Entry = A->getParent()->getEntryBlock();
633 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
634 return;
635 }
636 // Otherwise, this is a constant and we don't need to set a new
637 // insertion point.
638 assert(isa<Constant>(V) && "Setting insertion point for unknown value!")((isa<Constant>(V) && "Setting insertion point for unknown value!"
) ? static_cast<void> (0) : __assert_fail ("isa<Constant>(V) && \"Setting insertion point for unknown value!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 638, __PRETTY_FUNCTION__))
;
639}
640
641/// Returns a re-written value of Start as an indexed GEP using Base as a
642/// pointer.
643static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
644 const DataLayout &DL,
645 SetVector<Value *> &Explored) {
646 // Perform all the substitutions. This is a bit tricky because we can
647 // have cycles in our use-def chains.
648 // 1. Create the PHI nodes without any incoming values.
649 // 2. Create all the other values.
650 // 3. Add the edges for the PHI nodes.
651 // 4. Emit GEPs to get the original pointers.
652 // 5. Remove the original instructions.
653 Type *IndexType = IntegerType::get(
654 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
655
656 DenseMap<Value *, Value *> NewInsts;
657 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
658
659 // Create the new PHI nodes, without adding any incoming values.
660 for (Value *Val : Explored) {
661 if (Val == Base)
662 continue;
663 // Create empty phi nodes. This avoids cyclic dependencies when creating
664 // the remaining instructions.
665 if (auto *PHI = dyn_cast<PHINode>(Val))
666 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
667 PHI->getName() + ".idx", PHI);
668 }
669 IRBuilder<> Builder(Base->getContext());
670
671 // Create all the other instructions.
672 for (Value *Val : Explored) {
673
674 if (NewInsts.find(Val) != NewInsts.end())
675 continue;
676
677 if (auto *CI = dyn_cast<CastInst>(Val)) {
678 // Don't get rid of the intermediate variable here; the store can grow
679 // the map which will invalidate the reference to the input value.
680 Value *V = NewInsts[CI->getOperand(0)];
681 NewInsts[CI] = V;
682 continue;
683 }
684 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
685 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
686 : GEP->getOperand(1);
687 setInsertionPoint(Builder, GEP);
688 // Indices might need to be sign extended. GEPs will magically do
689 // this, but we need to do it ourselves here.
690 if (Index->getType()->getScalarSizeInBits() !=
691 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
692 Index = Builder.CreateSExtOrTrunc(
693 Index, NewInsts[GEP->getOperand(0)]->getType(),
694 GEP->getOperand(0)->getName() + ".sext");
695 }
696
697 auto *Op = NewInsts[GEP->getOperand(0)];
698 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
699 NewInsts[GEP] = Index;
700 else
701 NewInsts[GEP] = Builder.CreateNSWAdd(
702 Op, Index, GEP->getOperand(0)->getName() + ".add");
703 continue;
704 }
705 if (isa<PHINode>(Val))
706 continue;
707
708 llvm_unreachable("Unexpected instruction type")::llvm::llvm_unreachable_internal("Unexpected instruction type"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 708)
;
709 }
710
711 // Add the incoming values to the PHI nodes.
712 for (Value *Val : Explored) {
713 if (Val == Base)
714 continue;
715 // All the instructions have been created, we can now add edges to the
716 // phi nodes.
717 if (auto *PHI = dyn_cast<PHINode>(Val)) {
718 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
719 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
720 Value *NewIncoming = PHI->getIncomingValue(I);
721
722 if (NewInsts.find(NewIncoming) != NewInsts.end())
723 NewIncoming = NewInsts[NewIncoming];
724
725 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
726 }
727 }
728 }
729
730 for (Value *Val : Explored) {
731 if (Val == Base)
732 continue;
733
734 // Depending on the type, for external users we have to emit
735 // a GEP or a GEP + ptrtoint.
736 setInsertionPoint(Builder, Val, false);
737
738 // If required, create an inttoptr instruction for Base.
739 Value *NewBase = Base;
740 if (!Base->getType()->isPointerTy())
741 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
742 Start->getName() + "to.ptr");
743
744 Value *GEP = Builder.CreateInBoundsGEP(
745 Start->getType()->getPointerElementType(), NewBase,
746 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
747
748 if (!Val->getType()->isPointerTy()) {
749 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
750 Val->getName() + ".conv");
751 GEP = Cast;
752 }
753 Val->replaceAllUsesWith(GEP);
754 }
755
756 return NewInsts[Start];
757}
758
759/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
760/// the input Value as a constant indexed GEP. Returns a pair containing
761/// the GEPs Pointer and Index.
762static std::pair<Value *, Value *>
763getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
764 Type *IndexType = IntegerType::get(V->getContext(),
765 DL.getIndexTypeSizeInBits(V->getType()));
766
767 Constant *Index = ConstantInt::getNullValue(IndexType);
768 while (true) {
769 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
770 // We accept only inbouds GEPs here to exclude the possibility of
771 // overflow.
772 if (!GEP->isInBounds())
773 break;
774 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
775 GEP->getType() == V->getType()) {
776 V = GEP->getOperand(0);
777 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
778 Index = ConstantExpr::getAdd(
779 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
780 continue;
781 }
782 break;
783 }
784 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
785 if (!CI->isNoopCast(DL))
786 break;
787 V = CI->getOperand(0);
788 continue;
789 }
790 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
791 if (!CI->isNoopCast(DL))
792 break;
793 V = CI->getOperand(0);
794 continue;
795 }
796 break;
797 }
798 return {V, Index};
799}
800
801/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
802/// We can look through PHIs, GEPs and casts in order to determine a common base
803/// between GEPLHS and RHS.
804static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
805 ICmpInst::Predicate Cond,
806 const DataLayout &DL) {
807 // FIXME: Support vector of pointers.
808 if (GEPLHS->getType()->isVectorTy())
809 return nullptr;
810
811 if (!GEPLHS->hasAllConstantIndices())
812 return nullptr;
813
814 // Make sure the pointers have the same type.
815 if (GEPLHS->getType() != RHS->getType())
816 return nullptr;
817
818 Value *PtrBase, *Index;
819 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
820
821 // The set of nodes that will take part in this transformation.
822 SetVector<Value *> Nodes;
823
824 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
825 return nullptr;
826
827 // We know we can re-write this as
828 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
829 // Since we've only looked through inbouds GEPs we know that we
830 // can't have overflow on either side. We can therefore re-write
831 // this as:
832 // OFFSET1 cmp OFFSET2
833 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
834
835 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
836 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
837 // offset. Since Index is the offset of LHS to the base pointer, we will now
838 // compare the offsets instead of comparing the pointers.
839 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
840}
841
842/// Fold comparisons between a GEP instruction and something else. At this point
843/// we know that the GEP is on the LHS of the comparison.
844Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
845 ICmpInst::Predicate Cond,
846 Instruction &I) {
847 // Don't transform signed compares of GEPs into index compares. Even if the
848 // GEP is inbounds, the final add of the base pointer can have signed overflow
849 // and would change the result of the icmp.
850 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
851 // the maximum signed value for the pointer type.
852 if (ICmpInst::isSigned(Cond))
853 return nullptr;
854
855 // Look through bitcasts and addrspacecasts. We do not however want to remove
856 // 0 GEPs.
857 if (!isa<GetElementPtrInst>(RHS))
858 RHS = RHS->stripPointerCasts();
859
860 Value *PtrBase = GEPLHS->getOperand(0);
861 // FIXME: Support vector pointer GEPs.
862 if (PtrBase == RHS && GEPLHS->isInBounds() &&
863 !GEPLHS->getType()->isVectorTy()) {
864 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
865 // This transformation (ignoring the base and scales) is valid because we
866 // know pointers can't overflow since the gep is inbounds. See if we can
867 // output an optimized form.
868 Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL);
869
870 // If not, synthesize the offset the hard way.
871 if (!Offset)
872 Offset = EmitGEPOffset(GEPLHS);
873 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
874 Constant::getNullValue(Offset->getType()));
875 }
876
877 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
878 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
879 !NullPointerIsDefined(I.getFunction(),
880 RHS->getType()->getPointerAddressSpace())) {
881 // For most address spaces, an allocation can't be placed at null, but null
882 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
883 // the only valid inbounds address derived from null, is null itself.
884 // Thus, we have four cases to consider:
885 // 1) Base == nullptr, Offset == 0 -> inbounds, null
886 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
887 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
888 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
889 //
890 // (Note if we're indexing a type of size 0, that simply collapses into one
891 // of the buckets above.)
892 //
893 // In general, we're allowed to make values less poison (i.e. remove
894 // sources of full UB), so in this case, we just select between the two
895 // non-poison cases (1 and 4 above).
896 //
897 // For vectors, we apply the same reasoning on a per-lane basis.
898 auto *Base = GEPLHS->getPointerOperand();
899 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
900 int NumElts = GEPLHS->getType()->getVectorNumElements();
901 Base = Builder.CreateVectorSplat(NumElts, Base);
902 }
903 return new ICmpInst(Cond, Base,
904 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
905 cast<Constant>(RHS), Base->getType()));
906 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
907 // If the base pointers are different, but the indices are the same, just
908 // compare the base pointer.
909 if (PtrBase != GEPRHS->getOperand(0)) {
910 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
911 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
912 GEPRHS->getOperand(0)->getType();
913 if (IndicesTheSame)
914 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
915 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
916 IndicesTheSame = false;
917 break;
918 }
919
920 // If all indices are the same, just compare the base pointers.
921 Type *BaseType = GEPLHS->getOperand(0)->getType();
922 if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
923 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
924
925 // If we're comparing GEPs with two base pointers that only differ in type
926 // and both GEPs have only constant indices or just one use, then fold
927 // the compare with the adjusted indices.
928 // FIXME: Support vector of pointers.
929 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
930 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
931 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
932 PtrBase->stripPointerCasts() ==
933 GEPRHS->getOperand(0)->stripPointerCasts() &&
934 !GEPLHS->getType()->isVectorTy()) {
935 Value *LOffset = EmitGEPOffset(GEPLHS);
936 Value *ROffset = EmitGEPOffset(GEPRHS);
937
938 // If we looked through an addrspacecast between different sized address
939 // spaces, the LHS and RHS pointers are different sized
940 // integers. Truncate to the smaller one.
941 Type *LHSIndexTy = LOffset->getType();
942 Type *RHSIndexTy = ROffset->getType();
943 if (LHSIndexTy != RHSIndexTy) {
944 if (LHSIndexTy->getPrimitiveSizeInBits() <
945 RHSIndexTy->getPrimitiveSizeInBits()) {
946 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
947 } else
948 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
949 }
950
951 Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),
952 LOffset, ROffset);
953 return replaceInstUsesWith(I, Cmp);
954 }
955
956 // Otherwise, the base pointers are different and the indices are
957 // different. Try convert this to an indexed compare by looking through
958 // PHIs/casts.
959 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
960 }
961
962 // If one of the GEPs has all zero indices, recurse.
963 // FIXME: Handle vector of pointers.
964 if (!GEPLHS->getType()->isVectorTy() && GEPLHS->hasAllZeroIndices())
965 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
966 ICmpInst::getSwappedPredicate(Cond), I);
967
968 // If the other GEP has all zero indices, recurse.
969 // FIXME: Handle vector of pointers.
970 if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices())
971 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
972
973 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
974 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
975 // If the GEPs only differ by one index, compare it.
976 unsigned NumDifferences = 0; // Keep track of # differences.
977 unsigned DiffOperand = 0; // The operand that differs.
978 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
979 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
980 Type *LHSType = GEPLHS->getOperand(i)->getType();
981 Type *RHSType = GEPRHS->getOperand(i)->getType();
982 // FIXME: Better support for vector of pointers.
983 if (LHSType->getPrimitiveSizeInBits() !=
984 RHSType->getPrimitiveSizeInBits() ||
985 (GEPLHS->getType()->isVectorTy() &&
986 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
987 // Irreconcilable differences.
988 NumDifferences = 2;
989 break;
990 }
991
992 if (NumDifferences++) break;
993 DiffOperand = i;
994 }
995
996 if (NumDifferences == 0) // SAME GEP?
997 return replaceInstUsesWith(I, // No comparison is needed here.
998 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
999
1000 else if (NumDifferences == 1 && GEPsInBounds) {
1001 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1002 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1003 // Make sure we do a signed comparison here.
1004 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1005 }
1006 }
1007
1008 // Only lower this if the icmp is the only user of the GEP or if we expect
1009 // the result to fold to a constant!
1010 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
1011 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1012 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1013 Value *L = EmitGEPOffset(GEPLHS);
1014 Value *R = EmitGEPOffset(GEPRHS);
1015 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1016 }
1017 }
1018
1019 // Try convert this to an indexed compare by looking through PHIs/casts as a
1020 // last resort.
1021 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
1022}
1023
1024Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1025 const AllocaInst *Alloca,
1026 const Value *Other) {
1027 assert(ICI.isEquality() && "Cannot fold non-equality comparison.")((ICI.isEquality() && "Cannot fold non-equality comparison."
) ? static_cast<void> (0) : __assert_fail ("ICI.isEquality() && \"Cannot fold non-equality comparison.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 1027, __PRETTY_FUNCTION__))
;
1028
1029 // It would be tempting to fold away comparisons between allocas and any
1030 // pointer not based on that alloca (e.g. an argument). However, even
1031 // though such pointers cannot alias, they can still compare equal.
1032 //
1033 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1034 // doesn't escape we can argue that it's impossible to guess its value, and we
1035 // can therefore act as if any such guesses are wrong.
1036 //
1037 // The code below checks that the alloca doesn't escape, and that it's only
1038 // used in a comparison once (the current instruction). The
1039 // single-comparison-use condition ensures that we're trivially folding all
1040 // comparisons against the alloca consistently, and avoids the risk of
1041 // erroneously folding a comparison of the pointer with itself.
1042
1043 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1044
1045 SmallVector<const Use *, 32> Worklist;
1046 for (const Use &U : Alloca->uses()) {
1047 if (Worklist.size() >= MaxIter)
1048 return nullptr;
1049 Worklist.push_back(&U);
1050 }
1051
1052 unsigned NumCmps = 0;
1053 while (!Worklist.empty()) {
1054 assert(Worklist.size() <= MaxIter)((Worklist.size() <= MaxIter) ? static_cast<void> (0
) : __assert_fail ("Worklist.size() <= MaxIter", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 1054, __PRETTY_FUNCTION__))
;
1055 const Use *U = Worklist.pop_back_val();
1056 const Value *V = U->getUser();
1057 --MaxIter;
1058
1059 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1060 isa<SelectInst>(V)) {
1061 // Track the uses.
1062 } else if (isa<LoadInst>(V)) {
1063 // Loading from the pointer doesn't escape it.
1064 continue;
1065 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
1066 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1067 if (SI->getValueOperand() == U->get())
1068 return nullptr;
1069 continue;
1070 } else if (isa<ICmpInst>(V)) {
1071 if (NumCmps++)
1072 return nullptr; // Found more than one cmp.
1073 continue;
1074 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1075 switch (Intrin->getIntrinsicID()) {
1076 // These intrinsics don't escape or compare the pointer. Memset is safe
1077 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1078 // we don't allow stores, so src cannot point to V.
1079 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1080 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1081 continue;
1082 default:
1083 return nullptr;
1084 }
1085 } else {
1086 return nullptr;
1087 }
1088 for (const Use &U : V->uses()) {
1089 if (Worklist.size() >= MaxIter)
1090 return nullptr;
1091 Worklist.push_back(&U);
1092 }
1093 }
1094
1095 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
1096 return replaceInstUsesWith(
1097 ICI,
1098 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1099}
1100
1101/// Fold "icmp pred (X+C), X".
1102Instruction *InstCombiner::foldICmpAddOpConst(Value *X, const APInt &C,
1103 ICmpInst::Predicate Pred) {
1104 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
1105 // so the values can never be equal. Similarly for all other "or equals"
1106 // operators.
1107 assert(!!C && "C should not be zero!")((!!C && "C should not be zero!") ? static_cast<void
> (0) : __assert_fail ("!!C && \"C should not be zero!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 1107, __PRETTY_FUNCTION__))
;
1108
1109 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
1110 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1111 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1112 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1113 Constant *R = ConstantInt::get(X->getType(),
1114 APInt::getMaxValue(C.getBitWidth()) - C);
1115 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1116 }
1117
1118 // (X+1) >u X --> X <u (0-1) --> X != 255
1119 // (X+2) >u X --> X <u (0-2) --> X <u 254
1120 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
1121 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
1122 return new ICmpInst(ICmpInst::ICMP_ULT, X,
1123 ConstantInt::get(X->getType(), -C));
1124
1125 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
1126
1127 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1128 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1129 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1130 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1131 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1132 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
1133 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1134 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1135 ConstantInt::get(X->getType(), SMax - C));
1136
1137 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1138 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1139 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1140 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1141 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1142 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
1143
1144 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) ?
static_cast<void> (0) : __assert_fail ("Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 1144, __PRETTY_FUNCTION__))
;
1145 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1146 ConstantInt::get(X->getType(), SMax - (C - 1)));
1147}
1148
1149/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1150/// (icmp eq/ne A, Log2(AP2/AP1)) ->
1151/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
1152Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &I, Value *A,
1153 const APInt &AP1,
1154 const APInt &AP2) {
1155 assert(I.isEquality() && "Cannot fold icmp gt/lt")((I.isEquality() && "Cannot fold icmp gt/lt") ? static_cast
<void> (0) : __assert_fail ("I.isEquality() && \"Cannot fold icmp gt/lt\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 1155, __PRETTY_FUNCTION__))
;
1156
1157 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1158 if (I.getPredicate() == I.ICMP_NE)
1159 Pred = CmpInst::getInversePredicate(Pred);
1160 return new ICmpInst(Pred, LHS, RHS);
1161 };
1162
1163 // Don't bother doing any work for cases which InstSimplify handles.
1164 if (AP2.isNullValue())
1165 return nullptr;
1166
1167 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1168 if (IsAShr) {
1169 if (AP2.isAllOnesValue())
1170 return nullptr;
1171 if (AP2.isNegative() != AP1.isNegative())
1172 return nullptr;
1173 if (AP2.sgt(AP1))
1174 return nullptr;
1175 }
1176
1177 if (!AP1)
1178 // 'A' must be large enough to shift out the highest set bit.
1179 return getICmp(I.ICMP_UGT, A,
1180 ConstantInt::get(A->getType(), AP2.logBase2()));
1181
1182 if (AP1 == AP2)
1183 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1184
1185 int Shift;
1186 if (IsAShr && AP1.isNegative())
1187 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
1188 else
1189 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
1190
1191 if (Shift > 0) {
1192 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1193 // There are multiple solutions if we are comparing against -1 and the LHS
1194 // of the ashr is not a power of two.
1195 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1196 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1197 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1198 } else if (AP1 == AP2.lshr(Shift)) {
1199 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1200 }
1201 }
1202
1203 // Shifting const2 will never be equal to const1.
1204 // FIXME: This should always be handled by InstSimplify?
1205 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1206 return replaceInstUsesWith(I, TorF);
1207}
1208
1209/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1210/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1211Instruction *InstCombiner::foldICmpShlConstConst(ICmpInst &I, Value *A,
1212 const APInt &AP1,
1213 const APInt &AP2) {
1214 assert(I.isEquality() && "Cannot fold icmp gt/lt")((I.isEquality() && "Cannot fold icmp gt/lt") ? static_cast
<void> (0) : __assert_fail ("I.isEquality() && \"Cannot fold icmp gt/lt\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 1214, __PRETTY_FUNCTION__))
;
1215
1216 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1217 if (I.getPredicate() == I.ICMP_NE)
1218 Pred = CmpInst::getInversePredicate(Pred);
1219 return new ICmpInst(Pred, LHS, RHS);
1220 };
1221
1222 // Don't bother doing any work for cases which InstSimplify handles.
1223 if (AP2.isNullValue())
1224 return nullptr;
1225
1226 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1227
1228 if (!AP1 && AP2TrailingZeros != 0)
1229 return getICmp(
1230 I.ICMP_UGE, A,
1231 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1232
1233 if (AP1 == AP2)
1234 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1235
1236 // Get the distance between the lowest bits that are set.
1237 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1238
1239 if (Shift > 0 && AP2.shl(Shift) == AP1)
1240 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1241
1242 // Shifting const2 will never be equal to const1.
1243 // FIXME: This should always be handled by InstSimplify?
1244 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1245 return replaceInstUsesWith(I, TorF);
1246}
1247
1248/// The caller has matched a pattern of the form:
1249/// I = icmp ugt (add (add A, B), CI2), CI1
1250/// If this is of the form:
1251/// sum = a + b
1252/// if (sum+128 >u 255)
1253/// Then replace it with llvm.sadd.with.overflow.i8.
1254///
1255static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1256 ConstantInt *CI2, ConstantInt *CI1,
1257 InstCombiner &IC) {
1258 // The transformation we're trying to do here is to transform this into an
1259 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1260 // with a narrower add, and discard the add-with-constant that is part of the
1261 // range check (if we can't eliminate it, this isn't profitable).
1262
1263 // In order to eliminate the add-with-constant, the compare can be its only
1264 // use.
1265 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1266 if (!AddWithCst->hasOneUse())
1267 return nullptr;
1268
1269 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1270 if (!CI2->getValue().isPowerOf2())
1271 return nullptr;
1272 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1273 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1274 return nullptr;
1275
1276 // The width of the new add formed is 1 more than the bias.
1277 ++NewWidth;
1278
1279 // Check to see that CI1 is an all-ones value with NewWidth bits.
1280 if (CI1->getBitWidth() == NewWidth ||
1281 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1282 return nullptr;
1283
1284 // This is only really a signed overflow check if the inputs have been
1285 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1286 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1287 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1288 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
1289 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
1290 return nullptr;
1291
1292 // In order to replace the original add with a narrower
1293 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1294 // and truncates that discard the high bits of the add. Verify that this is
1295 // the case.
1296 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1297 for (User *U : OrigAdd->users()) {
1298 if (U == AddWithCst)
1299 continue;
1300
1301 // Only accept truncates for now. We would really like a nice recursive
1302 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1303 // chain to see which bits of a value are actually demanded. If the
1304 // original add had another add which was then immediately truncated, we
1305 // could still do the transformation.
1306 TruncInst *TI = dyn_cast<TruncInst>(U);
1307 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1308 return nullptr;
1309 }
1310
1311 // If the pattern matches, truncate the inputs to the narrower type and
1312 // use the sadd_with_overflow intrinsic to efficiently compute both the
1313 // result and the overflow bit.
1314 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1315 Function *F = Intrinsic::getDeclaration(
1316 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1317
1318 InstCombiner::BuilderTy &Builder = IC.Builder;
1319
1320 // Put the new code above the original add, in case there are any uses of the
1321 // add between the add and the compare.
1322 Builder.SetInsertPoint(OrigAdd);
1323
1324 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1325 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1326 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1327 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1328 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1329
1330 // The inner add was the result of the narrow add, zero extended to the
1331 // wider type. Replace it with the result computed by the intrinsic.
1332 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1333
1334 // The original icmp gets replaced with the overflow value.
1335 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1336}
1337
1338/// If we have:
1339/// icmp eq/ne (urem/srem %x, %y), 0
1340/// iff %y is a power-of-two, we can replace this with a bit test:
1341/// icmp eq/ne (and %x, (add %y, -1)), 0
1342Instruction *InstCombiner::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1343 // This fold is only valid for equality predicates.
1344 if (!I.isEquality())
1345 return nullptr;
1346 ICmpInst::Predicate Pred;
1347 Value *X, *Y, *Zero;
1348 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1349 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1350 return nullptr;
1351 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
1352 return nullptr;
1353 // This may increase instruction count, we don't enforce that Y is a constant.
1354 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1355 Value *Masked = Builder.CreateAnd(X, Mask);
1356 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1357}
1358
1359/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1360/// by one-less-than-bitwidth into a sign test on the original value.
1361Instruction *foldSignBitTest(ICmpInst &I) {
1362 ICmpInst::Predicate Pred;
1363 Value *X;
1364 Constant *C;
1365 if (!I.isEquality() ||
1366 !match(&I, m_ICmp(Pred, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))),
1367 m_Zero())))
1368 return nullptr;
1369
1370 Type *XTy = X->getType();
1371 unsigned XBitWidth = XTy->getScalarSizeInBits();
1372 if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1373 APInt(XBitWidth, XBitWidth - 1))))
1374 return nullptr;
1375
1376 return ICmpInst::Create(Instruction::ICmp,
1377 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1378 : ICmpInst::ICMP_SLT,
1379 X, ConstantInt::getNullValue(XTy));
1380}
1381
1382// Handle icmp pred X, 0
1383Instruction *InstCombiner::foldICmpWithZero(ICmpInst &Cmp) {
1384 CmpInst::Predicate Pred = Cmp.getPredicate();
1385 if (!match(Cmp.getOperand(1), m_Zero()))
1386 return nullptr;
1387
1388 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1389 if (Pred == ICmpInst::ICMP_SGT) {
1390 Value *A, *B;
1391 SelectPatternResult SPR = matchSelectPattern(Cmp.getOperand(0), A, B);
1392 if (SPR.Flavor == SPF_SMIN) {
1393 if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT))
1394 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1395 if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT))
1396 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1397 }
1398 }
1399
1400 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))
1401 return New;
1402
1403 // Given:
1404 // icmp eq/ne (urem %x, %y), 0
1405 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1406 // icmp eq/ne %x, 0
1407 Value *X, *Y;
1408 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1409 ICmpInst::isEquality(Pred)) {
1410 KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1411 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1412 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1413 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1414 }
1415
1416 return nullptr;
1417}
1418
1419/// Fold icmp Pred X, C.
1420/// TODO: This code structure does not make sense. The saturating add fold
1421/// should be moved to some other helper and extended as noted below (it is also
1422/// possible that code has been made unnecessary - do we canonicalize IR to
1423/// overflow/saturating intrinsics or not?).
1424Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) {
1425 // Match the following pattern, which is a common idiom when writing
1426 // overflow-safe integer arithmetic functions. The source performs an addition
1427 // in wider type and explicitly checks for overflow using comparisons against
1428 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1429 //
1430 // TODO: This could probably be generalized to handle other overflow-safe
1431 // operations if we worked out the formulas to compute the appropriate magic
1432 // constants.
1433 //
1434 // sum = a + b
1435 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1436 CmpInst::Predicate Pred = Cmp.getPredicate();
1437 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1438 Value *A, *B;
1439 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1440 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1441 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1442 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1443 return Res;
1444
1445 return nullptr;
1446}
1447
1448/// Canonicalize icmp instructions based on dominating conditions.
1449Instruction *InstCombiner::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1450 // This is a cheap/incomplete check for dominance - just match a single
1451 // predecessor with a conditional branch.
1452 BasicBlock *CmpBB = Cmp.getParent();
1453 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1454 if (!DomBB)
1455 return nullptr;
1456
1457 Value *DomCond;
1458 BasicBlock *TrueBB, *FalseBB;
1459 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1460 return nullptr;
1461
1462 assert((TrueBB == CmpBB || FalseBB == CmpBB) &&(((TrueBB == CmpBB || FalseBB == CmpBB) && "Predecessor block does not point to successor?"
) ? static_cast<void> (0) : __assert_fail ("(TrueBB == CmpBB || FalseBB == CmpBB) && \"Predecessor block does not point to successor?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 1463, __PRETTY_FUNCTION__))
1463 "Predecessor block does not point to successor?")(((TrueBB == CmpBB || FalseBB == CmpBB) && "Predecessor block does not point to successor?"
) ? static_cast<void> (0) : __assert_fail ("(TrueBB == CmpBB || FalseBB == CmpBB) && \"Predecessor block does not point to successor?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 1463, __PRETTY_FUNCTION__))
;
1464
1465 // The branch should get simplified. Don't bother simplifying this condition.
1466 if (TrueBB == FalseBB)
1467 return nullptr;
1468
1469 // Try to simplify this compare to T/F based on the dominating condition.
1470 Optional<bool> Imp = isImpliedCondition(DomCond, &Cmp, DL, TrueBB == CmpBB);
1471 if (Imp)
1472 return replaceInstUsesWith(Cmp, ConstantInt::get(Cmp.getType(), *Imp));
1473
1474 CmpInst::Predicate Pred = Cmp.getPredicate();
1475 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1476 ICmpInst::Predicate DomPred;
1477 const APInt *C, *DomC;
1478 if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) &&
1479 match(Y, m_APInt(C))) {
1480 // We have 2 compares of a variable with constants. Calculate the constant
1481 // ranges of those compares to see if we can transform the 2nd compare:
1482 // DomBB:
1483 // DomCond = icmp DomPred X, DomC
1484 // br DomCond, CmpBB, FalseBB
1485 // CmpBB:
1486 // Cmp = icmp Pred X, C
1487 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(Pred, *C);
1488 ConstantRange DominatingCR =
1489 (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC)
1490 : ConstantRange::makeExactICmpRegion(
1491 CmpInst::getInversePredicate(DomPred), *DomC);
1492 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1493 ConstantRange Difference = DominatingCR.difference(CR);
1494 if (Intersection.isEmptySet())
1495 return replaceInstUsesWith(Cmp, Builder.getFalse());
1496 if (Difference.isEmptySet())
1497 return replaceInstUsesWith(Cmp, Builder.getTrue());
1498
1499 // Canonicalizing a sign bit comparison that gets used in a branch,
1500 // pessimizes codegen by generating branch on zero instruction instead
1501 // of a test and branch. So we avoid canonicalizing in such situations
1502 // because test and branch instruction has better branch displacement
1503 // than compare and branch instruction.
1504 bool UnusedBit;
1505 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1506 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1507 return nullptr;
1508
1509 if (const APInt *EqC = Intersection.getSingleElement())
1510 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1511 if (const APInt *NeC = Difference.getSingleElement())
1512 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1513 }
1514
1515 return nullptr;
1516}
1517
1518/// Fold icmp (trunc X, Y), C.
1519Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp,
1520 TruncInst *Trunc,
1521 const APInt &C) {
1522 ICmpInst::Predicate Pred = Cmp.getPredicate();
1523 Value *X = Trunc->getOperand(0);
1524 if (C.isOneValue() && C.getBitWidth() > 1) {
1525 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1526 Value *V = nullptr;
1527 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1528 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1529 ConstantInt::get(V->getType(), 1));
1530 }
1531
1532 if (Cmp.isEquality() && Trunc->hasOneUse()) {
1533 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1534 // of the high bits truncated out of x are known.
1535 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1536 SrcBits = X->getType()->getScalarSizeInBits();
1537 KnownBits Known = computeKnownBits(X, 0, &Cmp);
1538
1539 // If all the high bits are known, we can do this xform.
1540 if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) {
1541 // Pull in the high bits from known-ones set.
1542 APInt NewRHS = C.zext(SrcBits);
1543 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1544 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS));
1545 }
1546 }
1547
1548 return nullptr;
1549}
1550
1551/// Fold icmp (xor X, Y), C.
1552Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp,
1553 BinaryOperator *Xor,
1554 const APInt &C) {
1555 Value *X = Xor->getOperand(0);
1556 Value *Y = Xor->getOperand(1);
1557 const APInt *XorC;
1558 if (!match(Y, m_APInt(XorC)))
1559 return nullptr;
1560
1561 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1562 // fold the xor.
1563 ICmpInst::Predicate Pred = Cmp.getPredicate();
1564 bool TrueIfSigned = false;
1565 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1566
1567 // If the sign bit of the XorCst is not set, there is no change to
1568 // the operation, just stop using the Xor.
1569 if (!XorC->isNegative()) {
1570 Cmp.setOperand(0, X);
1571 Worklist.Add(Xor);
1572 return &Cmp;
1573 }
1574
1575 // Emit the opposite comparison.
1576 if (TrueIfSigned)
1577 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1578 ConstantInt::getAllOnesValue(X->getType()));
1579 else
1580 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1581 ConstantInt::getNullValue(X->getType()));
1582 }
1583
1584 if (Xor->hasOneUse()) {
1585 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1586 if (!Cmp.isEquality() && XorC->isSignMask()) {
1587 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1588 : Cmp.getSignedPredicate();
1589 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1590 }
1591
1592 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1593 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1594 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1595 : Cmp.getSignedPredicate();
1596 Pred = Cmp.getSwappedPredicate(Pred);
1597 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1598 }
1599 }
1600
1601 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1602 if (Pred == ICmpInst::ICMP_UGT) {
1603 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1604 if (*XorC == ~C && (C + 1).isPowerOf2())
1605 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1606 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1607 if (*XorC == C && (C + 1).isPowerOf2())
1608 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1609 }
1610 if (Pred == ICmpInst::ICMP_ULT) {
1611 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1612 if (*XorC == -C && C.isPowerOf2())
1613 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1614 ConstantInt::get(X->getType(), ~C));
1615 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1616 if (*XorC == C && (-C).isPowerOf2())
1617 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1618 ConstantInt::get(X->getType(), ~C));
1619 }
1620 return nullptr;
1621}
1622
1623/// Fold icmp (and (sh X, Y), C2), C1.
1624Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
1625 const APInt &C1, const APInt &C2) {
1626 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1627 if (!Shift || !Shift->isShift())
1628 return nullptr;
1629
1630 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1631 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1632 // code produced by the clang front-end, for bitfield access.
1633 // This seemingly simple opportunity to fold away a shift turns out to be
1634 // rather complicated. See PR17827 for details.
1635 unsigned ShiftOpcode = Shift->getOpcode();
1636 bool IsShl = ShiftOpcode == Instruction::Shl;
1637 const APInt *C3;
1638 if (match(Shift->getOperand(1), m_APInt(C3))) {
1639 bool CanFold = false;
1640 if (ShiftOpcode == Instruction::Shl) {
1641 // For a left shift, we can fold if the comparison is not signed. We can
1642 // also fold a signed comparison if the mask value and comparison value
1643 // are not negative. These constraints may not be obvious, but we can
1644 // prove that they are correct using an SMT solver.
1645 if (!Cmp.isSigned() || (!C2.isNegative() && !C1.isNegative()))
1646 CanFold = true;
1647 } else {
1648 bool IsAshr = ShiftOpcode == Instruction::AShr;
1649 // For a logical right shift, we can fold if the comparison is not signed.
1650 // We can also fold a signed comparison if the shifted mask value and the
1651 // shifted comparison value are not negative. These constraints may not be
1652 // obvious, but we can prove that they are correct using an SMT solver.
1653 // For an arithmetic shift right we can do the same, if we ensure
1654 // the And doesn't use any bits being shifted in. Normally these would
1655 // be turned into lshr by SimplifyDemandedBits, but not if there is an
1656 // additional user.
1657 if (!IsAshr || (C2.shl(*C3).lshr(*C3) == C2)) {
1658 if (!Cmp.isSigned() ||
1659 (!C2.shl(*C3).isNegative() && !C1.shl(*C3).isNegative()))
1660 CanFold = true;
1661 }
1662 }
1663
1664 if (CanFold) {
1665 APInt NewCst = IsShl ? C1.lshr(*C3) : C1.shl(*C3);
1666 APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3);
1667 // Check to see if we are shifting out any of the bits being compared.
1668 if (SameAsC1 != C1) {
1669 // If we shifted bits out, the fold is not going to work out. As a
1670 // special case, check to see if this means that the result is always
1671 // true or false now.
1672 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1673 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1674 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1675 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1676 } else {
1677 Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst));
1678 APInt NewAndCst = IsShl ? C2.lshr(*C3) : C2.shl(*C3);
1679 And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst));
1680 And->setOperand(0, Shift->getOperand(0));
1681 Worklist.Add(Shift); // Shift is dead.
1682 return &Cmp;
1683 }
1684 }
1685 }
1686
1687 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1688 // preferable because it allows the C2 << Y expression to be hoisted out of a
1689 // loop if Y is invariant and X is not.
1690 if (Shift->hasOneUse() && C1.isNullValue() && Cmp.isEquality() &&
1691 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1692 // Compute C2 << Y.
1693 Value *NewShift =
1694 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1695 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1696
1697 // Compute X & (C2 << Y).
1698 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1699 Cmp.setOperand(0, NewAnd);
1700 return &Cmp;
1701 }
1702
1703 return nullptr;
1704}
1705
1706/// Fold icmp (and X, C2), C1.
1707Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp,
1708 BinaryOperator *And,
1709 const APInt &C1) {
1710 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1711
1712 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1713 // TODO: We canonicalize to the longer form for scalars because we have
1714 // better analysis/folds for icmp, and codegen may be better with icmp.
1715 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isNullValue() &&
1716 match(And->getOperand(1), m_One()))
1717 return new TruncInst(And->getOperand(0), Cmp.getType());
1718
1719 const APInt *C2;
1720 Value *X;
1721 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1722 return nullptr;
1723
1724 // Don't perform the following transforms if the AND has multiple uses
1725 if (!And->hasOneUse())
1726 return nullptr;
1727
1728 if (Cmp.isEquality() && C1.isNullValue()) {
1729 // Restrict this fold to single-use 'and' (PR10267).
1730 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1731 if (C2->isSignMask()) {
1732 Constant *Zero = Constant::getNullValue(X->getType());
1733 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1734 return new ICmpInst(NewPred, X, Zero);
1735 }
1736
1737 // Restrict this fold only for single-use 'and' (PR10267).
1738 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1739 if ((~(*C2) + 1).isPowerOf2()) {
1740 Constant *NegBOC =
1741 ConstantExpr::getNeg(cast<Constant>(And->getOperand(1)));
1742 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1743 return new ICmpInst(NewPred, X, NegBOC);
1744 }
1745 }
1746
1747 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1748 // the input width without changing the value produced, eliminate the cast:
1749 //
1750 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1751 //
1752 // We can do this transformation if the constants do not have their sign bits
1753 // set or if it is an equality comparison. Extending a relational comparison
1754 // when we're checking the sign bit would not work.
1755 Value *W;
1756 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1757 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1758 // TODO: Is this a good transform for vectors? Wider types may reduce
1759 // throughput. Should this transform be limited (even for scalars) by using
1760 // shouldChangeType()?
1761 if (!Cmp.getType()->isVectorTy()) {
1762 Type *WideType = W->getType();
1763 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1764 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1765 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1766 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1767 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1768 }
1769 }
1770
1771 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1772 return I;
1773
1774 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1775 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1776 //
1777 // iff pred isn't signed
1778 if (!Cmp.isSigned() && C1.isNullValue() && And->getOperand(0)->hasOneUse() &&
1779 match(And->getOperand(1), m_One())) {
1780 Constant *One = cast<Constant>(And->getOperand(1));
1781 Value *Or = And->getOperand(0);
1782 Value *A, *B, *LShr;
1783 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1784 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1785 unsigned UsesRemoved = 0;
1786 if (And->hasOneUse())
1787 ++UsesRemoved;
1788 if (Or->hasOneUse())
1789 ++UsesRemoved;
1790 if (LShr->hasOneUse())
1791 ++UsesRemoved;
1792
1793 // Compute A & ((1 << B) | 1)
1794 Value *NewOr = nullptr;
1795 if (auto *C = dyn_cast<Constant>(B)) {
1796 if (UsesRemoved >= 1)
1797 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1798 } else {
1799 if (UsesRemoved >= 3)
1800 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1801 /*HasNUW=*/true),
1802 One, Or->getName());
1803 }
1804 if (NewOr) {
1805 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1806 Cmp.setOperand(0, NewAnd);
1807 return &Cmp;
1808 }
1809 }
1810 }
1811
1812 return nullptr;
1813}
1814
1815/// Fold icmp (and X, Y), C.
1816Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp,
1817 BinaryOperator *And,
1818 const APInt &C) {
1819 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1820 return I;
1821
1822 // TODO: These all require that Y is constant too, so refactor with the above.
1823
1824 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1825 Value *X = And->getOperand(0);
1826 Value *Y = And->getOperand(1);
1827 if (auto *LI = dyn_cast<LoadInst>(X))
1828 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1829 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1830 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1831 !LI->isVolatile() && isa<ConstantInt>(Y)) {
1832 ConstantInt *C2 = cast<ConstantInt>(Y);
1833 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
1834 return Res;
1835 }
1836
1837 if (!Cmp.isEquality())
1838 return nullptr;
1839
1840 // X & -C == -C -> X > u ~C
1841 // X & -C != -C -> X <= u ~C
1842 // iff C is a power of 2
1843 if (Cmp.getOperand(1) == Y && (-C).isPowerOf2()) {
1844 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT
1845 : CmpInst::ICMP_ULE;
1846 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1847 }
1848
1849 // (X & C2) == 0 -> (trunc X) >= 0
1850 // (X & C2) != 0 -> (trunc X) < 0
1851 // iff C2 is a power of 2 and it masks the sign bit of a legal integer type.
1852 const APInt *C2;
1853 if (And->hasOneUse() && C.isNullValue() && match(Y, m_APInt(C2))) {
1854 int32_t ExactLogBase2 = C2->exactLogBase2();
1855 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1856 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1);
1857 if (And->getType()->isVectorTy())
1858 NTy = VectorType::get(NTy, And->getType()->getVectorNumElements());
1859 Value *Trunc = Builder.CreateTrunc(X, NTy);
1860 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE
1861 : CmpInst::ICMP_SLT;
1862 return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy));
1863 }
1864 }
1865
1866 return nullptr;
1867}
1868
1869/// Fold icmp (or X, Y), C.
1870Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
1871 const APInt &C) {
1872 ICmpInst::Predicate Pred = Cmp.getPredicate();
1873 if (C.isOneValue()) {
1874 // icmp slt signum(V) 1 --> icmp slt V, 1
1875 Value *V = nullptr;
1876 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
1877 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1878 ConstantInt::get(V->getType(), 1));
1879 }
1880
1881 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
1882 if (Cmp.isEquality() && Cmp.getOperand(1) == OrOp1) {
1883 // X | C == C --> X <=u C
1884 // X | C != C --> X >u C
1885 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
1886 if ((C + 1).isPowerOf2()) {
1887 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
1888 return new ICmpInst(Pred, OrOp0, OrOp1);
1889 }
1890 // More general: are all bits outside of a mask constant set or not set?
1891 // X | C == C --> (X & ~C) == 0
1892 // X | C != C --> (X & ~C) != 0
1893 if (Or->hasOneUse()) {
1894 Value *A = Builder.CreateAnd(OrOp0, ~C);
1895 return new ICmpInst(Pred, A, ConstantInt::getNullValue(OrOp0->getType()));
1896 }
1897 }
1898
1899 if (!Cmp.isEquality() || !C.isNullValue() || !Or->hasOneUse())
1900 return nullptr;
1901
1902 Value *P, *Q;
1903 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1904 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1905 // -> and (icmp eq P, null), (icmp eq Q, null).
1906 Value *CmpP =
1907 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1908 Value *CmpQ =
1909 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
1910 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1911 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
1912 }
1913
1914 // Are we using xors to bitwise check for a pair of (in)equalities? Convert to
1915 // a shorter form that has more potential to be folded even further.
1916 Value *X1, *X2, *X3, *X4;
1917 if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) &&
1918 match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) {
1919 // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4)
1920 // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4)
1921 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
1922 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
1923 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1924 return BinaryOperator::Create(BOpc, Cmp12, Cmp34);
1925 }
1926
1927 return nullptr;
1928}
1929
1930/// Fold icmp (mul X, Y), C.
1931Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp,
1932 BinaryOperator *Mul,
1933 const APInt &C) {
1934 const APInt *MulC;
1935 if (!match(Mul->getOperand(1), m_APInt(MulC)))
1936 return nullptr;
1937
1938 // If this is a test of the sign bit and the multiply is sign-preserving with
1939 // a constant operand, use the multiply LHS operand instead.
1940 ICmpInst::Predicate Pred = Cmp.getPredicate();
1941 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
1942 if (MulC->isNegative())
1943 Pred = ICmpInst::getSwappedPredicate(Pred);
1944 return new ICmpInst(Pred, Mul->getOperand(0),
1945 Constant::getNullValue(Mul->getType()));
1946 }
1947
1948 return nullptr;
1949}
1950
1951/// Fold icmp (shl 1, Y), C.
1952static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
1953 const APInt &C) {
1954 Value *Y;
1955 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
1956 return nullptr;
1957
1958 Type *ShiftType = Shl->getType();
1959 unsigned TypeBits = C.getBitWidth();
1960 bool CIsPowerOf2 = C.isPowerOf2();
1961 ICmpInst::Predicate Pred = Cmp.getPredicate();
1962 if (Cmp.isUnsigned()) {
1963 // (1 << Y) pred C -> Y pred Log2(C)
1964 if (!CIsPowerOf2) {
1965 // (1 << Y) < 30 -> Y <= 4
1966 // (1 << Y) <= 30 -> Y <= 4
1967 // (1 << Y) >= 30 -> Y > 4
1968 // (1 << Y) > 30 -> Y > 4
1969 if (Pred == ICmpInst::ICMP_ULT)
1970 Pred = ICmpInst::ICMP_ULE;
1971 else if (Pred == ICmpInst::ICMP_UGE)
1972 Pred = ICmpInst::ICMP_UGT;
1973 }
1974
1975 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31
1976 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31
1977 unsigned CLog2 = C.logBase2();
1978 if (CLog2 == TypeBits - 1) {
1979 if (Pred == ICmpInst::ICMP_UGE)
1980 Pred = ICmpInst::ICMP_EQ;
1981 else if (Pred == ICmpInst::ICMP_ULT)
1982 Pred = ICmpInst::ICMP_NE;
1983 }
1984 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
1985 } else if (Cmp.isSigned()) {
1986 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
1987 if (C.isAllOnesValue()) {
1988 // (1 << Y) <= -1 -> Y == 31
1989 if (Pred == ICmpInst::ICMP_SLE)
1990 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1991
1992 // (1 << Y) > -1 -> Y != 31
1993 if (Pred == ICmpInst::ICMP_SGT)
1994 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1995 } else if (!C) {
1996 // (1 << Y) < 0 -> Y == 31
1997 // (1 << Y) <= 0 -> Y == 31
1998 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1999 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2000
2001 // (1 << Y) >= 0 -> Y != 31
2002 // (1 << Y) > 0 -> Y != 31
2003 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
2004 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2005 }
2006 } else if (Cmp.isEquality() && CIsPowerOf2) {
2007 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C.logBase2()));
2008 }
2009
2010 return nullptr;
2011}
2012
2013/// Fold icmp (shl X, Y), C.
2014Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp,
2015 BinaryOperator *Shl,
2016 const APInt &C) {
2017 const APInt *ShiftVal;
2018 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2019 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2020
2021 const APInt *ShiftAmt;
2022 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2023 return foldICmpShlOne(Cmp, Shl, C);
2024
2025 // Check that the shift amount is in range. If not, don't perform undefined
2026 // shifts. When the shift is visited, it will be simplified.
2027 unsigned TypeBits = C.getBitWidth();
2028 if (ShiftAmt->uge(TypeBits))
2029 return nullptr;
2030
2031 ICmpInst::Predicate Pred = Cmp.getPredicate();
2032 Value *X = Shl->getOperand(0);
2033 Type *ShType = Shl->getType();
2034
2035 // NSW guarantees that we are only shifting out sign bits from the high bits,
2036 // so we can ASHR the compare constant without needing a mask and eliminate
2037 // the shift.
2038 if (Shl->hasNoSignedWrap()) {
2039 if (Pred == ICmpInst::ICMP_SGT) {
2040 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2041 APInt ShiftedC = C.ashr(*ShiftAmt);
2042 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2043 }
2044 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2045 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2046 APInt ShiftedC = C.ashr(*ShiftAmt);
2047 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2048 }
2049 if (Pred == ICmpInst::ICMP_SLT) {
2050 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2051 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2052 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2053 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2054 assert(!C.isMinSignedValue() && "Unexpected icmp slt")((!C.isMinSignedValue() && "Unexpected icmp slt") ? static_cast
<void> (0) : __assert_fail ("!C.isMinSignedValue() && \"Unexpected icmp slt\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2054, __PRETTY_FUNCTION__))
;
2055 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2056 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2057 }
2058 // If this is a signed comparison to 0 and the shift is sign preserving,
2059 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
2060 // do that if we're sure to not continue on in this function.
2061 if (isSignTest(Pred, C))
2062 return new ICmpInst(Pred, X, Constant::getNullValue(ShType));
2063 }
2064
2065 // NUW guarantees that we are only shifting out zero bits from the high bits,
2066 // so we can LSHR the compare constant without needing a mask and eliminate
2067 // the shift.
2068 if (Shl->hasNoUnsignedWrap()) {
2069 if (Pred == ICmpInst::ICMP_UGT) {
2070 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2071 APInt ShiftedC = C.lshr(*ShiftAmt);
2072 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2073 }
2074 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2075 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2076 APInt ShiftedC = C.lshr(*ShiftAmt);
2077 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2078 }
2079 if (Pred == ICmpInst::ICMP_ULT) {
2080 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2081 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2082 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2083 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2084 assert(C.ugt(0) && "ult 0 should have been eliminated")((C.ugt(0) && "ult 0 should have been eliminated") ? static_cast
<void> (0) : __assert_fail ("C.ugt(0) && \"ult 0 should have been eliminated\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2084, __PRETTY_FUNCTION__))
;
2085 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2086 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2087 }
2088 }
2089
2090 if (Cmp.isEquality() && Shl->hasOneUse()) {
2091 // Strength-reduce the shift into an 'and'.
2092 Constant *Mask = ConstantInt::get(
2093 ShType,
2094 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2095 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2096 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2097 return new ICmpInst(Pred, And, LShrC);
2098 }
2099
2100 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2101 bool TrueIfSigned = false;
2102 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2103 // (X << 31) <s 0 --> (X & 1) != 0
2104 Constant *Mask = ConstantInt::get(
2105 ShType,
2106 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2107 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2108 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2109 And, Constant::getNullValue(ShType));
2110 }
2111
2112 // Simplify 'shl' inequality test into 'and' equality test.
2113 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2114 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2115 if ((C + 1).isPowerOf2() &&
2116 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2117 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2118 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2119 : ICmpInst::ICMP_NE,
2120 And, Constant::getNullValue(ShType));
2121 }
2122 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2123 if (C.isPowerOf2() &&
2124 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2125 Value *And =
2126 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2127 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2128 : ICmpInst::ICMP_NE,
2129 And, Constant::getNullValue(ShType));
2130 }
2131 }
2132
2133 // Transform (icmp pred iM (shl iM %v, N), C)
2134 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2135 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2136 // This enables us to get rid of the shift in favor of a trunc that may be
2137 // free on the target. It has the additional benefit of comparing to a
2138 // smaller constant that may be more target-friendly.
2139 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2140 if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt &&
2141 DL.isLegalInteger(TypeBits - Amt)) {
2142 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2143 if (ShType->isVectorTy())
2144 TruncTy = VectorType::get(TruncTy, ShType->getVectorNumElements());
2145 Constant *NewC =
2146 ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2147 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2148 }
2149
2150 return nullptr;
2151}
2152
2153/// Fold icmp ({al}shr X, Y), C.
2154Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp,
2155 BinaryOperator *Shr,
2156 const APInt &C) {
2157 // An exact shr only shifts out zero bits, so:
2158 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2159 Value *X = Shr->getOperand(0);
2160 CmpInst::Predicate Pred = Cmp.getPredicate();
2161 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() &&
2162 C.isNullValue())
2163 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2164
2165 const APInt *ShiftVal;
2166 if (Cmp.isEquality() && match(Shr->getOperand(0), m_APInt(ShiftVal)))
2167 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftVal);
2168
2169 const APInt *ShiftAmt;
2170 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt)))
2171 return nullptr;
2172
2173 // Check that the shift amount is in range. If not, don't perform undefined
2174 // shifts. When the shift is visited it will be simplified.
2175 unsigned TypeBits = C.getBitWidth();
2176 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
2177 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2178 return nullptr;
2179
2180 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2181 bool IsExact = Shr->isExact();
2182 Type *ShrTy = Shr->getType();
2183 // TODO: If we could guarantee that InstSimplify would handle all of the
2184 // constant-value-based preconditions in the folds below, then we could assert
2185 // those conditions rather than checking them. This is difficult because of
2186 // undef/poison (PR34838).
2187 if (IsAShr) {
2188 if (Pred == CmpInst::ICMP_SLT || (Pred == CmpInst::ICMP_SGT && IsExact)) {
2189 // icmp slt (ashr X, ShAmtC), C --> icmp slt X, (C << ShAmtC)
2190 // icmp sgt (ashr exact X, ShAmtC), C --> icmp sgt X, (C << ShAmtC)
2191 APInt ShiftedC = C.shl(ShAmtVal);
2192 if (ShiftedC.ashr(ShAmtVal) == C)
2193 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2194 }
2195 if (Pred == CmpInst::ICMP_SGT) {
2196 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2197 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2198 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2199 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2200 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2201 }
2202 } else {
2203 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2204 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2205 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2206 APInt ShiftedC = C.shl(ShAmtVal);
2207 if (ShiftedC.lshr(ShAmtVal) == C)
2208 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2209 }
2210 if (Pred == CmpInst::ICMP_UGT) {
2211 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2212 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2213 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2214 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2215 }
2216 }
2217
2218 if (!Cmp.isEquality())
2219 return nullptr;
2220
2221 // Handle equality comparisons of shift-by-constant.
2222
2223 // If the comparison constant changes with the shift, the comparison cannot
2224 // succeed (bits of the comparison constant cannot match the shifted value).
2225 // This should be known by InstSimplify and already be folded to true/false.
2226 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||((((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
(!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
"Expected icmp+shr simplify did not occur.") ? static_cast<
void> (0) : __assert_fail ("((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) || (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) && \"Expected icmp+shr simplify did not occur.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2228, __PRETTY_FUNCTION__))
2227 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&((((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
(!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
"Expected icmp+shr simplify did not occur.") ? static_cast<
void> (0) : __assert_fail ("((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) || (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) && \"Expected icmp+shr simplify did not occur.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2228, __PRETTY_FUNCTION__))
2228 "Expected icmp+shr simplify did not occur.")((((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
(!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
"Expected icmp+shr simplify did not occur.") ? static_cast<
void> (0) : __assert_fail ("((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) || (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) && \"Expected icmp+shr simplify did not occur.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2228, __PRETTY_FUNCTION__))
;
2229
2230 // If the bits shifted out are known zero, compare the unshifted value:
2231 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2232 if (Shr->isExact())
2233 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2234
2235 if (Shr->hasOneUse()) {
2236 // Canonicalize the shift into an 'and':
2237 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2238 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2239 Constant *Mask = ConstantInt::get(ShrTy, Val);
2240 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2241 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2242 }
2243
2244 return nullptr;
2245}
2246
2247Instruction *InstCombiner::foldICmpSRemConstant(ICmpInst &Cmp,
2248 BinaryOperator *SRem,
2249 const APInt &C) {
2250 // Match an 'is positive' or 'is negative' comparison of remainder by a
2251 // constant power-of-2 value:
2252 // (X % pow2C) sgt/slt 0
2253 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2254 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT)
2255 return nullptr;
2256
2257 // TODO: The one-use check is standard because we do not typically want to
2258 // create longer instruction sequences, but this might be a special-case
2259 // because srem is not good for analysis or codegen.
2260 if (!SRem->hasOneUse())
2261 return nullptr;
2262
2263 const APInt *DivisorC;
2264 if (!C.isNullValue() || !match(SRem->getOperand(1), m_Power2(DivisorC)))
2265 return nullptr;
2266
2267 // Mask off the sign bit and the modulo bits (low-bits).
2268 Type *Ty = SRem->getType();
2269 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2270 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2271 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2272
2273 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2274 // bit is set. Example:
2275 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2276 if (Pred == ICmpInst::ICMP_SGT)
2277 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2278
2279 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2280 // bit is set. Example:
2281 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2282 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2283}
2284
2285/// Fold icmp (udiv X, Y), C.
2286Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp,
2287 BinaryOperator *UDiv,
2288 const APInt &C) {
2289 const APInt *C2;
2290 if (!match(UDiv->getOperand(0), m_APInt(C2)))
2291 return nullptr;
2292
2293 assert(*C2 != 0 && "udiv 0, X should have been simplified already.")((*C2 != 0 && "udiv 0, X should have been simplified already."
) ? static_cast<void> (0) : __assert_fail ("*C2 != 0 && \"udiv 0, X should have been simplified already.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2293, __PRETTY_FUNCTION__))
;
2294
2295 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2296 Value *Y = UDiv->getOperand(1);
2297 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
2298 assert(!C.isMaxValue() &&((!C.isMaxValue() && "icmp ugt X, UINT_MAX should have been simplified already."
) ? static_cast<void> (0) : __assert_fail ("!C.isMaxValue() && \"icmp ugt X, UINT_MAX should have been simplified already.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2299, __PRETTY_FUNCTION__))
2299 "icmp ugt X, UINT_MAX should have been simplified already.")((!C.isMaxValue() && "icmp ugt X, UINT_MAX should have been simplified already."
) ? static_cast<void> (0) : __assert_fail ("!C.isMaxValue() && \"icmp ugt X, UINT_MAX should have been simplified already.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2299, __PRETTY_FUNCTION__))
;
2300 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2301 ConstantInt::get(Y->getType(), C2->udiv(C + 1)));
2302 }
2303
2304 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2305 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) {
2306 assert(C != 0 && "icmp ult X, 0 should have been simplified already.")((C != 0 && "icmp ult X, 0 should have been simplified already."
) ? static_cast<void> (0) : __assert_fail ("C != 0 && \"icmp ult X, 0 should have been simplified already.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2306, __PRETTY_FUNCTION__))
;
2307 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2308 ConstantInt::get(Y->getType(), C2->udiv(C)));
2309 }
2310
2311 return nullptr;
2312}
2313
2314/// Fold icmp ({su}div X, Y), C.
2315Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp,
2316 BinaryOperator *Div,
2317 const APInt &C) {
2318 // Fold: icmp pred ([us]div X, C2), C -> range test
2319 // Fold this div into the comparison, producing a range check.
2320 // Determine, based on the divide type, what the range is being
2321 // checked. If there is an overflow on the low or high side, remember
2322 // it, otherwise compute the range [low, hi) bounding the new value.
2323 // See: InsertRangeTest above for the kinds of replacements possible.
2324 const APInt *C2;
2325 if (!match(Div->getOperand(1), m_APInt(C2)))
2326 return nullptr;
2327
2328 // FIXME: If the operand types don't match the type of the divide
2329 // then don't attempt this transform. The code below doesn't have the
2330 // logic to deal with a signed divide and an unsigned compare (and
2331 // vice versa). This is because (x /s C2) <s C produces different
2332 // results than (x /s C2) <u C or (x /u C2) <s C or even
2333 // (x /u C2) <u C. Simply casting the operands and result won't
2334 // work. :( The if statement below tests that condition and bails
2335 // if it finds it.
2336 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2337 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2338 return nullptr;
2339
2340 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2341 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2342 // division-by-constant cases should be present, we can not assert that they
2343 // have happened before we reach this icmp instruction.
2344 if (C2->isNullValue() || C2->isOneValue() ||
2345 (DivIsSigned && C2->isAllOnesValue()))
2346 return nullptr;
2347
2348 // Compute Prod = C * C2. We are essentially solving an equation of
2349 // form X / C2 = C. We solve for X by multiplying C2 and C.
2350 // By solving for X, we can turn this into a range check instead of computing
2351 // a divide.
2352 APInt Prod = C * *C2;
2353
2354 // Determine if the product overflows by seeing if the product is not equal to
2355 // the divide. Make sure we do the same kind of divide as in the LHS
2356 // instruction that we're folding.
2357 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2358
2359 ICmpInst::Predicate Pred = Cmp.getPredicate();
2360
2361 // If the division is known to be exact, then there is no remainder from the
2362 // divide, so the covered range size is unit, otherwise it is the divisor.
2363 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2364
2365 // Figure out the interval that is being checked. For example, a comparison
2366 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2367 // Compute this interval based on the constants involved and the signedness of
2368 // the compare/divide. This computes a half-open interval, keeping track of
2369 // whether either value in the interval overflows. After analysis each
2370 // overflow variable is set to 0 if it's corresponding bound variable is valid
2371 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2372 int LoOverflow = 0, HiOverflow = 0;
2373 APInt LoBound, HiBound;
2374
2375 if (!DivIsSigned) { // udiv
2376 // e.g. X/5 op 3 --> [15, 20)
2377 LoBound = Prod;
2378 HiOverflow = LoOverflow = ProdOV;
2379 if (!HiOverflow) {
2380 // If this is not an exact divide, then many values in the range collapse
2381 // to the same result value.
2382 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2383 }
2384 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2385 if (C.isNullValue()) { // (X / pos) op 0
2386 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2387 LoBound = -(RangeSize - 1);
2388 HiBound = RangeSize;
2389 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2390 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2391 HiOverflow = LoOverflow = ProdOV;
2392 if (!HiOverflow)
2393 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2394 } else { // (X / pos) op neg
2395 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2396 HiBound = Prod + 1;
2397 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2398 if (!LoOverflow) {
2399 APInt DivNeg = -RangeSize;
2400 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2401 }
2402 }
2403 } else if (C2->isNegative()) { // Divisor is < 0.
2404 if (Div->isExact())
2405 RangeSize.negate();
2406 if (C.isNullValue()) { // (X / neg) op 0
2407 // e.g. X/-5 op 0 --> [-4, 5)
2408 LoBound = RangeSize + 1;
2409 HiBound = -RangeSize;
2410 if (HiBound == *C2) { // -INTMIN = INTMIN
2411 HiOverflow = 1; // [INTMIN+1, overflow)
2412 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2413 }
2414 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2415 // e.g. X/-5 op 3 --> [-19, -14)
2416 HiBound = Prod + 1;
2417 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2418 if (!LoOverflow)
2419 LoOverflow = addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
2420 } else { // (X / neg) op neg
2421 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2422 LoOverflow = HiOverflow = ProdOV;
2423 if (!HiOverflow)
2424 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2425 }
2426
2427 // Dividing by a negative swaps the condition. LT <-> GT
2428 Pred = ICmpInst::getSwappedPredicate(Pred);
2429 }
2430
2431 Value *X = Div->getOperand(0);
2432 switch (Pred) {
2433 default: llvm_unreachable("Unhandled icmp opcode!")::llvm::llvm_unreachable_internal("Unhandled icmp opcode!", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2433)
;
2434 case ICmpInst::ICMP_EQ:
2435 if (LoOverflow && HiOverflow)
2436 return replaceInstUsesWith(Cmp, Builder.getFalse());
2437 if (HiOverflow)
2438 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2439 ICmpInst::ICMP_UGE, X,
2440 ConstantInt::get(Div->getType(), LoBound));
2441 if (LoOverflow)
2442 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2443 ICmpInst::ICMP_ULT, X,
2444 ConstantInt::get(Div->getType(), HiBound));
2445 return replaceInstUsesWith(
2446 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2447 case ICmpInst::ICMP_NE:
2448 if (LoOverflow && HiOverflow)
2449 return replaceInstUsesWith(Cmp, Builder.getTrue());
2450 if (HiOverflow)
2451 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2452 ICmpInst::ICMP_ULT, X,
2453 ConstantInt::get(Div->getType(), LoBound));
2454 if (LoOverflow)
2455 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2456 ICmpInst::ICMP_UGE, X,
2457 ConstantInt::get(Div->getType(), HiBound));
2458 return replaceInstUsesWith(Cmp,
2459 insertRangeTest(X, LoBound, HiBound,
2460 DivIsSigned, false));
2461 case ICmpInst::ICMP_ULT:
2462 case ICmpInst::ICMP_SLT:
2463 if (LoOverflow == +1) // Low bound is greater than input range.
2464 return replaceInstUsesWith(Cmp, Builder.getTrue());
2465 if (LoOverflow == -1) // Low bound is less than input range.
2466 return replaceInstUsesWith(Cmp, Builder.getFalse());
2467 return new ICmpInst(Pred, X, ConstantInt::get(Div->getType(), LoBound));
2468 case ICmpInst::ICMP_UGT:
2469 case ICmpInst::ICMP_SGT:
2470 if (HiOverflow == +1) // High bound greater than input range.
2471 return replaceInstUsesWith(Cmp, Builder.getFalse());
2472 if (HiOverflow == -1) // High bound less than input range.
2473 return replaceInstUsesWith(Cmp, Builder.getTrue());
2474 if (Pred == ICmpInst::ICMP_UGT)
2475 return new ICmpInst(ICmpInst::ICMP_UGE, X,
2476 ConstantInt::get(Div->getType(), HiBound));
2477 return new ICmpInst(ICmpInst::ICMP_SGE, X,
2478 ConstantInt::get(Div->getType(), HiBound));
2479 }
2480
2481 return nullptr;
2482}
2483
2484/// Fold icmp (sub X, Y), C.
2485Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp,
2486 BinaryOperator *Sub,
2487 const APInt &C) {
2488 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2489 ICmpInst::Predicate Pred = Cmp.getPredicate();
2490 const APInt *C2;
2491 APInt SubResult;
2492
2493 // icmp eq/ne (sub C, Y), C -> icmp eq/ne Y, 0
2494 if (match(X, m_APInt(C2)) && *C2 == C && Cmp.isEquality())
2495 return new ICmpInst(Cmp.getPredicate(), Y,
2496 ConstantInt::get(Y->getType(), 0));
2497
2498 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2499 if (match(X, m_APInt(C2)) &&
2500 ((Cmp.isUnsigned() && Sub->hasNoUnsignedWrap()) ||
2501 (Cmp.isSigned() && Sub->hasNoSignedWrap())) &&
2502 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2503 return new ICmpInst(Cmp.getSwappedPredicate(), Y,
2504 ConstantInt::get(Y->getType(), SubResult));
2505
2506 // The following transforms are only worth it if the only user of the subtract
2507 // is the icmp.
2508 if (!Sub->hasOneUse())
2509 return nullptr;
2510
2511 if (Sub->hasNoSignedWrap()) {
2512 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2513 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnesValue())
2514 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
2515
2516 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2517 if (Pred == ICmpInst::ICMP_SGT && C.isNullValue())
2518 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2519
2520 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2521 if (Pred == ICmpInst::ICMP_SLT && C.isNullValue())
2522 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2523
2524 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2525 if (Pred == ICmpInst::ICMP_SLT && C.isOneValue())
2526 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2527 }
2528
2529 if (!match(X, m_APInt(C2)))
2530 return nullptr;
2531
2532 // C2 - Y <u C -> (Y | (C - 1)) == C2
2533 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2534 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
2535 (*C2 & (C - 1)) == (C - 1))
2536 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
2537
2538 // C2 - Y >u C -> (Y | C) != C2
2539 // iff C2 & C == C and C + 1 is a power of 2
2540 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
2541 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
2542
2543 return nullptr;
2544}
2545
2546/// Fold icmp (add X, Y), C.
2547Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp,
2548 BinaryOperator *Add,
2549 const APInt &C) {
2550 Value *Y = Add->getOperand(1);
2551 const APInt *C2;
2552 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
2553 return nullptr;
2554
2555 // Fold icmp pred (add X, C2), C.
2556 Value *X = Add->getOperand(0);
2557 Type *Ty = Add->getType();
2558 CmpInst::Predicate Pred = Cmp.getPredicate();
2559
2560 if (!Add->hasOneUse())
2561 return nullptr;
2562
2563 // If the add does not wrap, we can always adjust the compare by subtracting
2564 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
2565 // are canonicalized to SGT/SLT/UGT/ULT.
2566 if ((Add->hasNoSignedWrap() &&
2567 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
2568 (Add->hasNoUnsignedWrap() &&
2569 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
2570 bool Overflow;
2571 APInt NewC =
2572 Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
2573 // If there is overflow, the result must be true or false.
2574 // TODO: Can we assert there is no overflow because InstSimplify always
2575 // handles those cases?
2576 if (!Overflow)
2577 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2578 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2579 }
2580
2581 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
2582 const APInt &Upper = CR.getUpper();
2583 const APInt &Lower = CR.getLower();
2584 if (Cmp.isSigned()) {
2585 if (Lower.isSignMask())
2586 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
2587 if (Upper.isSignMask())
2588 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
2589 } else {
2590 if (Lower.isMinValue())
2591 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
2592 if (Upper.isMinValue())
2593 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
2594 }
2595
2596 // X+C <u C2 -> (X & -C2) == C
2597 // iff C & (C2-1) == 0
2598 // C2 is a power of 2
2599 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
2600 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
2601 ConstantExpr::getNeg(cast<Constant>(Y)));
2602
2603 // X+C >u C2 -> (X & ~C2) != C
2604 // iff C & C2 == 0
2605 // C2+1 is a power of 2
2606 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
2607 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
2608 ConstantExpr::getNeg(cast<Constant>(Y)));
2609
2610 return nullptr;
2611}
2612
2613bool InstCombiner::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
2614 Value *&RHS, ConstantInt *&Less,
2615 ConstantInt *&Equal,
2616 ConstantInt *&Greater) {
2617 // TODO: Generalize this to work with other comparison idioms or ensure
2618 // they get canonicalized into this form.
2619
2620 // select i1 (a == b),
2621 // i32 Equal,
2622 // i32 (select i1 (a < b), i32 Less, i32 Greater)
2623 // where Equal, Less and Greater are placeholders for any three constants.
2624 ICmpInst::Predicate PredA;
2625 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
2626 !ICmpInst::isEquality(PredA))
2627 return false;
2628 Value *EqualVal = SI->getTrueValue();
2629 Value *UnequalVal = SI->getFalseValue();
2630 // We still can get non-canonical predicate here, so canonicalize.
2631 if (PredA == ICmpInst::ICMP_NE)
2632 std::swap(EqualVal, UnequalVal);
2633 if (!match(EqualVal, m_ConstantInt(Equal)))
2634 return false;
2635 ICmpInst::Predicate PredB;
2636 Value *LHS2, *RHS2;
2637 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
2638 m_ConstantInt(Less), m_ConstantInt(Greater))))
2639 return false;
2640 // We can get predicate mismatch here, so canonicalize if possible:
2641 // First, ensure that 'LHS' match.
2642 if (LHS2 != LHS) {
2643 // x sgt y <--> y slt x
2644 std::swap(LHS2, RHS2);
2645 PredB = ICmpInst::getSwappedPredicate(PredB);
2646 }
2647 if (LHS2 != LHS)
2648 return false;
2649 // We also need to canonicalize 'RHS'.
2650 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
2651 // x sgt C-1 <--> x sge C <--> not(x slt C)
2652 auto FlippedStrictness =
2653 getFlippedStrictnessPredicateAndConstant(PredB, cast<Constant>(RHS2));
2654 if (!FlippedStrictness)
2655 return false;
2656 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE && "Sanity check")((FlippedStrictness->first == ICmpInst::ICMP_SGE &&
"Sanity check") ? static_cast<void> (0) : __assert_fail
("FlippedStrictness->first == ICmpInst::ICMP_SGE && \"Sanity check\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2656, __PRETTY_FUNCTION__))
;
2657 RHS2 = FlippedStrictness->second;
2658 // And kind-of perform the result swap.
2659 std::swap(Less, Greater);
2660 PredB = ICmpInst::ICMP_SLT;
2661 }
2662 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
2663}
2664
2665Instruction *InstCombiner::foldICmpSelectConstant(ICmpInst &Cmp,
2666 SelectInst *Select,
2667 ConstantInt *C) {
2668
2669 assert(C && "Cmp RHS should be a constant int!")((C && "Cmp RHS should be a constant int!") ? static_cast
<void> (0) : __assert_fail ("C && \"Cmp RHS should be a constant int!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2669, __PRETTY_FUNCTION__))
;
2670 // If we're testing a constant value against the result of a three way
2671 // comparison, the result can be expressed directly in terms of the
2672 // original values being compared. Note: We could possibly be more
2673 // aggressive here and remove the hasOneUse test. The original select is
2674 // really likely to simplify or sink when we remove a test of the result.
2675 Value *OrigLHS, *OrigRHS;
2676 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2677 if (Cmp.hasOneUse() &&
2678 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
2679 C3GreaterThan)) {
2680 assert(C1LessThan && C2Equal && C3GreaterThan)((C1LessThan && C2Equal && C3GreaterThan) ? static_cast
<void> (0) : __assert_fail ("C1LessThan && C2Equal && C3GreaterThan"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 2680, __PRETTY_FUNCTION__))
;
2681
2682 bool TrueWhenLessThan =
2683 ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
2684 ->isAllOnesValue();
2685 bool TrueWhenEqual =
2686 ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
2687 ->isAllOnesValue();
2688 bool TrueWhenGreaterThan =
2689 ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
2690 ->isAllOnesValue();
2691
2692 // This generates the new instruction that will replace the original Cmp
2693 // Instruction. Instead of enumerating the various combinations when
2694 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
2695 // false, we rely on chaining of ORs and future passes of InstCombine to
2696 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
2697
2698 // When none of the three constants satisfy the predicate for the RHS (C),
2699 // the entire original Cmp can be simplified to a false.
2700 Value *Cond = Builder.getFalse();
2701 if (TrueWhenLessThan)
2702 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT,
2703 OrigLHS, OrigRHS));
2704 if (TrueWhenEqual)
2705 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ,
2706 OrigLHS, OrigRHS));
2707 if (TrueWhenGreaterThan)
2708 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT,
2709 OrigLHS, OrigRHS));
2710
2711 return replaceInstUsesWith(Cmp, Cond);
2712 }
2713 return nullptr;
2714}
2715
2716static Instruction *foldICmpBitCast(ICmpInst &Cmp,
2717 InstCombiner::BuilderTy &Builder) {
2718 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
2719 if (!Bitcast)
2720 return nullptr;
2721
2722 ICmpInst::Predicate Pred = Cmp.getPredicate();
2723 Value *Op1 = Cmp.getOperand(1);
2724 Value *BCSrcOp = Bitcast->getOperand(0);
2725
2726 // Make sure the bitcast doesn't change the number of vector elements.
2727 if (Bitcast->getSrcTy()->getScalarSizeInBits() ==
2728 Bitcast->getDestTy()->getScalarSizeInBits()) {
2729 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
2730 Value *X;
2731 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
2732 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
2733 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
2734 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
2735 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
2736 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
2737 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
2738 match(Op1, m_Zero()))
2739 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2740
2741 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
2742 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
2743 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
2744
2745 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
2746 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
2747 return new ICmpInst(Pred, X,
2748 ConstantInt::getAllOnesValue(X->getType()));
2749 }
2750
2751 // Zero-equality checks are preserved through unsigned floating-point casts:
2752 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
2753 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
2754 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
2755 if (Cmp.isEquality() && match(Op1, m_Zero()))
2756 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2757 }
2758
2759 // Test to see if the operands of the icmp are casted versions of other
2760 // values. If the ptr->ptr cast can be stripped off both arguments, do so.
2761 if (Bitcast->getType()->isPointerTy() &&
2762 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2763 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2764 // so eliminate it as well.
2765 if (auto *BC2 = dyn_cast<BitCastInst>(Op1))
2766 Op1 = BC2->getOperand(0);
2767
2768 Op1 = Builder.CreateBitCast(Op1, BCSrcOp->getType());
2769 return new ICmpInst(Pred, BCSrcOp, Op1);
2770 }
2771
2772 // Folding: icmp <pred> iN X, C
2773 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
2774 // and C is a splat of a K-bit pattern
2775 // and SC is a constant vector = <C', C', C', ..., C'>
2776 // Into:
2777 // %E = extractelement <M x iK> %vec, i32 C'
2778 // icmp <pred> iK %E, trunc(C)
2779 const APInt *C;
2780 if (!match(Cmp.getOperand(1), m_APInt(C)) ||
2781 !Bitcast->getType()->isIntegerTy() ||
2782 !Bitcast->getSrcTy()->isIntOrIntVectorTy())
2783 return nullptr;
2784
2785 Value *Vec;
2786 Constant *Mask;
2787 if (match(BCSrcOp,
2788 m_ShuffleVector(m_Value(Vec), m_Undef(), m_Constant(Mask)))) {
2789 // Check whether every element of Mask is the same constant
2790 if (auto *Elem = dyn_cast_or_null<ConstantInt>(Mask->getSplatValue())) {
2791 auto *VecTy = cast<VectorType>(BCSrcOp->getType());
2792 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
2793 if (C->isSplat(EltTy->getBitWidth())) {
2794 // Fold the icmp based on the value of C
2795 // If C is M copies of an iK sized bit pattern,
2796 // then:
2797 // => %E = extractelement <N x iK> %vec, i32 Elem
2798 // icmp <pred> iK %SplatVal, <pattern>
2799 Value *Extract = Builder.CreateExtractElement(Vec, Elem);
2800 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
2801 return new ICmpInst(Pred, Extract, NewC);
2802 }
2803 }
2804 }
2805 return nullptr;
2806}
2807
2808/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
2809/// where X is some kind of instruction.
2810Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) {
2811 const APInt *C;
2812 if (!match(Cmp.getOperand(1), m_APInt(C)))
2813 return nullptr;
2814
2815 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0))) {
2816 switch (BO->getOpcode()) {
2817 case Instruction::Xor:
2818 if (Instruction *I = foldICmpXorConstant(Cmp, BO, *C))
2819 return I;
2820 break;
2821 case Instruction::And:
2822 if (Instruction *I = foldICmpAndConstant(Cmp, BO, *C))
2823 return I;
2824 break;
2825 case Instruction::Or:
2826 if (Instruction *I = foldICmpOrConstant(Cmp, BO, *C))
2827 return I;
2828 break;
2829 case Instruction::Mul:
2830 if (Instruction *I = foldICmpMulConstant(Cmp, BO, *C))
2831 return I;
2832 break;
2833 case Instruction::Shl:
2834 if (Instruction *I = foldICmpShlConstant(Cmp, BO, *C))
2835 return I;
2836 break;
2837 case Instruction::LShr:
2838 case Instruction::AShr:
2839 if (Instruction *I = foldICmpShrConstant(Cmp, BO, *C))
2840 return I;
2841 break;
2842 case Instruction::SRem:
2843 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, *C))
2844 return I;
2845 break;
2846 case Instruction::UDiv:
2847 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, *C))
2848 return I;
2849 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2850 case Instruction::SDiv:
2851 if (Instruction *I = foldICmpDivConstant(Cmp, BO, *C))
2852 return I;
2853 break;
2854 case Instruction::Sub:
2855 if (Instruction *I = foldICmpSubConstant(Cmp, BO, *C))
2856 return I;
2857 break;
2858 case Instruction::Add:
2859 if (Instruction *I = foldICmpAddConstant(Cmp, BO, *C))
2860 return I;
2861 break;
2862 default:
2863 break;
2864 }
2865 // TODO: These folds could be refactored to be part of the above calls.
2866 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, *C))
2867 return I;
2868 }
2869
2870 // Match against CmpInst LHS being instructions other than binary operators.
2871
2872 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0))) {
2873 // For now, we only support constant integers while folding the
2874 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
2875 // similar to the cases handled by binary ops above.
2876 if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
2877 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
2878 return I;
2879 }
2880
2881 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0))) {
2882 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
2883 return I;
2884 }
2885
2886 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
2887 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
2888 return I;
2889
2890 return nullptr;
2891}
2892
2893/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
2894/// icmp eq/ne BO, C.
2895Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
2896 BinaryOperator *BO,
2897 const APInt &C) {
2898 // TODO: Some of these folds could work with arbitrary constants, but this
2899 // function is limited to scalar and vector splat constants.
2900 if (!Cmp.isEquality())
2901 return nullptr;
2902
2903 ICmpInst::Predicate Pred = Cmp.getPredicate();
2904 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
2905 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
2906 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2907
2908 switch (BO->getOpcode()) {
2909 case Instruction::SRem:
2910 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2911 if (C.isNullValue() && BO->hasOneUse()) {
2912 const APInt *BOC;
2913 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
2914 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
2915 return new ICmpInst(Pred, NewRem,
2916 Constant::getNullValue(BO->getType()));
2917 }
2918 }
2919 break;
2920 case Instruction::Add: {
2921 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2922 const APInt *BOC;
2923 if (match(BOp1, m_APInt(BOC))) {
2924 if (BO->hasOneUse()) {
2925 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
2926 return new ICmpInst(Pred, BOp0, SubC);
2927 }
2928 } else if (C.isNullValue()) {
2929 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2930 // efficiently invertible, or if the add has just this one use.
2931 if (Value *NegVal = dyn_castNegVal(BOp1))
2932 return new ICmpInst(Pred, BOp0, NegVal);
2933 if (Value *NegVal = dyn_castNegVal(BOp0))
2934 return new ICmpInst(Pred, NegVal, BOp1);
2935 if (BO->hasOneUse()) {
2936 Value *Neg = Builder.CreateNeg(BOp1);
2937 Neg->takeName(BO);
2938 return new ICmpInst(Pred, BOp0, Neg);
2939 }
2940 }
2941 break;
2942 }
2943 case Instruction::Xor:
2944 if (BO->hasOneUse()) {
2945 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
2946 // For the xor case, we can xor two constants together, eliminating
2947 // the explicit xor.
2948 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
2949 } else if (C.isNullValue()) {
2950 // Replace ((xor A, B) != 0) with (A != B)
2951 return new ICmpInst(Pred, BOp0, BOp1);
2952 }
2953 }
2954 break;
2955 case Instruction::Sub:
2956 if (BO->hasOneUse()) {
2957 const APInt *BOC;
2958 if (match(BOp0, m_APInt(BOC))) {
2959 // Replace ((sub BOC, B) != C) with (B != BOC-C).
2960 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
2961 return new ICmpInst(Pred, BOp1, SubC);
2962 } else if (C.isNullValue()) {
2963 // Replace ((sub A, B) != 0) with (A != B).
2964 return new ICmpInst(Pred, BOp0, BOp1);
2965 }
2966 }
2967 break;
2968 case Instruction::Or: {
2969 const APInt *BOC;
2970 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
2971 // Comparing if all bits outside of a constant mask are set?
2972 // Replace (X | C) == -1 with (X & ~C) == ~C.
2973 // This removes the -1 constant.
2974 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2975 Value *And = Builder.CreateAnd(BOp0, NotBOC);
2976 return new ICmpInst(Pred, And, NotBOC);
2977 }
2978 break;
2979 }
2980 case Instruction::And: {
2981 const APInt *BOC;
2982 if (match(BOp1, m_APInt(BOC))) {
2983 // If we have ((X & C) == C), turn it into ((X & C) != 0).
2984 if (C == *BOC && C.isPowerOf2())
2985 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
2986 BO, Constant::getNullValue(RHS->getType()));
2987 }
2988 break;
2989 }
2990 case Instruction::Mul:
2991 if (C.isNullValue() && BO->hasNoSignedWrap()) {
2992 const APInt *BOC;
2993 if (match(BOp1, m_APInt(BOC)) && !BOC->isNullValue()) {
2994 // The trivial case (mul X, 0) is handled by InstSimplify.
2995 // General case : (mul X, C) != 0 iff X != 0
2996 // (mul X, C) == 0 iff X == 0
2997 return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType()));
2998 }
2999 }
3000 break;
3001 case Instruction::UDiv:
3002 if (C.isNullValue()) {
3003 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3004 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3005 return new ICmpInst(NewPred, BOp1, BOp0);
3006 }
3007 break;
3008 default:
3009 break;
3010 }
3011 return nullptr;
3012}
3013
3014/// Fold an equality icmp with LLVM intrinsic and constant operand.
3015Instruction *InstCombiner::foldICmpEqIntrinsicWithConstant(ICmpInst &Cmp,
3016 IntrinsicInst *II,
3017 const APInt &C) {
3018 Type *Ty = II->getType();
3019 unsigned BitWidth = C.getBitWidth();
3020 switch (II->getIntrinsicID()) {
3021 case Intrinsic::bswap:
3022 Worklist.Add(II);
3023 Cmp.setOperand(0, II->getArgOperand(0));
3024 Cmp.setOperand(1, ConstantInt::get(Ty, C.byteSwap()));
3025 return &Cmp;
3026
3027 case Intrinsic::ctlz:
3028 case Intrinsic::cttz: {
3029 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3030 if (C == BitWidth) {
3031 Worklist.Add(II);
3032 Cmp.setOperand(0, II->getArgOperand(0));
3033 Cmp.setOperand(1, ConstantInt::getNullValue(Ty));
3034 return &Cmp;
3035 }
3036
3037 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3038 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3039 // Limit to one use to ensure we don't increase instruction count.
3040 unsigned Num = C.getLimitedValue(BitWidth);
3041 if (Num != BitWidth && II->hasOneUse()) {
3042 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3043 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3044 : APInt::getHighBitsSet(BitWidth, Num + 1);
3045 APInt Mask2 = IsTrailing
3046 ? APInt::getOneBitSet(BitWidth, Num)
3047 : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3048 Cmp.setOperand(0, Builder.CreateAnd(II->getArgOperand(0), Mask1));
3049 Cmp.setOperand(1, ConstantInt::get(Ty, Mask2));
3050 Worklist.Add(II);
3051 return &Cmp;
3052 }
3053 break;
3054 }
3055
3056 case Intrinsic::ctpop: {
3057 // popcount(A) == 0 -> A == 0 and likewise for !=
3058 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3059 bool IsZero = C.isNullValue();
3060 if (IsZero || C == BitWidth) {
3061 Worklist.Add(II);
3062 Cmp.setOperand(0, II->getArgOperand(0));
3063 auto *NewOp =
3064 IsZero ? Constant::getNullValue(Ty) : Constant::getAllOnesValue(Ty);
3065 Cmp.setOperand(1, NewOp);
3066 return &Cmp;
3067 }
3068 break;
3069 }
3070 default:
3071 break;
3072 }
3073
3074 return nullptr;
3075}
3076
3077/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
3078Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
3079 IntrinsicInst *II,
3080 const APInt &C) {
3081 if (Cmp.isEquality())
3082 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
3083
3084 Type *Ty = II->getType();
3085 unsigned BitWidth = C.getBitWidth();
3086 switch (II->getIntrinsicID()) {
3087 case Intrinsic::ctlz: {
3088 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
3089 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3090 unsigned Num = C.getLimitedValue();
3091 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3092 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
3093 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3094 }
3095
3096 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
3097 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT &&
3098 C.uge(1) && C.ule(BitWidth)) {
3099 unsigned Num = C.getLimitedValue();
3100 APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);
3101 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
3102 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3103 }
3104 break;
3105 }
3106 case Intrinsic::cttz: {
3107 // Limit to one use to ensure we don't increase instruction count.
3108 if (!II->hasOneUse())
3109 return nullptr;
3110
3111 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
3112 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3113 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
3114 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
3115 Builder.CreateAnd(II->getArgOperand(0), Mask),
3116 ConstantInt::getNullValue(Ty));
3117 }
3118
3119 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
3120 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT &&
3121 C.uge(1) && C.ule(BitWidth)) {
3122 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
3123 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
3124 Builder.CreateAnd(II->getArgOperand(0), Mask),
3125 ConstantInt::getNullValue(Ty));
3126 }
3127 break;
3128 }
3129 default:
3130 break;
3131 }
3132
3133 return nullptr;
3134}
3135
3136/// Handle icmp with constant (but not simple integer constant) RHS.
3137Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) {
3138 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139 Constant *RHSC = dyn_cast<Constant>(Op1);
3140 Instruction *LHSI = dyn_cast<Instruction>(Op0);
3141 if (!RHSC || !LHSI)
3142 return nullptr;
3143
3144 switch (LHSI->getOpcode()) {
3145 case Instruction::GetElementPtr:
3146 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3147 if (RHSC->isNullValue() &&
3148 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3149 return new ICmpInst(
3150 I.getPredicate(), LHSI->getOperand(0),
3151 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3152 break;
3153 case Instruction::PHI:
3154 // Only fold icmp into the PHI if the phi and icmp are in the same
3155 // block. If in the same block, we're encouraging jump threading. If
3156 // not, we are just pessimizing the code by making an i1 phi.
3157 if (LHSI->getParent() == I.getParent())
3158 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3159 return NV;
3160 break;
3161 case Instruction::Select: {
3162 // If either operand of the select is a constant, we can fold the
3163 // comparison into the select arms, which will cause one to be
3164 // constant folded and the select turned into a bitwise or.
3165 Value *Op1 = nullptr, *Op2 = nullptr;
3166 ConstantInt *CI = nullptr;
3167 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3168 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3169 CI = dyn_cast<ConstantInt>(Op1);
3170 }
3171 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3172 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3173 CI = dyn_cast<ConstantInt>(Op2);
3174 }
3175
3176 // We only want to perform this transformation if it will not lead to
3177 // additional code. This is true if either both sides of the select
3178 // fold to a constant (in which case the icmp is replaced with a select
3179 // which will usually simplify) or this is the only user of the
3180 // select (in which case we are trading a select+icmp for a simpler
3181 // select+icmp) or all uses of the select can be replaced based on
3182 // dominance information ("Global cases").
3183 bool Transform = false;
3184 if (Op1 && Op2)
3185 Transform = true;
3186 else if (Op1 || Op2) {
3187 // Local case
3188 if (LHSI->hasOneUse())
3189 Transform = true;
3190 // Global cases
3191 else if (CI && !CI->isZero())
3192 // When Op1 is constant try replacing select with second operand.
3193 // Otherwise Op2 is constant and try replacing select with first
3194 // operand.
3195 Transform =
3196 replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1);
3197 }
3198 if (Transform) {
3199 if (!Op1)
3200 Op1 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC,
3201 I.getName());
3202 if (!Op2)
3203 Op2 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC,
3204 I.getName());
3205 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3206 }
3207 break;
3208 }
3209 case Instruction::IntToPtr:
3210 // icmp pred inttoptr(X), null -> icmp pred X, 0
3211 if (RHSC->isNullValue() &&
3212 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3213 return new ICmpInst(
3214 I.getPredicate(), LHSI->getOperand(0),
3215 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3216 break;
3217
3218 case Instruction::Load:
3219 // Try to optimize things like "A[i] > 4" to index computations.
3220 if (GetElementPtrInst *GEP =
3221 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3222 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3223 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3224 !cast<LoadInst>(LHSI)->isVolatile())
3225 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
3226 return Res;
3227 }
3228 break;
3229 }
3230
3231 return nullptr;
3232}
3233
3234/// Some comparisons can be simplified.
3235/// In this case, we are looking for comparisons that look like
3236/// a check for a lossy truncation.
3237/// Folds:
3238/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
3239/// Where Mask is some pattern that produces all-ones in low bits:
3240/// (-1 >> y)
3241/// ((-1 << y) >> y) <- non-canonical, has extra uses
3242/// ~(-1 << y)
3243/// ((1 << y) + (-1)) <- non-canonical, has extra uses
3244/// The Mask can be a constant, too.
3245/// For some predicates, the operands are commutative.
3246/// For others, x can only be on a specific side.
3247static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I,
3248 InstCombiner::BuilderTy &Builder) {
3249 ICmpInst::Predicate SrcPred;
3250 Value *X, *M, *Y;
3251 auto m_VariableMask = m_CombineOr(
3252 m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())),
3253 m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
3254 m_CombineOr(m_LShr(m_AllOnes(), m_Value()),
3255 m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y))));
3256 auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
3257 if (!match(&I, m_c_ICmp(SrcPred,
3258 m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)),
3259 m_Deferred(X))))
3260 return nullptr;
3261
3262 ICmpInst::Predicate DstPred;
3263 switch (SrcPred) {
3264 case ICmpInst::Predicate::ICMP_EQ:
3265 // x & (-1 >> y) == x -> x u<= (-1 >> y)
3266 DstPred = ICmpInst::Predicate::ICMP_ULE;
3267 break;
3268 case ICmpInst::Predicate::ICMP_NE:
3269 // x & (-1 >> y) != x -> x u> (-1 >> y)
3270 DstPred = ICmpInst::Predicate::ICMP_UGT;
3271 break;
3272 case ICmpInst::Predicate::ICMP_UGT:
3273 // x u> x & (-1 >> y) -> x u> (-1 >> y)
3274 assert(X == I.getOperand(0) && "instsimplify took care of commut. variant")((X == I.getOperand(0) && "instsimplify took care of commut. variant"
) ? static_cast<void> (0) : __assert_fail ("X == I.getOperand(0) && \"instsimplify took care of commut. variant\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3274, __PRETTY_FUNCTION__))
;
3275 DstPred = ICmpInst::Predicate::ICMP_UGT;
3276 break;
3277 case ICmpInst::Predicate::ICMP_UGE:
3278 // x & (-1 >> y) u>= x -> x u<= (-1 >> y)
3279 assert(X == I.getOperand(1) && "instsimplify took care of commut. variant")((X == I.getOperand(1) && "instsimplify took care of commut. variant"
) ? static_cast<void> (0) : __assert_fail ("X == I.getOperand(1) && \"instsimplify took care of commut. variant\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3279, __PRETTY_FUNCTION__))
;
3280 DstPred = ICmpInst::Predicate::ICMP_ULE;
3281 break;
3282 case ICmpInst::Predicate::ICMP_ULT:
3283 // x & (-1 >> y) u< x -> x u> (-1 >> y)
3284 assert(X == I.getOperand(1) && "instsimplify took care of commut. variant")((X == I.getOperand(1) && "instsimplify took care of commut. variant"
) ? static_cast<void> (0) : __assert_fail ("X == I.getOperand(1) && \"instsimplify took care of commut. variant\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3284, __PRETTY_FUNCTION__))
;
3285 DstPred = ICmpInst::Predicate::ICMP_UGT;
3286 break;
3287 case ICmpInst::Predicate::ICMP_ULE:
3288 // x u<= x & (-1 >> y) -> x u<= (-1 >> y)
3289 assert(X == I.getOperand(0) && "instsimplify took care of commut. variant")((X == I.getOperand(0) && "instsimplify took care of commut. variant"
) ? static_cast<void> (0) : __assert_fail ("X == I.getOperand(0) && \"instsimplify took care of commut. variant\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3289, __PRETTY_FUNCTION__))
;
3290 DstPred = ICmpInst::Predicate::ICMP_ULE;
3291 break;
3292 case ICmpInst::Predicate::ICMP_SGT:
3293 // x s> x & (-1 >> y) -> x s> (-1 >> y)
3294 if (X != I.getOperand(0)) // X must be on LHS of comparison!
3295 return nullptr; // Ignore the other case.
3296 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3297 return nullptr;
3298 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3299 return nullptr;
3300 DstPred = ICmpInst::Predicate::ICMP_SGT;
3301 break;
3302 case ICmpInst::Predicate::ICMP_SGE:
3303 // x & (-1 >> y) s>= x -> x s<= (-1 >> y)
3304 if (X != I.getOperand(1)) // X must be on RHS of comparison!
3305 return nullptr; // Ignore the other case.
3306 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3307 return nullptr;
3308 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3309 return nullptr;
3310 DstPred = ICmpInst::Predicate::ICMP_SLE;
3311 break;
3312 case ICmpInst::Predicate::ICMP_SLT:
3313 // x & (-1 >> y) s< x -> x s> (-1 >> y)
3314 if (X != I.getOperand(1)) // X must be on RHS of comparison!
3315 return nullptr; // Ignore the other case.
3316 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3317 return nullptr;
3318 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3319 return nullptr;
3320 DstPred = ICmpInst::Predicate::ICMP_SGT;
3321 break;
3322 case ICmpInst::Predicate::ICMP_SLE:
3323 // x s<= x & (-1 >> y) -> x s<= (-1 >> y)
3324 if (X != I.getOperand(0)) // X must be on LHS of comparison!
3325 return nullptr; // Ignore the other case.
3326 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3327 return nullptr;
3328 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3329 return nullptr;
3330 DstPred = ICmpInst::Predicate::ICMP_SLE;
3331 break;
3332 default:
3333 llvm_unreachable("All possible folds are handled.")::llvm::llvm_unreachable_internal("All possible folds are handled."
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3333)
;
3334 }
3335
3336 return Builder.CreateICmp(DstPred, X, M);
3337}
3338
3339/// Some comparisons can be simplified.
3340/// In this case, we are looking for comparisons that look like
3341/// a check for a lossy signed truncation.
3342/// Folds: (MaskedBits is a constant.)
3343/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
3344/// Into:
3345/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
3346/// Where KeptBits = bitwidth(%x) - MaskedBits
3347static Value *
3348foldICmpWithTruncSignExtendedVal(ICmpInst &I,
3349 InstCombiner::BuilderTy &Builder) {
3350 ICmpInst::Predicate SrcPred;
3351 Value *X;
3352 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
3353 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
3354 if (!match(&I, m_c_ICmp(SrcPred,
3355 m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)),
3356 m_APInt(C1))),
3357 m_Deferred(X))))
3358 return nullptr;
3359
3360 // Potential handling of non-splats: for each element:
3361 // * if both are undef, replace with constant 0.
3362 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
3363 // * if both are not undef, and are different, bailout.
3364 // * else, only one is undef, then pick the non-undef one.
3365
3366 // The shift amount must be equal.
3367 if (*C0 != *C1)
3368 return nullptr;
3369 const APInt &MaskedBits = *C0;
3370 assert(MaskedBits != 0 && "shift by zero should be folded away already.")((MaskedBits != 0 && "shift by zero should be folded away already."
) ? static_cast<void> (0) : __assert_fail ("MaskedBits != 0 && \"shift by zero should be folded away already.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3370, __PRETTY_FUNCTION__))
;
3371
3372 ICmpInst::Predicate DstPred;
3373 switch (SrcPred) {
3374 case ICmpInst::Predicate::ICMP_EQ:
3375 // ((%x << MaskedBits) a>> MaskedBits) == %x
3376 // =>
3377 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
3378 DstPred = ICmpInst::Predicate::ICMP_ULT;
3379 break;
3380 case ICmpInst::Predicate::ICMP_NE:
3381 // ((%x << MaskedBits) a>> MaskedBits) != %x
3382 // =>
3383 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
3384 DstPred = ICmpInst::Predicate::ICMP_UGE;
3385 break;
3386 // FIXME: are more folds possible?
3387 default:
3388 return nullptr;
3389 }
3390
3391 auto *XType = X->getType();
3392 const unsigned XBitWidth = XType->getScalarSizeInBits();
3393 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
3394 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched")((BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched"
) ? static_cast<void> (0) : __assert_fail ("BitWidth.ugt(MaskedBits) && \"shifts should leave some bits untouched\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3394, __PRETTY_FUNCTION__))
;
3395
3396 // KeptBits = bitwidth(%x) - MaskedBits
3397 const APInt KeptBits = BitWidth - MaskedBits;
3398 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable")((KeptBits.ugt(0) && KeptBits.ult(BitWidth) &&
"unreachable") ? static_cast<void> (0) : __assert_fail
("KeptBits.ugt(0) && KeptBits.ult(BitWidth) && \"unreachable\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3398, __PRETTY_FUNCTION__))
;
3399 // ICmpCst = (1 << KeptBits)
3400 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
3401 assert(ICmpCst.isPowerOf2())((ICmpCst.isPowerOf2()) ? static_cast<void> (0) : __assert_fail
("ICmpCst.isPowerOf2()", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3401, __PRETTY_FUNCTION__))
;
3402 // AddCst = (1 << (KeptBits-1))
3403 const APInt AddCst = ICmpCst.lshr(1);
3404 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2())((AddCst.ult(ICmpCst) && AddCst.isPowerOf2()) ? static_cast
<void> (0) : __assert_fail ("AddCst.ult(ICmpCst) && AddCst.isPowerOf2()"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3404, __PRETTY_FUNCTION__))
;
3405
3406 // T0 = add %x, AddCst
3407 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
3408 // T1 = T0 DstPred ICmpCst
3409 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
3410
3411 return T1;
3412}
3413
3414// Given pattern:
3415// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3416// we should move shifts to the same hand of 'and', i.e. rewrite as
3417// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3418// We are only interested in opposite logical shifts here.
3419// One of the shifts can be truncated.
3420// If we can, we want to end up creating 'lshr' shift.
3421static Value *
3422foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
3423 InstCombiner::BuilderTy &Builder) {
3424 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
3425 !I.getOperand(0)->hasOneUse())
3426 return nullptr;
3427
3428 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
3429
3430 // Look for an 'and' of two logical shifts, one of which may be truncated.
3431 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
3432 Instruction *XShift, *MaybeTruncation, *YShift;
3433 if (!match(
3434 I.getOperand(0),
3435 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
3436 m_CombineAnd(m_TruncOrSelf(m_CombineAnd(
3437 m_AnyLogicalShift, m_Instruction(YShift))),
3438 m_Instruction(MaybeTruncation)))))
3439 return nullptr;
3440
3441 // We potentially looked past 'trunc', but only when matching YShift,
3442 // therefore YShift must have the widest type.
3443 Instruction *WidestShift = YShift;
3444 // Therefore XShift must have the shallowest type.
3445 // Or they both have identical types if there was no truncation.
3446 Instruction *NarrowestShift = XShift;
3447
3448 Type *WidestTy = WidestShift->getType();
3449 assert(NarrowestShift->getType() == I.getOperand(0)->getType() &&((NarrowestShift->getType() == I.getOperand(0)->getType
() && "We did not look past any shifts while matching XShift though."
) ? static_cast<void> (0) : __assert_fail ("NarrowestShift->getType() == I.getOperand(0)->getType() && \"We did not look past any shifts while matching XShift though.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3450, __PRETTY_FUNCTION__))
3450 "We did not look past any shifts while matching XShift though.")((NarrowestShift->getType() == I.getOperand(0)->getType
() && "We did not look past any shifts while matching XShift though."
) ? static_cast<void> (0) : __assert_fail ("NarrowestShift->getType() == I.getOperand(0)->getType() && \"We did not look past any shifts while matching XShift though.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3450, __PRETTY_FUNCTION__))
;
3451 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
3452
3453 // If YShift is a 'lshr', swap the shifts around.
3454 if (match(YShift, m_LShr(m_Value(), m_Value())))
3455 std::swap(XShift, YShift);
3456
3457 // The shifts must be in opposite directions.
3458 auto XShiftOpcode = XShift->getOpcode();
3459 if (XShiftOpcode == YShift->getOpcode())
3460 return nullptr; // Do not care about same-direction shifts here.
3461
3462 Value *X, *XShAmt, *Y, *YShAmt;
3463 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
3464 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
3465
3466 // If one of the values being shifted is a constant, then we will end with
3467 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
3468 // however, we will need to ensure that we won't increase instruction count.
3469 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
3470 // At least one of the hands of the 'and' should be one-use shift.
3471 if (!match(I.getOperand(0),
3472 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
3473 return nullptr;
3474 if (HadTrunc) {
3475 // Due to the 'trunc', we will need to widen X. For that either the old
3476 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
3477 if (!MaybeTruncation->hasOneUse() &&
3478 !NarrowestShift->getOperand(1)->hasOneUse())
3479 return nullptr;
3480 }
3481 }
3482
3483 // We have two shift amounts from two different shifts. The types of those
3484 // shift amounts may not match. If that's the case let's bailout now.
3485 if (XShAmt->getType() != YShAmt->getType())
3486 return nullptr;
3487
3488 // Can we fold (XShAmt+YShAmt) ?
3489 auto *NewShAmt = dyn_cast_or_null<Constant>(
3490 SimplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
3491 /*isNUW=*/false, SQ.getWithInstruction(&I)));
3492 if (!NewShAmt)
3493 return nullptr;
3494 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy);
3495 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
3496
3497 // Is the new shift amount smaller than the bit width?
3498 // FIXME: could also rely on ConstantRange.
3499 if (!match(NewShAmt,
3500 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
3501 APInt(WidestBitWidth, WidestBitWidth))))
3502 return nullptr;
3503
3504 // An extra legality check is needed if we had trunc-of-lshr.
3505 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
3506 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
3507 WidestShift]() {
3508 // It isn't obvious whether it's worth it to analyze non-constants here.
3509 // Also, let's basically give up on non-splat cases, pessimizing vectors.
3510 // If *any* of these preconditions matches we can perform the fold.
3511 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
3512 ? NewShAmt->getSplatValue()
3513 : NewShAmt;
3514 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
3515 if (NewShAmtSplat &&
3516 (NewShAmtSplat->isNullValue() ||
3517 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
3518 return true;
3519 // We consider *min* leading zeros so a single outlier
3520 // blocks the transform as opposed to allowing it.
3521 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
3522 KnownBits Known = computeKnownBits(C, SQ.DL);
3523 unsigned MinLeadZero = Known.countMinLeadingZeros();
3524 // If the value being shifted has at most lowest bit set we can fold.
3525 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
3526 if (MaxActiveBits <= 1)
3527 return true;
3528 // Precondition: NewShAmt u<= countLeadingZeros(C)
3529 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
3530 return true;
3531 }
3532 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
3533 KnownBits Known = computeKnownBits(C, SQ.DL);
3534 unsigned MinLeadZero = Known.countMinLeadingZeros();
3535 // If the value being shifted has at most lowest bit set we can fold.
3536 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
3537 if (MaxActiveBits <= 1)
3538 return true;
3539 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
3540 if (NewShAmtSplat) {
3541 APInt AdjNewShAmt =
3542 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
3543 if (AdjNewShAmt.ule(MinLeadZero))
3544 return true;
3545 }
3546 }
3547 return false; // Can't tell if it's ok.
3548 };
3549 if (!CanFold())
3550 return nullptr;
3551 }
3552
3553 // All good, we can do this fold.
3554 X = Builder.CreateZExt(X, WidestTy);
3555 Y = Builder.CreateZExt(Y, WidestTy);
3556 // The shift is the same that was for X.
3557 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
3558 ? Builder.CreateLShr(X, NewShAmt)
3559 : Builder.CreateShl(X, NewShAmt);
3560 Value *T1 = Builder.CreateAnd(T0, Y);
3561 return Builder.CreateICmp(I.getPredicate(), T1,
3562 Constant::getNullValue(WidestTy));
3563}
3564
3565/// Fold
3566/// (-1 u/ x) u< y
3567/// ((x * y) u/ x) != y
3568/// to
3569/// @llvm.umul.with.overflow(x, y) plus extraction of overflow bit
3570/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
3571/// will mean that we are looking for the opposite answer.
3572Value *InstCombiner::foldUnsignedMultiplicationOverflowCheck(ICmpInst &I) {
3573 ICmpInst::Predicate Pred;
3574 Value *X, *Y;
3575 Instruction *Mul;
3576 bool NeedNegation;
3577 // Look for: (-1 u/ x) u</u>= y
3578 if (!I.isEquality() &&
3579 match(&I, m_c_ICmp(Pred, m_OneUse(m_UDiv(m_AllOnes(), m_Value(X))),
3580 m_Value(Y)))) {
3581 Mul = nullptr;
3582 // Canonicalize as-if y was on RHS.
3583 if (I.getOperand(1) != Y)
3584 Pred = I.getSwappedPredicate();
3585
3586 // Are we checking that overflow does not happen, or does happen?
3587 switch (Pred) {
3588 case ICmpInst::Predicate::ICMP_ULT:
3589 NeedNegation = false;
3590 break; // OK
3591 case ICmpInst::Predicate::ICMP_UGE:
3592 NeedNegation = true;
3593 break; // OK
3594 default:
3595 return nullptr; // Wrong predicate.
3596 }
3597 } else // Look for: ((x * y) u/ x) !=/== y
3598 if (I.isEquality() &&
3599 match(&I, m_c_ICmp(Pred, m_Value(Y),
3600 m_OneUse(m_UDiv(m_CombineAnd(m_c_Mul(m_Deferred(Y),
3601 m_Value(X)),
3602 m_Instruction(Mul)),
3603 m_Deferred(X)))))) {
3604 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
3605 } else
3606 return nullptr;
3607
3608 BuilderTy::InsertPointGuard Guard(Builder);
3609 // If the pattern included (x * y), we'll want to insert new instructions
3610 // right before that original multiplication so that we can replace it.
3611 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
3612 if (MulHadOtherUses)
3613 Builder.SetInsertPoint(Mul);
3614
3615 Function *F = Intrinsic::getDeclaration(
3616 I.getModule(), Intrinsic::umul_with_overflow, X->getType());
3617 CallInst *Call = Builder.CreateCall(F, {X, Y}, "umul");
3618
3619 // If the multiplication was used elsewhere, to ensure that we don't leave
3620 // "duplicate" instructions, replace uses of that original multiplication
3621 // with the multiplication result from the with.overflow intrinsic.
3622 if (MulHadOtherUses)
3623 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "umul.val"));
3624
3625 Value *Res = Builder.CreateExtractValue(Call, 1, "umul.ov");
3626 if (NeedNegation) // This technically increases instruction count.
3627 Res = Builder.CreateNot(Res, "umul.not.ov");
3628
3629 return Res;
3630}
3631
3632/// Try to fold icmp (binop), X or icmp X, (binop).
3633/// TODO: A large part of this logic is duplicated in InstSimplify's
3634/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
3635/// duplication.
3636Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I, const SimplifyQuery &SQ) {
3637 const SimplifyQuery Q = SQ.getWithInstruction(&I);
3638 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3639
3640 // Special logic for binary operators.
3641 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3642 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3643 if (!BO0 && !BO1)
3644 return nullptr;
3645
3646 const CmpInst::Predicate Pred = I.getPredicate();
3647 Value *X;
3648
3649 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
3650 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
3651 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
3652 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
3653 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
3654 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
3655 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
3656 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
3657 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
3658
3659 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3660 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3661 NoOp0WrapProblem =
3662 ICmpInst::isEquality(Pred) ||
3663 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3664 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3665 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3666 NoOp1WrapProblem =
3667 ICmpInst::isEquality(Pred) ||
3668 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3669 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3670
3671 // Analyze the case when either Op0 or Op1 is an add instruction.
3672 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
3673 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3674 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3675 A = BO0->getOperand(0);
3676 B = BO0->getOperand(1);
3677 }
3678 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3679 C = BO1->getOperand(0);
3680 D = BO1->getOperand(1);
3681 }
3682
3683 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
3684 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
3685 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3686 return new ICmpInst(Pred, A == Op1 ? B : A,
3687 Constant::getNullValue(Op1->getType()));
3688
3689 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
3690 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
3691 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3692 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3693 C == Op0 ? D : C);
3694
3695 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
3696 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
3697 NoOp1WrapProblem) {
3698 // Determine Y and Z in the form icmp (X+Y), (X+Z).
3699 Value *Y, *Z;
3700 if (A == C) {
3701 // C + B == C + D -> B == D
3702 Y = B;
3703 Z = D;
3704 } else if (A == D) {
3705 // D + B == C + D -> B == C
3706 Y = B;
3707 Z = C;
3708 } else if (B == C) {
3709 // A + C == C + D -> A == D
3710 Y = A;
3711 Z = D;
3712 } else {
3713 assert(B == D)((B == D) ? static_cast<void> (0) : __assert_fail ("B == D"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 3713, __PRETTY_FUNCTION__))
;
3714 // A + D == C + D -> A == C
3715 Y = A;
3716 Z = C;
3717 }
3718 return new ICmpInst(Pred, Y, Z);
3719 }
3720
3721 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
3722 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3723 match(B, m_AllOnes()))
3724 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3725
3726 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
3727 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3728 match(B, m_AllOnes()))
3729 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3730
3731 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
3732 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
3733 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3734
3735 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
3736 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
3737 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3738
3739 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
3740 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3741 match(D, m_AllOnes()))
3742 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3743
3744 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
3745 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3746 match(D, m_AllOnes()))
3747 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3748
3749 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
3750 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
3751 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3752
3753 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
3754 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
3755 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3756
3757 // TODO: The subtraction-related identities shown below also hold, but
3758 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
3759 // wouldn't happen even if they were implemented.
3760 //
3761 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
3762 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
3763 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
3764 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
3765
3766 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
3767 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
3768 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
3769
3770 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
3771 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
3772 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
3773
3774 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
3775 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
3776 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
3777
3778 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
3779 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
3780 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
3781
3782 // if C1 has greater magnitude than C2:
3783 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
3784 // s.t. C3 = C1 - C2
3785 //
3786 // if C2 has greater magnitude than C1:
3787 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
3788 // s.t. C3 = C2 - C1
3789 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3790 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3791 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3792 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3793 const APInt &AP1 = C1->getValue();
3794 const APInt &AP2 = C2->getValue();
3795 if (AP1.isNegative() == AP2.isNegative()) {
3796 APInt AP1Abs = C1->getValue().abs();
3797 APInt AP2Abs = C2->getValue().abs();
3798 if (AP1Abs.uge(AP2Abs)) {
3799 ConstantInt *C3 = Builder.getInt(AP1 - AP2);
3800 Value *NewAdd = Builder.CreateNSWAdd(A, C3);
3801 return new ICmpInst(Pred, NewAdd, C);
3802 } else {
3803 ConstantInt *C3 = Builder.getInt(AP2 - AP1);
3804 Value *NewAdd = Builder.CreateNSWAdd(C, C3);
3805 return new ICmpInst(Pred, A, NewAdd);
3806 }
3807 }
3808 }
3809
3810 // Analyze the case when either Op0 or Op1 is a sub instruction.
3811 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
3812 A = nullptr;
3813 B = nullptr;
3814 C = nullptr;
3815 D = nullptr;
3816 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3817 A = BO0->getOperand(0);
3818 B = BO0->getOperand(1);
3819 }
3820 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3821 C = BO1->getOperand(0);
3822 D = BO1->getOperand(1);
3823 }
3824
3825 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
3826 if (A == Op1 && NoOp0WrapProblem)
3827 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3828 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
3829 if (C == Op0 && NoOp1WrapProblem)
3830 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3831
3832 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
3833 // (A - B) u>/u<= A --> B u>/u<= A
3834 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
3835 return new ICmpInst(Pred, B, A);
3836 // C u</u>= (C - D) --> C u</u>= D
3837 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
3838 return new ICmpInst(Pred, C, D);
3839 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
3840 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
3841 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
3842 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A);
3843 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
3844 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
3845 isKnownNonZero(D, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
3846 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D);
3847
3848 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
3849 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
3850 return new ICmpInst(Pred, A, C);
3851
3852 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
3853 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
3854 return new ICmpInst(Pred, D, B);
3855
3856 // icmp (0-X) < cst --> x > -cst
3857 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3858 Value *X;
3859 if (match(BO0, m_Neg(m_Value(X))))
3860 if (Constant *RHSC = dyn_cast<Constant>(Op1))
3861 if (RHSC->isNotMinSignedValue())
3862 return new ICmpInst(I.getSwappedPredicate(), X,
3863 ConstantExpr::getNeg(RHSC));
3864 }
3865
3866 BinaryOperator *SRem = nullptr;
3867 // icmp (srem X, Y), Y
3868 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
3869 SRem = BO0;
3870 // icmp Y, (srem X, Y)
3871 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3872 Op0 == BO1->getOperand(1))
3873 SRem = BO1;
3874 if (SRem) {
3875 // We don't check hasOneUse to avoid increasing register pressure because
3876 // the value we use is the same value this instruction was already using.
3877 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3878 default:
3879 break;
3880 case ICmpInst::ICMP_EQ:
3881 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3882 case ICmpInst::ICMP_NE:
3883 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3884 case ICmpInst::ICMP_SGT:
3885 case ICmpInst::ICMP_SGE:
3886 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3887 Constant::getAllOnesValue(SRem->getType()));
3888 case ICmpInst::ICMP_SLT:
3889 case ICmpInst::ICMP_SLE:
3890 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3891 Constant::getNullValue(SRem->getType()));
3892 }
3893 }
3894
3895 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
3896 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
3897 switch (BO0->getOpcode()) {
3898 default:
3899 break;
3900 case Instruction::Add:
3901 case Instruction::Sub:
3902 case Instruction::Xor: {
3903 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3904 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3905
3906 const APInt *C;
3907 if (match(BO0->getOperand(1), m_APInt(C))) {
3908 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
3909 if (C->isSignMask()) {
3910 ICmpInst::Predicate NewPred =
3911 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3912 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
3913 }
3914
3915 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
3916 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
3917 ICmpInst::Predicate NewPred =
3918 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3919 NewPred = I.getSwappedPredicate(NewPred);
3920 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
3921 }
3922 }
3923 break;
3924 }
3925 case Instruction::Mul: {
3926 if (!I.isEquality())
3927 break;
3928
3929 const APInt *C;
3930 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isNullValue() &&
3931 !C->isOneValue()) {
3932 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
3933 // Mask = -1 >> count-trailing-zeros(C).
3934 if (unsigned TZs = C->countTrailingZeros()) {
3935 Constant *Mask = ConstantInt::get(
3936 BO0->getType(),
3937 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
3938 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
3939 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
3940 return new ICmpInst(Pred, And1, And2);
3941 }
3942 // If there are no trailing zeros in the multiplier, just eliminate
3943 // the multiplies (no masking is needed):
3944 // icmp eq/ne (X * C), (Y * C) --> icmp eq/ne X, Y
3945 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3946 }
3947 break;
3948 }
3949 case Instruction::UDiv:
3950 case Instruction::LShr:
3951 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
3952 break;
3953 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3954
3955 case Instruction::SDiv:
3956 if (!I.isEquality() || !BO0->isExact() || !BO1->isExact())
3957 break;
3958 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3959
3960 case Instruction::AShr:
3961 if (!BO0->isExact() || !BO1->isExact())
3962 break;
3963 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3964
3965 case Instruction::Shl: {
3966 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3967 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3968 if (!NUW && !NSW)
3969 break;
3970 if (!NSW && I.isSigned())
3971 break;
3972 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3973 }
3974 }
3975 }
3976
3977 if (BO0) {
3978 // Transform A & (L - 1) `ult` L --> L != 0
3979 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
3980 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
3981
3982 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
3983 auto *Zero = Constant::getNullValue(BO0->getType());
3984 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3985 }
3986 }
3987
3988 if (Value *V = foldUnsignedMultiplicationOverflowCheck(I))
3989 return replaceInstUsesWith(I, V);
3990
3991 if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder))
3992 return replaceInstUsesWith(I, V);
3993
3994 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
3995 return replaceInstUsesWith(I, V);
3996
3997 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
3998 return replaceInstUsesWith(I, V);
3999
4000 return nullptr;
4001}
4002
4003/// Fold icmp Pred min|max(X, Y), X.
4004static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) {
4005 ICmpInst::Predicate Pred = Cmp.getPredicate();
4006 Value *Op0 = Cmp.getOperand(0);
4007 Value *X = Cmp.getOperand(1);
4008
4009 // Canonicalize minimum or maximum operand to LHS of the icmp.
4010 if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) ||
4011 match(X, m_c_SMax(m_Specific(Op0), m_Value())) ||
4012 match(X, m_c_UMin(m_Specific(Op0), m_Value())) ||
4013 match(X, m_c_UMax(m_Specific(Op0), m_Value()))) {
4014 std::swap(Op0, X);
4015 Pred = Cmp.getSwappedPredicate();
4016 }
4017
4018 Value *Y;
4019 if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) {
4020 // smin(X, Y) == X --> X s<= Y
4021 // smin(X, Y) s>= X --> X s<= Y
4022 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE)
4023 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
4024
4025 // smin(X, Y) != X --> X s> Y
4026 // smin(X, Y) s< X --> X s> Y
4027 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT)
4028 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
4029
4030 // These cases should be handled in InstSimplify:
4031 // smin(X, Y) s<= X --> true
4032 // smin(X, Y) s> X --> false
4033 return nullptr;
4034 }
4035
4036 if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) {
4037 // smax(X, Y) == X --> X s>= Y
4038 // smax(X, Y) s<= X --> X s>= Y
4039 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE)
4040 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
4041
4042 // smax(X, Y) != X --> X s< Y
4043 // smax(X, Y) s> X --> X s< Y
4044 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT)
4045 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
4046
4047 // These cases should be handled in InstSimplify:
4048 // smax(X, Y) s>= X --> true
4049 // smax(X, Y) s< X --> false
4050 return nullptr;
4051 }
4052
4053 if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) {
4054 // umin(X, Y) == X --> X u<= Y
4055 // umin(X, Y) u>= X --> X u<= Y
4056 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE)
4057 return new ICmpInst(ICmpInst::ICMP_ULE, X, Y);
4058
4059 // umin(X, Y) != X --> X u> Y
4060 // umin(X, Y) u< X --> X u> Y
4061 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT)
4062 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
4063
4064 // These cases should be handled in InstSimplify:
4065 // umin(X, Y) u<= X --> true
4066 // umin(X, Y) u> X --> false
4067 return nullptr;
4068 }
4069
4070 if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) {
4071 // umax(X, Y) == X --> X u>= Y
4072 // umax(X, Y) u<= X --> X u>= Y
4073 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE)
4074 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
4075
4076 // umax(X, Y) != X --> X u< Y
4077 // umax(X, Y) u> X --> X u< Y
4078 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT)
4079 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
4080
4081 // These cases should be handled in InstSimplify:
4082 // umax(X, Y) u>= X --> true
4083 // umax(X, Y) u< X --> false
4084 return nullptr;
4085 }
4086
4087 return nullptr;
4088}
4089
4090Instruction *InstCombiner::foldICmpEquality(ICmpInst &I) {
4091 if (!I.isEquality())
4092 return nullptr;
4093
4094 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4095 const CmpInst::Predicate Pred = I.getPredicate();
4096 Value *A, *B, *C, *D;
4097 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4098 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4099 Value *OtherVal = A == Op1 ? B : A;
4100 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
4101 }
4102
4103 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4104 // A^c1 == C^c2 --> A == C^(c1^c2)
4105 ConstantInt *C1, *C2;
4106 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
4107 Op1->hasOneUse()) {
4108 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
4109 Value *Xor = Builder.CreateXor(C, NC);
4110 return new ICmpInst(Pred, A, Xor);
4111 }
4112
4113 // A^B == A^D -> B == D
4114 if (A == C)
4115 return new ICmpInst(Pred, B, D);
4116 if (A == D)
4117 return new ICmpInst(Pred, B, C);
4118 if (B == C)
4119 return new ICmpInst(Pred, A, D);
4120 if (B == D)
4121 return new ICmpInst(Pred, A, C);
4122 }
4123 }
4124
4125 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
4126 // A == (A^B) -> B == 0
4127 Value *OtherVal = A == Op0 ? B : A;
4128 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
4129 }
4130
4131 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4132 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
4133 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
4134 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
4135
4136 if (A == C) {
4137 X = B;
4138 Y = D;
4139 Z = A;
4140 } else if (A == D) {
4141 X = B;
4142 Y = C;
4143 Z = A;
4144 } else if (B == C) {
4145 X = A;
4146 Y = D;
4147 Z = B;
4148 } else if (B == D) {
4149 X = A;
4150 Y = C;
4151 Z = B;
4152 }
4153
4154 if (X) { // Build (X^Y) & Z
4155 Op1 = Builder.CreateXor(X, Y);
4156 Op1 = Builder.CreateAnd(Op1, Z);
4157 I.setOperand(0, Op1);
4158 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4159 return &I;
4160 }
4161 }
4162
4163 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
4164 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
4165 ConstantInt *Cst1;
4166 if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) &&
4167 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4168 (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4169 match(Op1, m_ZExt(m_Value(A))))) {
4170 APInt Pow2 = Cst1->getValue() + 1;
4171 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4172 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4173 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
4174 }
4175
4176 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4177 // For lshr and ashr pairs.
4178 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4179 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4180 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4181 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4182 unsigned TypeBits = Cst1->getBitWidth();
4183 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4184 if (ShAmt < TypeBits && ShAmt != 0) {
4185 ICmpInst::Predicate NewPred =
4186 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
4187 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
4188 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4189 return new ICmpInst(NewPred, Xor, Builder.getInt(CmpVal));
4190 }
4191 }
4192
4193 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4194 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4195 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4196 unsigned TypeBits = Cst1->getBitWidth();
4197 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4198 if (ShAmt < TypeBits && ShAmt != 0) {
4199 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
4200 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4201 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
4202 I.getName() + ".mask");
4203 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
4204 }
4205 }
4206
4207 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4208 // "icmp (and X, mask), cst"
4209 uint64_t ShAmt = 0;
4210 if (Op0->hasOneUse() &&
4211 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
4212 match(Op1, m_ConstantInt(Cst1)) &&
4213 // Only do this when A has multiple uses. This is most important to do
4214 // when it exposes other optimizations.
4215 !A->hasOneUse()) {
4216 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
4217
4218 if (ShAmt < ASize) {
4219 APInt MaskV =
4220 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4221 MaskV <<= ShAmt;
4222
4223 APInt CmpV = Cst1->getValue().zext(ASize);
4224 CmpV <<= ShAmt;
4225
4226 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
4227 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
4228 }
4229 }
4230
4231 // If both operands are byte-swapped or bit-reversed, just compare the
4232 // original values.
4233 // TODO: Move this to a function similar to foldICmpIntrinsicWithConstant()
4234 // and handle more intrinsics.
4235 if ((match(Op0, m_BSwap(m_Value(A))) && match(Op1, m_BSwap(m_Value(B)))) ||
4236 (match(Op0, m_BitReverse(m_Value(A))) &&
4237 match(Op1, m_BitReverse(m_Value(B)))))
4238 return new ICmpInst(Pred, A, B);
4239
4240 // Canonicalize checking for a power-of-2-or-zero value:
4241 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
4242 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
4243 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
4244 m_Deferred(A)))) ||
4245 !match(Op1, m_ZeroInt()))
4246 A = nullptr;
4247
4248 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
4249 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
4250 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
4251 A = Op1;
4252 else if (match(Op1,
4253 m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))
4254 A = Op0;
4255
4256 if (A) {
4257 Type *Ty = A->getType();
4258 CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
4259 return Pred == ICmpInst::ICMP_EQ
4260 ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop, ConstantInt::get(Ty, 2))
4261 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop, ConstantInt::get(Ty, 1));
4262 }
4263
4264 return nullptr;
4265}
4266
4267static Instruction *foldICmpWithZextOrSext(ICmpInst &ICmp,
4268 InstCombiner::BuilderTy &Builder) {
4269 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0")((isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0"
) ? static_cast<void> (0) : __assert_fail ("isa<CastInst>(ICmp.getOperand(0)) && \"Expected cast for operand 0\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4269, __PRETTY_FUNCTION__))
;
4270 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
4271 Value *X;
4272 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
4273 return nullptr;
4274
4275 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
4276 bool IsSignedCmp = ICmp.isSigned();
4277 if (auto *CastOp1 = dyn_cast<CastInst>(ICmp.getOperand(1))) {
4278 // If the signedness of the two casts doesn't agree (i.e. one is a sext
4279 // and the other is a zext), then we can't handle this.
4280 // TODO: This is too strict. We can handle some predicates (equality?).
4281 if (CastOp0->getOpcode() != CastOp1->getOpcode())
4282 return nullptr;
4283
4284 // Not an extension from the same type?
4285 Value *Y = CastOp1->getOperand(0);
4286 Type *XTy = X->getType(), *YTy = Y->getType();
4287 if (XTy != YTy) {
4288 // One of the casts must have one use because we are creating a new cast.
4289 if (!CastOp0->hasOneUse() && !CastOp1->hasOneUse())
4290 return nullptr;
4291 // Extend the narrower operand to the type of the wider operand.
4292 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
4293 X = Builder.CreateCast(CastOp0->getOpcode(), X, YTy);
4294 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
4295 Y = Builder.CreateCast(CastOp0->getOpcode(), Y, XTy);
4296 else
4297 return nullptr;
4298 }
4299
4300 // (zext X) == (zext Y) --> X == Y
4301 // (sext X) == (sext Y) --> X == Y
4302 if (ICmp.isEquality())
4303 return new ICmpInst(ICmp.getPredicate(), X, Y);
4304
4305 // A signed comparison of sign extended values simplifies into a
4306 // signed comparison.
4307 if (IsSignedCmp && IsSignedExt)
4308 return new ICmpInst(ICmp.getPredicate(), X, Y);
4309
4310 // The other three cases all fold into an unsigned comparison.
4311 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
4312 }
4313
4314 // Below here, we are only folding a compare with constant.
4315 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
4316 if (!C)
4317 return nullptr;
4318
4319 // Compute the constant that would happen if we truncated to SrcTy then
4320 // re-extended to DestTy.
4321 Type *SrcTy = CastOp0->getSrcTy();
4322 Type *DestTy = CastOp0->getDestTy();
4323 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
4324 Constant *Res2 = ConstantExpr::getCast(CastOp0->getOpcode(), Res1, DestTy);
4325
4326 // If the re-extended constant didn't change...
4327 if (Res2 == C) {
4328 if (ICmp.isEquality())
4329 return new ICmpInst(ICmp.getPredicate(), X, Res1);
4330
4331 // A signed comparison of sign extended values simplifies into a
4332 // signed comparison.
4333 if (IsSignedExt && IsSignedCmp)
4334 return new ICmpInst(ICmp.getPredicate(), X, Res1);
4335
4336 // The other three cases all fold into an unsigned comparison.
4337 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res1);
4338 }
4339
4340 // The re-extended constant changed, partly changed (in the case of a vector),
4341 // or could not be determined to be equal (in the case of a constant
4342 // expression), so the constant cannot be represented in the shorter type.
4343 // All the cases that fold to true or false will have already been handled
4344 // by SimplifyICmpInst, so only deal with the tricky case.
4345 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
4346 return nullptr;
4347
4348 // Is source op positive?
4349 // icmp ult (sext X), C --> icmp sgt X, -1
4350 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
4351 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy));
4352
4353 // Is source op negative?
4354 // icmp ugt (sext X), C --> icmp slt X, 0
4355 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!")((ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!"
) ? static_cast<void> (0) : __assert_fail ("ICmp.getPredicate() == ICmpInst::ICMP_UGT && \"ICmp should be folded!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4355, __PRETTY_FUNCTION__))
;
4356 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));
4357}
4358
4359/// Handle icmp (cast x), (cast or constant).
4360Instruction *InstCombiner::foldICmpWithCastOp(ICmpInst &ICmp) {
4361 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
4362 if (!CastOp0)
4363 return nullptr;
4364 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
4365 return nullptr;
4366
4367 Value *Op0Src = CastOp0->getOperand(0);
4368 Type *SrcTy = CastOp0->getSrcTy();
4369 Type *DestTy = CastOp0->getDestTy();
4370
4371 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
4372 // integer type is the same size as the pointer type.
4373 auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) {
4374 if (isa<VectorType>(SrcTy)) {
4375 SrcTy = cast<VectorType>(SrcTy)->getElementType();
4376 DestTy = cast<VectorType>(DestTy)->getElementType();
4377 }
4378 return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth();
4379 };
4380 if (CastOp0->getOpcode() == Instruction::PtrToInt &&
4381 CompatibleSizes(SrcTy, DestTy)) {
4382 Value *NewOp1 = nullptr;
4383 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
4384 Value *PtrSrc = PtrToIntOp1->getOperand(0);
4385 if (PtrSrc->getType()->getPointerAddressSpace() ==
4386 Op0Src->getType()->getPointerAddressSpace()) {
4387 NewOp1 = PtrToIntOp1->getOperand(0);
4388 // If the pointer types don't match, insert a bitcast.
4389 if (Op0Src->getType() != NewOp1->getType())
4390 NewOp1 = Builder.CreateBitCast(NewOp1, Op0Src->getType());
4391 }
4392 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
4393 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
4394 }
4395
4396 if (NewOp1)
4397 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
4398 }
4399
4400 return foldICmpWithZextOrSext(ICmp, Builder);
4401}
4402
4403static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS) {
4404 switch (BinaryOp) {
4405 default:
4406 llvm_unreachable("Unsupported binary op")::llvm::llvm_unreachable_internal("Unsupported binary op", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4406)
;
4407 case Instruction::Add:
4408 case Instruction::Sub:
4409 return match(RHS, m_Zero());
4410 case Instruction::Mul:
4411 return match(RHS, m_One());
4412 }
4413}
4414
4415OverflowResult InstCombiner::computeOverflow(
4416 Instruction::BinaryOps BinaryOp, bool IsSigned,
4417 Value *LHS, Value *RHS, Instruction *CxtI) const {
4418 switch (BinaryOp) {
4419 default:
4420 llvm_unreachable("Unsupported binary op")::llvm::llvm_unreachable_internal("Unsupported binary op", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4420)
;
4421 case Instruction::Add:
4422 if (IsSigned)
4423 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
4424 else
4425 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
4426 case Instruction::Sub:
4427 if (IsSigned)
4428 return computeOverflowForSignedSub(LHS, RHS, CxtI);
4429 else
4430 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
4431 case Instruction::Mul:
4432 if (IsSigned)
4433 return computeOverflowForSignedMul(LHS, RHS, CxtI);
4434 else
4435 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
4436 }
4437}
4438
4439bool InstCombiner::OptimizeOverflowCheck(
4440 Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS,
4441 Instruction &OrigI, Value *&Result, Constant *&Overflow) {
4442 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
4443 std::swap(LHS, RHS);
4444
4445 // If the overflow check was an add followed by a compare, the insertion point
4446 // may be pointing to the compare. We want to insert the new instructions
4447 // before the add in case there are uses of the add between the add and the
4448 // compare.
4449 Builder.SetInsertPoint(&OrigI);
4450
4451 if (isNeutralValue(BinaryOp, RHS)) {
4452 Result = LHS;
4453 Overflow = Builder.getFalse();
4454 return true;
4455 }
4456
4457 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
4458 case OverflowResult::MayOverflow:
4459 return false;
4460 case OverflowResult::AlwaysOverflowsLow:
4461 case OverflowResult::AlwaysOverflowsHigh:
4462 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
4463 Result->takeName(&OrigI);
4464 Overflow = Builder.getTrue();
4465 return true;
4466 case OverflowResult::NeverOverflows:
4467 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
4468 Result->takeName(&OrigI);
4469 Overflow = Builder.getFalse();
4470 if (auto *Inst = dyn_cast<Instruction>(Result)) {
4471 if (IsSigned)
4472 Inst->setHasNoSignedWrap();
4473 else
4474 Inst->setHasNoUnsignedWrap();
4475 }
4476 return true;
4477 }
4478
4479 llvm_unreachable("Unexpected overflow result")::llvm::llvm_unreachable_internal("Unexpected overflow result"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4479)
;
4480}
4481
4482/// Recognize and process idiom involving test for multiplication
4483/// overflow.
4484///
4485/// The caller has matched a pattern of the form:
4486/// I = cmp u (mul(zext A, zext B), V
4487/// The function checks if this is a test for overflow and if so replaces
4488/// multiplication with call to 'mul.with.overflow' intrinsic.
4489///
4490/// \param I Compare instruction.
4491/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
4492/// the compare instruction. Must be of integer type.
4493/// \param OtherVal The other argument of compare instruction.
4494/// \returns Instruction which must replace the compare instruction, NULL if no
4495/// replacement required.
4496static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
4497 Value *OtherVal, InstCombiner &IC) {
4498 // Don't bother doing this transformation for pointers, don't do it for
4499 // vectors.
4500 if (!isa<IntegerType>(MulVal->getType()))
4501 return nullptr;
4502
4503 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal)((I.getOperand(0) == MulVal || I.getOperand(1) == MulVal) ? static_cast
<void> (0) : __assert_fail ("I.getOperand(0) == MulVal || I.getOperand(1) == MulVal"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4503, __PRETTY_FUNCTION__))
;
4504 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal)((I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal)
? static_cast<void> (0) : __assert_fail ("I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4504, __PRETTY_FUNCTION__))
;
4505 auto *MulInstr = dyn_cast<Instruction>(MulVal);
4506 if (!MulInstr)
4507 return nullptr;
4508 assert(MulInstr->getOpcode() == Instruction::Mul)((MulInstr->getOpcode() == Instruction::Mul) ? static_cast
<void> (0) : __assert_fail ("MulInstr->getOpcode() == Instruction::Mul"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4508, __PRETTY_FUNCTION__))
;
4509
4510 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
4511 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
4512 assert(LHS->getOpcode() == Instruction::ZExt)((LHS->getOpcode() == Instruction::ZExt) ? static_cast<
void> (0) : __assert_fail ("LHS->getOpcode() == Instruction::ZExt"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4512, __PRETTY_FUNCTION__))
;
4513 assert(RHS->getOpcode() == Instruction::ZExt)((RHS->getOpcode() == Instruction::ZExt) ? static_cast<
void> (0) : __assert_fail ("RHS->getOpcode() == Instruction::ZExt"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4513, __PRETTY_FUNCTION__))
;
4514 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
4515
4516 // Calculate type and width of the result produced by mul.with.overflow.
4517 Type *TyA = A->getType(), *TyB = B->getType();
4518 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
4519 WidthB = TyB->getPrimitiveSizeInBits();
4520 unsigned MulWidth;
4521 Type *MulType;
4522 if (WidthB > WidthA) {
4523 MulWidth = WidthB;
4524 MulType = TyB;
4525 } else {
4526 MulWidth = WidthA;
4527 MulType = TyA;
4528 }
4529
4530 // In order to replace the original mul with a narrower mul.with.overflow,
4531 // all uses must ignore upper bits of the product. The number of used low
4532 // bits must be not greater than the width of mul.with.overflow.
4533 if (MulVal->hasNUsesOrMore(2))
4534 for (User *U : MulVal->users()) {
4535 if (U == &I)
4536 continue;
4537 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
4538 // Check if truncation ignores bits above MulWidth.
4539 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
4540 if (TruncWidth > MulWidth)
4541 return nullptr;
4542 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
4543 // Check if AND ignores bits above MulWidth.
4544 if (BO->getOpcode() != Instruction::And)
4545 return nullptr;
4546 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4547 const APInt &CVal = CI->getValue();
4548 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
4549 return nullptr;
4550 } else {
4551 // In this case we could have the operand of the binary operation
4552 // being defined in another block, and performing the replacement
4553 // could break the dominance relation.
4554 return nullptr;
4555 }
4556 } else {
4557 // Other uses prohibit this transformation.
4558 return nullptr;
4559 }
4560 }
4561
4562 // Recognize patterns
4563 switch (I.getPredicate()) {
4564 case ICmpInst::ICMP_EQ:
4565 case ICmpInst::ICMP_NE:
4566 // Recognize pattern:
4567 // mulval = mul(zext A, zext B)
4568 // cmp eq/neq mulval, zext trunc mulval
4569 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
4570 if (Zext->hasOneUse()) {
4571 Value *ZextArg = Zext->getOperand(0);
4572 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
4573 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
4574 break; //Recognized
4575 }
4576
4577 // Recognize pattern:
4578 // mulval = mul(zext A, zext B)
4579 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
4580 ConstantInt *CI;
4581 Value *ValToMask;
4582 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
4583 if (ValToMask != MulVal)
4584 return nullptr;
4585 const APInt &CVal = CI->getValue() + 1;
4586 if (CVal.isPowerOf2()) {
4587 unsigned MaskWidth = CVal.logBase2();
4588 if (MaskWidth == MulWidth)
4589 break; // Recognized
4590 }
4591 }
4592 return nullptr;
4593
4594 case ICmpInst::ICMP_UGT:
4595 // Recognize pattern:
4596 // mulval = mul(zext A, zext B)
4597 // cmp ugt mulval, max
4598 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4599 APInt MaxVal = APInt::getMaxValue(MulWidth);
4600 MaxVal = MaxVal.zext(CI->getBitWidth());
4601 if (MaxVal.eq(CI->getValue()))
4602 break; // Recognized
4603 }
4604 return nullptr;
4605
4606 case ICmpInst::ICMP_UGE:
4607 // Recognize pattern:
4608 // mulval = mul(zext A, zext B)
4609 // cmp uge mulval, max+1
4610 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4611 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
4612 if (MaxVal.eq(CI->getValue()))
4613 break; // Recognized
4614 }
4615 return nullptr;
4616
4617 case ICmpInst::ICMP_ULE:
4618 // Recognize pattern:
4619 // mulval = mul(zext A, zext B)
4620 // cmp ule mulval, max
4621 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4622 APInt MaxVal = APInt::getMaxValue(MulWidth);
4623 MaxVal = MaxVal.zext(CI->getBitWidth());
4624 if (MaxVal.eq(CI->getValue()))
4625 break; // Recognized
4626 }
4627 return nullptr;
4628
4629 case ICmpInst::ICMP_ULT:
4630 // Recognize pattern:
4631 // mulval = mul(zext A, zext B)
4632 // cmp ule mulval, max + 1
4633 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4634 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
4635 if (MaxVal.eq(CI->getValue()))
4636 break; // Recognized
4637 }
4638 return nullptr;
4639
4640 default:
4641 return nullptr;
4642 }
4643
4644 InstCombiner::BuilderTy &Builder = IC.Builder;
4645 Builder.SetInsertPoint(MulInstr);
4646
4647 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
4648 Value *MulA = A, *MulB = B;
4649 if (WidthA < MulWidth)
4650 MulA = Builder.CreateZExt(A, MulType);
4651 if (WidthB < MulWidth)
4652 MulB = Builder.CreateZExt(B, MulType);
4653 Function *F = Intrinsic::getDeclaration(
4654 I.getModule(), Intrinsic::umul_with_overflow, MulType);
4655 CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul");
4656 IC.Worklist.Add(MulInstr);
4657
4658 // If there are uses of mul result other than the comparison, we know that
4659 // they are truncation or binary AND. Change them to use result of
4660 // mul.with.overflow and adjust properly mask/size.
4661 if (MulVal->hasNUsesOrMore(2)) {
4662 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
4663 for (auto UI = MulVal->user_begin(), UE = MulVal->user_end(); UI != UE;) {
4664 User *U = *UI++;
4665 if (U == &I || U == OtherVal)
4666 continue;
4667 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
4668 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
4669 IC.replaceInstUsesWith(*TI, Mul);
4670 else
4671 TI->setOperand(0, Mul);
4672 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
4673 assert(BO->getOpcode() == Instruction::And)((BO->getOpcode() == Instruction::And) ? static_cast<void
> (0) : __assert_fail ("BO->getOpcode() == Instruction::And"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4673, __PRETTY_FUNCTION__))
;
4674 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
4675 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
4676 APInt ShortMask = CI->getValue().trunc(MulWidth);
4677 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
4678 Instruction *Zext =
4679 cast<Instruction>(Builder.CreateZExt(ShortAnd, BO->getType()));
4680 IC.Worklist.Add(Zext);
4681 IC.replaceInstUsesWith(*BO, Zext);
4682 } else {
4683 llvm_unreachable("Unexpected Binary operation")::llvm::llvm_unreachable_internal("Unexpected Binary operation"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4683)
;
4684 }
4685 IC.Worklist.Add(cast<Instruction>(U));
4686 }
4687 }
4688 if (isa<Instruction>(OtherVal))
4689 IC.Worklist.Add(cast<Instruction>(OtherVal));
4690
4691 // The original icmp gets replaced with the overflow value, maybe inverted
4692 // depending on predicate.
4693 bool Inverse = false;
4694 switch (I.getPredicate()) {
4695 case ICmpInst::ICMP_NE:
4696 break;
4697 case ICmpInst::ICMP_EQ:
4698 Inverse = true;
4699 break;
4700 case ICmpInst::ICMP_UGT:
4701 case ICmpInst::ICMP_UGE:
4702 if (I.getOperand(0) == MulVal)
4703 break;
4704 Inverse = true;
4705 break;
4706 case ICmpInst::ICMP_ULT:
4707 case ICmpInst::ICMP_ULE:
4708 if (I.getOperand(1) == MulVal)
4709 break;
4710 Inverse = true;
4711 break;
4712 default:
4713 llvm_unreachable("Unexpected predicate")::llvm::llvm_unreachable_internal("Unexpected predicate", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4713)
;
4714 }
4715 if (Inverse) {
4716 Value *Res = Builder.CreateExtractValue(Call, 1);
4717 return BinaryOperator::CreateNot(Res);
4718 }
4719
4720 return ExtractValueInst::Create(Call, 1);
4721}
4722
4723/// When performing a comparison against a constant, it is possible that not all
4724/// the bits in the LHS are demanded. This helper method computes the mask that
4725/// IS demanded.
4726static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
4727 const APInt *RHS;
4728 if (!match(I.getOperand(1), m_APInt(RHS)))
4729 return APInt::getAllOnesValue(BitWidth);
4730
4731 // If this is a normal comparison, it demands all bits. If it is a sign bit
4732 // comparison, it only demands the sign bit.
4733 bool UnusedBit;
4734 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
4735 return APInt::getSignMask(BitWidth);
4736
4737 switch (I.getPredicate()) {
4738 // For a UGT comparison, we don't care about any bits that
4739 // correspond to the trailing ones of the comparand. The value of these
4740 // bits doesn't impact the outcome of the comparison, because any value
4741 // greater than the RHS must differ in a bit higher than these due to carry.
4742 case ICmpInst::ICMP_UGT:
4743 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingOnes());
4744
4745 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
4746 // Any value less than the RHS must differ in a higher bit because of carries.
4747 case ICmpInst::ICMP_ULT:
4748 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingZeros());
4749
4750 default:
4751 return APInt::getAllOnesValue(BitWidth);
4752 }
4753}
4754
4755/// Check if the order of \p Op0 and \p Op1 as operands in an ICmpInst
4756/// should be swapped.
4757/// The decision is based on how many times these two operands are reused
4758/// as subtract operands and their positions in those instructions.
4759/// The rationale is that several architectures use the same instruction for
4760/// both subtract and cmp. Thus, it is better if the order of those operands
4761/// match.
4762/// \return true if Op0 and Op1 should be swapped.
4763static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1) {
4764 // Filter out pointer values as those cannot appear directly in subtract.
4765 // FIXME: we may want to go through inttoptrs or bitcasts.
4766 if (Op0->getType()->isPointerTy())
4767 return false;
4768 // If a subtract already has the same operands as a compare, swapping would be
4769 // bad. If a subtract has the same operands as a compare but in reverse order,
4770 // then swapping is good.
4771 int GoodToSwap = 0;
4772 for (const User *U : Op0->users()) {
4773 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
4774 GoodToSwap++;
4775 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
4776 GoodToSwap--;
4777 }
4778 return GoodToSwap > 0;
4779}
4780
4781/// Check that one use is in the same block as the definition and all
4782/// other uses are in blocks dominated by a given block.
4783///
4784/// \param DI Definition
4785/// \param UI Use
4786/// \param DB Block that must dominate all uses of \p DI outside
4787/// the parent block
4788/// \return true when \p UI is the only use of \p DI in the parent block
4789/// and all other uses of \p DI are in blocks dominated by \p DB.
4790///
4791bool InstCombiner::dominatesAllUses(const Instruction *DI,
4792 const Instruction *UI,
4793 const BasicBlock *DB) const {
4794 assert(DI && UI && "Instruction not defined\n")((DI && UI && "Instruction not defined\n") ? static_cast
<void> (0) : __assert_fail ("DI && UI && \"Instruction not defined\\n\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4794, __PRETTY_FUNCTION__))
;
4795 // Ignore incomplete definitions.
4796 if (!DI->getParent())
4797 return false;
4798 // DI and UI must be in the same block.
4799 if (DI->getParent() != UI->getParent())
4800 return false;
4801 // Protect from self-referencing blocks.
4802 if (DI->getParent() == DB)
4803 return false;
4804 for (const User *U : DI->users()) {
4805 auto *Usr = cast<Instruction>(U);
4806 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
4807 return false;
4808 }
4809 return true;
4810}
4811
4812/// Return true when the instruction sequence within a block is select-cmp-br.
4813static bool isChainSelectCmpBranch(const SelectInst *SI) {
4814 const BasicBlock *BB = SI->getParent();
4815 if (!BB)
4816 return false;
4817 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
4818 if (!BI || BI->getNumSuccessors() != 2)
4819 return false;
4820 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
4821 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
4822 return false;
4823 return true;
4824}
4825
4826/// True when a select result is replaced by one of its operands
4827/// in select-icmp sequence. This will eventually result in the elimination
4828/// of the select.
4829///
4830/// \param SI Select instruction
4831/// \param Icmp Compare instruction
4832/// \param SIOpd Operand that replaces the select
4833///
4834/// Notes:
4835/// - The replacement is global and requires dominator information
4836/// - The caller is responsible for the actual replacement
4837///
4838/// Example:
4839///
4840/// entry:
4841/// %4 = select i1 %3, %C* %0, %C* null
4842/// %5 = icmp eq %C* %4, null
4843/// br i1 %5, label %9, label %7
4844/// ...
4845/// ; <label>:7 ; preds = %entry
4846/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
4847/// ...
4848///
4849/// can be transformed to
4850///
4851/// %5 = icmp eq %C* %0, null
4852/// %6 = select i1 %3, i1 %5, i1 true
4853/// br i1 %6, label %9, label %7
4854/// ...
4855/// ; <label>:7 ; preds = %entry
4856/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
4857///
4858/// Similar when the first operand of the select is a constant or/and
4859/// the compare is for not equal rather than equal.
4860///
4861/// NOTE: The function is only called when the select and compare constants
4862/// are equal, the optimization can work only for EQ predicates. This is not a
4863/// major restriction since a NE compare should be 'normalized' to an equal
4864/// compare, which usually happens in the combiner and test case
4865/// select-cmp-br.ll checks for it.
4866bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
4867 const ICmpInst *Icmp,
4868 const unsigned SIOpd) {
4869 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!")(((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!"
) ? static_cast<void> (0) : __assert_fail ("(SIOpd == 1 || SIOpd == 2) && \"Invalid select operand!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4869, __PRETTY_FUNCTION__))
;
4870 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
4871 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
4872 // The check for the single predecessor is not the best that can be
4873 // done. But it protects efficiently against cases like when SI's
4874 // home block has two successors, Succ and Succ1, and Succ1 predecessor
4875 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
4876 // replaced can be reached on either path. So the uniqueness check
4877 // guarantees that the path all uses of SI (outside SI's parent) are on
4878 // is disjoint from all other paths out of SI. But that information
4879 // is more expensive to compute, and the trade-off here is in favor
4880 // of compile-time. It should also be noticed that we check for a single
4881 // predecessor and not only uniqueness. This to handle the situation when
4882 // Succ and Succ1 points to the same basic block.
4883 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
4884 NumSel++;
4885 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
4886 return true;
4887 }
4888 }
4889 return false;
4890}
4891
4892/// Try to fold the comparison based on range information we can get by checking
4893/// whether bits are known to be zero or one in the inputs.
4894Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) {
4895 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4896 Type *Ty = Op0->getType();
4897 ICmpInst::Predicate Pred = I.getPredicate();
4898
4899 // Get scalar or pointer size.
4900 unsigned BitWidth = Ty->isIntOrIntVectorTy()
4901 ? Ty->getScalarSizeInBits()
4902 : DL.getIndexTypeSizeInBits(Ty->getScalarType());
4903
4904 if (!BitWidth)
4905 return nullptr;
4906
4907 KnownBits Op0Known(BitWidth);
4908 KnownBits Op1Known(BitWidth);
4909
4910 if (SimplifyDemandedBits(&I, 0,
4911 getDemandedBitsLHSMask(I, BitWidth),
4912 Op0Known, 0))
4913 return &I;
4914
4915 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnesValue(BitWidth),
4916 Op1Known, 0))
4917 return &I;
4918
4919 // Given the known and unknown bits, compute a range that the LHS could be
4920 // in. Compute the Min, Max and RHS values based on the known bits. For the
4921 // EQ and NE we use unsigned values.
4922 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
4923 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
4924 if (I.isSigned()) {
4925 computeSignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max);
4926 computeSignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max);
4927 } else {
4928 computeUnsignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max);
4929 computeUnsignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max);
4930 }
4931
4932 // If Min and Max are known to be the same, then SimplifyDemandedBits figured
4933 // out that the LHS or RHS is a constant. Constant fold this now, so that
4934 // code below can assume that Min != Max.
4935 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
4936 return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1);
4937 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
4938 return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min));
4939
4940 // Based on the range information we know about the LHS, see if we can
4941 // simplify this comparison. For example, (x&4) < 8 is always true.
4942 switch (Pred) {
4943 default:
4944 llvm_unreachable("Unknown icmp opcode!")::llvm::llvm_unreachable_internal("Unknown icmp opcode!", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 4944)
;
4945 case ICmpInst::ICMP_EQ:
4946 case ICmpInst::ICMP_NE: {
4947 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) {
4948 return Pred == CmpInst::ICMP_EQ
4949 ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()))
4950 : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4951 }
4952
4953 // If all bits are known zero except for one, then we know at most one bit
4954 // is set. If the comparison is against zero, then this is a check to see if
4955 // *that* bit is set.
4956 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
4957 if (Op1Known.isZero()) {
4958 // If the LHS is an AND with the same constant, look through it.
4959 Value *LHS = nullptr;
4960 const APInt *LHSC;
4961 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
4962 *LHSC != Op0KnownZeroInverted)
4963 LHS = Op0;
4964
4965 Value *X;
4966 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
4967 APInt ValToCheck = Op0KnownZeroInverted;
4968 Type *XTy = X->getType();
4969 if (ValToCheck.isPowerOf2()) {
4970 // ((1 << X) & 8) == 0 -> X != 3
4971 // ((1 << X) & 8) != 0 -> X == 3
4972 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4973 auto NewPred = ICmpInst::getInversePredicate(Pred);
4974 return new ICmpInst(NewPred, X, CmpC);
4975 } else if ((++ValToCheck).isPowerOf2()) {
4976 // ((1 << X) & 7) == 0 -> X >= 3
4977 // ((1 << X) & 7) != 0 -> X < 3
4978 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4979 auto NewPred =
4980 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
4981 return new ICmpInst(NewPred, X, CmpC);
4982 }
4983 }
4984
4985 // Check if the LHS is 8 >>u x and the result is a power of 2 like 1.
4986 const APInt *CI;
4987 if (Op0KnownZeroInverted.isOneValue() &&
4988 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) {
4989 // ((8 >>u X) & 1) == 0 -> X != 3
4990 // ((8 >>u X) & 1) != 0 -> X == 3
4991 unsigned CmpVal = CI->countTrailingZeros();
4992 auto NewPred = ICmpInst::getInversePredicate(Pred);
4993 return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal));
4994 }
4995 }
4996 break;
4997 }
4998 case ICmpInst::ICMP_ULT: {
4999 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
5000 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5001 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
5002 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5003 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
5004 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5005
5006 const APInt *CmpC;
5007 if (match(Op1, m_APInt(CmpC))) {
5008 // A <u C -> A == C-1 if min(A)+1 == C
5009 if (*CmpC == Op0Min + 1)
5010 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5011 ConstantInt::get(Op1->getType(), *CmpC - 1));
5012 // X <u C --> X == 0, if the number of zero bits in the bottom of X
5013 // exceeds the log2 of C.
5014 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
5015 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5016 Constant::getNullValue(Op1->getType()));
5017 }
5018 break;
5019 }
5020 case ICmpInst::ICMP_UGT: {
5021 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
5022 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5023 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
5024 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5025 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
5026 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5027
5028 const APInt *CmpC;
5029 if (match(Op1, m_APInt(CmpC))) {
5030 // A >u C -> A == C+1 if max(a)-1 == C
5031 if (*CmpC == Op0Max - 1)
5032 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5033 ConstantInt::get(Op1->getType(), *CmpC + 1));
5034 // X >u C --> X != 0, if the number of zero bits in the bottom of X
5035 // exceeds the log2 of C.
5036 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
5037 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
5038 Constant::getNullValue(Op1->getType()));
5039 }
5040 break;
5041 }
5042 case ICmpInst::ICMP_SLT: {
5043 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
5044 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5045 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
5046 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5047 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
5048 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5049 const APInt *CmpC;
5050 if (match(Op1, m_APInt(CmpC))) {
5051 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
5052 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5053 ConstantInt::get(Op1->getType(), *CmpC - 1));
5054 }
5055 break;
5056 }
5057 case ICmpInst::ICMP_SGT: {
5058 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
5059 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5060 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
5061 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5062 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
5063 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5064 const APInt *CmpC;
5065 if (match(Op1, m_APInt(CmpC))) {
5066 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
5067 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5068 ConstantInt::get(Op1->getType(), *CmpC + 1));
5069 }
5070 break;
5071 }
5072 case ICmpInst::ICMP_SGE:
5073 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!")((!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ConstantInt>(Op1) && \"ICMP_SGE with ConstantInt not folded!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5073, __PRETTY_FUNCTION__))
;
5074 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
5075 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5076 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
5077 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5078 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
5079 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5080 break;
5081 case ICmpInst::ICMP_SLE:
5082 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!")((!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ConstantInt>(Op1) && \"ICMP_SLE with ConstantInt not folded!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5082, __PRETTY_FUNCTION__))
;
5083 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
5084 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5085 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
5086 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5087 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
5088 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5089 break;
5090 case ICmpInst::ICMP_UGE:
5091 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!")((!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ConstantInt>(Op1) && \"ICMP_UGE with ConstantInt not folded!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5091, __PRETTY_FUNCTION__))
;
5092 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
5093 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5094 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
5095 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5096 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
5097 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5098 break;
5099 case ICmpInst::ICMP_ULE:
5100 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!")((!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ConstantInt>(Op1) && \"ICMP_ULE with ConstantInt not folded!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5100, __PRETTY_FUNCTION__))
;
5101 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
5102 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5103 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
5104 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5105 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
5106 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5107 break;
5108 }
5109
5110 // Turn a signed comparison into an unsigned one if both operands are known to
5111 // have the same sign.
5112 if (I.isSigned() &&
5113 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
5114 (Op0Known.One.isNegative() && Op1Known.One.isNegative())))
5115 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
5116
5117 return nullptr;
5118}
5119
5120llvm::Optional<std::pair<CmpInst::Predicate, Constant *>>
5121llvm::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred,
5122 Constant *C) {
5123 assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) &&((ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate
(Pred) && "Only for relational integer predicates.") ?
static_cast<void> (0) : __assert_fail ("ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) && \"Only for relational integer predicates.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5124, __PRETTY_FUNCTION__))
5124 "Only for relational integer predicates.")((ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate
(Pred) && "Only for relational integer predicates.") ?
static_cast<void> (0) : __assert_fail ("ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) && \"Only for relational integer predicates.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5124, __PRETTY_FUNCTION__))
;
5125
5126 Type *Type = C->getType();
5127 bool IsSigned = ICmpInst::isSigned(Pred);
5128
5129 CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred);
5130 bool WillIncrement =
5131 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
5132
5133 // Check if the constant operand can be safely incremented/decremented
5134 // without overflowing/underflowing.
5135 auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) {
5136 return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);
5137 };
5138
5139 if (auto *CI = dyn_cast<ConstantInt>(C)) {
5140 // Bail out if the constant can't be safely incremented/decremented.
5141 if (!ConstantIsOk(CI))
5142 return llvm::None;
5143 } else if (Type->isVectorTy()) {
5144 unsigned NumElts = Type->getVectorNumElements();
5145 for (unsigned i = 0; i != NumElts; ++i) {
5146 Constant *Elt = C->getAggregateElement(i);
5147 if (!Elt)
5148 return llvm::None;
5149
5150 if (isa<UndefValue>(Elt))
5151 continue;
5152
5153 // Bail out if we can't determine if this constant is min/max or if we
5154 // know that this constant is min/max.
5155 auto *CI = dyn_cast<ConstantInt>(Elt);
5156 if (!CI || !ConstantIsOk(CI))
5157 return llvm::None;
5158 }
5159 } else {
5160 // ConstantExpr?
5161 return llvm::None;
5162 }
5163
5164 CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred);
5165
5166 // Increment or decrement the constant.
5167 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
5168 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
5169
5170 return std::make_pair(NewPred, NewC);
5171}
5172
5173/// If we have an icmp le or icmp ge instruction with a constant operand, turn
5174/// it into the appropriate icmp lt or icmp gt instruction. This transform
5175/// allows them to be folded in visitICmpInst.
5176static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
5177 ICmpInst::Predicate Pred = I.getPredicate();
5178 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
5179 isCanonicalPredicate(Pred))
5180 return nullptr;
5181
5182 Value *Op0 = I.getOperand(0);
5183 Value *Op1 = I.getOperand(1);
5184 auto *Op1C = dyn_cast<Constant>(Op1);
5185 if (!Op1C)
5186 return nullptr;
5187
5188 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
5189 if (!FlippedStrictness)
5190 return nullptr;
5191
5192 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
5193}
5194
5195/// Integer compare with boolean values can always be turned into bitwise ops.
5196static Instruction *canonicalizeICmpBool(ICmpInst &I,
5197 InstCombiner::BuilderTy &Builder) {
5198 Value *A = I.getOperand(0), *B = I.getOperand(1);
5199 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only")((A->getType()->isIntOrIntVectorTy(1) && "Bools only"
) ? static_cast<void> (0) : __assert_fail ("A->getType()->isIntOrIntVectorTy(1) && \"Bools only\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5199, __PRETTY_FUNCTION__))
;
5200
5201 // A boolean compared to true/false can be simplified to Op0/true/false in
5202 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
5203 // Cases not handled by InstSimplify are always 'not' of Op0.
5204 if (match(B, m_Zero())) {
5205 switch (I.getPredicate()) {
5206 case CmpInst::ICMP_EQ: // A == 0 -> !A
5207 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
5208 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
5209 return BinaryOperator::CreateNot(A);
5210 default:
5211 llvm_unreachable("ICmp i1 X, C not simplified as expected.")::llvm::llvm_unreachable_internal("ICmp i1 X, C not simplified as expected."
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5211)
;
5212 }
5213 } else if (match(B, m_One())) {
5214 switch (I.getPredicate()) {
5215 case CmpInst::ICMP_NE: // A != 1 -> !A
5216 case CmpInst::ICMP_ULT: // A <u 1 -> !A
5217 case CmpInst::ICMP_SGT: // A >s -1 -> !A
5218 return BinaryOperator::CreateNot(A);
5219 default:
5220 llvm_unreachable("ICmp i1 X, C not simplified as expected.")::llvm::llvm_unreachable_internal("ICmp i1 X, C not simplified as expected."
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5220)
;
5221 }
5222 }
5223
5224 switch (I.getPredicate()) {
5225 default:
5226 llvm_unreachable("Invalid icmp instruction!")::llvm::llvm_unreachable_internal("Invalid icmp instruction!"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5226)
;
5227 case ICmpInst::ICMP_EQ:
5228 // icmp eq i1 A, B -> ~(A ^ B)
5229 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
5230
5231 case ICmpInst::ICMP_NE:
5232 // icmp ne i1 A, B -> A ^ B
5233 return BinaryOperator::CreateXor(A, B);
5234
5235 case ICmpInst::ICMP_UGT:
5236 // icmp ugt -> icmp ult
5237 std::swap(A, B);
5238 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5239 case ICmpInst::ICMP_ULT:
5240 // icmp ult i1 A, B -> ~A & B
5241 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
5242
5243 case ICmpInst::ICMP_SGT:
5244 // icmp sgt -> icmp slt
5245 std::swap(A, B);
5246 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5247 case ICmpInst::ICMP_SLT:
5248 // icmp slt i1 A, B -> A & ~B
5249 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
5250
5251 case ICmpInst::ICMP_UGE:
5252 // icmp uge -> icmp ule
5253 std::swap(A, B);
5254 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5255 case ICmpInst::ICMP_ULE:
5256 // icmp ule i1 A, B -> ~A | B
5257 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
5258
5259 case ICmpInst::ICMP_SGE:
5260 // icmp sge -> icmp sle
5261 std::swap(A, B);
5262 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5263 case ICmpInst::ICMP_SLE:
5264 // icmp sle i1 A, B -> A | ~B
5265 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
5266 }
5267}
5268
5269// Transform pattern like:
5270// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
5271// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
5272// Into:
5273// (X l>> Y) != 0
5274// (X l>> Y) == 0
5275static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
5276 InstCombiner::BuilderTy &Builder) {
5277 ICmpInst::Predicate Pred, NewPred;
5278 Value *X, *Y;
5279 if (match(&Cmp,
12
Calling 'match<llvm::ICmpInst, llvm::PatternMatch::CmpClass_match<llvm::PatternMatch::OneUse_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false> >, llvm::PatternMatch::bind_ty<llvm::Value>, llvm::ICmpInst, llvm::CmpInst::Predicate, true>>'
27
Returning from 'match<llvm::ICmpInst, llvm::PatternMatch::CmpClass_match<llvm::PatternMatch::OneUse_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false> >, llvm::PatternMatch::bind_ty<llvm::Value>, llvm::ICmpInst, llvm::CmpInst::Predicate, true>>'
28
Taking false branch
5280 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
1
Calling 'm_Value'
5
Returning from 'm_Value'
6
Calling 'm_c_ICmp<llvm::PatternMatch::OneUse_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false> >, llvm::PatternMatch::bind_ty<llvm::Value>>'
11
Returning from 'm_c_ICmp<llvm::PatternMatch::OneUse_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false> >, llvm::PatternMatch::bind_ty<llvm::Value>>'
5281 // We want X to be the icmp's second operand, so swap predicate if it isn't.
5282 if (Cmp.getOperand(0) == X)
5283 Pred = Cmp.getSwappedPredicate();
5284
5285 switch (Pred) {
5286 case ICmpInst::ICMP_ULE:
5287 NewPred = ICmpInst::ICMP_NE;
5288 break;
5289 case ICmpInst::ICMP_UGT:
5290 NewPred = ICmpInst::ICMP_EQ;
5291 break;
5292 default:
5293 return nullptr;
5294 }
5295 } else if (match(&Cmp, m_c_ICmp(Pred,
34
Calling 'm_c_ICmp<llvm::PatternMatch::OneUse_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 30, true>, llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 13, false> > >, llvm::PatternMatch::bind_ty<llvm::Value>>'
39
Returning from 'm_c_ICmp<llvm::PatternMatch::OneUse_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 30, true>, llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 13, false> > >, llvm::PatternMatch::bind_ty<llvm::Value>>'
40
Calling 'match<llvm::ICmpInst, llvm::PatternMatch::CmpClass_match<llvm::PatternMatch::OneUse_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 30, true>, llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 13, false> > >, llvm::PatternMatch::bind_ty<llvm::Value>, llvm::ICmpInst, llvm::CmpInst::Predicate, true>>'
61
Returning from 'match<llvm::ICmpInst, llvm::PatternMatch::CmpClass_match<llvm::PatternMatch::OneUse_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 30, true>, llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_one>, llvm::PatternMatch::bind_ty<llvm::Value>, 25, false>, llvm::PatternMatch::cst_pred_ty<llvm::PatternMatch::is_all_ones>, 13, false> > >, llvm::PatternMatch::bind_ty<llvm::Value>, llvm::ICmpInst, llvm::CmpInst::Predicate, true>>'
62
Taking true branch
5296 m_OneUse(m_CombineOr(
5297 m_Not(m_Shl(m_AllOnes(), m_Value(Y))),
5298 m_Add(m_Shl(m_One(), m_Value(Y)),
5299 m_AllOnes()))),
5300 m_Value(X)))) {
29
Calling 'm_Value'
33
Returning from 'm_Value'
5301 // The variant with 'add' is not canonical, (the variant with 'not' is)
5302 // we only get it because it has extra uses, and can't be canonicalized,
5303
5304 // We want X to be the icmp's second operand, so swap predicate if it isn't.
5305 if (Cmp.getOperand(0) == X)
63
Assuming pointer value is null
64
Taking true branch
5306 Pred = Cmp.getSwappedPredicate();
5307
5308 switch (Pred) {
65
Control jumps to 'case ICMP_UGE:' at line 5312
5309 case ICmpInst::ICMP_ULT:
5310 NewPred = ICmpInst::ICMP_NE;
5311 break;
5312 case ICmpInst::ICMP_UGE:
5313 NewPred = ICmpInst::ICMP_EQ;
5314 break;
66
Execution continues on line 5321
5315 default:
5316 return nullptr;
5317 }
5318 } else
5319 return nullptr;
5320
5321 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
67
Called C++ object pointer is null
5322 Constant *Zero = Constant::getNullValue(NewX->getType());
5323 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
5324}
5325
5326static Instruction *foldVectorCmp(CmpInst &Cmp,
5327 InstCombiner::BuilderTy &Builder) {
5328 // If both arguments of the cmp are shuffles that use the same mask and
5329 // shuffle within a single vector, move the shuffle after the cmp.
5330 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
5331 Value *V1, *V2;
5332 Constant *M;
5333 if (match(LHS, m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(M))) &&
5334 match(RHS, m_ShuffleVector(m_Value(V2), m_Undef(), m_Specific(M))) &&
5335 V1->getType() == V2->getType() &&
5336 (LHS->hasOneUse() || RHS->hasOneUse())) {
5337 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
5338 CmpInst::Predicate P = Cmp.getPredicate();
5339 Value *NewCmp = isa<ICmpInst>(Cmp) ? Builder.CreateICmp(P, V1, V2)
5340 : Builder.CreateFCmp(P, V1, V2);
5341 return new ShuffleVectorInst(NewCmp, UndefValue::get(NewCmp->getType()), M);
5342 }
5343 return nullptr;
5344}
5345
5346Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5347 bool Changed = false;
5348 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5349 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5350 unsigned Op0Cplxity = getComplexity(Op0);
5351 unsigned Op1Cplxity = getComplexity(Op1);
5352
5353 /// Orders the operands of the compare so that they are listed from most
5354 /// complex to least complex. This puts constants before unary operators,
5355 /// before binary operators.
5356 if (Op0Cplxity < Op1Cplxity ||
5357 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
5358 I.swapOperands();
5359 std::swap(Op0, Op1);
5360 Changed = true;
5361 }
5362
5363 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, Q))
5364 return replaceInstUsesWith(I, V);
5365
5366 // Comparing -val or val with non-zero is the same as just comparing val
5367 // ie, abs(val) != 0 -> val != 0
5368 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
5369 Value *Cond, *SelectTrue, *SelectFalse;
5370 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
5371 m_Value(SelectFalse)))) {
5372 if (Value *V = dyn_castNegVal(SelectTrue)) {
5373 if (V == SelectFalse)
5374 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
5375 }
5376 else if (Value *V = dyn_castNegVal(SelectFalse)) {
5377 if (V == SelectTrue)
5378 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
5379 }
5380 }
5381 }
5382
5383 if (Op0->getType()->isIntOrIntVectorTy(1))
5384 if (Instruction *Res = canonicalizeICmpBool(I, Builder))
5385 return Res;
5386
5387 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
5388 return NewICmp;
5389
5390 if (Instruction *Res = foldICmpWithConstant(I))
5391 return Res;
5392
5393 if (Instruction *Res = foldICmpWithDominatingICmp(I))
5394 return Res;
5395
5396 if (Instruction *Res = foldICmpBinOp(I, Q))
5397 return Res;
5398
5399 if (Instruction *Res = foldICmpUsingKnownBits(I))
5400 return Res;
5401
5402 // Test if the ICmpInst instruction is used exclusively by a select as
5403 // part of a minimum or maximum operation. If so, refrain from doing
5404 // any other folding. This helps out other analyses which understand
5405 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5406 // and CodeGen. And in this case, at least one of the comparison
5407 // operands has at least one user besides the compare (the select),
5408 // which would often largely negate the benefit of folding anyway.
5409 //
5410 // Do the same for the other patterns recognized by matchSelectPattern.
5411 if (I.hasOneUse())
5412 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
5413 Value *A, *B;
5414 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
5415 if (SPR.Flavor != SPF_UNKNOWN)
5416 return nullptr;
5417 }
5418
5419 // Do this after checking for min/max to prevent infinite looping.
5420 if (Instruction *Res = foldICmpWithZero(I))
5421 return Res;
5422
5423 // FIXME: We only do this after checking for min/max to prevent infinite
5424 // looping caused by a reverse canonicalization of these patterns for min/max.
5425 // FIXME: The organization of folds is a mess. These would naturally go into
5426 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
5427 // down here after the min/max restriction.
5428 ICmpInst::Predicate Pred = I.getPredicate();
5429 const APInt *C;
5430 if (match(Op1, m_APInt(C))) {
5431 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
5432 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
5433 Constant *Zero = Constant::getNullValue(Op0->getType());
5434 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
5435 }
5436
5437 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
5438 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
5439 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
5440 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
5441 }
5442 }
5443
5444 if (Instruction *Res = foldICmpInstWithConstant(I))
5445 return Res;
5446
5447 // Try to match comparison as a sign bit test. Intentionally do this after
5448 // foldICmpInstWithConstant() to potentially let other folds to happen first.
5449 if (Instruction *New = foldSignBitTest(I))
5450 return New;
5451
5452 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
5453 return Res;
5454
5455 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5456 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
5457 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
5458 return NI;
5459 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
5460 if (Instruction *NI = foldGEPICmp(GEP, Op0,
5461 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5462 return NI;
5463
5464 // Try to optimize equality comparisons against alloca-based pointers.
5465 if (Op0->getType()->isPointerTy() && I.isEquality()) {
5466 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?")((Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?"
) ? static_cast<void> (0) : __assert_fail ("Op1->getType()->isPointerTy() && \"Comparing pointer with non-pointer?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5466, __PRETTY_FUNCTION__))
;
5467 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
5468 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
5469 return New;
5470 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
5471 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
5472 return New;
5473 }
5474
5475 if (Instruction *Res = foldICmpBitCast(I, Builder))
5476 return Res;
5477
5478 if (Instruction *R = foldICmpWithCastOp(I))
5479 return R;
5480
5481 if (Instruction *Res = foldICmpWithMinMax(I))
5482 return Res;
5483
5484 {
5485 Value *A, *B;
5486 // Transform (A & ~B) == 0 --> (A & B) != 0
5487 // and (A & ~B) != 0 --> (A & B) == 0
5488 // if A is a power of 2.
5489 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
5490 match(Op1, m_Zero()) &&
5491 isKnownToBeAPowerOfTwo(A, false, 0, &I) && I.isEquality())
5492 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(A, B),
5493 Op1);
5494
5495 // ~X < ~Y --> Y < X
5496 // ~X < C --> X > ~C
5497 if (match(Op0, m_Not(m_Value(A)))) {
5498 if (match(Op1, m_Not(m_Value(B))))
5499 return new ICmpInst(I.getPredicate(), B, A);
5500
5501 const APInt *C;
5502 if (match(Op1, m_APInt(C)))
5503 return new ICmpInst(I.getSwappedPredicate(), A,
5504 ConstantInt::get(Op1->getType(), ~(*C)));
5505 }
5506
5507 Instruction *AddI = nullptr;
5508 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
5509 m_Instruction(AddI))) &&
5510 isa<IntegerType>(A->getType())) {
5511 Value *Result;
5512 Constant *Overflow;
5513 if (OptimizeOverflowCheck(Instruction::Add, /*Signed*/false, A, B,
5514 *AddI, Result, Overflow)) {
5515 replaceInstUsesWith(*AddI, Result);
5516 return replaceInstUsesWith(I, Overflow);
5517 }
5518 }
5519
5520 // (zext a) * (zext b) --> llvm.umul.with.overflow.
5521 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
5522 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this))
5523 return R;
5524 }
5525 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
5526 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this))
5527 return R;
5528 }
5529 }
5530
5531 if (Instruction *Res = foldICmpEquality(I))
5532 return Res;
5533
5534 // The 'cmpxchg' instruction returns an aggregate containing the old value and
5535 // an i1 which indicates whether or not we successfully did the swap.
5536 //
5537 // Replace comparisons between the old value and the expected value with the
5538 // indicator that 'cmpxchg' returns.
5539 //
5540 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
5541 // spuriously fail. In those cases, the old value may equal the expected
5542 // value but it is possible for the swap to not occur.
5543 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5544 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
5545 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
5546 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
5547 !ACXI->isWeak())
5548 return ExtractValueInst::Create(ACXI, 1);
5549
5550 {
5551 Value *X;
5552 const APInt *C;
5553 // icmp X+Cst, X
5554 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
5555 return foldICmpAddOpConst(X, *C, I.getPredicate());
5556
5557 // icmp X, X+Cst
5558 if (match(Op1, m_Add(m_Value(X), m_APInt(C))) && Op0 == X)
5559 return foldICmpAddOpConst(X, *C, I.getSwappedPredicate());
5560 }
5561
5562 if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))
5563 return Res;
5564
5565 if (I.getType()->isVectorTy())
5566 if (Instruction *Res = foldVectorCmp(I, Builder))
5567 return Res;
5568
5569 return Changed ? &I : nullptr;
5570}
5571
5572/// Fold fcmp ([us]itofp x, cst) if possible.
5573Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
5574 Constant *RHSC) {
5575 if (!isa<ConstantFP>(RHSC)) return nullptr;
5576 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5577
5578 // Get the width of the mantissa. We don't want to hack on conversions that
5579 // might lose information from the integer, e.g. "i64 -> float"
5580 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5581 if (MantissaWidth == -1) return nullptr; // Unknown.
5582
5583 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5584
5585 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5586
5587 if (I.isEquality()) {
5588 FCmpInst::Predicate P = I.getPredicate();
5589 bool IsExact = false;
5590 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
5591 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
5592
5593 // If the floating point constant isn't an integer value, we know if we will
5594 // ever compare equal / not equal to it.
5595 if (!IsExact) {
5596 // TODO: Can never be -0.0 and other non-representable values
5597 APFloat RHSRoundInt(RHS);
5598 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
5599 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
5600 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
5601 return replaceInstUsesWith(I, Builder.getFalse());
5602
5603 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE)((P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE) ? static_cast
<void> (0) : __assert_fail ("P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5603, __PRETTY_FUNCTION__))
;
5604 return replaceInstUsesWith(I, Builder.getTrue());
5605 }
5606 }
5607
5608 // TODO: If the constant is exactly representable, is it always OK to do
5609 // equality compares as integer?
5610 }
5611
5612 // Check to see that the input is converted from an integer type that is small
5613 // enough that preserves all bits. TODO: check here for "known" sign bits.
5614 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5615 unsigned InputSize = IntTy->getScalarSizeInBits();
5616
5617 // Following test does NOT adjust InputSize downwards for signed inputs,
5618 // because the most negative value still requires all the mantissa bits
5619 // to distinguish it from one less than that value.
5620 if ((int)InputSize > MantissaWidth) {
5621 // Conversion would lose accuracy. Check if loss can impact comparison.
5622 int Exp = ilogb(RHS);
5623 if (Exp == APFloat::IEK_Inf) {
5624 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
5625 if (MaxExponent < (int)InputSize - !LHSUnsigned)
5626 // Conversion could create infinity.
5627 return nullptr;
5628 } else {
5629 // Note that if RHS is zero or NaN, then Exp is negative
5630 // and first condition is trivially false.
5631 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
5632 // Conversion could affect comparison.
5633 return nullptr;
5634 }
5635 }
5636
5637 // Otherwise, we can potentially simplify the comparison. We know that it
5638 // will always come through as an integer value and we know the constant is
5639 // not a NAN (it would have been previously simplified).
5640 assert(!RHS.isNaN() && "NaN comparison not already folded!")((!RHS.isNaN() && "NaN comparison not already folded!"
) ? static_cast<void> (0) : __assert_fail ("!RHS.isNaN() && \"NaN comparison not already folded!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5640, __PRETTY_FUNCTION__))
;
5641
5642 ICmpInst::Predicate Pred;
5643 switch (I.getPredicate()) {
5644 default: llvm_unreachable("Unexpected predicate!")::llvm::llvm_unreachable_internal("Unexpected predicate!", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5644)
;
5645 case FCmpInst::FCMP_UEQ:
5646 case FCmpInst::FCMP_OEQ:
5647 Pred = ICmpInst::ICMP_EQ;
5648 break;
5649 case FCmpInst::FCMP_UGT:
5650 case FCmpInst::FCMP_OGT:
5651 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5652 break;
5653 case FCmpInst::FCMP_UGE:
5654 case FCmpInst::FCMP_OGE:
5655 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5656 break;
5657 case FCmpInst::FCMP_ULT:
5658 case FCmpInst::FCMP_OLT:
5659 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5660 break;
5661 case FCmpInst::FCMP_ULE:
5662 case FCmpInst::FCMP_OLE:
5663 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5664 break;
5665 case FCmpInst::FCMP_UNE:
5666 case FCmpInst::FCMP_ONE:
5667 Pred = ICmpInst::ICMP_NE;
5668 break;
5669 case FCmpInst::FCMP_ORD:
5670 return replaceInstUsesWith(I, Builder.getTrue());
5671 case FCmpInst::FCMP_UNO:
5672 return replaceInstUsesWith(I, Builder.getFalse());
5673 }
5674
5675 // Now we know that the APFloat is a normal number, zero or inf.
5676
5677 // See if the FP constant is too large for the integer. For example,
5678 // comparing an i8 to 300.0.
5679 unsigned IntWidth = IntTy->getScalarSizeInBits();
5680
5681 if (!LHSUnsigned) {
5682 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5683 // and large values.
5684 APFloat SMax(RHS.getSemantics());
5685 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5686 APFloat::rmNearestTiesToEven);
5687 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5688 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5689 Pred == ICmpInst::ICMP_SLE)
5690 return replaceInstUsesWith(I, Builder.getTrue());
5691 return replaceInstUsesWith(I, Builder.getFalse());
5692 }
5693 } else {
5694 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5695 // +INF and large values.
5696 APFloat UMax(RHS.getSemantics());
5697 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5698 APFloat::rmNearestTiesToEven);
5699 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5700 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5701 Pred == ICmpInst::ICMP_ULE)
5702 return replaceInstUsesWith(I, Builder.getTrue());
5703 return replaceInstUsesWith(I, Builder.getFalse());
5704 }
5705 }
5706
5707 if (!LHSUnsigned) {
5708 // See if the RHS value is < SignedMin.
5709 APFloat SMin(RHS.getSemantics());
5710 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5711 APFloat::rmNearestTiesToEven);
5712 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5713 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5714 Pred == ICmpInst::ICMP_SGE)
5715 return replaceInstUsesWith(I, Builder.getTrue());
5716 return replaceInstUsesWith(I, Builder.getFalse());
5717 }
5718 } else {
5719 // See if the RHS value is < UnsignedMin.
5720 APFloat SMin(RHS.getSemantics());
5721 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
5722 APFloat::rmNearestTiesToEven);
5723 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
5724 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
5725 Pred == ICmpInst::ICMP_UGE)
5726 return replaceInstUsesWith(I, Builder.getTrue());
5727 return replaceInstUsesWith(I, Builder.getFalse());
5728 }
5729 }
5730
5731 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5732 // [0, UMAX], but it may still be fractional. See if it is fractional by
5733 // casting the FP value to the integer value and back, checking for equality.
5734 // Don't do this for zero, because -0.0 is not fractional.
5735 Constant *RHSInt = LHSUnsigned
5736 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5737 : ConstantExpr::getFPToSI(RHSC, IntTy);
5738 if (!RHS.isZero()) {
5739 bool Equal = LHSUnsigned
5740 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5741 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5742 if (!Equal) {
5743 // If we had a comparison against a fractional value, we have to adjust
5744 // the compare predicate and sometimes the value. RHSC is rounded towards
5745 // zero at this point.
5746 switch (Pred) {
5747 default: llvm_unreachable("Unexpected integer comparison!")::llvm::llvm_unreachable_internal("Unexpected integer comparison!"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineCompares.cpp"
, 5747)
;
5748 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5749 return replaceInstUsesWith(I, Builder.getTrue());
5750 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5751 return replaceInstUsesWith(I, Builder.getFalse());
5752 case ICmpInst::ICMP_ULE:
5753 // (float)int <= 4.4 --> int <= 4
5754 // (float)int <= -4.4 --> false
5755 if (RHS.isNegative())
5756 return replaceInstUsesWith(I, Builder.getFalse());
5757 break;
5758 case ICmpInst::ICMP_SLE:
5759 // (float)int <= 4.4 --> int <= 4
5760 // (float)int <= -4.4 --> int < -4
5761 if (RHS.isNegative())
5762 Pred = ICmpInst::ICMP_SLT;
5763 break;
5764 case ICmpInst::ICMP_ULT:
5765 // (float)int < -4.4 --> false
5766 // (float)int < 4.4 --> int <= 4
5767 if (RHS.isNegative())
5768 return replaceInstUsesWith(I, Builder.getFalse());
5769 Pred = ICmpInst::ICMP_ULE;
5770 break;
5771 case ICmpInst::ICMP_SLT:
5772 // (float)int < -4.4 --> int < -4
5773 // (float)int < 4.4 --> int <= 4
5774 if (!RHS.isNegative())
5775 Pred = ICmpInst::ICMP_SLE;
5776 break;
5777 case ICmpInst::ICMP_UGT:
5778 // (float)int > 4.4 --> int > 4
5779 // (float)int > -4.4 --> true
5780 if (RHS.isNegative())
5781 return replaceInstUsesWith(I, Builder.getTrue());
5782 break;
5783 case ICmpInst::ICMP_SGT:
5784 // (float)int > 4.4 --> int > 4
5785 // (float)int > -4.4 --> int >= -4
5786 if (RHS.isNegative())
5787 Pred = ICmpInst::ICMP_SGE;
5788 break