blob: 42db444ff6d7926648669dc43e6777ca7755430c [file] [log] [blame]
Chris Lattner02446fc2010-01-04 07:37:31 +00001//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitICmp and visitFCmp functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/IntrinsicInst.h"
16#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Analysis/MemoryBuiltins.h"
18#include "llvm/Target/TargetData.h"
19#include "llvm/Support/ConstantRange.h"
20#include "llvm/Support/GetElementPtrTypeIterator.h"
21#include "llvm/Support/PatternMatch.h"
22using namespace llvm;
23using namespace PatternMatch;
24
Chris Lattnerb20c0b52011-02-10 05:23:05 +000025static ConstantInt *getOne(Constant *C) {
26 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
27}
28
Chris Lattner02446fc2010-01-04 07:37:31 +000029/// AddOne - Add one to a ConstantInt
30static Constant *AddOne(Constant *C) {
31 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
32}
33/// SubOne - Subtract one from a ConstantInt
Chris Lattnerb20c0b52011-02-10 05:23:05 +000034static Constant *SubOne(Constant *C) {
35 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner02446fc2010-01-04 07:37:31 +000036}
37
38static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
39 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
40}
41
42static bool HasAddOverflow(ConstantInt *Result,
43 ConstantInt *In1, ConstantInt *In2,
44 bool IsSigned) {
45 if (IsSigned)
46 if (In2->getValue().isNegative())
47 return Result->getValue().sgt(In1->getValue());
48 else
49 return Result->getValue().slt(In1->getValue());
50 else
51 return Result->getValue().ult(In1->getValue());
52}
53
54/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
55/// overflowed for this type.
56static bool AddWithOverflow(Constant *&Result, Constant *In1,
57 Constant *In2, bool IsSigned = false) {
58 Result = ConstantExpr::getAdd(In1, In2);
59
60 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
61 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
62 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
63 if (HasAddOverflow(ExtractElement(Result, Idx),
64 ExtractElement(In1, Idx),
65 ExtractElement(In2, Idx),
66 IsSigned))
67 return true;
68 }
69 return false;
70 }
71
72 return HasAddOverflow(cast<ConstantInt>(Result),
73 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
74 IsSigned);
75}
76
77static bool HasSubOverflow(ConstantInt *Result,
78 ConstantInt *In1, ConstantInt *In2,
79 bool IsSigned) {
80 if (IsSigned)
81 if (In2->getValue().isNegative())
82 return Result->getValue().slt(In1->getValue());
83 else
84 return Result->getValue().sgt(In1->getValue());
85 else
86 return Result->getValue().ugt(In1->getValue());
87}
88
89/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
90/// overflowed for this type.
91static bool SubWithOverflow(Constant *&Result, Constant *In1,
92 Constant *In2, bool IsSigned = false) {
93 Result = ConstantExpr::getSub(In1, In2);
94
95 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
96 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
97 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
98 if (HasSubOverflow(ExtractElement(Result, Idx),
99 ExtractElement(In1, Idx),
100 ExtractElement(In2, Idx),
101 IsSigned))
102 return true;
103 }
104 return false;
105 }
106
107 return HasSubOverflow(cast<ConstantInt>(Result),
108 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
109 IsSigned);
110}
111
112/// isSignBitCheck - Given an exploded icmp instruction, return true if the
113/// comparison only checks the sign bit. If it only checks the sign bit, set
114/// TrueIfSigned if the result of the comparison is true when the input value is
115/// signed.
116static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
117 bool &TrueIfSigned) {
118 switch (pred) {
119 case ICmpInst::ICMP_SLT: // True if LHS s< 0
120 TrueIfSigned = true;
121 return RHS->isZero();
122 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
123 TrueIfSigned = true;
124 return RHS->isAllOnesValue();
125 case ICmpInst::ICMP_SGT: // True if LHS s> -1
126 TrueIfSigned = false;
127 return RHS->isAllOnesValue();
128 case ICmpInst::ICMP_UGT:
129 // True if LHS u> RHS and RHS == high-bit-mask - 1
130 TrueIfSigned = true;
131 return RHS->getValue() ==
132 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
133 case ICmpInst::ICMP_UGE:
134 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
135 TrueIfSigned = true;
136 return RHS->getValue().isSignBit();
137 default:
138 return false;
139 }
140}
141
142// isHighOnes - Return true if the constant is of the form 1+0+.
143// This is the same as lowones(~X).
144static bool isHighOnes(const ConstantInt *CI) {
145 return (~CI->getValue() + 1).isPowerOf2();
146}
147
148/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
149/// set of known zero and one bits, compute the maximum and minimum values that
150/// could have the specified known zero and known one bits, returning them in
151/// min/max.
152static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
153 const APInt& KnownOne,
154 APInt& Min, APInt& Max) {
155 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
156 KnownZero.getBitWidth() == Min.getBitWidth() &&
157 KnownZero.getBitWidth() == Max.getBitWidth() &&
158 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
159 APInt UnknownBits = ~(KnownZero|KnownOne);
160
161 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
162 // bit if it is unknown.
163 Min = KnownOne;
164 Max = KnownOne|UnknownBits;
165
166 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad7a874dd2010-12-01 08:53:58 +0000167 Min.setBit(Min.getBitWidth()-1);
168 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000169 }
170}
171
172// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
173// a set of known zero and one bits, compute the maximum and minimum values that
174// could have the specified known zero and known one bits, returning them in
175// min/max.
176static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
177 const APInt &KnownOne,
178 APInt &Min, APInt &Max) {
179 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
180 KnownZero.getBitWidth() == Min.getBitWidth() &&
181 KnownZero.getBitWidth() == Max.getBitWidth() &&
182 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
183 APInt UnknownBits = ~(KnownZero|KnownOne);
184
185 // The minimum value is when the unknown bits are all zeros.
186 Min = KnownOne;
187 // The maximum value is when the unknown bits are all ones.
188 Max = KnownOne|UnknownBits;
189}
190
191
192
193/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
194/// cmp pred (load (gep GV, ...)), cmpcst
195/// where GV is a global variable with a constant initializer. Try to simplify
196/// this into some simple computation that does not need the load. For example
197/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
198///
199/// If AndCst is non-null, then the loaded value is masked with that constant
200/// before doing the comparison. This handles cases like "A[i]&4 == 0".
201Instruction *InstCombiner::
202FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
203 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000204 // We need TD information to know the pointer size unless this is inbounds.
205 if (!GEP->isInBounds() && TD == 0) return 0;
206
Chris Lattner02446fc2010-01-04 07:37:31 +0000207 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
208 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
209
210 // There are many forms of this optimization we can handle, for now, just do
211 // the simple index into a single-dimensional array.
212 //
213 // Require: GEP GV, 0, i {{, constant indices}}
214 if (GEP->getNumOperands() < 3 ||
215 !isa<ConstantInt>(GEP->getOperand(1)) ||
216 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
217 isa<Constant>(GEP->getOperand(2)))
218 return 0;
219
220 // Check that indices after the variable are constants and in-range for the
221 // type they index. Collect the indices. This is typically for arrays of
222 // structs.
223 SmallVector<unsigned, 4> LaterIndices;
224
225 const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
226 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
227 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
228 if (Idx == 0) return 0; // Variable index.
229
230 uint64_t IdxVal = Idx->getZExtValue();
231 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
232
233 if (const StructType *STy = dyn_cast<StructType>(EltTy))
234 EltTy = STy->getElementType(IdxVal);
235 else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
236 if (IdxVal >= ATy->getNumElements()) return 0;
237 EltTy = ATy->getElementType();
238 } else {
239 return 0; // Unknown type.
240 }
241
242 LaterIndices.push_back(IdxVal);
243 }
244
245 enum { Overdefined = -3, Undefined = -2 };
246
247 // Variables for our state machines.
248
249 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
250 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
251 // and 87 is the second (and last) index. FirstTrueElement is -2 when
252 // undefined, otherwise set to the first true element. SecondTrueElement is
253 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
254 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
255
256 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
257 // form "i != 47 & i != 87". Same state transitions as for true elements.
258 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
259
260 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
261 /// define a state machine that triggers for ranges of values that the index
262 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
263 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
264 /// index in the range (inclusive). We use -2 for undefined here because we
265 /// use relative comparisons and don't want 0-1 to match -1.
266 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
267
268 // MagicBitvector - This is a magic bitvector where we set a bit if the
269 // comparison is true for element 'i'. If there are 64 elements or less in
270 // the array, this will fully represent all the comparison results.
271 uint64_t MagicBitvector = 0;
272
273
274 // Scan the array and see if one of our patterns matches.
275 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
276 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
277 Constant *Elt = Init->getOperand(i);
278
279 // If this is indexing an array of structures, get the structure element.
280 if (!LaterIndices.empty())
281 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(),
282 LaterIndices.size());
283
284 // If the element is masked, handle it.
285 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
286
287 // Find out if the comparison would be true or false for the i'th element.
288 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
289 CompareRHS, TD);
290 // If the result is undef for this element, ignore it.
291 if (isa<UndefValue>(C)) {
292 // Extend range state machines to cover this element in case there is an
293 // undef in the middle of the range.
294 if (TrueRangeEnd == (int)i-1)
295 TrueRangeEnd = i;
296 if (FalseRangeEnd == (int)i-1)
297 FalseRangeEnd = i;
298 continue;
299 }
300
301 // If we can't compute the result for any of the elements, we have to give
302 // up evaluating the entire conditional.
303 if (!isa<ConstantInt>(C)) return 0;
304
305 // Otherwise, we know if the comparison is true or false for this element,
306 // update our state machines.
307 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
308
309 // State machine for single/double/range index comparison.
310 if (IsTrueForElt) {
311 // Update the TrueElement state machine.
312 if (FirstTrueElement == Undefined)
313 FirstTrueElement = TrueRangeEnd = i; // First true element.
314 else {
315 // Update double-compare state machine.
316 if (SecondTrueElement == Undefined)
317 SecondTrueElement = i;
318 else
319 SecondTrueElement = Overdefined;
320
321 // Update range state machine.
322 if (TrueRangeEnd == (int)i-1)
323 TrueRangeEnd = i;
324 else
325 TrueRangeEnd = Overdefined;
326 }
327 } else {
328 // Update the FalseElement state machine.
329 if (FirstFalseElement == Undefined)
330 FirstFalseElement = FalseRangeEnd = i; // First false element.
331 else {
332 // Update double-compare state machine.
333 if (SecondFalseElement == Undefined)
334 SecondFalseElement = i;
335 else
336 SecondFalseElement = Overdefined;
337
338 // Update range state machine.
339 if (FalseRangeEnd == (int)i-1)
340 FalseRangeEnd = i;
341 else
342 FalseRangeEnd = Overdefined;
343 }
344 }
345
346
347 // If this element is in range, update our magic bitvector.
348 if (i < 64 && IsTrueForElt)
349 MagicBitvector |= 1ULL << i;
350
351 // If all of our states become overdefined, bail out early. Since the
352 // predicate is expensive, only check it every 8 elements. This is only
353 // really useful for really huge arrays.
354 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
355 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
356 FalseRangeEnd == Overdefined)
357 return 0;
358 }
359
360 // Now that we've scanned the entire array, emit our new comparison(s). We
361 // order the state machines in complexity of the generated code.
362 Value *Idx = GEP->getOperand(2);
363
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000364 // If the index is larger than the pointer size of the target, truncate the
365 // index down like the GEP would do implicitly. We don't have to do this for
366 // an inbounds GEP because the index can't be out of range.
367 if (!GEP->isInBounds() &&
368 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
369 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
Chris Lattner02446fc2010-01-04 07:37:31 +0000370
371 // If the comparison is only true for one or two elements, emit direct
372 // comparisons.
373 if (SecondTrueElement != Overdefined) {
374 // None true -> false.
375 if (FirstTrueElement == Undefined)
376 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
377
378 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
379
380 // True for one element -> 'i == 47'.
381 if (SecondTrueElement == Undefined)
382 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
383
384 // True for two elements -> 'i == 47 | i == 72'.
385 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
386 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
387 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
388 return BinaryOperator::CreateOr(C1, C2);
389 }
390
391 // If the comparison is only false for one or two elements, emit direct
392 // comparisons.
393 if (SecondFalseElement != Overdefined) {
394 // None false -> true.
395 if (FirstFalseElement == Undefined)
396 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
397
398 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
399
400 // False for one element -> 'i != 47'.
401 if (SecondFalseElement == Undefined)
402 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
403
404 // False for two elements -> 'i != 47 & i != 72'.
405 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
406 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
407 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
408 return BinaryOperator::CreateAnd(C1, C2);
409 }
410
411 // If the comparison can be replaced with a range comparison for the elements
412 // where it is true, emit the range check.
413 if (TrueRangeEnd != Overdefined) {
414 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
415
416 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
417 if (FirstTrueElement) {
418 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
419 Idx = Builder->CreateAdd(Idx, Offs);
420 }
421
422 Value *End = ConstantInt::get(Idx->getType(),
423 TrueRangeEnd-FirstTrueElement+1);
424 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
425 }
426
427 // False range check.
428 if (FalseRangeEnd != Overdefined) {
429 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
430 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
431 if (FirstFalseElement) {
432 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
433 Idx = Builder->CreateAdd(Idx, Offs);
434 }
435
436 Value *End = ConstantInt::get(Idx->getType(),
437 FalseRangeEnd-FirstFalseElement);
438 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
439 }
440
441
442 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
443 // of this load, replace it with computation that does:
444 // ((magic_cst >> i) & 1) != 0
445 if (Init->getNumOperands() <= 32 ||
446 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
447 const Type *Ty;
448 if (Init->getNumOperands() <= 32)
449 Ty = Type::getInt32Ty(Init->getContext());
450 else
451 Ty = Type::getInt64Ty(Init->getContext());
452 Value *V = Builder->CreateIntCast(Idx, Ty, false);
453 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
454 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
455 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
456 }
457
458 return 0;
459}
460
461
462/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
463/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
464/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
465/// be complex, and scales are involved. The above expression would also be
466/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
467/// This later form is less amenable to optimization though, and we are allowed
468/// to generate the first by knowing that pointer arithmetic doesn't overflow.
469///
470/// If we can't emit an optimized form for this expression, this returns null.
471///
Eli Friedman107ffd52011-05-18 23:11:30 +0000472static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000473 TargetData &TD = *IC.getTargetData();
474 gep_type_iterator GTI = gep_type_begin(GEP);
475
476 // Check to see if this gep only has a single variable index. If so, and if
477 // any constant indices are a multiple of its scale, then we can compute this
478 // in terms of the scale of the variable index. For example, if the GEP
479 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
480 // because the expression will cross zero at the same point.
481 unsigned i, e = GEP->getNumOperands();
482 int64_t Offset = 0;
483 for (i = 1; i != e; ++i, ++GTI) {
484 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
485 // Compute the aggregate offset of constant indices.
486 if (CI->isZero()) continue;
487
488 // Handle a struct index, which adds its field offset to the pointer.
489 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
490 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
491 } else {
492 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
493 Offset += Size*CI->getSExtValue();
494 }
495 } else {
496 // Found our variable index.
497 break;
498 }
499 }
500
501 // If there are no variable indices, we must have a constant offset, just
502 // evaluate it the general way.
503 if (i == e) return 0;
504
505 Value *VariableIdx = GEP->getOperand(i);
506 // Determine the scale factor of the variable element. For example, this is
507 // 4 if the variable index is into an array of i32.
508 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
509
510 // Verify that there are no other variable indices. If so, emit the hard way.
511 for (++i, ++GTI; i != e; ++i, ++GTI) {
512 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
513 if (!CI) return 0;
514
515 // Compute the aggregate offset of constant indices.
516 if (CI->isZero()) continue;
517
518 // Handle a struct index, which adds its field offset to the pointer.
519 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
520 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
521 } else {
522 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
523 Offset += Size*CI->getSExtValue();
524 }
525 }
526
527 // Okay, we know we have a single variable index, which must be a
528 // pointer/array/vector index. If there is no offset, life is simple, return
529 // the index.
530 unsigned IntPtrWidth = TD.getPointerSizeInBits();
531 if (Offset == 0) {
532 // Cast to intptrty in case a truncation occurs. If an extension is needed,
533 // we don't need to bother extending: the extension won't affect where the
534 // computation crosses zero.
Eli Friedman107ffd52011-05-18 23:11:30 +0000535 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
536 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
537 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
538 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000539 return VariableIdx;
540 }
541
542 // Otherwise, there is an index. The computation we will do will be modulo
543 // the pointer size, so get it.
544 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
545
546 Offset &= PtrSizeMask;
547 VariableScale &= PtrSizeMask;
548
549 // To do this transformation, any constant index must be a multiple of the
550 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
551 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
552 // multiple of the variable scale.
553 int64_t NewOffs = Offset / (int64_t)VariableScale;
554 if (Offset != NewOffs*(int64_t)VariableScale)
555 return 0;
556
557 // Okay, we can do this evaluation. Start by converting the index to intptr.
558 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
559 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman107ffd52011-05-18 23:11:30 +0000560 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
561 true /*Signed*/);
Chris Lattner02446fc2010-01-04 07:37:31 +0000562 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman107ffd52011-05-18 23:11:30 +0000563 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner02446fc2010-01-04 07:37:31 +0000564}
565
566/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
567/// else. At this point we know that the GEP is on the LHS of the comparison.
568Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
569 ICmpInst::Predicate Cond,
570 Instruction &I) {
571 // Look through bitcasts.
572 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
573 RHS = BCI->getOperand(0);
574
575 Value *PtrBase = GEPLHS->getOperand(0);
576 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
577 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
578 // This transformation (ignoring the base and scales) is valid because we
579 // know pointers can't overflow since the gep is inbounds. See if we can
580 // output an optimized form.
Eli Friedman107ffd52011-05-18 23:11:30 +0000581 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Chris Lattner02446fc2010-01-04 07:37:31 +0000582
583 // If not, synthesize the offset the hard way.
584 if (Offset == 0)
585 Offset = EmitGEPOffset(GEPLHS);
586 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
587 Constant::getNullValue(Offset->getType()));
588 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
589 // If the base pointers are different, but the indices are the same, just
590 // compare the base pointer.
591 if (PtrBase != GEPRHS->getOperand(0)) {
592 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
593 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
594 GEPRHS->getOperand(0)->getType();
595 if (IndicesTheSame)
596 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
597 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
598 IndicesTheSame = false;
599 break;
600 }
601
602 // If all indices are the same, just compare the base pointers.
603 if (IndicesTheSame)
604 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
605 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
606
607 // Otherwise, the base pointers are different and the indices are
608 // different, bail out.
609 return 0;
610 }
611
612 // If one of the GEPs has all zero indices, recurse.
613 bool AllZeros = true;
614 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
615 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
616 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
617 AllZeros = false;
618 break;
619 }
620 if (AllZeros)
621 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
622 ICmpInst::getSwappedPredicate(Cond), I);
623
624 // If the other GEP has all zero indices, recurse.
625 AllZeros = true;
626 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
627 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
628 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
629 AllZeros = false;
630 break;
631 }
632 if (AllZeros)
633 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
634
Stuart Hastings67f071e2011-05-14 05:55:10 +0000635 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner02446fc2010-01-04 07:37:31 +0000636 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
637 // If the GEPs only differ by one index, compare it.
638 unsigned NumDifferences = 0; // Keep track of # differences.
639 unsigned DiffOperand = 0; // The operand that differs.
640 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
641 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
642 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
643 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
644 // Irreconcilable differences.
645 NumDifferences = 2;
646 break;
647 } else {
648 if (NumDifferences++) break;
649 DiffOperand = i;
650 }
651 }
652
653 if (NumDifferences == 0) // SAME GEP?
654 return ReplaceInstUsesWith(I, // No comparison is needed here.
655 ConstantInt::get(Type::getInt1Ty(I.getContext()),
656 ICmpInst::isTrueWhenEqual(Cond)));
657
Stuart Hastings67f071e2011-05-14 05:55:10 +0000658 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000659 Value *LHSV = GEPLHS->getOperand(DiffOperand);
660 Value *RHSV = GEPRHS->getOperand(DiffOperand);
661 // Make sure we do a signed comparison here.
662 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
663 }
664 }
665
666 // Only lower this if the icmp is the only user of the GEP or if we expect
667 // the result to fold to a constant!
668 if (TD &&
Stuart Hastings67f071e2011-05-14 05:55:10 +0000669 GEPsInBounds &&
Chris Lattner02446fc2010-01-04 07:37:31 +0000670 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
671 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
672 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
673 Value *L = EmitGEPOffset(GEPLHS);
674 Value *R = EmitGEPOffset(GEPRHS);
675 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
676 }
677 }
678 return 0;
679}
680
681/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
682Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
683 Value *X, ConstantInt *CI,
684 ICmpInst::Predicate Pred,
685 Value *TheAdd) {
686 // If we have X+0, exit early (simplifying logic below) and let it get folded
687 // elsewhere. icmp X+0, X -> icmp X, X
688 if (CI->isZero()) {
689 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
690 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
691 }
692
693 // (X+4) == X -> false.
694 if (Pred == ICmpInst::ICMP_EQ)
695 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
696
697 // (X+4) != X -> true.
698 if (Pred == ICmpInst::ICMP_NE)
699 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
700
Chris Lattner02446fc2010-01-04 07:37:31 +0000701 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000702 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner02446fc2010-01-04 07:37:31 +0000703 // operators.
704
Chris Lattner9aa1e242010-01-08 17:48:19 +0000705 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner02446fc2010-01-04 07:37:31 +0000706 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
707 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
708 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner9aa1e242010-01-08 17:48:19 +0000709 Value *R =
710 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000711 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
712 }
713
714 // (X+1) >u X --> X <u (0-1) --> X != 255
715 // (X+2) >u X --> X <u (0-2) --> X <u 254
716 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandsa7724332011-02-17 07:46:37 +0000717 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000718 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner02446fc2010-01-04 07:37:31 +0000719
720 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
721 ConstantInt *SMax = ConstantInt::get(X->getContext(),
722 APInt::getSignedMaxValue(BitWidth));
723
724 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
725 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
726 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
727 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
728 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
729 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandsa7724332011-02-17 07:46:37 +0000730 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000731 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner02446fc2010-01-04 07:37:31 +0000732
733 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
734 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
735 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
736 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
737 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
738 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
739
Chris Lattner02446fc2010-01-04 07:37:31 +0000740 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
741 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
742 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
743}
744
745/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
746/// and CmpRHS are both known to be integer constants.
747Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
748 ConstantInt *DivRHS) {
749 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
750 const APInt &CmpRHSV = CmpRHS->getValue();
751
752 // FIXME: If the operand types don't match the type of the divide
753 // then don't attempt this transform. The code below doesn't have the
754 // logic to deal with a signed divide and an unsigned compare (and
755 // vice versa). This is because (x /s C1) <s C2 produces different
756 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
757 // (x /u C1) <u C2. Simply casting the operands and result won't
758 // work. :( The if statement below tests that condition and bails
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000759 // if it finds it.
Chris Lattner02446fc2010-01-04 07:37:31 +0000760 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
761 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
762 return 0;
763 if (DivRHS->isZero())
764 return 0; // The ProdOV computation fails on divide by zero.
765 if (DivIsSigned && DivRHS->isAllOnesValue())
766 return 0; // The overflow computation also screws up here
Chris Lattnerbb75d332011-02-13 08:07:21 +0000767 if (DivRHS->isOne()) {
768 // This eliminates some funny cases with INT_MIN.
769 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
770 return &ICI;
771 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000772
773 // Compute Prod = CI * DivRHS. We are essentially solving an equation
774 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
775 // C2 (CI). By solving for X we can turn this into a range check
776 // instead of computing a divide.
777 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
778
779 // Determine if the product overflows by seeing if the product is
780 // not equal to the divide. Make sure we do the same kind of divide
781 // as in the LHS instruction that we're folding.
782 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
783 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
784
785 // Get the ICmp opcode
786 ICmpInst::Predicate Pred = ICI.getPredicate();
787
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000788 /// If the division is known to be exact, then there is no remainder from the
789 /// divide, so the covered range size is unit, otherwise it is the divisor.
790 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
791
Chris Lattner02446fc2010-01-04 07:37:31 +0000792 // Figure out the interval that is being checked. For example, a comparison
793 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
794 // Compute this interval based on the constants involved and the signedness of
795 // the compare/divide. This computes a half-open interval, keeping track of
796 // whether either value in the interval overflows. After analysis each
797 // overflow variable is set to 0 if it's corresponding bound variable is valid
798 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
799 int LoOverflow = 0, HiOverflow = 0;
800 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000801
Chris Lattner02446fc2010-01-04 07:37:31 +0000802 if (!DivIsSigned) { // udiv
803 // e.g. X/5 op 3 --> [15, 20)
804 LoBound = Prod;
805 HiOverflow = LoOverflow = ProdOV;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000806 if (!HiOverflow) {
807 // If this is not an exact divide, then many values in the range collapse
808 // to the same result value.
809 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
810 }
811
Chris Lattner02446fc2010-01-04 07:37:31 +0000812 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
813 if (CmpRHSV == 0) { // (X / pos) op 0
814 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000815 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
816 HiBound = RangeSize;
Chris Lattner02446fc2010-01-04 07:37:31 +0000817 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
818 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
819 HiOverflow = LoOverflow = ProdOV;
820 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000821 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000822 } else { // (X / pos) op neg
823 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
824 HiBound = AddOne(Prod);
825 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
826 if (!LoOverflow) {
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000827 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000828 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000829 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000830 }
831 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000832 if (DivI->isExact())
833 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000834 if (CmpRHSV == 0) { // (X / neg) op 0
835 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000836 LoBound = AddOne(RangeSize);
837 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000838 if (HiBound == DivRHS) { // -INTMIN = INTMIN
839 HiOverflow = 1; // [INTMIN+1, overflow)
840 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
841 }
842 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
843 // e.g. X/-5 op 3 --> [-19, -14)
844 HiBound = AddOne(Prod);
845 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
846 if (!LoOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000847 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner02446fc2010-01-04 07:37:31 +0000848 } else { // (X / neg) op neg
849 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
850 LoOverflow = HiOverflow = ProdOV;
851 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000852 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000853 }
854
855 // Dividing by a negative swaps the condition. LT <-> GT
856 Pred = ICmpInst::getSwappedPredicate(Pred);
857 }
858
859 Value *X = DivI->getOperand(0);
860 switch (Pred) {
861 default: llvm_unreachable("Unhandled icmp opcode!");
862 case ICmpInst::ICMP_EQ:
863 if (LoOverflow && HiOverflow)
864 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000865 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000866 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
867 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000868 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000869 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
870 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000871 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
872 DivIsSigned, true));
Chris Lattner02446fc2010-01-04 07:37:31 +0000873 case ICmpInst::ICMP_NE:
874 if (LoOverflow && HiOverflow)
875 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000876 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000877 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
878 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000879 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000880 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
881 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000882 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
883 DivIsSigned, false));
Chris Lattner02446fc2010-01-04 07:37:31 +0000884 case ICmpInst::ICMP_ULT:
885 case ICmpInst::ICMP_SLT:
886 if (LoOverflow == +1) // Low bound is greater than input range.
887 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
888 if (LoOverflow == -1) // Low bound is less than input range.
889 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
890 return new ICmpInst(Pred, X, LoBound);
891 case ICmpInst::ICMP_UGT:
892 case ICmpInst::ICMP_SGT:
893 if (HiOverflow == +1) // High bound greater than input range.
894 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000895 if (HiOverflow == -1) // High bound less than input range.
Chris Lattner02446fc2010-01-04 07:37:31 +0000896 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
897 if (Pred == ICmpInst::ICMP_UGT)
898 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000899 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner02446fc2010-01-04 07:37:31 +0000900 }
901}
902
Chris Lattner74542aa2011-02-13 07:43:07 +0000903/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
904Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
905 ConstantInt *ShAmt) {
Chris Lattner74542aa2011-02-13 07:43:07 +0000906 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
907
908 // Check that the shift amount is in range. If not, don't perform
909 // undefined shifts. When the shift is visited it will be
910 // simplified.
911 uint32_t TypeBits = CmpRHSV.getBitWidth();
912 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnerbb75d332011-02-13 08:07:21 +0000913 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattner74542aa2011-02-13 07:43:07 +0000914 return 0;
915
Chris Lattnerbb75d332011-02-13 08:07:21 +0000916 if (!ICI.isEquality()) {
917 // If we have an unsigned comparison and an ashr, we can't simplify this.
918 // Similarly for signed comparisons with lshr.
919 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
920 return 0;
921
Eli Friedmana831a9b2011-05-25 23:26:20 +0000922 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
923 // by a power of 2. Since we already have logic to simplify these,
924 // transform to div and then simplify the resultant comparison.
Chris Lattnerbb75d332011-02-13 08:07:21 +0000925 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedmana831a9b2011-05-25 23:26:20 +0000926 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattnerbb75d332011-02-13 08:07:21 +0000927 return 0;
928
929 // Revisit the shift (to delete it).
930 Worklist.Add(Shr);
931
932 Constant *DivCst =
933 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
934
935 Value *Tmp =
936 Shr->getOpcode() == Instruction::AShr ?
937 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
938 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
939
940 ICI.setOperand(0, Tmp);
941
942 // If the builder folded the binop, just return it.
943 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
944 if (TheDiv == 0)
945 return &ICI;
946
947 // Otherwise, fold this div/compare.
948 assert(TheDiv->getOpcode() == Instruction::SDiv ||
949 TheDiv->getOpcode() == Instruction::UDiv);
950
951 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
952 assert(Res && "This div/cst should have folded!");
953 return Res;
954 }
955
956
Chris Lattner74542aa2011-02-13 07:43:07 +0000957 // If we are comparing against bits always shifted out, the
958 // comparison cannot succeed.
959 APInt Comp = CmpRHSV << ShAmtVal;
960 ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
961 if (Shr->getOpcode() == Instruction::LShr)
962 Comp = Comp.lshr(ShAmtVal);
963 else
964 Comp = Comp.ashr(ShAmtVal);
965
966 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
967 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
968 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
969 IsICMP_NE);
970 return ReplaceInstUsesWith(ICI, Cst);
971 }
972
973 // Otherwise, check to see if the bits shifted out are known to be zero.
974 // If so, we can compare against the unshifted value:
975 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattnere5116f82011-02-13 18:30:09 +0000976 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattner74542aa2011-02-13 07:43:07 +0000977 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
978
979 if (Shr->hasOneUse()) {
980 // Otherwise strength reduce the shift into an and.
981 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
982 Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
983
984 Value *And = Builder->CreateAnd(Shr->getOperand(0),
985 Mask, Shr->getName()+".mask");
986 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
987 }
988 return 0;
989}
990
Chris Lattner02446fc2010-01-04 07:37:31 +0000991
992/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
993///
994Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
995 Instruction *LHSI,
996 ConstantInt *RHS) {
997 const APInt &RHSV = RHS->getValue();
998
999 switch (LHSI->getOpcode()) {
1000 case Instruction::Trunc:
1001 if (ICI.isEquality() && LHSI->hasOneUse()) {
1002 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1003 // of the high bits truncated out of x are known.
1004 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1005 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1006 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
1007 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1008 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
1009
1010 // If all the high bits are known, we can do this xform.
1011 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1012 // Pull in the high bits from known-ones set.
Jay Foad40f8f622010-12-07 08:25:19 +00001013 APInt NewRHS = RHS->getValue().zext(SrcBits);
Chris Lattner02446fc2010-01-04 07:37:31 +00001014 NewRHS |= KnownOne;
1015 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1016 ConstantInt::get(ICI.getContext(), NewRHS));
1017 }
1018 }
1019 break;
1020
1021 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1022 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1023 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1024 // fold the xor.
1025 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1026 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1027 Value *CompareVal = LHSI->getOperand(0);
1028
1029 // If the sign bit of the XorCST is not set, there is no change to
1030 // the operation, just stop using the Xor.
1031 if (!XorCST->getValue().isNegative()) {
1032 ICI.setOperand(0, CompareVal);
1033 Worklist.Add(LHSI);
1034 return &ICI;
1035 }
1036
1037 // Was the old condition true if the operand is positive?
1038 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1039
1040 // If so, the new one isn't.
1041 isTrueIfPositive ^= true;
1042
1043 if (isTrueIfPositive)
1044 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1045 SubOne(RHS));
1046 else
1047 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1048 AddOne(RHS));
1049 }
1050
1051 if (LHSI->hasOneUse()) {
1052 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1053 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1054 const APInt &SignBit = XorCST->getValue();
1055 ICmpInst::Predicate Pred = ICI.isSigned()
1056 ? ICI.getUnsignedPredicate()
1057 : ICI.getSignedPredicate();
1058 return new ICmpInst(Pred, LHSI->getOperand(0),
1059 ConstantInt::get(ICI.getContext(),
1060 RHSV ^ SignBit));
1061 }
1062
1063 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1064 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
1065 const APInt &NotSignBit = XorCST->getValue();
1066 ICmpInst::Predicate Pred = ICI.isSigned()
1067 ? ICI.getUnsignedPredicate()
1068 : ICI.getSignedPredicate();
1069 Pred = ICI.getSwappedPredicate(Pred);
1070 return new ICmpInst(Pred, LHSI->getOperand(0),
1071 ConstantInt::get(ICI.getContext(),
1072 RHSV ^ NotSignBit));
1073 }
1074 }
1075 }
1076 break;
1077 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1078 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1079 LHSI->getOperand(0)->hasOneUse()) {
1080 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1081
1082 // If the LHS is an AND of a truncating cast, we can widen the
1083 // and/compare to be the input width without changing the value
1084 // produced, eliminating a cast.
1085 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1086 // We can do this transformation if either the AND constant does not
1087 // have its sign bit set or if it is an equality comparison.
1088 // Extending a relational comparison when we're checking the sign
1089 // bit would not work.
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001090 if (ICI.isEquality() ||
1091 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative())) {
1092 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001093 Builder->CreateAnd(Cast->getOperand(0),
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001094 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1095 NewAnd->takeName(LHSI);
Chris Lattner02446fc2010-01-04 07:37:31 +00001096 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001097 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001098 }
1099 }
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001100
1101 // If the LHS is an AND of a zext, and we have an equality compare, we can
1102 // shrink the and/compare to the smaller type, eliminating the cast.
1103 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1104 const IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1105 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1106 // should fold the icmp to true/false in that case.
1107 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1108 Value *NewAnd =
1109 Builder->CreateAnd(Cast->getOperand(0),
1110 ConstantExpr::getTrunc(AndCST, Ty));
1111 NewAnd->takeName(LHSI);
1112 return new ICmpInst(ICI.getPredicate(), NewAnd,
1113 ConstantExpr::getTrunc(RHS, Ty));
1114 }
1115 }
1116
Chris Lattner02446fc2010-01-04 07:37:31 +00001117 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1118 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1119 // happens a LOT in code produced by the C front-end, for bitfield
1120 // access.
1121 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1122 if (Shift && !Shift->isShift())
1123 Shift = 0;
1124
1125 ConstantInt *ShAmt;
1126 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1127 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1128 const Type *AndTy = AndCST->getType(); // Type of the and.
1129
1130 // We can fold this as long as we can't shift unknown bits
1131 // into the mask. This can only happen with signed shift
1132 // rights, as they sign-extend.
1133 if (ShAmt) {
1134 bool CanFold = Shift->isLogicalShift();
1135 if (!CanFold) {
1136 // To test for the bad case of the signed shr, see if any
1137 // of the bits shifted in could be tested after the mask.
1138 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1139 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
1140
1141 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
1142 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
1143 AndCST->getValue()) == 0)
1144 CanFold = true;
1145 }
1146
1147 if (CanFold) {
1148 Constant *NewCst;
1149 if (Shift->getOpcode() == Instruction::Shl)
1150 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1151 else
1152 NewCst = ConstantExpr::getShl(RHS, ShAmt);
1153
1154 // Check to see if we are shifting out any of the bits being
1155 // compared.
1156 if (ConstantExpr::get(Shift->getOpcode(),
1157 NewCst, ShAmt) != RHS) {
1158 // If we shifted bits out, the fold is not going to work out.
1159 // As a special case, check to see if this means that the
1160 // result is always true or false now.
1161 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1162 return ReplaceInstUsesWith(ICI,
1163 ConstantInt::getFalse(ICI.getContext()));
1164 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1165 return ReplaceInstUsesWith(ICI,
1166 ConstantInt::getTrue(ICI.getContext()));
1167 } else {
1168 ICI.setOperand(1, NewCst);
1169 Constant *NewAndCST;
1170 if (Shift->getOpcode() == Instruction::Shl)
1171 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1172 else
1173 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1174 LHSI->setOperand(1, NewAndCST);
1175 LHSI->setOperand(0, Shift->getOperand(0));
1176 Worklist.Add(Shift); // Shift is dead.
1177 return &ICI;
1178 }
1179 }
1180 }
1181
1182 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1183 // preferable because it allows the C<<Y expression to be hoisted out
1184 // of a loop if Y is invariant and X is not.
1185 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1186 ICI.isEquality() && !Shift->isArithmeticShift() &&
1187 !isa<Constant>(Shift->getOperand(0))) {
1188 // Compute C << Y.
1189 Value *NS;
1190 if (Shift->getOpcode() == Instruction::LShr) {
1191 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
1192 } else {
1193 // Insert a logical shift.
1194 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
1195 }
1196
1197 // Compute X & (C << Y).
1198 Value *NewAnd =
1199 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1200
1201 ICI.setOperand(0, NewAnd);
1202 return &ICI;
1203 }
1204 }
1205
1206 // Try to optimize things like "A[i]&42 == 0" to index computations.
1207 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1208 if (GetElementPtrInst *GEP =
1209 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1210 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1211 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1212 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1213 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1214 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1215 return Res;
1216 }
1217 }
1218 break;
1219
1220 case Instruction::Or: {
1221 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1222 break;
1223 Value *P, *Q;
1224 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1225 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1226 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner02446fc2010-01-04 07:37:31 +00001227 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1228 Constant::getNullValue(P->getType()));
1229 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1230 Constant::getNullValue(Q->getType()));
1231 Instruction *Op;
1232 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1233 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1234 else
1235 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1236 return Op;
1237 }
1238 break;
1239 }
1240
1241 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
1242 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1243 if (!ShAmt) break;
1244
1245 uint32_t TypeBits = RHSV.getBitWidth();
1246
1247 // Check that the shift amount is in range. If not, don't perform
1248 // undefined shifts. When the shift is visited it will be
1249 // simplified.
1250 if (ShAmt->uge(TypeBits))
1251 break;
1252
1253 if (ICI.isEquality()) {
1254 // If we are comparing against bits always shifted out, the
1255 // comparison cannot succeed.
1256 Constant *Comp =
1257 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1258 ShAmt);
1259 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1260 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1261 Constant *Cst =
1262 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1263 return ReplaceInstUsesWith(ICI, Cst);
1264 }
1265
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001266 // If the shift is NUW, then it is just shifting out zeros, no need for an
1267 // AND.
1268 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1269 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1270 ConstantExpr::getLShr(RHS, ShAmt));
1271
Chris Lattner02446fc2010-01-04 07:37:31 +00001272 if (LHSI->hasOneUse()) {
1273 // Otherwise strength reduce the shift into an and.
1274 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1275 Constant *Mask =
1276 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
1277 TypeBits-ShAmtVal));
1278
1279 Value *And =
1280 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1281 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001282 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner02446fc2010-01-04 07:37:31 +00001283 }
1284 }
1285
1286 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1287 bool TrueIfSigned = false;
1288 if (LHSI->hasOneUse() &&
1289 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1290 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattnerbb75d332011-02-13 08:07:21 +00001291 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1292 APInt::getOneBitSet(TypeBits,
1293 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001294 Value *And =
1295 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1296 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1297 And, Constant::getNullValue(And->getType()));
1298 }
1299 break;
1300 }
1301
1302 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001303 case Instruction::AShr: {
1304 // Handle equality comparisons of shift-by-constant.
1305 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1306 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1307 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattner74542aa2011-02-13 07:43:07 +00001308 return Res;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001309 }
1310
1311 // Handle exact shr's.
1312 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1313 if (RHSV.isMinValue())
1314 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1315 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001316 break;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001317 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001318
1319 case Instruction::SDiv:
1320 case Instruction::UDiv:
1321 // Fold: icmp pred ([us]div X, C1), C2 -> range test
1322 // Fold this div into the comparison, producing a range check.
1323 // Determine, based on the divide type, what the range is being
1324 // checked. If there is an overflow on the low or high side, remember
1325 // it, otherwise compute the range [low, hi) bounding the new value.
1326 // See: InsertRangeTest above for the kinds of replacements possible.
1327 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1328 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1329 DivRHS))
1330 return R;
1331 break;
1332
1333 case Instruction::Add:
1334 // Fold: icmp pred (add X, C1), C2
1335 if (!ICI.isEquality()) {
1336 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1337 if (!LHSC) break;
1338 const APInt &LHSV = LHSC->getValue();
1339
1340 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1341 .subtract(LHSV);
1342
1343 if (ICI.isSigned()) {
1344 if (CR.getLower().isSignBit()) {
1345 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1346 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1347 } else if (CR.getUpper().isSignBit()) {
1348 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1349 ConstantInt::get(ICI.getContext(),CR.getLower()));
1350 }
1351 } else {
1352 if (CR.getLower().isMinValue()) {
1353 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1354 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1355 } else if (CR.getUpper().isMinValue()) {
1356 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1357 ConstantInt::get(ICI.getContext(),CR.getLower()));
1358 }
1359 }
1360 }
1361 break;
1362 }
1363
1364 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1365 if (ICI.isEquality()) {
1366 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1367
1368 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1369 // the second operand is a constant, simplify a bit.
1370 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1371 switch (BO->getOpcode()) {
1372 case Instruction::SRem:
1373 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1374 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1375 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohmane0567812010-04-08 23:03:40 +00001376 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001377 Value *NewRem =
1378 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1379 BO->getName());
1380 return new ICmpInst(ICI.getPredicate(), NewRem,
1381 Constant::getNullValue(BO->getType()));
1382 }
1383 }
1384 break;
1385 case Instruction::Add:
1386 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1387 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1388 if (BO->hasOneUse())
1389 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1390 ConstantExpr::getSub(RHS, BOp1C));
1391 } else if (RHSV == 0) {
1392 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1393 // efficiently invertible, or if the add has just this one use.
1394 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1395
1396 if (Value *NegVal = dyn_castNegVal(BOp1))
1397 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner5036ce42011-04-26 20:02:45 +00001398 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner02446fc2010-01-04 07:37:31 +00001399 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner5036ce42011-04-26 20:02:45 +00001400 if (BO->hasOneUse()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001401 Value *Neg = Builder->CreateNeg(BOp1);
1402 Neg->takeName(BO);
1403 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1404 }
1405 }
1406 break;
1407 case Instruction::Xor:
1408 // For the xor case, we can xor two constants together, eliminating
1409 // the explicit xor.
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001410 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1411 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner02446fc2010-01-04 07:37:31 +00001412 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001413 } else if (RHSV == 0) {
1414 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner02446fc2010-01-04 07:37:31 +00001415 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1416 BO->getOperand(1));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001417 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001418 break;
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001419 case Instruction::Sub:
1420 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1421 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1422 if (BO->hasOneUse())
1423 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1424 ConstantExpr::getSub(BOp0C, RHS));
1425 } else if (RHSV == 0) {
1426 // Replace ((sub A, B) != 0) with (A != B)
1427 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1428 BO->getOperand(1));
1429 }
1430 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001431 case Instruction::Or:
1432 // If bits are being or'd in that are not present in the constant we
1433 // are comparing against, then the comparison could never succeed!
Eli Friedman618898e2010-07-29 18:03:33 +00001434 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001435 Constant *NotCI = ConstantExpr::getNot(RHS);
1436 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1437 return ReplaceInstUsesWith(ICI,
1438 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1439 isICMP_NE));
1440 }
1441 break;
1442
1443 case Instruction::And:
1444 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1445 // If bits are being compared against that are and'd out, then the
1446 // comparison can never succeed!
1447 if ((RHSV & ~BOC->getValue()) != 0)
1448 return ReplaceInstUsesWith(ICI,
1449 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1450 isICMP_NE));
1451
1452 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1453 if (RHS == BOC && RHSV.isPowerOf2())
1454 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1455 ICmpInst::ICMP_NE, LHSI,
1456 Constant::getNullValue(RHS->getType()));
1457
1458 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1459 if (BOC->getValue().isSignBit()) {
1460 Value *X = BO->getOperand(0);
1461 Constant *Zero = Constant::getNullValue(X->getType());
1462 ICmpInst::Predicate pred = isICMP_NE ?
1463 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1464 return new ICmpInst(pred, X, Zero);
1465 }
1466
1467 // ((X & ~7) == 0) --> X < 8
1468 if (RHSV == 0 && isHighOnes(BOC)) {
1469 Value *X = BO->getOperand(0);
1470 Constant *NegX = ConstantExpr::getNeg(BOC);
1471 ICmpInst::Predicate pred = isICMP_NE ?
1472 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1473 return new ICmpInst(pred, X, NegX);
1474 }
1475 }
1476 default: break;
1477 }
1478 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1479 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001480 switch (II->getIntrinsicID()) {
1481 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001482 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001483 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00001484 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1485 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001486 case Intrinsic::ctlz:
1487 case Intrinsic::cttz:
1488 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1489 if (RHSV == RHS->getType()->getBitWidth()) {
1490 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001491 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001492 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1493 return &ICI;
1494 }
1495 break;
1496 case Intrinsic::ctpop:
1497 // popcount(A) == 0 -> A == 0 and likewise for !=
1498 if (RHS->isZero()) {
1499 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001500 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001501 ICI.setOperand(1, RHS);
1502 return &ICI;
1503 }
1504 break;
1505 default:
Duncan Sands34727662010-07-12 08:16:59 +00001506 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001507 }
1508 }
1509 }
1510 return 0;
1511}
1512
1513/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1514/// We only handle extending casts so far.
1515///
1516Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1517 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1518 Value *LHSCIOp = LHSCI->getOperand(0);
1519 const Type *SrcTy = LHSCIOp->getType();
1520 const Type *DestTy = LHSCI->getType();
1521 Value *RHSCIOp;
1522
1523 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1524 // integer type is the same size as the pointer type.
1525 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1526 TD->getPointerSizeInBits() ==
1527 cast<IntegerType>(DestTy)->getBitWidth()) {
1528 Value *RHSOp = 0;
1529 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1530 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1531 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1532 RHSOp = RHSC->getOperand(0);
1533 // If the pointer types don't match, insert a bitcast.
1534 if (LHSCIOp->getType() != RHSOp->getType())
1535 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1536 }
1537
1538 if (RHSOp)
1539 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1540 }
1541
1542 // The code below only handles extension cast instructions, so far.
1543 // Enforce this.
1544 if (LHSCI->getOpcode() != Instruction::ZExt &&
1545 LHSCI->getOpcode() != Instruction::SExt)
1546 return 0;
1547
1548 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1549 bool isSignedCmp = ICI.isSigned();
1550
1551 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1552 // Not an extension from the same type?
1553 RHSCIOp = CI->getOperand(0);
1554 if (RHSCIOp->getType() != LHSCIOp->getType())
1555 return 0;
1556
1557 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1558 // and the other is a zext), then we can't handle this.
1559 if (CI->getOpcode() != LHSCI->getOpcode())
1560 return 0;
1561
1562 // Deal with equality cases early.
1563 if (ICI.isEquality())
1564 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1565
1566 // A signed comparison of sign extended values simplifies into a
1567 // signed comparison.
1568 if (isSignedCmp && isSignedExt)
1569 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1570
1571 // The other three cases all fold into an unsigned comparison.
1572 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1573 }
1574
1575 // If we aren't dealing with a constant on the RHS, exit early
1576 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1577 if (!CI)
1578 return 0;
1579
1580 // Compute the constant that would happen if we truncated to SrcTy then
1581 // reextended to DestTy.
1582 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1583 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1584 Res1, DestTy);
1585
1586 // If the re-extended constant didn't change...
1587 if (Res2 == CI) {
1588 // Deal with equality cases early.
1589 if (ICI.isEquality())
1590 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1591
1592 // A signed comparison of sign extended values simplifies into a
1593 // signed comparison.
1594 if (isSignedExt && isSignedCmp)
1595 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1596
1597 // The other three cases all fold into an unsigned comparison.
1598 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1599 }
1600
1601 // The re-extended constant changed so the constant cannot be represented
1602 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001603 // All the cases that fold to true or false will have already been handled
1604 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001605
Duncan Sands9d32f602011-01-20 13:21:55 +00001606 if (isSignedCmp || !isSignedExt)
1607 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001608
1609 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1610 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001611
1612 // We're performing an unsigned comp with a sign extended value.
1613 // This is true if the input is >= 0. [aka >s -1]
1614 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1615 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001616
1617 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001618 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001619 return ReplaceInstUsesWith(ICI, Result);
1620
Duncan Sands9d32f602011-01-20 13:21:55 +00001621 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001622 return BinaryOperator::CreateNot(Result);
1623}
1624
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001625/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1626/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001627/// If this is of the form:
1628/// sum = a + b
1629/// if (sum+128 >u 255)
1630/// Then replace it with llvm.sadd.with.overflow.i8.
1631///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001632static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1633 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001634 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001635 // The transformation we're trying to do here is to transform this into an
1636 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1637 // with a narrower add, and discard the add-with-constant that is part of the
1638 // range check (if we can't eliminate it, this isn't profitable).
1639
1640 // In order to eliminate the add-with-constant, the compare can be its only
1641 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001642 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001643 if (!AddWithCst->hasOneUse()) return 0;
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001644
1645 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1646 if (!CI2->getValue().isPowerOf2()) return 0;
1647 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1648 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1649
1650 // The width of the new add formed is 1 more than the bias.
1651 ++NewWidth;
1652
1653 // Check to see that CI1 is an all-ones value with NewWidth bits.
1654 if (CI1->getBitWidth() == NewWidth ||
1655 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1656 return 0;
1657
1658 // In order to replace the original add with a narrower
1659 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1660 // and truncates that discard the high bits of the add. Verify that this is
1661 // the case.
1662 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1663 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1664 UI != E; ++UI) {
1665 if (*UI == AddWithCst) continue;
1666
1667 // Only accept truncates for now. We would really like a nice recursive
1668 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1669 // chain to see which bits of a value are actually demanded. If the
1670 // original add had another add which was then immediately truncated, we
1671 // could still do the transformation.
1672 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1673 if (TI == 0 ||
1674 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1675 }
1676
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001677 // If the pattern matches, truncate the inputs to the narrower type and
1678 // use the sadd_with_overflow intrinsic to efficiently compute both the
1679 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001680 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001681
Chris Lattner0a624742010-12-19 18:35:09 +00001682 const Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1683 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1684 &NewType, 1);
1685
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001686 InstCombiner::BuilderTy *Builder = IC.Builder;
1687
Chris Lattner0a624742010-12-19 18:35:09 +00001688 // Put the new code above the original add, in case there are any uses of the
1689 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001690 Builder->SetInsertPoint(OrigAdd);
Chris Lattner0a624742010-12-19 18:35:09 +00001691
1692 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1693 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1694 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1695 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1696 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001697
1698 // The inner add was the result of the narrow add, zero extended to the
1699 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001700 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001701
Chris Lattner0a624742010-12-19 18:35:09 +00001702 // The original icmp gets replaced with the overflow value.
1703 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001704}
Chris Lattner02446fc2010-01-04 07:37:31 +00001705
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001706static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1707 InstCombiner &IC) {
1708 // Don't bother doing this transformation for pointers, don't do it for
1709 // vectors.
1710 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1711
1712 // If the add is a constant expr, then we don't bother transforming it.
1713 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1714 if (OrigAdd == 0) return 0;
1715
1716 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1717
1718 // Put the new code above the original add, in case there are any uses of the
1719 // add between the add and the compare.
1720 InstCombiner::BuilderTy *Builder = IC.Builder;
1721 Builder->SetInsertPoint(OrigAdd);
1722
1723 Module *M = I.getParent()->getParent()->getParent();
1724 const Type *Ty = LHS->getType();
1725 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, &Ty,1);
1726 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1727 Value *Add = Builder->CreateExtractValue(Call, 0);
1728
1729 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1730
1731 // The original icmp gets replaced with the overflow value.
1732 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1733}
1734
Owen Andersonda1c1222011-01-11 00:36:45 +00001735// DemandedBitsLHSMask - When performing a comparison against a constant,
1736// it is possible that not all the bits in the LHS are demanded. This helper
1737// method computes the mask that IS demanded.
1738static APInt DemandedBitsLHSMask(ICmpInst &I,
1739 unsigned BitWidth, bool isSignCheck) {
1740 if (isSignCheck)
1741 return APInt::getSignBit(BitWidth);
1742
1743 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1744 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00001745 const APInt &RHS = CI->getValue();
Owen Andersonda1c1222011-01-11 00:36:45 +00001746
1747 switch (I.getPredicate()) {
1748 // For a UGT comparison, we don't care about any bits that
1749 // correspond to the trailing ones of the comparand. The value of these
1750 // bits doesn't impact the outcome of the comparison, because any value
1751 // greater than the RHS must differ in a bit higher than these due to carry.
1752 case ICmpInst::ICMP_UGT: {
1753 unsigned trailingOnes = RHS.countTrailingOnes();
1754 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1755 return ~lowBitsSet;
1756 }
1757
1758 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1759 // Any value less than the RHS must differ in a higher bit because of carries.
1760 case ICmpInst::ICMP_ULT: {
1761 unsigned trailingZeros = RHS.countTrailingZeros();
1762 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1763 return ~lowBitsSet;
1764 }
1765
1766 default:
1767 return APInt::getAllOnesValue(BitWidth);
1768 }
1769
Owen Andersonda1c1222011-01-11 00:36:45 +00001770}
Chris Lattner02446fc2010-01-04 07:37:31 +00001771
1772Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1773 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00001774 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001775
1776 /// Orders the operands of the compare so that they are listed from most
1777 /// complex to least complex. This puts constants before unary operators,
1778 /// before binary operators.
Chris Lattner5f670d42010-02-01 19:54:45 +00001779 if (getComplexity(Op0) < getComplexity(Op1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001780 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00001781 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001782 Changed = true;
1783 }
1784
Chris Lattner02446fc2010-01-04 07:37:31 +00001785 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1786 return ReplaceInstUsesWith(I, V);
1787
1788 const Type *Ty = Op0->getType();
1789
1790 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001791 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001792 switch (I.getPredicate()) {
1793 default: llvm_unreachable("Invalid icmp instruction!");
1794 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
1795 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1796 return BinaryOperator::CreateNot(Xor);
1797 }
1798 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
1799 return BinaryOperator::CreateXor(Op0, Op1);
1800
1801 case ICmpInst::ICMP_UGT:
1802 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
1803 // FALL THROUGH
1804 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
1805 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1806 return BinaryOperator::CreateAnd(Not, Op1);
1807 }
1808 case ICmpInst::ICMP_SGT:
1809 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
1810 // FALL THROUGH
1811 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
1812 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1813 return BinaryOperator::CreateAnd(Not, Op0);
1814 }
1815 case ICmpInst::ICMP_UGE:
1816 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
1817 // FALL THROUGH
1818 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
1819 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1820 return BinaryOperator::CreateOr(Not, Op1);
1821 }
1822 case ICmpInst::ICMP_SGE:
1823 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
1824 // FALL THROUGH
1825 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
1826 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1827 return BinaryOperator::CreateOr(Not, Op0);
1828 }
1829 }
1830 }
1831
1832 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001833 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00001834 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001835 else if (TD) // Pointers require TD info to get their size.
1836 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
1837
Chris Lattner02446fc2010-01-04 07:37:31 +00001838 bool isSignBit = false;
1839
1840 // See if we are doing a comparison with a constant.
1841 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1842 Value *A = 0, *B = 0;
1843
Owen Andersone63dda52010-12-17 18:08:00 +00001844 // Match the following pattern, which is a common idiom when writing
1845 // overflow-safe integer arithmetic function. The source performs an
1846 // addition in wider type, and explicitly checks for overflow using
1847 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
1848 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001849 //
1850 // TODO: This could probably be generalized to handle other overflow-safe
Owen Andersone63dda52010-12-17 18:08:00 +00001851 // operations if we worked out the formulas to compute the appropriate
1852 // magic constants.
1853 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001854 // sum = a + b
1855 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00001856 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001857 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00001858 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001859 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001860 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001861 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00001862 }
1863
Chris Lattner02446fc2010-01-04 07:37:31 +00001864 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1865 if (I.isEquality() && CI->isZero() &&
1866 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1867 // (icmp cond A B) if cond is equality
1868 return new ICmpInst(I.getPredicate(), A, B);
1869 }
1870
1871 // If we have an icmp le or icmp ge instruction, turn it into the
1872 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
1873 // them being folded in the code below. The SimplifyICmpInst code has
1874 // already handled the edge cases for us, so we just assert on them.
1875 switch (I.getPredicate()) {
1876 default: break;
1877 case ICmpInst::ICMP_ULE:
1878 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
1879 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1880 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1881 case ICmpInst::ICMP_SLE:
1882 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
1883 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1884 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1885 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001886 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001887 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1888 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1889 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001890 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001891 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1892 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1893 }
1894
1895 // If this comparison is a normal comparison, it demands all
1896 // bits, if it is a sign bit comparison, it only demands the sign bit.
1897 bool UnusedBit;
1898 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1899 }
1900
1901 // See if we can fold the comparison based on range information we can get
1902 // by checking whether bits are known to be zero or one in the input.
1903 if (BitWidth != 0) {
1904 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1905 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1906
1907 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00001908 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00001909 Op0KnownZero, Op0KnownOne, 0))
1910 return &I;
1911 if (SimplifyDemandedBits(I.getOperandUse(1),
1912 APInt::getAllOnesValue(BitWidth),
1913 Op1KnownZero, Op1KnownOne, 0))
1914 return &I;
1915
1916 // Given the known and unknown bits, compute a range that the LHS could be
1917 // in. Compute the Min, Max and RHS values based on the known bits. For the
1918 // EQ and NE we use unsigned values.
1919 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1920 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1921 if (I.isSigned()) {
1922 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1923 Op0Min, Op0Max);
1924 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1925 Op1Min, Op1Max);
1926 } else {
1927 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1928 Op0Min, Op0Max);
1929 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1930 Op1Min, Op1Max);
1931 }
1932
1933 // If Min and Max are known to be the same, then SimplifyDemandedBits
1934 // figured out that the LHS is a constant. Just constant fold this now so
1935 // that code below can assume that Min != Max.
1936 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1937 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001938 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001939 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1940 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001941 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00001942
1943 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001944 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00001945 switch (I.getPredicate()) {
1946 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00001947 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00001948 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001949 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner75d8f592010-11-21 06:44:42 +00001950
1951 // If all bits are known zero except for one, then we know at most one
1952 // bit is set. If the comparison is against zero, then this is a check
1953 // to see if *that* bit is set.
1954 APInt Op0KnownZeroInverted = ~Op0KnownZero;
1955 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1956 // If the LHS is an AND with the same constant, look through it.
1957 Value *LHS = 0;
1958 ConstantInt *LHSC = 0;
1959 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1960 LHSC->getValue() != Op0KnownZeroInverted)
1961 LHS = Op0;
1962
1963 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattner79b967b2010-11-23 02:42:04 +00001964 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00001965 Value *X = 0;
1966 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
1967 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00001968 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00001969 ConstantInt::get(X->getType(), CmpVal));
1970 }
1971
1972 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattner79b967b2010-11-23 02:42:04 +00001973 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001974 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00001975 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001976 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00001977 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001978 ConstantInt::get(X->getType(),
1979 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00001980 }
1981
Chris Lattner02446fc2010-01-04 07:37:31 +00001982 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00001983 }
1984 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00001985 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001986 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner75d8f592010-11-21 06:44:42 +00001987
1988 // If all bits are known zero except for one, then we know at most one
1989 // bit is set. If the comparison is against zero, then this is a check
1990 // to see if *that* bit is set.
1991 APInt Op0KnownZeroInverted = ~Op0KnownZero;
1992 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1993 // If the LHS is an AND with the same constant, look through it.
1994 Value *LHS = 0;
1995 ConstantInt *LHSC = 0;
1996 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1997 LHSC->getValue() != Op0KnownZeroInverted)
1998 LHS = Op0;
1999
2000 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattner79b967b2010-11-23 02:42:04 +00002001 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002002 Value *X = 0;
2003 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2004 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002005 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002006 ConstantInt::get(X->getType(), CmpVal));
2007 }
2008
2009 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattner79b967b2010-11-23 02:42:04 +00002010 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002011 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002012 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002013 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002014 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002015 ConstantInt::get(X->getType(),
2016 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002017 }
2018
Chris Lattner02446fc2010-01-04 07:37:31 +00002019 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002020 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002021 case ICmpInst::ICMP_ULT:
2022 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002023 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002024 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002025 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002026 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2027 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2028 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2029 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2030 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2031 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2032
2033 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2034 if (CI->isMinValue(true))
2035 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2036 Constant::getAllOnesValue(Op0->getType()));
2037 }
2038 break;
2039 case ICmpInst::ICMP_UGT:
2040 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002041 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002042 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002043 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002044
2045 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2046 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2047 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2048 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2049 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2050 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2051
2052 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2053 if (CI->isMaxValue(true))
2054 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2055 Constant::getNullValue(Op0->getType()));
2056 }
2057 break;
2058 case ICmpInst::ICMP_SLT:
2059 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002060 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002061 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002062 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002063 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2064 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2065 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2066 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2067 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2068 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2069 }
2070 break;
2071 case ICmpInst::ICMP_SGT:
2072 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002073 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002074 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002075 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002076
2077 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2078 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2079 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2080 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2081 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2082 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2083 }
2084 break;
2085 case ICmpInst::ICMP_SGE:
2086 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2087 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002088 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002089 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002090 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002091 break;
2092 case ICmpInst::ICMP_SLE:
2093 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2094 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002095 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002096 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002097 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002098 break;
2099 case ICmpInst::ICMP_UGE:
2100 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2101 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002102 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002103 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002104 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002105 break;
2106 case ICmpInst::ICMP_ULE:
2107 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2108 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002109 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002110 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002111 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002112 break;
2113 }
2114
2115 // Turn a signed comparison into an unsigned one if both operands
2116 // are known to have the same sign.
2117 if (I.isSigned() &&
2118 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2119 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2120 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2121 }
2122
2123 // Test if the ICmpInst instruction is used exclusively by a select as
2124 // part of a minimum or maximum operation. If so, refrain from doing
2125 // any other folding. This helps out other analyses which understand
2126 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2127 // and CodeGen. And in this case, at least one of the comparison
2128 // operands has at least one user besides the compare (the select),
2129 // which would often largely negate the benefit of folding anyway.
2130 if (I.hasOneUse())
2131 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2132 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2133 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2134 return 0;
2135
2136 // See if we are doing a comparison between a constant and an instruction that
2137 // can be folded into the comparison.
2138 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2139 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2140 // instruction, see if that instruction also has constants so that the
2141 // instruction can be folded into the icmp
2142 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2143 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2144 return Res;
2145 }
2146
2147 // Handle icmp with constant (but not simple integer constant) RHS
2148 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2149 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2150 switch (LHSI->getOpcode()) {
2151 case Instruction::GetElementPtr:
2152 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2153 if (RHSC->isNullValue() &&
2154 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2155 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2156 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2157 break;
2158 case Instruction::PHI:
2159 // Only fold icmp into the PHI if the phi and icmp are in the same
2160 // block. If in the same block, we're encouraging jump threading. If
2161 // not, we are just pessimizing the code by making an i1 phi.
2162 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002163 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002164 return NV;
2165 break;
2166 case Instruction::Select: {
2167 // If either operand of the select is a constant, we can fold the
2168 // comparison into the select arms, which will cause one to be
2169 // constant folded and the select turned into a bitwise or.
2170 Value *Op1 = 0, *Op2 = 0;
2171 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2172 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2173 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2174 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2175
2176 // We only want to perform this transformation if it will not lead to
2177 // additional code. This is true if either both sides of the select
2178 // fold to a constant (in which case the icmp is replaced with a select
2179 // which will usually simplify) or this is the only user of the
2180 // select (in which case we are trading a select+icmp for a simpler
2181 // select+icmp).
2182 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2183 if (!Op1)
2184 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2185 RHSC, I.getName());
2186 if (!Op2)
2187 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2188 RHSC, I.getName());
2189 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2190 }
2191 break;
2192 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002193 case Instruction::IntToPtr:
2194 // icmp pred inttoptr(X), null -> icmp pred X, 0
2195 if (RHSC->isNullValue() && TD &&
2196 TD->getIntPtrType(RHSC->getContext()) ==
2197 LHSI->getOperand(0)->getType())
2198 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2199 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2200 break;
2201
2202 case Instruction::Load:
2203 // Try to optimize things like "A[i] > 4" to index computations.
2204 if (GetElementPtrInst *GEP =
2205 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2206 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2207 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2208 !cast<LoadInst>(LHSI)->isVolatile())
2209 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2210 return Res;
2211 }
2212 break;
2213 }
2214 }
2215
2216 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2217 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2218 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2219 return NI;
2220 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2221 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2222 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2223 return NI;
2224
2225 // Test to see if the operands of the icmp are casted versions of other
2226 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2227 // now.
2228 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Duncan Sands1df98592010-02-16 11:11:14 +00002229 if (Op0->getType()->isPointerTy() &&
Chris Lattner02446fc2010-01-04 07:37:31 +00002230 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2231 // We keep moving the cast from the left operand over to the right
2232 // operand, where it can often be eliminated completely.
2233 Op0 = CI->getOperand(0);
2234
2235 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2236 // so eliminate it as well.
2237 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2238 Op1 = CI2->getOperand(0);
2239
2240 // If Op1 is a constant, we can fold the cast into the constant.
2241 if (Op0->getType() != Op1->getType()) {
2242 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2243 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2244 } else {
2245 // Otherwise, cast the RHS right before the icmp
2246 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2247 }
2248 }
2249 return new ICmpInst(I.getPredicate(), Op0, Op1);
2250 }
2251 }
2252
2253 if (isa<CastInst>(Op0)) {
2254 // Handle the special case of: icmp (cast bool to X), <cst>
2255 // This comes up when you have code like
2256 // int X = A < B;
2257 // if (X) ...
2258 // For generality, we handle any zero-extension of any operand comparison
2259 // with a constant or another cast from the same type.
2260 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2261 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2262 return R;
2263 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002264
Duncan Sandsa7724332011-02-17 07:46:37 +00002265 // Special logic for binary operators.
2266 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2267 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2268 if (BO0 || BO1) {
2269 CmpInst::Predicate Pred = I.getPredicate();
2270 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2271 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2272 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2273 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2274 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2275 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2276 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2277 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2278 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2279
2280 // Analyze the case when either Op0 or Op1 is an add instruction.
2281 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2282 Value *A = 0, *B = 0, *C = 0, *D = 0;
2283 if (BO0 && BO0->getOpcode() == Instruction::Add)
2284 A = BO0->getOperand(0), B = BO0->getOperand(1);
2285 if (BO1 && BO1->getOpcode() == Instruction::Add)
2286 C = BO1->getOperand(0), D = BO1->getOperand(1);
2287
2288 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2289 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2290 return new ICmpInst(Pred, A == Op1 ? B : A,
2291 Constant::getNullValue(Op1->getType()));
2292
2293 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2294 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2295 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2296 C == Op0 ? D : C);
2297
Duncan Sands39a7de72011-02-18 16:25:37 +00002298 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002299 if (A && C && (A == C || A == D || B == C || B == D) &&
2300 NoOp0WrapProblem && NoOp1WrapProblem &&
2301 // Try not to increase register pressure.
2302 BO0->hasOneUse() && BO1->hasOneUse()) {
2303 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2304 Value *Y = (A == C || A == D) ? B : A;
2305 Value *Z = (C == A || C == B) ? D : C;
2306 return new ICmpInst(Pred, Y, Z);
2307 }
2308
2309 // Analyze the case when either Op0 or Op1 is a sub instruction.
2310 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2311 A = 0; B = 0; C = 0; D = 0;
2312 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2313 A = BO0->getOperand(0), B = BO0->getOperand(1);
2314 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2315 C = BO1->getOperand(0), D = BO1->getOperand(1);
2316
Duncan Sands39a7de72011-02-18 16:25:37 +00002317 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2318 if (A == Op1 && NoOp0WrapProblem)
2319 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2320
2321 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2322 if (C == Op0 && NoOp1WrapProblem)
2323 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2324
2325 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002326 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2327 // Try not to increase register pressure.
2328 BO0->hasOneUse() && BO1->hasOneUse())
2329 return new ICmpInst(Pred, A, C);
2330
Duncan Sands39a7de72011-02-18 16:25:37 +00002331 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2332 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2333 // Try not to increase register pressure.
2334 BO0->hasOneUse() && BO1->hasOneUse())
2335 return new ICmpInst(Pred, D, B);
2336
Nick Lewycky9feda172011-03-05 04:28:48 +00002337 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002338 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002339 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2340 Op1 == BO0->getOperand(1))
2341 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002342 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002343 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2344 Op0 == BO1->getOperand(1))
2345 SRem = BO1;
2346 if (SRem) {
2347 // We don't check hasOneUse to avoid increasing register pressure because
2348 // the value we use is the same value this instruction was already using.
2349 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2350 default: break;
2351 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002352 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002353 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002354 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002355 case ICmpInst::ICMP_SGT:
2356 case ICmpInst::ICMP_SGE:
2357 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2358 Constant::getAllOnesValue(SRem->getType()));
2359 case ICmpInst::ICMP_SLT:
2360 case ICmpInst::ICMP_SLE:
2361 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2362 Constant::getNullValue(SRem->getType()));
2363 }
2364 }
2365
Duncan Sandsa7724332011-02-17 07:46:37 +00002366 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2367 BO0->hasOneUse() && BO1->hasOneUse() &&
2368 BO0->getOperand(1) == BO1->getOperand(1)) {
2369 switch (BO0->getOpcode()) {
2370 default: break;
2371 case Instruction::Add:
2372 case Instruction::Sub:
2373 case Instruction::Xor:
2374 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2375 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2376 BO1->getOperand(0));
2377 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2378 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2379 if (CI->getValue().isSignBit()) {
2380 ICmpInst::Predicate Pred = I.isSigned()
2381 ? I.getUnsignedPredicate()
2382 : I.getSignedPredicate();
2383 return new ICmpInst(Pred, BO0->getOperand(0),
2384 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002385 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002386
2387 if (CI->getValue().isMaxSignedValue()) {
2388 ICmpInst::Predicate Pred = I.isSigned()
2389 ? I.getUnsignedPredicate()
2390 : I.getSignedPredicate();
2391 Pred = I.getSwappedPredicate(Pred);
2392 return new ICmpInst(Pred, BO0->getOperand(0),
2393 BO1->getOperand(0));
2394 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002395 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002396 break;
2397 case Instruction::Mul:
2398 if (!I.isEquality())
2399 break;
2400
2401 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2402 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2403 // Mask = -1 >> count-trailing-zeros(Cst).
2404 if (!CI->isZero() && !CI->isOne()) {
2405 const APInt &AP = CI->getValue();
2406 ConstantInt *Mask = ConstantInt::get(I.getContext(),
2407 APInt::getLowBitsSet(AP.getBitWidth(),
2408 AP.getBitWidth() -
2409 AP.countTrailingZeros()));
2410 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2411 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2412 return new ICmpInst(I.getPredicate(), And1, And2);
2413 }
2414 }
2415 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002416 case Instruction::UDiv:
2417 case Instruction::LShr:
2418 if (I.isSigned())
2419 break;
2420 // fall-through
2421 case Instruction::SDiv:
2422 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002423 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002424 break;
2425 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2426 BO1->getOperand(0));
2427 case Instruction::Shl: {
2428 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2429 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2430 if (!NUW && !NSW)
2431 break;
2432 if (!NSW && I.isSigned())
2433 break;
2434 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2435 BO1->getOperand(0));
2436 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002437 }
2438 }
2439 }
2440
Chris Lattner02446fc2010-01-04 07:37:31 +00002441 { Value *A, *B;
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002442 // ~x < ~y --> y < x
2443 // ~x < cst --> ~cst < x
2444 if (match(Op0, m_Not(m_Value(A)))) {
2445 if (match(Op1, m_Not(m_Value(B))))
2446 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002447 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002448 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2449 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002450
2451 // (a+b) <u a --> llvm.uadd.with.overflow.
2452 // (a+b) <u b --> llvm.uadd.with.overflow.
2453 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2454 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2455 (Op1 == A || Op1 == B))
2456 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2457 return R;
2458
2459 // a >u (a+b) --> llvm.uadd.with.overflow.
2460 // b >u (a+b) --> llvm.uadd.with.overflow.
2461 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2462 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2463 (Op0 == A || Op0 == B))
2464 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2465 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002466 }
2467
2468 if (I.isEquality()) {
2469 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002470
Chris Lattner02446fc2010-01-04 07:37:31 +00002471 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2472 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2473 Value *OtherVal = A == Op1 ? B : A;
2474 return new ICmpInst(I.getPredicate(), OtherVal,
2475 Constant::getNullValue(A->getType()));
2476 }
2477
2478 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2479 // A^c1 == C^c2 --> A == C^(c1^c2)
2480 ConstantInt *C1, *C2;
2481 if (match(B, m_ConstantInt(C1)) &&
2482 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2483 Constant *NC = ConstantInt::get(I.getContext(),
2484 C1->getValue() ^ C2->getValue());
2485 Value *Xor = Builder->CreateXor(C, NC, "tmp");
2486 return new ICmpInst(I.getPredicate(), A, Xor);
2487 }
2488
2489 // A^B == A^D -> B == D
2490 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2491 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2492 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2493 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2494 }
2495 }
2496
2497 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2498 (A == Op0 || B == Op0)) {
2499 // A == (A^B) -> B == 0
2500 Value *OtherVal = A == Op0 ? B : A;
2501 return new ICmpInst(I.getPredicate(), OtherVal,
2502 Constant::getNullValue(A->getType()));
2503 }
2504
Chris Lattner02446fc2010-01-04 07:37:31 +00002505 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Chris Lattner5036ce42011-04-26 20:02:45 +00002506 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
2507 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002508 Value *X = 0, *Y = 0, *Z = 0;
2509
2510 if (A == C) {
2511 X = B; Y = D; Z = A;
2512 } else if (A == D) {
2513 X = B; Y = C; Z = A;
2514 } else if (B == C) {
2515 X = A; Y = D; Z = B;
2516 } else if (B == D) {
2517 X = A; Y = C; Z = B;
2518 }
2519
2520 if (X) { // Build (X^Y) & Z
2521 Op1 = Builder->CreateXor(X, Y, "tmp");
2522 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
2523 I.setOperand(0, Op1);
2524 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2525 return &I;
2526 }
2527 }
Chris Lattner5036ce42011-04-26 20:02:45 +00002528
Chris Lattner325eeb12011-04-26 20:18:20 +00002529 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2530 // "icmp (and X, mask), cst"
2531 uint64_t ShAmt = 0;
2532 ConstantInt *Cst1;
2533 if (Op0->hasOneUse() &&
2534 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2535 m_ConstantInt(ShAmt))))) &&
2536 match(Op1, m_ConstantInt(Cst1)) &&
2537 // Only do this when A has multiple uses. This is most important to do
2538 // when it exposes other optimizations.
2539 !A->hasOneUse()) {
2540 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2541
2542 if (ShAmt < ASize) {
2543 APInt MaskV =
2544 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2545 MaskV <<= ShAmt;
2546
2547 APInt CmpV = Cst1->getValue().zext(ASize);
2548 CmpV <<= ShAmt;
2549
2550 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2551 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2552 }
2553 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002554 }
2555
2556 {
2557 Value *X; ConstantInt *Cst;
2558 // icmp X+Cst, X
2559 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2560 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2561
2562 // icmp X, X+Cst
2563 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2564 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2565 }
2566 return Changed ? &I : 0;
2567}
2568
2569
2570
2571
2572
2573
2574/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2575///
2576Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2577 Instruction *LHSI,
2578 Constant *RHSC) {
2579 if (!isa<ConstantFP>(RHSC)) return 0;
2580 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
2581
2582 // Get the width of the mantissa. We don't want to hack on conversions that
2583 // might lose information from the integer, e.g. "i64 -> float"
2584 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2585 if (MantissaWidth == -1) return 0; // Unknown.
2586
2587 // Check to see that the input is converted from an integer type that is small
2588 // enough that preserves all bits. TODO: check here for "known" sign bits.
2589 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2590 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
2591
2592 // If this is a uitofp instruction, we need an extra bit to hold the sign.
2593 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2594 if (LHSUnsigned)
2595 ++InputSize;
2596
2597 // If the conversion would lose info, don't hack on this.
2598 if ((int)InputSize > MantissaWidth)
2599 return 0;
2600
2601 // Otherwise, we can potentially simplify the comparison. We know that it
2602 // will always come through as an integer value and we know the constant is
2603 // not a NAN (it would have been previously simplified).
2604 assert(!RHS.isNaN() && "NaN comparison not already folded!");
2605
2606 ICmpInst::Predicate Pred;
2607 switch (I.getPredicate()) {
2608 default: llvm_unreachable("Unexpected predicate!");
2609 case FCmpInst::FCMP_UEQ:
2610 case FCmpInst::FCMP_OEQ:
2611 Pred = ICmpInst::ICMP_EQ;
2612 break;
2613 case FCmpInst::FCMP_UGT:
2614 case FCmpInst::FCMP_OGT:
2615 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2616 break;
2617 case FCmpInst::FCMP_UGE:
2618 case FCmpInst::FCMP_OGE:
2619 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2620 break;
2621 case FCmpInst::FCMP_ULT:
2622 case FCmpInst::FCMP_OLT:
2623 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2624 break;
2625 case FCmpInst::FCMP_ULE:
2626 case FCmpInst::FCMP_OLE:
2627 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2628 break;
2629 case FCmpInst::FCMP_UNE:
2630 case FCmpInst::FCMP_ONE:
2631 Pred = ICmpInst::ICMP_NE;
2632 break;
2633 case FCmpInst::FCMP_ORD:
2634 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2635 case FCmpInst::FCMP_UNO:
2636 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2637 }
2638
2639 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
2640
2641 // Now we know that the APFloat is a normal number, zero or inf.
2642
2643 // See if the FP constant is too large for the integer. For example,
2644 // comparing an i8 to 300.0.
2645 unsigned IntWidth = IntTy->getScalarSizeInBits();
2646
2647 if (!LHSUnsigned) {
2648 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
2649 // and large values.
2650 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2651 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2652 APFloat::rmNearestTiesToEven);
2653 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
2654 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
2655 Pred == ICmpInst::ICMP_SLE)
2656 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2657 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2658 }
2659 } else {
2660 // If the RHS value is > UnsignedMax, fold the comparison. This handles
2661 // +INF and large values.
2662 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2663 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2664 APFloat::rmNearestTiesToEven);
2665 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
2666 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
2667 Pred == ICmpInst::ICMP_ULE)
2668 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2669 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2670 }
2671 }
2672
2673 if (!LHSUnsigned) {
2674 // See if the RHS value is < SignedMin.
2675 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2676 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2677 APFloat::rmNearestTiesToEven);
2678 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2679 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2680 Pred == ICmpInst::ICMP_SGE)
2681 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2682 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2683 }
2684 }
2685
2686 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2687 // [0, UMAX], but it may still be fractional. See if it is fractional by
2688 // casting the FP value to the integer value and back, checking for equality.
2689 // Don't do this for zero, because -0.0 is not fractional.
2690 Constant *RHSInt = LHSUnsigned
2691 ? ConstantExpr::getFPToUI(RHSC, IntTy)
2692 : ConstantExpr::getFPToSI(RHSC, IntTy);
2693 if (!RHS.isZero()) {
2694 bool Equal = LHSUnsigned
2695 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2696 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2697 if (!Equal) {
2698 // If we had a comparison against a fractional value, we have to adjust
2699 // the compare predicate and sometimes the value. RHSC is rounded towards
2700 // zero at this point.
2701 switch (Pred) {
2702 default: llvm_unreachable("Unexpected integer comparison!");
2703 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
2704 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2705 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
2706 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2707 case ICmpInst::ICMP_ULE:
2708 // (float)int <= 4.4 --> int <= 4
2709 // (float)int <= -4.4 --> false
2710 if (RHS.isNegative())
2711 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2712 break;
2713 case ICmpInst::ICMP_SLE:
2714 // (float)int <= 4.4 --> int <= 4
2715 // (float)int <= -4.4 --> int < -4
2716 if (RHS.isNegative())
2717 Pred = ICmpInst::ICMP_SLT;
2718 break;
2719 case ICmpInst::ICMP_ULT:
2720 // (float)int < -4.4 --> false
2721 // (float)int < 4.4 --> int <= 4
2722 if (RHS.isNegative())
2723 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2724 Pred = ICmpInst::ICMP_ULE;
2725 break;
2726 case ICmpInst::ICMP_SLT:
2727 // (float)int < -4.4 --> int < -4
2728 // (float)int < 4.4 --> int <= 4
2729 if (!RHS.isNegative())
2730 Pred = ICmpInst::ICMP_SLE;
2731 break;
2732 case ICmpInst::ICMP_UGT:
2733 // (float)int > 4.4 --> int > 4
2734 // (float)int > -4.4 --> true
2735 if (RHS.isNegative())
2736 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2737 break;
2738 case ICmpInst::ICMP_SGT:
2739 // (float)int > 4.4 --> int > 4
2740 // (float)int > -4.4 --> int >= -4
2741 if (RHS.isNegative())
2742 Pred = ICmpInst::ICMP_SGE;
2743 break;
2744 case ICmpInst::ICMP_UGE:
2745 // (float)int >= -4.4 --> true
2746 // (float)int >= 4.4 --> int > 4
2747 if (!RHS.isNegative())
2748 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2749 Pred = ICmpInst::ICMP_UGT;
2750 break;
2751 case ICmpInst::ICMP_SGE:
2752 // (float)int >= -4.4 --> int >= -4
2753 // (float)int >= 4.4 --> int > 4
2754 if (!RHS.isNegative())
2755 Pred = ICmpInst::ICMP_SGT;
2756 break;
2757 }
2758 }
2759 }
2760
2761 // Lower this FP comparison into an appropriate integer version of the
2762 // comparison.
2763 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2764}
2765
2766Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2767 bool Changed = false;
2768
2769 /// Orders the operands of the compare so that they are listed from most
2770 /// complex to least complex. This puts constants before unary operators,
2771 /// before binary operators.
2772 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2773 I.swapOperands();
2774 Changed = true;
2775 }
2776
2777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2778
2779 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2780 return ReplaceInstUsesWith(I, V);
2781
2782 // Simplify 'fcmp pred X, X'
2783 if (Op0 == Op1) {
2784 switch (I.getPredicate()) {
2785 default: llvm_unreachable("Unknown predicate!");
2786 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
2787 case FCmpInst::FCMP_ULT: // True if unordered or less than
2788 case FCmpInst::FCMP_UGT: // True if unordered or greater than
2789 case FCmpInst::FCMP_UNE: // True if unordered or not equal
2790 // Canonicalize these to be 'fcmp uno %X, 0.0'.
2791 I.setPredicate(FCmpInst::FCMP_UNO);
2792 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2793 return &I;
2794
2795 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
2796 case FCmpInst::FCMP_OEQ: // True if ordered and equal
2797 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
2798 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
2799 // Canonicalize these to be 'fcmp ord %X, 0.0'.
2800 I.setPredicate(FCmpInst::FCMP_ORD);
2801 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2802 return &I;
2803 }
2804 }
2805
2806 // Handle fcmp with constant RHS
2807 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2808 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2809 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002810 case Instruction::FPExt: {
2811 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
2812 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
2813 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
2814 if (!RHSF)
2815 break;
2816
Benjamin Kramer7ebdc372011-03-31 21:35:49 +00002817 // We can't convert a PPC double double.
2818 if (RHSF->getType()->isPPC_FP128Ty())
2819 break;
2820
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002821 const fltSemantics *Sem;
2822 // FIXME: This shouldn't be here.
2823 if (LHSExt->getSrcTy()->isFloatTy())
2824 Sem = &APFloat::IEEEsingle;
2825 else if (LHSExt->getSrcTy()->isDoubleTy())
2826 Sem = &APFloat::IEEEdouble;
2827 else if (LHSExt->getSrcTy()->isFP128Ty())
2828 Sem = &APFloat::IEEEquad;
2829 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
2830 Sem = &APFloat::x87DoubleExtended;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002831 else
2832 break;
2833
2834 bool Lossy;
2835 APFloat F = RHSF->getValueAPF();
2836 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
2837
2838 // Avoid lossy conversions and denormals.
2839 if (!Lossy &&
2840 F.compare(APFloat::getSmallestNormalized(*Sem)) !=
2841 APFloat::cmpLessThan)
2842 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2843 ConstantFP::get(RHSC->getContext(), F));
2844 break;
2845 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002846 case Instruction::PHI:
2847 // Only fold fcmp into the PHI if the phi and fcmp are in the same
2848 // block. If in the same block, we're encouraging jump threading. If
2849 // not, we are just pessimizing the code by making an i1 phi.
2850 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002851 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002852 return NV;
2853 break;
2854 case Instruction::SIToFP:
2855 case Instruction::UIToFP:
2856 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2857 return NV;
2858 break;
2859 case Instruction::Select: {
2860 // If either operand of the select is a constant, we can fold the
2861 // comparison into the select arms, which will cause one to be
2862 // constant folded and the select turned into a bitwise or.
2863 Value *Op1 = 0, *Op2 = 0;
2864 if (LHSI->hasOneUse()) {
2865 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2866 // Fold the known value into the constant operand.
2867 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2868 // Insert a new FCmp of the other select operand.
2869 Op2 = Builder->CreateFCmp(I.getPredicate(),
2870 LHSI->getOperand(2), RHSC, I.getName());
2871 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2872 // Fold the known value into the constant operand.
2873 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2874 // Insert a new FCmp of the other select operand.
2875 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2876 RHSC, I.getName());
2877 }
2878 }
2879
2880 if (Op1)
2881 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2882 break;
2883 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00002884 case Instruction::FSub: {
2885 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
2886 Value *Op;
2887 if (match(LHSI, m_FNeg(m_Value(Op))))
2888 return new FCmpInst(I.getSwappedPredicate(), Op,
2889 ConstantExpr::getFNeg(RHSC));
2890 break;
2891 }
Dan Gohman39516a62010-02-24 06:46:09 +00002892 case Instruction::Load:
2893 if (GetElementPtrInst *GEP =
2894 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2895 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2896 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2897 !cast<LoadInst>(LHSI)->isVolatile())
2898 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2899 return Res;
2900 }
2901 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00002902 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002903 }
2904
Benjamin Kramer00e00d62011-03-31 10:46:03 +00002905 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00002906 Value *X, *Y;
2907 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00002908 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00002909
Benjamin Kramercd0274c2011-03-31 10:11:58 +00002910 // fcmp (fpext x), (fpext y) -> fcmp x, y
2911 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
2912 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
2913 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
2914 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2915 RHSExt->getOperand(0));
2916
Chris Lattner02446fc2010-01-04 07:37:31 +00002917 return Changed ? &I : 0;
2918}