blob: 3cdb705c160ff720dbaa30ca9f5f5acdbe85cb94 [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()));
Benjamin Kramerfc87cdc2011-07-04 20:16:36 +00001457
1458 // Don't perform the following transforms if the AND has multiple uses
1459 if (!BO->hasOneUse())
1460 break;
1461
Chris Lattner02446fc2010-01-04 07:37:31 +00001462 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1463 if (BOC->getValue().isSignBit()) {
1464 Value *X = BO->getOperand(0);
1465 Constant *Zero = Constant::getNullValue(X->getType());
1466 ICmpInst::Predicate pred = isICMP_NE ?
1467 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1468 return new ICmpInst(pred, X, Zero);
1469 }
1470
1471 // ((X & ~7) == 0) --> X < 8
1472 if (RHSV == 0 && isHighOnes(BOC)) {
1473 Value *X = BO->getOperand(0);
1474 Constant *NegX = ConstantExpr::getNeg(BOC);
1475 ICmpInst::Predicate pred = isICMP_NE ?
1476 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1477 return new ICmpInst(pred, X, NegX);
1478 }
1479 }
1480 default: break;
1481 }
1482 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1483 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001484 switch (II->getIntrinsicID()) {
1485 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001486 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001487 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00001488 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1489 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001490 case Intrinsic::ctlz:
1491 case Intrinsic::cttz:
1492 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1493 if (RHSV == RHS->getType()->getBitWidth()) {
1494 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001495 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001496 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1497 return &ICI;
1498 }
1499 break;
1500 case Intrinsic::ctpop:
1501 // popcount(A) == 0 -> A == 0 and likewise for !=
1502 if (RHS->isZero()) {
1503 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001504 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001505 ICI.setOperand(1, RHS);
1506 return &ICI;
1507 }
1508 break;
1509 default:
Duncan Sands34727662010-07-12 08:16:59 +00001510 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001511 }
1512 }
1513 }
1514 return 0;
1515}
1516
1517/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1518/// We only handle extending casts so far.
1519///
1520Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1521 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1522 Value *LHSCIOp = LHSCI->getOperand(0);
1523 const Type *SrcTy = LHSCIOp->getType();
1524 const Type *DestTy = LHSCI->getType();
1525 Value *RHSCIOp;
1526
1527 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1528 // integer type is the same size as the pointer type.
1529 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1530 TD->getPointerSizeInBits() ==
1531 cast<IntegerType>(DestTy)->getBitWidth()) {
1532 Value *RHSOp = 0;
1533 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1534 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1535 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1536 RHSOp = RHSC->getOperand(0);
1537 // If the pointer types don't match, insert a bitcast.
1538 if (LHSCIOp->getType() != RHSOp->getType())
1539 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1540 }
1541
1542 if (RHSOp)
1543 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1544 }
1545
1546 // The code below only handles extension cast instructions, so far.
1547 // Enforce this.
1548 if (LHSCI->getOpcode() != Instruction::ZExt &&
1549 LHSCI->getOpcode() != Instruction::SExt)
1550 return 0;
1551
1552 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1553 bool isSignedCmp = ICI.isSigned();
1554
1555 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1556 // Not an extension from the same type?
1557 RHSCIOp = CI->getOperand(0);
1558 if (RHSCIOp->getType() != LHSCIOp->getType())
1559 return 0;
1560
1561 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1562 // and the other is a zext), then we can't handle this.
1563 if (CI->getOpcode() != LHSCI->getOpcode())
1564 return 0;
1565
1566 // Deal with equality cases early.
1567 if (ICI.isEquality())
1568 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1569
1570 // A signed comparison of sign extended values simplifies into a
1571 // signed comparison.
1572 if (isSignedCmp && isSignedExt)
1573 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1574
1575 // The other three cases all fold into an unsigned comparison.
1576 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1577 }
1578
1579 // If we aren't dealing with a constant on the RHS, exit early
1580 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1581 if (!CI)
1582 return 0;
1583
1584 // Compute the constant that would happen if we truncated to SrcTy then
1585 // reextended to DestTy.
1586 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1587 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1588 Res1, DestTy);
1589
1590 // If the re-extended constant didn't change...
1591 if (Res2 == CI) {
1592 // Deal with equality cases early.
1593 if (ICI.isEquality())
1594 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1595
1596 // A signed comparison of sign extended values simplifies into a
1597 // signed comparison.
1598 if (isSignedExt && isSignedCmp)
1599 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1600
1601 // The other three cases all fold into an unsigned comparison.
1602 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1603 }
1604
1605 // The re-extended constant changed so the constant cannot be represented
1606 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001607 // All the cases that fold to true or false will have already been handled
1608 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001609
Duncan Sands9d32f602011-01-20 13:21:55 +00001610 if (isSignedCmp || !isSignedExt)
1611 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001612
1613 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1614 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001615
1616 // We're performing an unsigned comp with a sign extended value.
1617 // This is true if the input is >= 0. [aka >s -1]
1618 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1619 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001620
1621 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001622 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001623 return ReplaceInstUsesWith(ICI, Result);
1624
Duncan Sands9d32f602011-01-20 13:21:55 +00001625 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001626 return BinaryOperator::CreateNot(Result);
1627}
1628
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001629/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1630/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001631/// If this is of the form:
1632/// sum = a + b
1633/// if (sum+128 >u 255)
1634/// Then replace it with llvm.sadd.with.overflow.i8.
1635///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001636static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1637 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001638 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001639 // The transformation we're trying to do here is to transform this into an
1640 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1641 // with a narrower add, and discard the add-with-constant that is part of the
1642 // range check (if we can't eliminate it, this isn't profitable).
1643
1644 // In order to eliminate the add-with-constant, the compare can be its only
1645 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001646 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001647 if (!AddWithCst->hasOneUse()) return 0;
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001648
1649 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1650 if (!CI2->getValue().isPowerOf2()) return 0;
1651 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1652 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1653
1654 // The width of the new add formed is 1 more than the bias.
1655 ++NewWidth;
1656
1657 // Check to see that CI1 is an all-ones value with NewWidth bits.
1658 if (CI1->getBitWidth() == NewWidth ||
1659 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1660 return 0;
1661
1662 // In order to replace the original add with a narrower
1663 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1664 // and truncates that discard the high bits of the add. Verify that this is
1665 // the case.
1666 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1667 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1668 UI != E; ++UI) {
1669 if (*UI == AddWithCst) continue;
1670
1671 // Only accept truncates for now. We would really like a nice recursive
1672 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1673 // chain to see which bits of a value are actually demanded. If the
1674 // original add had another add which was then immediately truncated, we
1675 // could still do the transformation.
1676 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1677 if (TI == 0 ||
1678 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1679 }
1680
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001681 // If the pattern matches, truncate the inputs to the narrower type and
1682 // use the sadd_with_overflow intrinsic to efficiently compute both the
1683 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001684 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001685
Jay Foad5fdd6c82011-07-12 14:06:48 +00001686 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner0a624742010-12-19 18:35:09 +00001687 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1688 &NewType, 1);
1689
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001690 InstCombiner::BuilderTy *Builder = IC.Builder;
1691
Chris Lattner0a624742010-12-19 18:35:09 +00001692 // Put the new code above the original add, in case there are any uses of the
1693 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001694 Builder->SetInsertPoint(OrigAdd);
Chris Lattner0a624742010-12-19 18:35:09 +00001695
1696 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1697 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1698 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1699 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1700 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001701
1702 // The inner add was the result of the narrow add, zero extended to the
1703 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001704 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001705
Chris Lattner0a624742010-12-19 18:35:09 +00001706 // The original icmp gets replaced with the overflow value.
1707 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001708}
Chris Lattner02446fc2010-01-04 07:37:31 +00001709
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001710static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1711 InstCombiner &IC) {
1712 // Don't bother doing this transformation for pointers, don't do it for
1713 // vectors.
1714 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1715
1716 // If the add is a constant expr, then we don't bother transforming it.
1717 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1718 if (OrigAdd == 0) return 0;
1719
1720 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1721
1722 // Put the new code above the original add, in case there are any uses of the
1723 // add between the add and the compare.
1724 InstCombiner::BuilderTy *Builder = IC.Builder;
1725 Builder->SetInsertPoint(OrigAdd);
1726
1727 Module *M = I.getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001728 Type *Ty = LHS->getType();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001729 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, &Ty,1);
1730 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1731 Value *Add = Builder->CreateExtractValue(Call, 0);
1732
1733 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1734
1735 // The original icmp gets replaced with the overflow value.
1736 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1737}
1738
Owen Andersonda1c1222011-01-11 00:36:45 +00001739// DemandedBitsLHSMask - When performing a comparison against a constant,
1740// it is possible that not all the bits in the LHS are demanded. This helper
1741// method computes the mask that IS demanded.
1742static APInt DemandedBitsLHSMask(ICmpInst &I,
1743 unsigned BitWidth, bool isSignCheck) {
1744 if (isSignCheck)
1745 return APInt::getSignBit(BitWidth);
1746
1747 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1748 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00001749 const APInt &RHS = CI->getValue();
Owen Andersonda1c1222011-01-11 00:36:45 +00001750
1751 switch (I.getPredicate()) {
1752 // For a UGT comparison, we don't care about any bits that
1753 // correspond to the trailing ones of the comparand. The value of these
1754 // bits doesn't impact the outcome of the comparison, because any value
1755 // greater than the RHS must differ in a bit higher than these due to carry.
1756 case ICmpInst::ICMP_UGT: {
1757 unsigned trailingOnes = RHS.countTrailingOnes();
1758 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1759 return ~lowBitsSet;
1760 }
1761
1762 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1763 // Any value less than the RHS must differ in a higher bit because of carries.
1764 case ICmpInst::ICMP_ULT: {
1765 unsigned trailingZeros = RHS.countTrailingZeros();
1766 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1767 return ~lowBitsSet;
1768 }
1769
1770 default:
1771 return APInt::getAllOnesValue(BitWidth);
1772 }
1773
Owen Andersonda1c1222011-01-11 00:36:45 +00001774}
Chris Lattner02446fc2010-01-04 07:37:31 +00001775
1776Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1777 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00001778 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001779
1780 /// Orders the operands of the compare so that they are listed from most
1781 /// complex to least complex. This puts constants before unary operators,
1782 /// before binary operators.
Chris Lattner5f670d42010-02-01 19:54:45 +00001783 if (getComplexity(Op0) < getComplexity(Op1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001784 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00001785 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001786 Changed = true;
1787 }
1788
Chris Lattner02446fc2010-01-04 07:37:31 +00001789 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1790 return ReplaceInstUsesWith(I, V);
1791
1792 const Type *Ty = Op0->getType();
1793
1794 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001795 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001796 switch (I.getPredicate()) {
1797 default: llvm_unreachable("Invalid icmp instruction!");
1798 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
1799 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1800 return BinaryOperator::CreateNot(Xor);
1801 }
1802 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
1803 return BinaryOperator::CreateXor(Op0, Op1);
1804
1805 case ICmpInst::ICMP_UGT:
1806 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
1807 // FALL THROUGH
1808 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
1809 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1810 return BinaryOperator::CreateAnd(Not, Op1);
1811 }
1812 case ICmpInst::ICMP_SGT:
1813 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
1814 // FALL THROUGH
1815 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
1816 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1817 return BinaryOperator::CreateAnd(Not, Op0);
1818 }
1819 case ICmpInst::ICMP_UGE:
1820 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
1821 // FALL THROUGH
1822 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
1823 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1824 return BinaryOperator::CreateOr(Not, Op1);
1825 }
1826 case ICmpInst::ICMP_SGE:
1827 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
1828 // FALL THROUGH
1829 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
1830 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1831 return BinaryOperator::CreateOr(Not, Op0);
1832 }
1833 }
1834 }
1835
1836 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001837 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00001838 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001839 else if (TD) // Pointers require TD info to get their size.
1840 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
1841
Chris Lattner02446fc2010-01-04 07:37:31 +00001842 bool isSignBit = false;
1843
1844 // See if we are doing a comparison with a constant.
1845 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1846 Value *A = 0, *B = 0;
1847
Owen Andersone63dda52010-12-17 18:08:00 +00001848 // Match the following pattern, which is a common idiom when writing
1849 // overflow-safe integer arithmetic function. The source performs an
1850 // addition in wider type, and explicitly checks for overflow using
1851 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
1852 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001853 //
1854 // TODO: This could probably be generalized to handle other overflow-safe
Owen Andersone63dda52010-12-17 18:08:00 +00001855 // operations if we worked out the formulas to compute the appropriate
1856 // magic constants.
1857 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001858 // sum = a + b
1859 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00001860 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001861 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00001862 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001863 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001864 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001865 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00001866 }
1867
Chris Lattner02446fc2010-01-04 07:37:31 +00001868 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1869 if (I.isEquality() && CI->isZero() &&
1870 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1871 // (icmp cond A B) if cond is equality
1872 return new ICmpInst(I.getPredicate(), A, B);
1873 }
1874
1875 // If we have an icmp le or icmp ge instruction, turn it into the
1876 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
1877 // them being folded in the code below. The SimplifyICmpInst code has
1878 // already handled the edge cases for us, so we just assert on them.
1879 switch (I.getPredicate()) {
1880 default: break;
1881 case ICmpInst::ICMP_ULE:
1882 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
1883 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1884 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1885 case ICmpInst::ICMP_SLE:
1886 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
1887 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1888 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1889 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001890 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001891 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1892 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1893 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001894 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001895 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1896 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1897 }
1898
1899 // If this comparison is a normal comparison, it demands all
1900 // bits, if it is a sign bit comparison, it only demands the sign bit.
1901 bool UnusedBit;
1902 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1903 }
1904
1905 // See if we can fold the comparison based on range information we can get
1906 // by checking whether bits are known to be zero or one in the input.
1907 if (BitWidth != 0) {
1908 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1909 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1910
1911 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00001912 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00001913 Op0KnownZero, Op0KnownOne, 0))
1914 return &I;
1915 if (SimplifyDemandedBits(I.getOperandUse(1),
1916 APInt::getAllOnesValue(BitWidth),
1917 Op1KnownZero, Op1KnownOne, 0))
1918 return &I;
1919
1920 // Given the known and unknown bits, compute a range that the LHS could be
1921 // in. Compute the Min, Max and RHS values based on the known bits. For the
1922 // EQ and NE we use unsigned values.
1923 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1924 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1925 if (I.isSigned()) {
1926 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1927 Op0Min, Op0Max);
1928 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1929 Op1Min, Op1Max);
1930 } else {
1931 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1932 Op0Min, Op0Max);
1933 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1934 Op1Min, Op1Max);
1935 }
1936
1937 // If Min and Max are known to be the same, then SimplifyDemandedBits
1938 // figured out that the LHS is a constant. Just constant fold this now so
1939 // that code below can assume that Min != Max.
1940 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1941 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001942 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001943 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1944 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001945 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00001946
1947 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001948 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00001949 switch (I.getPredicate()) {
1950 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00001951 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00001952 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001953 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner75d8f592010-11-21 06:44:42 +00001954
1955 // If all bits are known zero except for one, then we know at most one
1956 // bit is set. If the comparison is against zero, then this is a check
1957 // to see if *that* bit is set.
1958 APInt Op0KnownZeroInverted = ~Op0KnownZero;
1959 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1960 // If the LHS is an AND with the same constant, look through it.
1961 Value *LHS = 0;
1962 ConstantInt *LHSC = 0;
1963 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1964 LHSC->getValue() != Op0KnownZeroInverted)
1965 LHS = Op0;
1966
1967 // 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 +00001968 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00001969 Value *X = 0;
1970 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
1971 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00001972 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00001973 ConstantInt::get(X->getType(), CmpVal));
1974 }
1975
1976 // 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 +00001977 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001978 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00001979 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001980 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00001981 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001982 ConstantInt::get(X->getType(),
1983 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00001984 }
1985
Chris Lattner02446fc2010-01-04 07:37:31 +00001986 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00001987 }
1988 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00001989 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001990 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner75d8f592010-11-21 06:44:42 +00001991
1992 // If all bits are known zero except for one, then we know at most one
1993 // bit is set. If the comparison is against zero, then this is a check
1994 // to see if *that* bit is set.
1995 APInt Op0KnownZeroInverted = ~Op0KnownZero;
1996 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1997 // If the LHS is an AND with the same constant, look through it.
1998 Value *LHS = 0;
1999 ConstantInt *LHSC = 0;
2000 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2001 LHSC->getValue() != Op0KnownZeroInverted)
2002 LHS = Op0;
2003
2004 // 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 +00002005 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002006 Value *X = 0;
2007 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2008 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002009 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002010 ConstantInt::get(X->getType(), CmpVal));
2011 }
2012
2013 // 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 +00002014 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002015 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002016 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002017 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002018 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002019 ConstantInt::get(X->getType(),
2020 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002021 }
2022
Chris Lattner02446fc2010-01-04 07:37:31 +00002023 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002024 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002025 case ICmpInst::ICMP_ULT:
2026 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002027 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002028 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002029 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002030 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2031 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2032 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2033 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2034 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2035 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2036
2037 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2038 if (CI->isMinValue(true))
2039 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2040 Constant::getAllOnesValue(Op0->getType()));
2041 }
2042 break;
2043 case ICmpInst::ICMP_UGT:
2044 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002045 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002046 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002047 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002048
2049 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2050 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2051 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2052 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2053 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2054 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2055
2056 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2057 if (CI->isMaxValue(true))
2058 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2059 Constant::getNullValue(Op0->getType()));
2060 }
2061 break;
2062 case ICmpInst::ICMP_SLT:
2063 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002064 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002065 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002066 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002067 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2068 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2069 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2070 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2071 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2072 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2073 }
2074 break;
2075 case ICmpInst::ICMP_SGT:
2076 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002077 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002078 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002079 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002080
2081 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2082 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2083 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2084 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2085 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2086 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2087 }
2088 break;
2089 case ICmpInst::ICMP_SGE:
2090 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2091 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002092 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002093 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002094 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002095 break;
2096 case ICmpInst::ICMP_SLE:
2097 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2098 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002099 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002100 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002101 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002102 break;
2103 case ICmpInst::ICMP_UGE:
2104 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2105 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002106 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002107 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002108 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002109 break;
2110 case ICmpInst::ICMP_ULE:
2111 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2112 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002113 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002114 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002115 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002116 break;
2117 }
2118
2119 // Turn a signed comparison into an unsigned one if both operands
2120 // are known to have the same sign.
2121 if (I.isSigned() &&
2122 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2123 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2124 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2125 }
2126
2127 // Test if the ICmpInst instruction is used exclusively by a select as
2128 // part of a minimum or maximum operation. If so, refrain from doing
2129 // any other folding. This helps out other analyses which understand
2130 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2131 // and CodeGen. And in this case, at least one of the comparison
2132 // operands has at least one user besides the compare (the select),
2133 // which would often largely negate the benefit of folding anyway.
2134 if (I.hasOneUse())
2135 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2136 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2137 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2138 return 0;
2139
2140 // See if we are doing a comparison between a constant and an instruction that
2141 // can be folded into the comparison.
2142 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2143 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2144 // instruction, see if that instruction also has constants so that the
2145 // instruction can be folded into the icmp
2146 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2147 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2148 return Res;
2149 }
2150
2151 // Handle icmp with constant (but not simple integer constant) RHS
2152 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2153 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2154 switch (LHSI->getOpcode()) {
2155 case Instruction::GetElementPtr:
2156 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2157 if (RHSC->isNullValue() &&
2158 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2159 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2160 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2161 break;
2162 case Instruction::PHI:
2163 // Only fold icmp into the PHI if the phi and icmp are in the same
2164 // block. If in the same block, we're encouraging jump threading. If
2165 // not, we are just pessimizing the code by making an i1 phi.
2166 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002167 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002168 return NV;
2169 break;
2170 case Instruction::Select: {
2171 // If either operand of the select is a constant, we can fold the
2172 // comparison into the select arms, which will cause one to be
2173 // constant folded and the select turned into a bitwise or.
2174 Value *Op1 = 0, *Op2 = 0;
2175 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2176 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2177 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2178 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2179
2180 // We only want to perform this transformation if it will not lead to
2181 // additional code. This is true if either both sides of the select
2182 // fold to a constant (in which case the icmp is replaced with a select
2183 // which will usually simplify) or this is the only user of the
2184 // select (in which case we are trading a select+icmp for a simpler
2185 // select+icmp).
2186 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2187 if (!Op1)
2188 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2189 RHSC, I.getName());
2190 if (!Op2)
2191 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2192 RHSC, I.getName());
2193 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2194 }
2195 break;
2196 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002197 case Instruction::IntToPtr:
2198 // icmp pred inttoptr(X), null -> icmp pred X, 0
2199 if (RHSC->isNullValue() && TD &&
2200 TD->getIntPtrType(RHSC->getContext()) ==
2201 LHSI->getOperand(0)->getType())
2202 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2203 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2204 break;
2205
2206 case Instruction::Load:
2207 // Try to optimize things like "A[i] > 4" to index computations.
2208 if (GetElementPtrInst *GEP =
2209 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2210 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2211 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2212 !cast<LoadInst>(LHSI)->isVolatile())
2213 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2214 return Res;
2215 }
2216 break;
2217 }
2218 }
2219
2220 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2221 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2222 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2223 return NI;
2224 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2225 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2226 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2227 return NI;
2228
2229 // Test to see if the operands of the icmp are casted versions of other
2230 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2231 // now.
2232 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Duncan Sands1df98592010-02-16 11:11:14 +00002233 if (Op0->getType()->isPointerTy() &&
Chris Lattner02446fc2010-01-04 07:37:31 +00002234 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2235 // We keep moving the cast from the left operand over to the right
2236 // operand, where it can often be eliminated completely.
2237 Op0 = CI->getOperand(0);
2238
2239 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2240 // so eliminate it as well.
2241 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2242 Op1 = CI2->getOperand(0);
2243
2244 // If Op1 is a constant, we can fold the cast into the constant.
2245 if (Op0->getType() != Op1->getType()) {
2246 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2247 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2248 } else {
2249 // Otherwise, cast the RHS right before the icmp
2250 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2251 }
2252 }
2253 return new ICmpInst(I.getPredicate(), Op0, Op1);
2254 }
2255 }
2256
2257 if (isa<CastInst>(Op0)) {
2258 // Handle the special case of: icmp (cast bool to X), <cst>
2259 // This comes up when you have code like
2260 // int X = A < B;
2261 // if (X) ...
2262 // For generality, we handle any zero-extension of any operand comparison
2263 // with a constant or another cast from the same type.
2264 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2265 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2266 return R;
2267 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002268
Duncan Sandsa7724332011-02-17 07:46:37 +00002269 // Special logic for binary operators.
2270 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2271 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2272 if (BO0 || BO1) {
2273 CmpInst::Predicate Pred = I.getPredicate();
2274 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2275 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2276 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2277 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2278 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2279 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2280 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2281 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2282 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2283
2284 // Analyze the case when either Op0 or Op1 is an add instruction.
2285 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2286 Value *A = 0, *B = 0, *C = 0, *D = 0;
2287 if (BO0 && BO0->getOpcode() == Instruction::Add)
2288 A = BO0->getOperand(0), B = BO0->getOperand(1);
2289 if (BO1 && BO1->getOpcode() == Instruction::Add)
2290 C = BO1->getOperand(0), D = BO1->getOperand(1);
2291
2292 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2293 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2294 return new ICmpInst(Pred, A == Op1 ? B : A,
2295 Constant::getNullValue(Op1->getType()));
2296
2297 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2298 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2299 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2300 C == Op0 ? D : C);
2301
Duncan Sands39a7de72011-02-18 16:25:37 +00002302 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002303 if (A && C && (A == C || A == D || B == C || B == D) &&
2304 NoOp0WrapProblem && NoOp1WrapProblem &&
2305 // Try not to increase register pressure.
2306 BO0->hasOneUse() && BO1->hasOneUse()) {
2307 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2308 Value *Y = (A == C || A == D) ? B : A;
2309 Value *Z = (C == A || C == B) ? D : C;
2310 return new ICmpInst(Pred, Y, Z);
2311 }
2312
2313 // Analyze the case when either Op0 or Op1 is a sub instruction.
2314 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2315 A = 0; B = 0; C = 0; D = 0;
2316 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2317 A = BO0->getOperand(0), B = BO0->getOperand(1);
2318 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2319 C = BO1->getOperand(0), D = BO1->getOperand(1);
2320
Duncan Sands39a7de72011-02-18 16:25:37 +00002321 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2322 if (A == Op1 && NoOp0WrapProblem)
2323 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2324
2325 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2326 if (C == Op0 && NoOp1WrapProblem)
2327 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2328
2329 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002330 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2331 // Try not to increase register pressure.
2332 BO0->hasOneUse() && BO1->hasOneUse())
2333 return new ICmpInst(Pred, A, C);
2334
Duncan Sands39a7de72011-02-18 16:25:37 +00002335 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2336 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2337 // Try not to increase register pressure.
2338 BO0->hasOneUse() && BO1->hasOneUse())
2339 return new ICmpInst(Pred, D, B);
2340
Nick Lewycky9feda172011-03-05 04:28:48 +00002341 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002342 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002343 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2344 Op1 == BO0->getOperand(1))
2345 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002346 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002347 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2348 Op0 == BO1->getOperand(1))
2349 SRem = BO1;
2350 if (SRem) {
2351 // We don't check hasOneUse to avoid increasing register pressure because
2352 // the value we use is the same value this instruction was already using.
2353 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2354 default: break;
2355 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002356 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002357 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002358 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002359 case ICmpInst::ICMP_SGT:
2360 case ICmpInst::ICMP_SGE:
2361 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2362 Constant::getAllOnesValue(SRem->getType()));
2363 case ICmpInst::ICMP_SLT:
2364 case ICmpInst::ICMP_SLE:
2365 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2366 Constant::getNullValue(SRem->getType()));
2367 }
2368 }
2369
Duncan Sandsa7724332011-02-17 07:46:37 +00002370 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2371 BO0->hasOneUse() && BO1->hasOneUse() &&
2372 BO0->getOperand(1) == BO1->getOperand(1)) {
2373 switch (BO0->getOpcode()) {
2374 default: break;
2375 case Instruction::Add:
2376 case Instruction::Sub:
2377 case Instruction::Xor:
2378 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2379 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2380 BO1->getOperand(0));
2381 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2382 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2383 if (CI->getValue().isSignBit()) {
2384 ICmpInst::Predicate Pred = I.isSigned()
2385 ? I.getUnsignedPredicate()
2386 : I.getSignedPredicate();
2387 return new ICmpInst(Pred, BO0->getOperand(0),
2388 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002389 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002390
2391 if (CI->getValue().isMaxSignedValue()) {
2392 ICmpInst::Predicate Pred = I.isSigned()
2393 ? I.getUnsignedPredicate()
2394 : I.getSignedPredicate();
2395 Pred = I.getSwappedPredicate(Pred);
2396 return new ICmpInst(Pred, BO0->getOperand(0),
2397 BO1->getOperand(0));
2398 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002399 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002400 break;
2401 case Instruction::Mul:
2402 if (!I.isEquality())
2403 break;
2404
2405 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2406 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2407 // Mask = -1 >> count-trailing-zeros(Cst).
2408 if (!CI->isZero() && !CI->isOne()) {
2409 const APInt &AP = CI->getValue();
2410 ConstantInt *Mask = ConstantInt::get(I.getContext(),
2411 APInt::getLowBitsSet(AP.getBitWidth(),
2412 AP.getBitWidth() -
2413 AP.countTrailingZeros()));
2414 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2415 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2416 return new ICmpInst(I.getPredicate(), And1, And2);
2417 }
2418 }
2419 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002420 case Instruction::UDiv:
2421 case Instruction::LShr:
2422 if (I.isSigned())
2423 break;
2424 // fall-through
2425 case Instruction::SDiv:
2426 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002427 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002428 break;
2429 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2430 BO1->getOperand(0));
2431 case Instruction::Shl: {
2432 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2433 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2434 if (!NUW && !NSW)
2435 break;
2436 if (!NSW && I.isSigned())
2437 break;
2438 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2439 BO1->getOperand(0));
2440 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002441 }
2442 }
2443 }
2444
Chris Lattner02446fc2010-01-04 07:37:31 +00002445 { Value *A, *B;
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002446 // ~x < ~y --> y < x
2447 // ~x < cst --> ~cst < x
2448 if (match(Op0, m_Not(m_Value(A)))) {
2449 if (match(Op1, m_Not(m_Value(B))))
2450 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002451 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002452 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2453 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002454
2455 // (a+b) <u a --> llvm.uadd.with.overflow.
2456 // (a+b) <u b --> llvm.uadd.with.overflow.
2457 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2458 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2459 (Op1 == A || Op1 == B))
2460 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2461 return R;
2462
2463 // a >u (a+b) --> llvm.uadd.with.overflow.
2464 // b >u (a+b) --> llvm.uadd.with.overflow.
2465 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2466 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2467 (Op0 == A || Op0 == B))
2468 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2469 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002470 }
2471
2472 if (I.isEquality()) {
2473 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002474
Chris Lattner02446fc2010-01-04 07:37:31 +00002475 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2476 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2477 Value *OtherVal = A == Op1 ? B : A;
2478 return new ICmpInst(I.getPredicate(), OtherVal,
2479 Constant::getNullValue(A->getType()));
2480 }
2481
2482 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2483 // A^c1 == C^c2 --> A == C^(c1^c2)
2484 ConstantInt *C1, *C2;
2485 if (match(B, m_ConstantInt(C1)) &&
2486 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2487 Constant *NC = ConstantInt::get(I.getContext(),
2488 C1->getValue() ^ C2->getValue());
2489 Value *Xor = Builder->CreateXor(C, NC, "tmp");
2490 return new ICmpInst(I.getPredicate(), A, Xor);
2491 }
2492
2493 // A^B == A^D -> B == D
2494 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2495 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2496 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2497 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2498 }
2499 }
2500
2501 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2502 (A == Op0 || B == Op0)) {
2503 // A == (A^B) -> B == 0
2504 Value *OtherVal = A == Op0 ? B : A;
2505 return new ICmpInst(I.getPredicate(), OtherVal,
2506 Constant::getNullValue(A->getType()));
2507 }
2508
Chris Lattner02446fc2010-01-04 07:37:31 +00002509 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Chris Lattner5036ce42011-04-26 20:02:45 +00002510 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
2511 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002512 Value *X = 0, *Y = 0, *Z = 0;
2513
2514 if (A == C) {
2515 X = B; Y = D; Z = A;
2516 } else if (A == D) {
2517 X = B; Y = C; Z = A;
2518 } else if (B == C) {
2519 X = A; Y = D; Z = B;
2520 } else if (B == D) {
2521 X = A; Y = C; Z = B;
2522 }
2523
2524 if (X) { // Build (X^Y) & Z
2525 Op1 = Builder->CreateXor(X, Y, "tmp");
2526 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
2527 I.setOperand(0, Op1);
2528 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2529 return &I;
2530 }
2531 }
Chris Lattner5036ce42011-04-26 20:02:45 +00002532
Chris Lattner325eeb12011-04-26 20:18:20 +00002533 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2534 // "icmp (and X, mask), cst"
2535 uint64_t ShAmt = 0;
2536 ConstantInt *Cst1;
2537 if (Op0->hasOneUse() &&
2538 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2539 m_ConstantInt(ShAmt))))) &&
2540 match(Op1, m_ConstantInt(Cst1)) &&
2541 // Only do this when A has multiple uses. This is most important to do
2542 // when it exposes other optimizations.
2543 !A->hasOneUse()) {
2544 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2545
2546 if (ShAmt < ASize) {
2547 APInt MaskV =
2548 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2549 MaskV <<= ShAmt;
2550
2551 APInt CmpV = Cst1->getValue().zext(ASize);
2552 CmpV <<= ShAmt;
2553
2554 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2555 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2556 }
2557 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002558 }
2559
2560 {
2561 Value *X; ConstantInt *Cst;
2562 // icmp X+Cst, X
2563 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2564 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2565
2566 // icmp X, X+Cst
2567 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2568 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2569 }
2570 return Changed ? &I : 0;
2571}
2572
2573
2574
2575
2576
2577
2578/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2579///
2580Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2581 Instruction *LHSI,
2582 Constant *RHSC) {
2583 if (!isa<ConstantFP>(RHSC)) return 0;
2584 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
2585
2586 // Get the width of the mantissa. We don't want to hack on conversions that
2587 // might lose information from the integer, e.g. "i64 -> float"
2588 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2589 if (MantissaWidth == -1) return 0; // Unknown.
2590
2591 // Check to see that the input is converted from an integer type that is small
2592 // enough that preserves all bits. TODO: check here for "known" sign bits.
2593 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2594 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
2595
2596 // If this is a uitofp instruction, we need an extra bit to hold the sign.
2597 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2598 if (LHSUnsigned)
2599 ++InputSize;
2600
2601 // If the conversion would lose info, don't hack on this.
2602 if ((int)InputSize > MantissaWidth)
2603 return 0;
2604
2605 // Otherwise, we can potentially simplify the comparison. We know that it
2606 // will always come through as an integer value and we know the constant is
2607 // not a NAN (it would have been previously simplified).
2608 assert(!RHS.isNaN() && "NaN comparison not already folded!");
2609
2610 ICmpInst::Predicate Pred;
2611 switch (I.getPredicate()) {
2612 default: llvm_unreachable("Unexpected predicate!");
2613 case FCmpInst::FCMP_UEQ:
2614 case FCmpInst::FCMP_OEQ:
2615 Pred = ICmpInst::ICMP_EQ;
2616 break;
2617 case FCmpInst::FCMP_UGT:
2618 case FCmpInst::FCMP_OGT:
2619 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2620 break;
2621 case FCmpInst::FCMP_UGE:
2622 case FCmpInst::FCMP_OGE:
2623 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2624 break;
2625 case FCmpInst::FCMP_ULT:
2626 case FCmpInst::FCMP_OLT:
2627 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2628 break;
2629 case FCmpInst::FCMP_ULE:
2630 case FCmpInst::FCMP_OLE:
2631 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2632 break;
2633 case FCmpInst::FCMP_UNE:
2634 case FCmpInst::FCMP_ONE:
2635 Pred = ICmpInst::ICMP_NE;
2636 break;
2637 case FCmpInst::FCMP_ORD:
2638 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2639 case FCmpInst::FCMP_UNO:
2640 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2641 }
2642
2643 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
2644
2645 // Now we know that the APFloat is a normal number, zero or inf.
2646
2647 // See if the FP constant is too large for the integer. For example,
2648 // comparing an i8 to 300.0.
2649 unsigned IntWidth = IntTy->getScalarSizeInBits();
2650
2651 if (!LHSUnsigned) {
2652 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
2653 // and large values.
2654 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2655 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2656 APFloat::rmNearestTiesToEven);
2657 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
2658 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
2659 Pred == ICmpInst::ICMP_SLE)
2660 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2661 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2662 }
2663 } else {
2664 // If the RHS value is > UnsignedMax, fold the comparison. This handles
2665 // +INF and large values.
2666 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2667 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2668 APFloat::rmNearestTiesToEven);
2669 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
2670 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
2671 Pred == ICmpInst::ICMP_ULE)
2672 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2673 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2674 }
2675 }
2676
2677 if (!LHSUnsigned) {
2678 // See if the RHS value is < SignedMin.
2679 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2680 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2681 APFloat::rmNearestTiesToEven);
2682 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2683 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2684 Pred == ICmpInst::ICMP_SGE)
2685 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2686 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2687 }
2688 }
2689
2690 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2691 // [0, UMAX], but it may still be fractional. See if it is fractional by
2692 // casting the FP value to the integer value and back, checking for equality.
2693 // Don't do this for zero, because -0.0 is not fractional.
2694 Constant *RHSInt = LHSUnsigned
2695 ? ConstantExpr::getFPToUI(RHSC, IntTy)
2696 : ConstantExpr::getFPToSI(RHSC, IntTy);
2697 if (!RHS.isZero()) {
2698 bool Equal = LHSUnsigned
2699 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2700 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2701 if (!Equal) {
2702 // If we had a comparison against a fractional value, we have to adjust
2703 // the compare predicate and sometimes the value. RHSC is rounded towards
2704 // zero at this point.
2705 switch (Pred) {
2706 default: llvm_unreachable("Unexpected integer comparison!");
2707 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
2708 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2709 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
2710 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2711 case ICmpInst::ICMP_ULE:
2712 // (float)int <= 4.4 --> int <= 4
2713 // (float)int <= -4.4 --> false
2714 if (RHS.isNegative())
2715 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2716 break;
2717 case ICmpInst::ICMP_SLE:
2718 // (float)int <= 4.4 --> int <= 4
2719 // (float)int <= -4.4 --> int < -4
2720 if (RHS.isNegative())
2721 Pred = ICmpInst::ICMP_SLT;
2722 break;
2723 case ICmpInst::ICMP_ULT:
2724 // (float)int < -4.4 --> false
2725 // (float)int < 4.4 --> int <= 4
2726 if (RHS.isNegative())
2727 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2728 Pred = ICmpInst::ICMP_ULE;
2729 break;
2730 case ICmpInst::ICMP_SLT:
2731 // (float)int < -4.4 --> int < -4
2732 // (float)int < 4.4 --> int <= 4
2733 if (!RHS.isNegative())
2734 Pred = ICmpInst::ICMP_SLE;
2735 break;
2736 case ICmpInst::ICMP_UGT:
2737 // (float)int > 4.4 --> int > 4
2738 // (float)int > -4.4 --> true
2739 if (RHS.isNegative())
2740 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2741 break;
2742 case ICmpInst::ICMP_SGT:
2743 // (float)int > 4.4 --> int > 4
2744 // (float)int > -4.4 --> int >= -4
2745 if (RHS.isNegative())
2746 Pred = ICmpInst::ICMP_SGE;
2747 break;
2748 case ICmpInst::ICMP_UGE:
2749 // (float)int >= -4.4 --> true
2750 // (float)int >= 4.4 --> int > 4
2751 if (!RHS.isNegative())
2752 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2753 Pred = ICmpInst::ICMP_UGT;
2754 break;
2755 case ICmpInst::ICMP_SGE:
2756 // (float)int >= -4.4 --> int >= -4
2757 // (float)int >= 4.4 --> int > 4
2758 if (!RHS.isNegative())
2759 Pred = ICmpInst::ICMP_SGT;
2760 break;
2761 }
2762 }
2763 }
2764
2765 // Lower this FP comparison into an appropriate integer version of the
2766 // comparison.
2767 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2768}
2769
2770Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2771 bool Changed = false;
2772
2773 /// Orders the operands of the compare so that they are listed from most
2774 /// complex to least complex. This puts constants before unary operators,
2775 /// before binary operators.
2776 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2777 I.swapOperands();
2778 Changed = true;
2779 }
2780
2781 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2782
2783 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2784 return ReplaceInstUsesWith(I, V);
2785
2786 // Simplify 'fcmp pred X, X'
2787 if (Op0 == Op1) {
2788 switch (I.getPredicate()) {
2789 default: llvm_unreachable("Unknown predicate!");
2790 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
2791 case FCmpInst::FCMP_ULT: // True if unordered or less than
2792 case FCmpInst::FCMP_UGT: // True if unordered or greater than
2793 case FCmpInst::FCMP_UNE: // True if unordered or not equal
2794 // Canonicalize these to be 'fcmp uno %X, 0.0'.
2795 I.setPredicate(FCmpInst::FCMP_UNO);
2796 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2797 return &I;
2798
2799 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
2800 case FCmpInst::FCMP_OEQ: // True if ordered and equal
2801 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
2802 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
2803 // Canonicalize these to be 'fcmp ord %X, 0.0'.
2804 I.setPredicate(FCmpInst::FCMP_ORD);
2805 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2806 return &I;
2807 }
2808 }
2809
2810 // Handle fcmp with constant RHS
2811 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2812 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2813 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002814 case Instruction::FPExt: {
2815 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
2816 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
2817 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
2818 if (!RHSF)
2819 break;
2820
Benjamin Kramer7ebdc372011-03-31 21:35:49 +00002821 // We can't convert a PPC double double.
2822 if (RHSF->getType()->isPPC_FP128Ty())
2823 break;
2824
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002825 const fltSemantics *Sem;
2826 // FIXME: This shouldn't be here.
2827 if (LHSExt->getSrcTy()->isFloatTy())
2828 Sem = &APFloat::IEEEsingle;
2829 else if (LHSExt->getSrcTy()->isDoubleTy())
2830 Sem = &APFloat::IEEEdouble;
2831 else if (LHSExt->getSrcTy()->isFP128Ty())
2832 Sem = &APFloat::IEEEquad;
2833 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
2834 Sem = &APFloat::x87DoubleExtended;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002835 else
2836 break;
2837
2838 bool Lossy;
2839 APFloat F = RHSF->getValueAPF();
2840 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
2841
2842 // Avoid lossy conversions and denormals.
2843 if (!Lossy &&
2844 F.compare(APFloat::getSmallestNormalized(*Sem)) !=
2845 APFloat::cmpLessThan)
2846 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2847 ConstantFP::get(RHSC->getContext(), F));
2848 break;
2849 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002850 case Instruction::PHI:
2851 // Only fold fcmp into the PHI if the phi and fcmp are in the same
2852 // block. If in the same block, we're encouraging jump threading. If
2853 // not, we are just pessimizing the code by making an i1 phi.
2854 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002855 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002856 return NV;
2857 break;
2858 case Instruction::SIToFP:
2859 case Instruction::UIToFP:
2860 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2861 return NV;
2862 break;
2863 case Instruction::Select: {
2864 // If either operand of the select is a constant, we can fold the
2865 // comparison into the select arms, which will cause one to be
2866 // constant folded and the select turned into a bitwise or.
2867 Value *Op1 = 0, *Op2 = 0;
2868 if (LHSI->hasOneUse()) {
2869 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2870 // Fold the known value into the constant operand.
2871 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2872 // Insert a new FCmp of the other select operand.
2873 Op2 = Builder->CreateFCmp(I.getPredicate(),
2874 LHSI->getOperand(2), RHSC, I.getName());
2875 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2876 // Fold the known value into the constant operand.
2877 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2878 // Insert a new FCmp of the other select operand.
2879 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2880 RHSC, I.getName());
2881 }
2882 }
2883
2884 if (Op1)
2885 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2886 break;
2887 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00002888 case Instruction::FSub: {
2889 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
2890 Value *Op;
2891 if (match(LHSI, m_FNeg(m_Value(Op))))
2892 return new FCmpInst(I.getSwappedPredicate(), Op,
2893 ConstantExpr::getFNeg(RHSC));
2894 break;
2895 }
Dan Gohman39516a62010-02-24 06:46:09 +00002896 case Instruction::Load:
2897 if (GetElementPtrInst *GEP =
2898 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2899 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2900 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2901 !cast<LoadInst>(LHSI)->isVolatile())
2902 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2903 return Res;
2904 }
2905 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00002906 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002907 }
2908
Benjamin Kramer00e00d62011-03-31 10:46:03 +00002909 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00002910 Value *X, *Y;
2911 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00002912 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00002913
Benjamin Kramercd0274c2011-03-31 10:11:58 +00002914 // fcmp (fpext x), (fpext y) -> fcmp x, y
2915 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
2916 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
2917 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
2918 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2919 RHSExt->getOperand(0));
2920
Chris Lattner02446fc2010-01-04 07:37:31 +00002921 return Changed ? &I : 0;
2922}