1 //===- InstCombineCompares.cpp --------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitICmp and visitFCmp functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/MemoryBuiltins.h"
18 #include "llvm/IR/ConstantRange.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/GetElementPtrTypeIterator.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/PatternMatch.h"
23 #include "llvm/Target/TargetLibraryInfo.h"
26 using namespace PatternMatch;
28 #define DEBUG_TYPE "instcombine"
30 static ConstantInt *getOne(Constant *C) {
31 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
34 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
35 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
38 static bool HasAddOverflow(ConstantInt *Result,
39 ConstantInt *In1, ConstantInt *In2,
42 return Result->getValue().ult(In1->getValue());
44 if (In2->isNegative())
45 return Result->getValue().sgt(In1->getValue());
46 return Result->getValue().slt(In1->getValue());
49 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
50 /// overflowed for this type.
51 static bool AddWithOverflow(Constant *&Result, Constant *In1,
52 Constant *In2, bool IsSigned = false) {
53 Result = ConstantExpr::getAdd(In1, In2);
55 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
56 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
57 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
58 if (HasAddOverflow(ExtractElement(Result, Idx),
59 ExtractElement(In1, Idx),
60 ExtractElement(In2, Idx),
67 return HasAddOverflow(cast<ConstantInt>(Result),
68 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
72 static bool HasSubOverflow(ConstantInt *Result,
73 ConstantInt *In1, ConstantInt *In2,
76 return Result->getValue().ugt(In1->getValue());
78 if (In2->isNegative())
79 return Result->getValue().slt(In1->getValue());
81 return Result->getValue().sgt(In1->getValue());
84 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
85 /// overflowed for this type.
86 static bool SubWithOverflow(Constant *&Result, Constant *In1,
87 Constant *In2, bool IsSigned = false) {
88 Result = ConstantExpr::getSub(In1, In2);
90 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
91 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
92 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
93 if (HasSubOverflow(ExtractElement(Result, Idx),
94 ExtractElement(In1, Idx),
95 ExtractElement(In2, Idx),
102 return HasSubOverflow(cast<ConstantInt>(Result),
103 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
107 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
108 /// comparison only checks the sign bit. If it only checks the sign bit, set
109 /// TrueIfSigned if the result of the comparison is true when the input value is
111 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
112 bool &TrueIfSigned) {
114 case ICmpInst::ICMP_SLT: // True if LHS s< 0
116 return RHS->isZero();
117 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
119 return RHS->isAllOnesValue();
120 case ICmpInst::ICMP_SGT: // True if LHS s> -1
121 TrueIfSigned = false;
122 return RHS->isAllOnesValue();
123 case ICmpInst::ICMP_UGT:
124 // True if LHS u> RHS and RHS == high-bit-mask - 1
126 return RHS->isMaxValue(true);
127 case ICmpInst::ICMP_UGE:
128 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
130 return RHS->getValue().isSignBit();
136 /// Returns true if the exploded icmp can be expressed as a signed comparison
137 /// to zero and updates the predicate accordingly.
138 /// The signedness of the comparison is preserved.
139 static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
140 if (!ICmpInst::isSigned(pred))
144 return ICmpInst::isRelational(pred);
147 if (pred == ICmpInst::ICMP_SLT) {
148 pred = ICmpInst::ICMP_SLE;
151 } else if (RHS->isAllOnesValue()) {
152 if (pred == ICmpInst::ICMP_SGT) {
153 pred = ICmpInst::ICMP_SGE;
161 // isHighOnes - Return true if the constant is of the form 1+0+.
162 // This is the same as lowones(~X).
163 static bool isHighOnes(const ConstantInt *CI) {
164 return (~CI->getValue() + 1).isPowerOf2();
167 /// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
168 /// set of known zero and one bits, compute the maximum and minimum values that
169 /// could have the specified known zero and known one bits, returning them in
171 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
172 const APInt& KnownOne,
173 APInt& Min, APInt& Max) {
174 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
175 KnownZero.getBitWidth() == Min.getBitWidth() &&
176 KnownZero.getBitWidth() == Max.getBitWidth() &&
177 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
178 APInt UnknownBits = ~(KnownZero|KnownOne);
180 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
181 // bit if it is unknown.
183 Max = KnownOne|UnknownBits;
185 if (UnknownBits.isNegative()) { // Sign bit is unknown
186 Min.setBit(Min.getBitWidth()-1);
187 Max.clearBit(Max.getBitWidth()-1);
191 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
192 // a set of known zero and one bits, compute the maximum and minimum values that
193 // could have the specified known zero and known one bits, returning them in
195 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
196 const APInt &KnownOne,
197 APInt &Min, APInt &Max) {
198 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
199 KnownZero.getBitWidth() == Min.getBitWidth() &&
200 KnownZero.getBitWidth() == Max.getBitWidth() &&
201 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
202 APInt UnknownBits = ~(KnownZero|KnownOne);
204 // The minimum value is when the unknown bits are all zeros.
206 // The maximum value is when the unknown bits are all ones.
207 Max = KnownOne|UnknownBits;
212 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
213 /// cmp pred (load (gep GV, ...)), cmpcst
214 /// where GV is a global variable with a constant initializer. Try to simplify
215 /// this into some simple computation that does not need the load. For example
216 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
218 /// If AndCst is non-null, then the loaded value is masked with that constant
219 /// before doing the comparison. This handles cases like "A[i]&4 == 0".
220 Instruction *InstCombiner::
221 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
222 CmpInst &ICI, ConstantInt *AndCst) {
223 // We need TD information to know the pointer size unless this is inbounds.
224 if (!GEP->isInBounds() && !DL)
227 Constant *Init = GV->getInitializer();
228 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
231 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
232 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
234 // There are many forms of this optimization we can handle, for now, just do
235 // the simple index into a single-dimensional array.
237 // Require: GEP GV, 0, i {{, constant indices}}
238 if (GEP->getNumOperands() < 3 ||
239 !isa<ConstantInt>(GEP->getOperand(1)) ||
240 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
241 isa<Constant>(GEP->getOperand(2)))
244 // Check that indices after the variable are constants and in-range for the
245 // type they index. Collect the indices. This is typically for arrays of
247 SmallVector<unsigned, 4> LaterIndices;
249 Type *EltTy = Init->getType()->getArrayElementType();
250 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
251 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
252 if (!Idx) return nullptr; // Variable index.
254 uint64_t IdxVal = Idx->getZExtValue();
255 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
257 if (StructType *STy = dyn_cast<StructType>(EltTy))
258 EltTy = STy->getElementType(IdxVal);
259 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
260 if (IdxVal >= ATy->getNumElements()) return nullptr;
261 EltTy = ATy->getElementType();
263 return nullptr; // Unknown type.
266 LaterIndices.push_back(IdxVal);
269 enum { Overdefined = -3, Undefined = -2 };
271 // Variables for our state machines.
273 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
274 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
275 // and 87 is the second (and last) index. FirstTrueElement is -2 when
276 // undefined, otherwise set to the first true element. SecondTrueElement is
277 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
278 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
280 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
281 // form "i != 47 & i != 87". Same state transitions as for true elements.
282 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
284 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
285 /// define a state machine that triggers for ranges of values that the index
286 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
287 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
288 /// index in the range (inclusive). We use -2 for undefined here because we
289 /// use relative comparisons and don't want 0-1 to match -1.
290 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
292 // MagicBitvector - This is a magic bitvector where we set a bit if the
293 // comparison is true for element 'i'. If there are 64 elements or less in
294 // the array, this will fully represent all the comparison results.
295 uint64_t MagicBitvector = 0;
298 // Scan the array and see if one of our patterns matches.
299 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
300 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
301 Constant *Elt = Init->getAggregateElement(i);
302 if (!Elt) return nullptr;
304 // If this is indexing an array of structures, get the structure element.
305 if (!LaterIndices.empty())
306 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
308 // If the element is masked, handle it.
309 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
311 // Find out if the comparison would be true or false for the i'th element.
312 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
313 CompareRHS, DL, TLI);
314 // If the result is undef for this element, ignore it.
315 if (isa<UndefValue>(C)) {
316 // Extend range state machines to cover this element in case there is an
317 // undef in the middle of the range.
318 if (TrueRangeEnd == (int)i-1)
320 if (FalseRangeEnd == (int)i-1)
325 // If we can't compute the result for any of the elements, we have to give
326 // up evaluating the entire conditional.
327 if (!isa<ConstantInt>(C)) return nullptr;
329 // Otherwise, we know if the comparison is true or false for this element,
330 // update our state machines.
331 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
333 // State machine for single/double/range index comparison.
335 // Update the TrueElement state machine.
336 if (FirstTrueElement == Undefined)
337 FirstTrueElement = TrueRangeEnd = i; // First true element.
339 // Update double-compare state machine.
340 if (SecondTrueElement == Undefined)
341 SecondTrueElement = i;
343 SecondTrueElement = Overdefined;
345 // Update range state machine.
346 if (TrueRangeEnd == (int)i-1)
349 TrueRangeEnd = Overdefined;
352 // Update the FalseElement state machine.
353 if (FirstFalseElement == Undefined)
354 FirstFalseElement = FalseRangeEnd = i; // First false element.
356 // Update double-compare state machine.
357 if (SecondFalseElement == Undefined)
358 SecondFalseElement = i;
360 SecondFalseElement = Overdefined;
362 // Update range state machine.
363 if (FalseRangeEnd == (int)i-1)
366 FalseRangeEnd = Overdefined;
371 // If this element is in range, update our magic bitvector.
372 if (i < 64 && IsTrueForElt)
373 MagicBitvector |= 1ULL << i;
375 // If all of our states become overdefined, bail out early. Since the
376 // predicate is expensive, only check it every 8 elements. This is only
377 // really useful for really huge arrays.
378 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
379 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
380 FalseRangeEnd == Overdefined)
384 // Now that we've scanned the entire array, emit our new comparison(s). We
385 // order the state machines in complexity of the generated code.
386 Value *Idx = GEP->getOperand(2);
388 // If the index is larger than the pointer size of the target, truncate the
389 // index down like the GEP would do implicitly. We don't have to do this for
390 // an inbounds GEP because the index can't be out of range.
391 if (!GEP->isInBounds()) {
392 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
393 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
394 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
395 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
398 // If the comparison is only true for one or two elements, emit direct
400 if (SecondTrueElement != Overdefined) {
401 // None true -> false.
402 if (FirstTrueElement == Undefined)
403 return ReplaceInstUsesWith(ICI, Builder->getFalse());
405 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
407 // True for one element -> 'i == 47'.
408 if (SecondTrueElement == Undefined)
409 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
411 // True for two elements -> 'i == 47 | i == 72'.
412 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
413 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
414 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
415 return BinaryOperator::CreateOr(C1, C2);
418 // If the comparison is only false for one or two elements, emit direct
420 if (SecondFalseElement != Overdefined) {
421 // None false -> true.
422 if (FirstFalseElement == Undefined)
423 return ReplaceInstUsesWith(ICI, Builder->getTrue());
425 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
427 // False for one element -> 'i != 47'.
428 if (SecondFalseElement == Undefined)
429 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
431 // False for two elements -> 'i != 47 & i != 72'.
432 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
433 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
434 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
435 return BinaryOperator::CreateAnd(C1, C2);
438 // If the comparison can be replaced with a range comparison for the elements
439 // where it is true, emit the range check.
440 if (TrueRangeEnd != Overdefined) {
441 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
443 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
444 if (FirstTrueElement) {
445 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
446 Idx = Builder->CreateAdd(Idx, Offs);
449 Value *End = ConstantInt::get(Idx->getType(),
450 TrueRangeEnd-FirstTrueElement+1);
451 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
454 // False range check.
455 if (FalseRangeEnd != Overdefined) {
456 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
457 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
458 if (FirstFalseElement) {
459 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
460 Idx = Builder->CreateAdd(Idx, Offs);
463 Value *End = ConstantInt::get(Idx->getType(),
464 FalseRangeEnd-FirstFalseElement);
465 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
469 // If a magic bitvector captures the entire comparison state
470 // of this load, replace it with computation that does:
471 // ((magic_cst >> i) & 1) != 0
475 // Look for an appropriate type:
476 // - The type of Idx if the magic fits
477 // - The smallest fitting legal type if we have a DataLayout
479 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
482 Ty = DL->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
483 else if (ArrayElementCount <= 32)
484 Ty = Type::getInt32Ty(Init->getContext());
487 Value *V = Builder->CreateIntCast(Idx, Ty, false);
488 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
489 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
490 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
498 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
499 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
500 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
501 /// be complex, and scales are involved. The above expression would also be
502 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
503 /// This later form is less amenable to optimization though, and we are allowed
504 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
506 /// If we can't emit an optimized form for this expression, this returns null.
508 static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
509 const DataLayout &DL = *IC.getDataLayout();
510 gep_type_iterator GTI = gep_type_begin(GEP);
512 // Check to see if this gep only has a single variable index. If so, and if
513 // any constant indices are a multiple of its scale, then we can compute this
514 // in terms of the scale of the variable index. For example, if the GEP
515 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
516 // because the expression will cross zero at the same point.
517 unsigned i, e = GEP->getNumOperands();
519 for (i = 1; i != e; ++i, ++GTI) {
520 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
521 // Compute the aggregate offset of constant indices.
522 if (CI->isZero()) continue;
524 // Handle a struct index, which adds its field offset to the pointer.
525 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
526 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
528 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
529 Offset += Size*CI->getSExtValue();
532 // Found our variable index.
537 // If there are no variable indices, we must have a constant offset, just
538 // evaluate it the general way.
539 if (i == e) return nullptr;
541 Value *VariableIdx = GEP->getOperand(i);
542 // Determine the scale factor of the variable element. For example, this is
543 // 4 if the variable index is into an array of i32.
544 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
546 // Verify that there are no other variable indices. If so, emit the hard way.
547 for (++i, ++GTI; i != e; ++i, ++GTI) {
548 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
549 if (!CI) return nullptr;
551 // Compute the aggregate offset of constant indices.
552 if (CI->isZero()) continue;
554 // Handle a struct index, which adds its field offset to the pointer.
555 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
556 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
558 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
559 Offset += Size*CI->getSExtValue();
565 // Okay, we know we have a single variable index, which must be a
566 // pointer/array/vector index. If there is no offset, life is simple, return
568 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
569 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
571 // Cast to intptrty in case a truncation occurs. If an extension is needed,
572 // we don't need to bother extending: the extension won't affect where the
573 // computation crosses zero.
574 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
575 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
580 // Otherwise, there is an index. The computation we will do will be modulo
581 // the pointer size, so get it.
582 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
584 Offset &= PtrSizeMask;
585 VariableScale &= PtrSizeMask;
587 // To do this transformation, any constant index must be a multiple of the
588 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
589 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
590 // multiple of the variable scale.
591 int64_t NewOffs = Offset / (int64_t)VariableScale;
592 if (Offset != NewOffs*(int64_t)VariableScale)
595 // Okay, we can do this evaluation. Start by converting the index to intptr.
596 if (VariableIdx->getType() != IntPtrTy)
597 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
599 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
600 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
603 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
604 /// else. At this point we know that the GEP is on the LHS of the comparison.
605 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
606 ICmpInst::Predicate Cond,
608 // Don't transform signed compares of GEPs into index compares. Even if the
609 // GEP is inbounds, the final add of the base pointer can have signed overflow
610 // and would change the result of the icmp.
611 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
612 // the maximum signed value for the pointer type.
613 if (ICmpInst::isSigned(Cond))
616 // Look through bitcasts and addrspacecasts. We do not however want to remove
618 if (!isa<GetElementPtrInst>(RHS))
619 RHS = RHS->stripPointerCasts();
621 Value *PtrBase = GEPLHS->getOperand(0);
622 if (DL && PtrBase == RHS && GEPLHS->isInBounds()) {
623 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
624 // This transformation (ignoring the base and scales) is valid because we
625 // know pointers can't overflow since the gep is inbounds. See if we can
626 // output an optimized form.
627 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
629 // If not, synthesize the offset the hard way.
631 Offset = EmitGEPOffset(GEPLHS);
632 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
633 Constant::getNullValue(Offset->getType()));
634 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
635 // If the base pointers are different, but the indices are the same, just
636 // compare the base pointer.
637 if (PtrBase != GEPRHS->getOperand(0)) {
638 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
639 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
640 GEPRHS->getOperand(0)->getType();
642 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
643 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
644 IndicesTheSame = false;
648 // If all indices are the same, just compare the base pointers.
650 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
652 // If we're comparing GEPs with two base pointers that only differ in type
653 // and both GEPs have only constant indices or just one use, then fold
654 // the compare with the adjusted indices.
655 if (DL && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
656 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
657 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
658 PtrBase->stripPointerCasts() ==
659 GEPRHS->getOperand(0)->stripPointerCasts()) {
660 Value *LOffset = EmitGEPOffset(GEPLHS);
661 Value *ROffset = EmitGEPOffset(GEPRHS);
663 // If we looked through an addrspacecast between different sized address
664 // spaces, the LHS and RHS pointers are different sized
665 // integers. Truncate to the smaller one.
666 Type *LHSIndexTy = LOffset->getType();
667 Type *RHSIndexTy = ROffset->getType();
668 if (LHSIndexTy != RHSIndexTy) {
669 if (LHSIndexTy->getPrimitiveSizeInBits() <
670 RHSIndexTy->getPrimitiveSizeInBits()) {
671 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
673 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
676 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
678 return ReplaceInstUsesWith(I, Cmp);
681 // Otherwise, the base pointers are different and the indices are
682 // different, bail out.
686 // If one of the GEPs has all zero indices, recurse.
687 if (GEPLHS->hasAllZeroIndices())
688 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
689 ICmpInst::getSwappedPredicate(Cond), I);
691 // If the other GEP has all zero indices, recurse.
692 if (GEPRHS->hasAllZeroIndices())
693 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
695 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
696 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
697 // If the GEPs only differ by one index, compare it.
698 unsigned NumDifferences = 0; // Keep track of # differences.
699 unsigned DiffOperand = 0; // The operand that differs.
700 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
701 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
702 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
703 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
704 // Irreconcilable differences.
708 if (NumDifferences++) break;
713 if (NumDifferences == 0) // SAME GEP?
714 return ReplaceInstUsesWith(I, // No comparison is needed here.
715 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
717 else if (NumDifferences == 1 && GEPsInBounds) {
718 Value *LHSV = GEPLHS->getOperand(DiffOperand);
719 Value *RHSV = GEPRHS->getOperand(DiffOperand);
720 // Make sure we do a signed comparison here.
721 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
725 // Only lower this if the icmp is the only user of the GEP or if we expect
726 // the result to fold to a constant!
729 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
730 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
731 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
732 Value *L = EmitGEPOffset(GEPLHS);
733 Value *R = EmitGEPOffset(GEPRHS);
734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
740 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
741 Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
742 Value *X, ConstantInt *CI,
743 ICmpInst::Predicate Pred) {
744 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
745 // so the values can never be equal. Similarly for all other "or equals"
748 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
749 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
750 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
751 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
753 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
754 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
757 // (X+1) >u X --> X <u (0-1) --> X != 255
758 // (X+2) >u X --> X <u (0-2) --> X <u 254
759 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
760 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
761 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
763 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
764 ConstantInt *SMax = ConstantInt::get(X->getContext(),
765 APInt::getSignedMaxValue(BitWidth));
767 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
768 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
769 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
770 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
771 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
772 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
773 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
774 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
776 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
777 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
778 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
779 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
780 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
781 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
783 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
784 Constant *C = Builder->getInt(CI->getValue()-1);
785 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
788 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
789 /// and CmpRHS are both known to be integer constants.
790 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
791 ConstantInt *DivRHS) {
792 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
793 const APInt &CmpRHSV = CmpRHS->getValue();
795 // FIXME: If the operand types don't match the type of the divide
796 // then don't attempt this transform. The code below doesn't have the
797 // logic to deal with a signed divide and an unsigned compare (and
798 // vice versa). This is because (x /s C1) <s C2 produces different
799 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
800 // (x /u C1) <u C2. Simply casting the operands and result won't
801 // work. :( The if statement below tests that condition and bails
803 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
804 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
806 if (DivRHS->isZero())
807 return nullptr; // The ProdOV computation fails on divide by zero.
808 if (DivIsSigned && DivRHS->isAllOnesValue())
809 return nullptr; // The overflow computation also screws up here
810 if (DivRHS->isOne()) {
811 // This eliminates some funny cases with INT_MIN.
812 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
816 // Compute Prod = CI * DivRHS. We are essentially solving an equation
817 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
818 // C2 (CI). By solving for X we can turn this into a range check
819 // instead of computing a divide.
820 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
822 // Determine if the product overflows by seeing if the product is
823 // not equal to the divide. Make sure we do the same kind of divide
824 // as in the LHS instruction that we're folding.
825 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
826 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
828 // Get the ICmp opcode
829 ICmpInst::Predicate Pred = ICI.getPredicate();
831 /// If the division is known to be exact, then there is no remainder from the
832 /// divide, so the covered range size is unit, otherwise it is the divisor.
833 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
835 // Figure out the interval that is being checked. For example, a comparison
836 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
837 // Compute this interval based on the constants involved and the signedness of
838 // the compare/divide. This computes a half-open interval, keeping track of
839 // whether either value in the interval overflows. After analysis each
840 // overflow variable is set to 0 if it's corresponding bound variable is valid
841 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
842 int LoOverflow = 0, HiOverflow = 0;
843 Constant *LoBound = nullptr, *HiBound = nullptr;
845 if (!DivIsSigned) { // udiv
846 // e.g. X/5 op 3 --> [15, 20)
848 HiOverflow = LoOverflow = ProdOV;
850 // If this is not an exact divide, then many values in the range collapse
851 // to the same result value.
852 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
855 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
856 if (CmpRHSV == 0) { // (X / pos) op 0
857 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
858 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
860 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
861 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
862 HiOverflow = LoOverflow = ProdOV;
864 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
865 } else { // (X / pos) op neg
866 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
867 HiBound = AddOne(Prod);
868 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
870 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
871 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
874 } else if (DivRHS->isNegative()) { // Divisor is < 0.
876 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
877 if (CmpRHSV == 0) { // (X / neg) op 0
878 // e.g. X/-5 op 0 --> [-4, 5)
879 LoBound = AddOne(RangeSize);
880 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
881 if (HiBound == DivRHS) { // -INTMIN = INTMIN
882 HiOverflow = 1; // [INTMIN+1, overflow)
883 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
885 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
886 // e.g. X/-5 op 3 --> [-19, -14)
887 HiBound = AddOne(Prod);
888 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
890 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
891 } else { // (X / neg) op neg
892 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
893 LoOverflow = HiOverflow = ProdOV;
895 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
898 // Dividing by a negative swaps the condition. LT <-> GT
899 Pred = ICmpInst::getSwappedPredicate(Pred);
902 Value *X = DivI->getOperand(0);
904 default: llvm_unreachable("Unhandled icmp opcode!");
905 case ICmpInst::ICMP_EQ:
906 if (LoOverflow && HiOverflow)
907 return ReplaceInstUsesWith(ICI, Builder->getFalse());
909 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
910 ICmpInst::ICMP_UGE, X, LoBound);
912 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
913 ICmpInst::ICMP_ULT, X, HiBound);
914 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
916 case ICmpInst::ICMP_NE:
917 if (LoOverflow && HiOverflow)
918 return ReplaceInstUsesWith(ICI, Builder->getTrue());
920 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
921 ICmpInst::ICMP_ULT, X, LoBound);
923 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
924 ICmpInst::ICMP_UGE, X, HiBound);
925 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
926 DivIsSigned, false));
927 case ICmpInst::ICMP_ULT:
928 case ICmpInst::ICMP_SLT:
929 if (LoOverflow == +1) // Low bound is greater than input range.
930 return ReplaceInstUsesWith(ICI, Builder->getTrue());
931 if (LoOverflow == -1) // Low bound is less than input range.
932 return ReplaceInstUsesWith(ICI, Builder->getFalse());
933 return new ICmpInst(Pred, X, LoBound);
934 case ICmpInst::ICMP_UGT:
935 case ICmpInst::ICMP_SGT:
936 if (HiOverflow == +1) // High bound greater than input range.
937 return ReplaceInstUsesWith(ICI, Builder->getFalse());
938 if (HiOverflow == -1) // High bound less than input range.
939 return ReplaceInstUsesWith(ICI, Builder->getTrue());
940 if (Pred == ICmpInst::ICMP_UGT)
941 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
942 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
946 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
947 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
948 ConstantInt *ShAmt) {
949 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
951 // Check that the shift amount is in range. If not, don't perform
952 // undefined shifts. When the shift is visited it will be
954 uint32_t TypeBits = CmpRHSV.getBitWidth();
955 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
956 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
959 if (!ICI.isEquality()) {
960 // If we have an unsigned comparison and an ashr, we can't simplify this.
961 // Similarly for signed comparisons with lshr.
962 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
965 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
966 // by a power of 2. Since we already have logic to simplify these,
967 // transform to div and then simplify the resultant comparison.
968 if (Shr->getOpcode() == Instruction::AShr &&
969 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
972 // Revisit the shift (to delete it).
976 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
979 Shr->getOpcode() == Instruction::AShr ?
980 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
981 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
983 ICI.setOperand(0, Tmp);
985 // If the builder folded the binop, just return it.
986 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
990 // Otherwise, fold this div/compare.
991 assert(TheDiv->getOpcode() == Instruction::SDiv ||
992 TheDiv->getOpcode() == Instruction::UDiv);
994 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
995 assert(Res && "This div/cst should have folded!");
1000 // If we are comparing against bits always shifted out, the
1001 // comparison cannot succeed.
1002 APInt Comp = CmpRHSV << ShAmtVal;
1003 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
1004 if (Shr->getOpcode() == Instruction::LShr)
1005 Comp = Comp.lshr(ShAmtVal);
1007 Comp = Comp.ashr(ShAmtVal);
1009 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1010 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1011 Constant *Cst = Builder->getInt1(IsICMP_NE);
1012 return ReplaceInstUsesWith(ICI, Cst);
1015 // Otherwise, check to see if the bits shifted out are known to be zero.
1016 // If so, we can compare against the unshifted value:
1017 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
1018 if (Shr->hasOneUse() && Shr->isExact())
1019 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
1021 if (Shr->hasOneUse()) {
1022 // Otherwise strength reduce the shift into an and.
1023 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1024 Constant *Mask = Builder->getInt(Val);
1026 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1027 Mask, Shr->getName()+".mask");
1028 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1033 /// FoldICmpCstShrCst - Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
1034 /// (icmp eq/ne A, Log2(const2/const1)) ->
1035 /// (icmp eq/ne A, Log2(const2) - Log2(const1)).
1036 Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
1039 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1041 auto getConstant = [&I, this](bool IsTrue) {
1042 if (I.getPredicate() == I.ICMP_NE)
1044 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1047 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1048 if (I.getPredicate() == I.ICMP_NE)
1049 Pred = CmpInst::getInversePredicate(Pred);
1050 return new ICmpInst(Pred, LHS, RHS);
1053 APInt AP1 = CI1->getValue();
1054 APInt AP2 = CI2->getValue();
1058 // Both Constants are 0.
1059 return getConstant(true);
1062 if (cast<BinaryOperator>(Op)->isExact())
1063 return getConstant(false);
1065 if (AP2.isNegative()) {
1066 // MSB is set, so a lshr with a large enough 'A' would be undefined.
1067 return getConstant(false);
1070 // 'A' must be large enough to shift out the highest set bit.
1071 return getICmp(I.ICMP_UGT, A,
1072 ConstantInt::get(A->getType(), AP2.logBase2()));
1076 // Shifting 0 by any value gives 0.
1077 return getConstant(false);
1080 bool IsAShr = isa<AShrOperator>(Op);
1082 if (AP1.isAllOnesValue() && IsAShr) {
1083 // Arithmatic shift of -1 is always -1.
1084 return getConstant(true);
1086 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1089 bool IsNegative = false;
1091 if (AP1.isNegative() != AP2.isNegative()) {
1092 // Arithmetic shift will never change the sign.
1093 return getConstant(false);
1095 // Both the constants are negative, take their positive to calculate log.
1096 if (AP1.isNegative()) {
1098 // Right-shifting won't increase the magnitude.
1099 return getConstant(false);
1104 if (!IsNegative && AP1.ugt(AP2))
1105 // Right-shifting will not increase the value.
1106 return getConstant(false);
1108 // Get the distance between the highest bit that's set.
1111 Shift = (-AP2).logBase2() - (-AP1).logBase2();
1113 Shift = AP2.logBase2() - AP1.logBase2();
1115 if (IsAShr ? AP1 == AP2.ashr(Shift) : AP1 == AP2.lshr(Shift))
1116 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1118 // Shifting const2 will never be equal to const1.
1119 return getConstant(false);
1122 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1124 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1127 const APInt &RHSV = RHS->getValue();
1129 switch (LHSI->getOpcode()) {
1130 case Instruction::Trunc:
1131 if (ICI.isEquality() && LHSI->hasOneUse()) {
1132 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1133 // of the high bits truncated out of x are known.
1134 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1135 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1136 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1137 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
1139 // If all the high bits are known, we can do this xform.
1140 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1141 // Pull in the high bits from known-ones set.
1142 APInt NewRHS = RHS->getValue().zext(SrcBits);
1143 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
1144 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1145 Builder->getInt(NewRHS));
1150 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1151 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1152 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1154 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1155 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1156 Value *CompareVal = LHSI->getOperand(0);
1158 // If the sign bit of the XorCst is not set, there is no change to
1159 // the operation, just stop using the Xor.
1160 if (!XorCst->isNegative()) {
1161 ICI.setOperand(0, CompareVal);
1166 // Was the old condition true if the operand is positive?
1167 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1169 // If so, the new one isn't.
1170 isTrueIfPositive ^= true;
1172 if (isTrueIfPositive)
1173 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1176 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1180 if (LHSI->hasOneUse()) {
1181 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1182 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1183 const APInt &SignBit = XorCst->getValue();
1184 ICmpInst::Predicate Pred = ICI.isSigned()
1185 ? ICI.getUnsignedPredicate()
1186 : ICI.getSignedPredicate();
1187 return new ICmpInst(Pred, LHSI->getOperand(0),
1188 Builder->getInt(RHSV ^ SignBit));
1191 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1192 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1193 const APInt &NotSignBit = XorCst->getValue();
1194 ICmpInst::Predicate Pred = ICI.isSigned()
1195 ? ICI.getUnsignedPredicate()
1196 : ICI.getSignedPredicate();
1197 Pred = ICI.getSwappedPredicate(Pred);
1198 return new ICmpInst(Pred, LHSI->getOperand(0),
1199 Builder->getInt(RHSV ^ NotSignBit));
1203 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1204 // iff -C is a power of 2
1205 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
1206 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1207 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
1209 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1210 // iff -C is a power of 2
1211 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
1212 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1213 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
1216 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
1217 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1218 LHSI->getOperand(0)->hasOneUse()) {
1219 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
1221 // If the LHS is an AND of a truncating cast, we can widen the
1222 // and/compare to be the input width without changing the value
1223 // produced, eliminating a cast.
1224 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1225 // We can do this transformation if either the AND constant does not
1226 // have its sign bit set or if it is an equality comparison.
1227 // Extending a relational comparison when we're checking the sign
1228 // bit would not work.
1229 if (ICI.isEquality() ||
1230 (!AndCst->isNegative() && RHSV.isNonNegative())) {
1232 Builder->CreateAnd(Cast->getOperand(0),
1233 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
1234 NewAnd->takeName(LHSI);
1235 return new ICmpInst(ICI.getPredicate(), NewAnd,
1236 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1240 // If the LHS is an AND of a zext, and we have an equality compare, we can
1241 // shrink the and/compare to the smaller type, eliminating the cast.
1242 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1243 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1244 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1245 // should fold the icmp to true/false in that case.
1246 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1248 Builder->CreateAnd(Cast->getOperand(0),
1249 ConstantExpr::getTrunc(AndCst, Ty));
1250 NewAnd->takeName(LHSI);
1251 return new ICmpInst(ICI.getPredicate(), NewAnd,
1252 ConstantExpr::getTrunc(RHS, Ty));
1256 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1257 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1258 // happens a LOT in code produced by the C front-end, for bitfield
1260 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1261 if (Shift && !Shift->isShift())
1265 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
1267 // This seemingly simple opportunity to fold away a shift turns out to
1268 // be rather complicated. See PR17827
1269 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
1271 bool CanFold = false;
1272 unsigned ShiftOpcode = Shift->getOpcode();
1273 if (ShiftOpcode == Instruction::AShr) {
1274 // There may be some constraints that make this possible,
1275 // but nothing simple has been discovered yet.
1277 } else if (ShiftOpcode == Instruction::Shl) {
1278 // For a left shift, we can fold if the comparison is not signed.
1279 // We can also fold a signed comparison if the mask value and
1280 // comparison value are not negative. These constraints may not be
1281 // obvious, but we can prove that they are correct using an SMT
1283 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
1285 } else if (ShiftOpcode == Instruction::LShr) {
1286 // For a logical right shift, we can fold if the comparison is not
1287 // signed. We can also fold a signed comparison if the shifted mask
1288 // value and the shifted comparison value are not negative.
1289 // These constraints may not be obvious, but we can prove that they
1290 // are correct using an SMT solver.
1291 if (!ICI.isSigned())
1294 ConstantInt *ShiftedAndCst =
1295 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1296 ConstantInt *ShiftedRHSCst =
1297 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1299 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1306 if (ShiftOpcode == Instruction::Shl)
1307 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1309 NewCst = ConstantExpr::getShl(RHS, ShAmt);
1311 // Check to see if we are shifting out any of the bits being
1313 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
1314 // If we shifted bits out, the fold is not going to work out.
1315 // As a special case, check to see if this means that the
1316 // result is always true or false now.
1317 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1318 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1319 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1320 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1322 ICI.setOperand(1, NewCst);
1323 Constant *NewAndCst;
1324 if (ShiftOpcode == Instruction::Shl)
1325 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
1327 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1328 LHSI->setOperand(1, NewAndCst);
1329 LHSI->setOperand(0, Shift->getOperand(0));
1330 Worklist.Add(Shift); // Shift is dead.
1336 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1337 // preferable because it allows the C<<Y expression to be hoisted out
1338 // of a loop if Y is invariant and X is not.
1339 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1340 ICI.isEquality() && !Shift->isArithmeticShift() &&
1341 !isa<Constant>(Shift->getOperand(0))) {
1344 if (Shift->getOpcode() == Instruction::LShr) {
1345 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
1347 // Insert a logical shift.
1348 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
1351 // Compute X & (C << Y).
1353 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1355 ICI.setOperand(0, NewAnd);
1359 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1360 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1362 // iff pred isn't signed
1364 Value *X, *Y, *LShr;
1365 if (!ICI.isSigned() && RHSV == 0) {
1366 if (match(LHSI->getOperand(1), m_One())) {
1367 Constant *One = cast<Constant>(LHSI->getOperand(1));
1368 Value *Or = LHSI->getOperand(0);
1369 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1370 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1371 unsigned UsesRemoved = 0;
1372 if (LHSI->hasOneUse())
1374 if (Or->hasOneUse())
1376 if (LShr->hasOneUse())
1378 Value *NewOr = nullptr;
1379 // Compute X & ((1 << Y) | 1)
1380 if (auto *C = dyn_cast<Constant>(Y)) {
1381 if (UsesRemoved >= 1)
1383 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1385 if (UsesRemoved >= 3)
1386 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1389 One, Or->getName());
1392 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1393 ICI.setOperand(0, NewAnd);
1401 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1402 // bit set in (X & AndCst) will produce a result greater than RHSV.
1403 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1404 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1405 if ((NTZ < AndCst->getBitWidth()) &&
1406 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
1407 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1408 Constant::getNullValue(RHS->getType()));
1412 // Try to optimize things like "A[i]&42 == 0" to index computations.
1413 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1414 if (GetElementPtrInst *GEP =
1415 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1416 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1417 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1418 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1419 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1420 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1425 // X & -C == -C -> X > u ~C
1426 // X & -C != -C -> X <= u ~C
1427 // iff C is a power of 2
1428 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1429 return new ICmpInst(
1430 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1431 : ICmpInst::ICMP_ULE,
1432 LHSI->getOperand(0), SubOne(RHS));
1435 case Instruction::Or: {
1436 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1439 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1440 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1441 // -> and (icmp eq P, null), (icmp eq Q, null).
1442 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1443 Constant::getNullValue(P->getType()));
1444 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1445 Constant::getNullValue(Q->getType()));
1447 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1448 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1450 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1456 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1457 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1460 // If this is a signed comparison to 0 and the mul is sign preserving,
1461 // use the mul LHS operand instead.
1462 ICmpInst::Predicate pred = ICI.getPredicate();
1463 if (isSignTest(pred, RHS) && !Val->isZero() &&
1464 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1465 return new ICmpInst(Val->isNegative() ?
1466 ICmpInst::getSwappedPredicate(pred) : pred,
1467 LHSI->getOperand(0),
1468 Constant::getNullValue(RHS->getType()));
1473 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
1474 uint32_t TypeBits = RHSV.getBitWidth();
1475 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1478 // (1 << X) pred P2 -> X pred Log2(P2)
1479 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1480 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1481 ICmpInst::Predicate Pred = ICI.getPredicate();
1482 if (ICI.isUnsigned()) {
1483 if (!RHSVIsPowerOf2) {
1484 // (1 << X) < 30 -> X <= 4
1485 // (1 << X) <= 30 -> X <= 4
1486 // (1 << X) >= 30 -> X > 4
1487 // (1 << X) > 30 -> X > 4
1488 if (Pred == ICmpInst::ICMP_ULT)
1489 Pred = ICmpInst::ICMP_ULE;
1490 else if (Pred == ICmpInst::ICMP_UGE)
1491 Pred = ICmpInst::ICMP_UGT;
1493 unsigned RHSLog2 = RHSV.logBase2();
1495 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1496 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1497 if (RHSLog2 == TypeBits-1) {
1498 if (Pred == ICmpInst::ICMP_UGE)
1499 Pred = ICmpInst::ICMP_EQ;
1500 else if (Pred == ICmpInst::ICMP_ULT)
1501 Pred = ICmpInst::ICMP_NE;
1504 return new ICmpInst(Pred, X,
1505 ConstantInt::get(RHS->getType(), RHSLog2));
1506 } else if (ICI.isSigned()) {
1507 if (RHSV.isAllOnesValue()) {
1508 // (1 << X) <= -1 -> X == 31
1509 if (Pred == ICmpInst::ICMP_SLE)
1510 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1511 ConstantInt::get(RHS->getType(), TypeBits-1));
1513 // (1 << X) > -1 -> X != 31
1514 if (Pred == ICmpInst::ICMP_SGT)
1515 return new ICmpInst(ICmpInst::ICMP_NE, X,
1516 ConstantInt::get(RHS->getType(), TypeBits-1));
1518 // (1 << X) < 0 -> X == 31
1519 // (1 << X) <= 0 -> X == 31
1520 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1521 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1522 ConstantInt::get(RHS->getType(), TypeBits-1));
1524 // (1 << X) >= 0 -> X != 31
1525 // (1 << X) > 0 -> X != 31
1526 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1527 return new ICmpInst(ICmpInst::ICMP_NE, X,
1528 ConstantInt::get(RHS->getType(), TypeBits-1));
1530 } else if (ICI.isEquality()) {
1532 return new ICmpInst(
1533 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1539 // Check that the shift amount is in range. If not, don't perform
1540 // undefined shifts. When the shift is visited it will be
1542 if (ShAmt->uge(TypeBits))
1545 if (ICI.isEquality()) {
1546 // If we are comparing against bits always shifted out, the
1547 // comparison cannot succeed.
1549 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1551 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1552 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1553 Constant *Cst = Builder->getInt1(IsICMP_NE);
1554 return ReplaceInstUsesWith(ICI, Cst);
1557 // If the shift is NUW, then it is just shifting out zeros, no need for an
1559 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1560 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1561 ConstantExpr::getLShr(RHS, ShAmt));
1563 // If the shift is NSW and we compare to 0, then it is just shifting out
1564 // sign bits, no need for an AND either.
1565 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1566 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1567 ConstantExpr::getLShr(RHS, ShAmt));
1569 if (LHSI->hasOneUse()) {
1570 // Otherwise strength reduce the shift into an and.
1571 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1572 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1573 TypeBits - ShAmtVal));
1576 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1577 return new ICmpInst(ICI.getPredicate(), And,
1578 ConstantExpr::getLShr(RHS, ShAmt));
1582 // If this is a signed comparison to 0 and the shift is sign preserving,
1583 // use the shift LHS operand instead.
1584 ICmpInst::Predicate pred = ICI.getPredicate();
1585 if (isSignTest(pred, RHS) &&
1586 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1587 return new ICmpInst(pred,
1588 LHSI->getOperand(0),
1589 Constant::getNullValue(RHS->getType()));
1591 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1592 bool TrueIfSigned = false;
1593 if (LHSI->hasOneUse() &&
1594 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1595 // (X << 31) <s 0 --> (X&1) != 0
1596 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1597 APInt::getOneBitSet(TypeBits,
1598 TypeBits-ShAmt->getZExtValue()-1));
1600 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1601 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1602 And, Constant::getNullValue(And->getType()));
1605 // Transform (icmp pred iM (shl iM %v, N), CI)
1606 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1607 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
1608 // This enables to get rid of the shift in favor of a trunc which can be
1609 // free on the target. It has the additional benefit of comparing to a
1610 // smaller constant, which will be target friendly.
1611 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
1612 if (LHSI->hasOneUse() &&
1613 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
1614 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1615 Constant *NCI = ConstantExpr::getTrunc(
1616 ConstantExpr::getAShr(RHS,
1617 ConstantInt::get(RHS->getType(), Amt)),
1619 return new ICmpInst(ICI.getPredicate(),
1620 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
1627 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
1628 case Instruction::AShr: {
1629 // Handle equality comparisons of shift-by-constant.
1630 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1631 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1632 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
1636 // Handle exact shr's.
1637 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1638 if (RHSV.isMinValue())
1639 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1644 case Instruction::SDiv:
1645 case Instruction::UDiv:
1646 // Fold: icmp pred ([us]div X, C1), C2 -> range test
1647 // Fold this div into the comparison, producing a range check.
1648 // Determine, based on the divide type, what the range is being
1649 // checked. If there is an overflow on the low or high side, remember
1650 // it, otherwise compute the range [low, hi) bounding the new value.
1651 // See: InsertRangeTest above for the kinds of replacements possible.
1652 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1653 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1658 case Instruction::Sub: {
1659 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1661 const APInt &LHSV = LHSC->getValue();
1663 // C1-X <u C2 -> (X|(C2-1)) == C1
1664 // iff C1 & (C2-1) == C2-1
1665 // C2 is a power of 2
1666 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1667 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1668 return new ICmpInst(ICmpInst::ICMP_EQ,
1669 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1672 // C1-X >u C2 -> (X|C2) != C1
1673 // iff C1 & C2 == C2
1674 // C2+1 is a power of 2
1675 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1676 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1677 return new ICmpInst(ICmpInst::ICMP_NE,
1678 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1682 case Instruction::Add:
1683 // Fold: icmp pred (add X, C1), C2
1684 if (!ICI.isEquality()) {
1685 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1687 const APInt &LHSV = LHSC->getValue();
1689 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1692 if (ICI.isSigned()) {
1693 if (CR.getLower().isSignBit()) {
1694 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1695 Builder->getInt(CR.getUpper()));
1696 } else if (CR.getUpper().isSignBit()) {
1697 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1698 Builder->getInt(CR.getLower()));
1701 if (CR.getLower().isMinValue()) {
1702 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1703 Builder->getInt(CR.getUpper()));
1704 } else if (CR.getUpper().isMinValue()) {
1705 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1706 Builder->getInt(CR.getLower()));
1710 // X-C1 <u C2 -> (X & -C2) == C1
1711 // iff C1 & (C2-1) == 0
1712 // C2 is a power of 2
1713 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1714 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
1715 return new ICmpInst(ICmpInst::ICMP_EQ,
1716 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1717 ConstantExpr::getNeg(LHSC));
1719 // X-C1 >u C2 -> (X & ~C2) != C1
1721 // C2+1 is a power of 2
1722 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1723 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1724 return new ICmpInst(ICmpInst::ICMP_NE,
1725 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1726 ConstantExpr::getNeg(LHSC));
1731 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1732 if (ICI.isEquality()) {
1733 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1735 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1736 // the second operand is a constant, simplify a bit.
1737 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1738 switch (BO->getOpcode()) {
1739 case Instruction::SRem:
1740 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1741 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1742 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1743 if (V.sgt(1) && V.isPowerOf2()) {
1745 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1747 return new ICmpInst(ICI.getPredicate(), NewRem,
1748 Constant::getNullValue(BO->getType()));
1752 case Instruction::Add:
1753 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1754 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1755 if (BO->hasOneUse())
1756 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1757 ConstantExpr::getSub(RHS, BOp1C));
1758 } else if (RHSV == 0) {
1759 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1760 // efficiently invertible, or if the add has just this one use.
1761 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1763 if (Value *NegVal = dyn_castNegVal(BOp1))
1764 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1765 if (Value *NegVal = dyn_castNegVal(BOp0))
1766 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1767 if (BO->hasOneUse()) {
1768 Value *Neg = Builder->CreateNeg(BOp1);
1770 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1774 case Instruction::Xor:
1775 // For the xor case, we can xor two constants together, eliminating
1776 // the explicit xor.
1777 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1778 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1779 ConstantExpr::getXor(RHS, BOC));
1780 } else if (RHSV == 0) {
1781 // Replace ((xor A, B) != 0) with (A != B)
1782 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1786 case Instruction::Sub:
1787 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1788 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1789 if (BO->hasOneUse())
1790 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1791 ConstantExpr::getSub(BOp0C, RHS));
1792 } else if (RHSV == 0) {
1793 // Replace ((sub A, B) != 0) with (A != B)
1794 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1798 case Instruction::Or:
1799 // If bits are being or'd in that are not present in the constant we
1800 // are comparing against, then the comparison could never succeed!
1801 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1802 Constant *NotCI = ConstantExpr::getNot(RHS);
1803 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1804 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1808 case Instruction::And:
1809 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1810 // If bits are being compared against that are and'd out, then the
1811 // comparison can never succeed!
1812 if ((RHSV & ~BOC->getValue()) != 0)
1813 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1815 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1816 if (RHS == BOC && RHSV.isPowerOf2())
1817 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1818 ICmpInst::ICMP_NE, LHSI,
1819 Constant::getNullValue(RHS->getType()));
1821 // Don't perform the following transforms if the AND has multiple uses
1822 if (!BO->hasOneUse())
1825 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1826 if (BOC->getValue().isSignBit()) {
1827 Value *X = BO->getOperand(0);
1828 Constant *Zero = Constant::getNullValue(X->getType());
1829 ICmpInst::Predicate pred = isICMP_NE ?
1830 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1831 return new ICmpInst(pred, X, Zero);
1834 // ((X & ~7) == 0) --> X < 8
1835 if (RHSV == 0 && isHighOnes(BOC)) {
1836 Value *X = BO->getOperand(0);
1837 Constant *NegX = ConstantExpr::getNeg(BOC);
1838 ICmpInst::Predicate pred = isICMP_NE ?
1839 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1840 return new ICmpInst(pred, X, NegX);
1844 case Instruction::Mul:
1845 if (RHSV == 0 && BO->hasNoSignedWrap()) {
1846 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1847 // The trivial case (mul X, 0) is handled by InstSimplify
1848 // General case : (mul X, C) != 0 iff X != 0
1849 // (mul X, C) == 0 iff X == 0
1851 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1852 Constant::getNullValue(RHS->getType()));
1858 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1859 // Handle icmp {eq|ne} <intrinsic>, intcst.
1860 switch (II->getIntrinsicID()) {
1861 case Intrinsic::bswap:
1863 ICI.setOperand(0, II->getArgOperand(0));
1864 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
1866 case Intrinsic::ctlz:
1867 case Intrinsic::cttz:
1868 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1869 if (RHSV == RHS->getType()->getBitWidth()) {
1871 ICI.setOperand(0, II->getArgOperand(0));
1872 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1876 case Intrinsic::ctpop:
1877 // popcount(A) == 0 -> A == 0 and likewise for !=
1878 if (RHS->isZero()) {
1880 ICI.setOperand(0, II->getArgOperand(0));
1881 ICI.setOperand(1, RHS);
1893 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1894 /// We only handle extending casts so far.
1896 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1897 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1898 Value *LHSCIOp = LHSCI->getOperand(0);
1899 Type *SrcTy = LHSCIOp->getType();
1900 Type *DestTy = LHSCI->getType();
1903 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1904 // integer type is the same size as the pointer type.
1905 if (DL && LHSCI->getOpcode() == Instruction::PtrToInt &&
1906 DL->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
1907 Value *RHSOp = nullptr;
1908 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1909 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1910 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1911 RHSOp = RHSC->getOperand(0);
1912 // If the pointer types don't match, insert a bitcast.
1913 if (LHSCIOp->getType() != RHSOp->getType())
1914 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1918 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1921 // The code below only handles extension cast instructions, so far.
1923 if (LHSCI->getOpcode() != Instruction::ZExt &&
1924 LHSCI->getOpcode() != Instruction::SExt)
1927 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1928 bool isSignedCmp = ICI.isSigned();
1930 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1931 // Not an extension from the same type?
1932 RHSCIOp = CI->getOperand(0);
1933 if (RHSCIOp->getType() != LHSCIOp->getType())
1936 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1937 // and the other is a zext), then we can't handle this.
1938 if (CI->getOpcode() != LHSCI->getOpcode())
1941 // Deal with equality cases early.
1942 if (ICI.isEquality())
1943 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1945 // A signed comparison of sign extended values simplifies into a
1946 // signed comparison.
1947 if (isSignedCmp && isSignedExt)
1948 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1950 // The other three cases all fold into an unsigned comparison.
1951 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1954 // If we aren't dealing with a constant on the RHS, exit early
1955 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1959 // Compute the constant that would happen if we truncated to SrcTy then
1960 // reextended to DestTy.
1961 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1962 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1965 // If the re-extended constant didn't change...
1967 // Deal with equality cases early.
1968 if (ICI.isEquality())
1969 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1971 // A signed comparison of sign extended values simplifies into a
1972 // signed comparison.
1973 if (isSignedExt && isSignedCmp)
1974 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1976 // The other three cases all fold into an unsigned comparison.
1977 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1980 // The re-extended constant changed so the constant cannot be represented
1981 // in the shorter type. Consequently, we cannot emit a simple comparison.
1982 // All the cases that fold to true or false will have already been handled
1983 // by SimplifyICmpInst, so only deal with the tricky case.
1985 if (isSignedCmp || !isSignedExt)
1988 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1989 // should have been folded away previously and not enter in here.
1991 // We're performing an unsigned comp with a sign extended value.
1992 // This is true if the input is >= 0. [aka >s -1]
1993 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1994 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1996 // Finally, return the value computed.
1997 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1998 return ReplaceInstUsesWith(ICI, Result);
2000 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
2001 return BinaryOperator::CreateNot(Result);
2004 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
2005 /// I = icmp ugt (add (add A, B), CI2), CI1
2006 /// If this is of the form:
2008 /// if (sum+128 >u 255)
2009 /// Then replace it with llvm.sadd.with.overflow.i8.
2011 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2012 ConstantInt *CI2, ConstantInt *CI1,
2014 // The transformation we're trying to do here is to transform this into an
2015 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2016 // with a narrower add, and discard the add-with-constant that is part of the
2017 // range check (if we can't eliminate it, this isn't profitable).
2019 // In order to eliminate the add-with-constant, the compare can be its only
2021 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
2022 if (!AddWithCst->hasOneUse()) return nullptr;
2024 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
2025 if (!CI2->getValue().isPowerOf2()) return nullptr;
2026 unsigned NewWidth = CI2->getValue().countTrailingZeros();
2027 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
2029 // The width of the new add formed is 1 more than the bias.
2032 // Check to see that CI1 is an all-ones value with NewWidth bits.
2033 if (CI1->getBitWidth() == NewWidth ||
2034 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
2037 // This is only really a signed overflow check if the inputs have been
2038 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2039 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2040 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
2041 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2042 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
2045 // In order to replace the original add with a narrower
2046 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2047 // and truncates that discard the high bits of the add. Verify that this is
2049 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
2050 for (User *U : OrigAdd->users()) {
2051 if (U == AddWithCst) continue;
2053 // Only accept truncates for now. We would really like a nice recursive
2054 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2055 // chain to see which bits of a value are actually demanded. If the
2056 // original add had another add which was then immediately truncated, we
2057 // could still do the transformation.
2058 TruncInst *TI = dyn_cast<TruncInst>(U);
2059 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2063 // If the pattern matches, truncate the inputs to the narrower type and
2064 // use the sadd_with_overflow intrinsic to efficiently compute both the
2065 // result and the overflow bit.
2066 Module *M = I.getParent()->getParent()->getParent();
2068 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
2069 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
2072 InstCombiner::BuilderTy *Builder = IC.Builder;
2074 // Put the new code above the original add, in case there are any uses of the
2075 // add between the add and the compare.
2076 Builder->SetInsertPoint(OrigAdd);
2078 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2079 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
2080 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
2081 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2082 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
2084 // The inner add was the result of the narrow add, zero extended to the
2085 // wider type. Replace it with the result computed by the intrinsic.
2086 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
2088 // The original icmp gets replaced with the overflow value.
2089 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
2092 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
2094 // Don't bother doing this transformation for pointers, don't do it for
2096 if (!isa<IntegerType>(OrigAddV->getType())) return nullptr;
2098 // If the add is a constant expr, then we don't bother transforming it.
2099 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
2100 if (!OrigAdd) return nullptr;
2102 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
2104 // Put the new code above the original add, in case there are any uses of the
2105 // add between the add and the compare.
2106 InstCombiner::BuilderTy *Builder = IC.Builder;
2107 Builder->SetInsertPoint(OrigAdd);
2109 Module *M = I.getParent()->getParent()->getParent();
2110 Type *Ty = LHS->getType();
2111 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
2112 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
2113 Value *Add = Builder->CreateExtractValue(Call, 0);
2115 IC.ReplaceInstUsesWith(*OrigAdd, Add);
2117 // The original icmp gets replaced with the overflow value.
2118 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2121 /// \brief Recognize and process idiom involving test for multiplication
2124 /// The caller has matched a pattern of the form:
2125 /// I = cmp u (mul(zext A, zext B), V
2126 /// The function checks if this is a test for overflow and if so replaces
2127 /// multiplication with call to 'mul.with.overflow' intrinsic.
2129 /// \param I Compare instruction.
2130 /// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2131 /// the compare instruction. Must be of integer type.
2132 /// \param OtherVal The other argument of compare instruction.
2133 /// \returns Instruction which must replace the compare instruction, NULL if no
2134 /// replacement required.
2135 static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2136 Value *OtherVal, InstCombiner &IC) {
2137 // Don't bother doing this transformation for pointers, don't do it for
2139 if (!isa<IntegerType>(MulVal->getType()))
2142 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2143 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
2144 Instruction *MulInstr = cast<Instruction>(MulVal);
2145 assert(MulInstr->getOpcode() == Instruction::Mul);
2147 Instruction *LHS = cast<Instruction>(MulInstr->getOperand(0)),
2148 *RHS = cast<Instruction>(MulInstr->getOperand(1));
2149 assert(LHS->getOpcode() == Instruction::ZExt);
2150 assert(RHS->getOpcode() == Instruction::ZExt);
2151 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2153 // Calculate type and width of the result produced by mul.with.overflow.
2154 Type *TyA = A->getType(), *TyB = B->getType();
2155 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2156 WidthB = TyB->getPrimitiveSizeInBits();
2159 if (WidthB > WidthA) {
2167 // In order to replace the original mul with a narrower mul.with.overflow,
2168 // all uses must ignore upper bits of the product. The number of used low
2169 // bits must be not greater than the width of mul.with.overflow.
2170 if (MulVal->hasNUsesOrMore(2))
2171 for (User *U : MulVal->users()) {
2174 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2175 // Check if truncation ignores bits above MulWidth.
2176 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2177 if (TruncWidth > MulWidth)
2179 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2180 // Check if AND ignores bits above MulWidth.
2181 if (BO->getOpcode() != Instruction::And)
2183 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2184 const APInt &CVal = CI->getValue();
2185 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
2189 // Other uses prohibit this transformation.
2194 // Recognize patterns
2195 switch (I.getPredicate()) {
2196 case ICmpInst::ICMP_EQ:
2197 case ICmpInst::ICMP_NE:
2198 // Recognize pattern:
2199 // mulval = mul(zext A, zext B)
2200 // cmp eq/neq mulval, zext trunc mulval
2201 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2202 if (Zext->hasOneUse()) {
2203 Value *ZextArg = Zext->getOperand(0);
2204 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2205 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2209 // Recognize pattern:
2210 // mulval = mul(zext A, zext B)
2211 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2214 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2215 if (ValToMask != MulVal)
2217 const APInt &CVal = CI->getValue() + 1;
2218 if (CVal.isPowerOf2()) {
2219 unsigned MaskWidth = CVal.logBase2();
2220 if (MaskWidth == MulWidth)
2221 break; // Recognized
2226 case ICmpInst::ICMP_UGT:
2227 // Recognize pattern:
2228 // mulval = mul(zext A, zext B)
2229 // cmp ugt mulval, max
2230 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2231 APInt MaxVal = APInt::getMaxValue(MulWidth);
2232 MaxVal = MaxVal.zext(CI->getBitWidth());
2233 if (MaxVal.eq(CI->getValue()))
2234 break; // Recognized
2238 case ICmpInst::ICMP_UGE:
2239 // Recognize pattern:
2240 // mulval = mul(zext A, zext B)
2241 // cmp uge mulval, max+1
2242 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2243 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2244 if (MaxVal.eq(CI->getValue()))
2245 break; // Recognized
2249 case ICmpInst::ICMP_ULE:
2250 // Recognize pattern:
2251 // mulval = mul(zext A, zext B)
2252 // cmp ule mulval, max
2253 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2254 APInt MaxVal = APInt::getMaxValue(MulWidth);
2255 MaxVal = MaxVal.zext(CI->getBitWidth());
2256 if (MaxVal.eq(CI->getValue()))
2257 break; // Recognized
2261 case ICmpInst::ICMP_ULT:
2262 // Recognize pattern:
2263 // mulval = mul(zext A, zext B)
2264 // cmp ule mulval, max + 1
2265 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2266 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2267 if (MaxVal.eq(CI->getValue()))
2268 break; // Recognized
2276 InstCombiner::BuilderTy *Builder = IC.Builder;
2277 Builder->SetInsertPoint(MulInstr);
2278 Module *M = I.getParent()->getParent()->getParent();
2280 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2281 Value *MulA = A, *MulB = B;
2282 if (WidthA < MulWidth)
2283 MulA = Builder->CreateZExt(A, MulType);
2284 if (WidthB < MulWidth)
2285 MulB = Builder->CreateZExt(B, MulType);
2287 Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow, MulType);
2288 CallInst *Call = Builder->CreateCall2(F, MulA, MulB, "umul");
2289 IC.Worklist.Add(MulInstr);
2291 // If there are uses of mul result other than the comparison, we know that
2292 // they are truncation or binary AND. Change them to use result of
2293 // mul.with.overflow and adjust properly mask/size.
2294 if (MulVal->hasNUsesOrMore(2)) {
2295 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2296 for (User *U : MulVal->users()) {
2297 if (U == &I || U == OtherVal)
2299 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2300 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
2301 IC.ReplaceInstUsesWith(*TI, Mul);
2303 TI->setOperand(0, Mul);
2304 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2305 assert(BO->getOpcode() == Instruction::And);
2306 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2307 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2308 APInt ShortMask = CI->getValue().trunc(MulWidth);
2309 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2311 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2312 IC.Worklist.Add(Zext);
2313 IC.ReplaceInstUsesWith(*BO, Zext);
2315 llvm_unreachable("Unexpected Binary operation");
2317 IC.Worklist.Add(cast<Instruction>(U));
2320 if (isa<Instruction>(OtherVal))
2321 IC.Worklist.Add(cast<Instruction>(OtherVal));
2323 // The original icmp gets replaced with the overflow value, maybe inverted
2324 // depending on predicate.
2325 bool Inverse = false;
2326 switch (I.getPredicate()) {
2327 case ICmpInst::ICMP_NE:
2329 case ICmpInst::ICMP_EQ:
2332 case ICmpInst::ICMP_UGT:
2333 case ICmpInst::ICMP_UGE:
2334 if (I.getOperand(0) == MulVal)
2338 case ICmpInst::ICMP_ULT:
2339 case ICmpInst::ICMP_ULE:
2340 if (I.getOperand(1) == MulVal)
2345 llvm_unreachable("Unexpected predicate");
2348 Value *Res = Builder->CreateExtractValue(Call, 1);
2349 return BinaryOperator::CreateNot(Res);
2352 return ExtractValueInst::Create(Call, 1);
2355 // DemandedBitsLHSMask - When performing a comparison against a constant,
2356 // it is possible that not all the bits in the LHS are demanded. This helper
2357 // method computes the mask that IS demanded.
2358 static APInt DemandedBitsLHSMask(ICmpInst &I,
2359 unsigned BitWidth, bool isSignCheck) {
2361 return APInt::getSignBit(BitWidth);
2363 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2364 if (!CI) return APInt::getAllOnesValue(BitWidth);
2365 const APInt &RHS = CI->getValue();
2367 switch (I.getPredicate()) {
2368 // For a UGT comparison, we don't care about any bits that
2369 // correspond to the trailing ones of the comparand. The value of these
2370 // bits doesn't impact the outcome of the comparison, because any value
2371 // greater than the RHS must differ in a bit higher than these due to carry.
2372 case ICmpInst::ICMP_UGT: {
2373 unsigned trailingOnes = RHS.countTrailingOnes();
2374 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2378 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2379 // Any value less than the RHS must differ in a higher bit because of carries.
2380 case ICmpInst::ICMP_ULT: {
2381 unsigned trailingZeros = RHS.countTrailingZeros();
2382 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2387 return APInt::getAllOnesValue(BitWidth);
2392 /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2393 /// should be swapped.
2394 /// The decision is based on how many times these two operands are reused
2395 /// as subtract operands and their positions in those instructions.
2396 /// The rational is that several architectures use the same instruction for
2397 /// both subtract and cmp, thus it is better if the order of those operands
2399 /// \return true if Op0 and Op1 should be swapped.
2400 static bool swapMayExposeCSEOpportunities(const Value * Op0,
2401 const Value * Op1) {
2402 // Filter out pointer value as those cannot appears directly in subtract.
2403 // FIXME: we may want to go through inttoptrs or bitcasts.
2404 if (Op0->getType()->isPointerTy())
2406 // Count every uses of both Op0 and Op1 in a subtract.
2407 // Each time Op0 is the first operand, count -1: swapping is bad, the
2408 // subtract has already the same layout as the compare.
2409 // Each time Op0 is the second operand, count +1: swapping is good, the
2410 // subtract has a different layout as the compare.
2411 // At the end, if the benefit is greater than 0, Op0 should come second to
2412 // expose more CSE opportunities.
2413 int GlobalSwapBenefits = 0;
2414 for (const User *U : Op0->users()) {
2415 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
2416 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2418 // If Op0 is the first argument, this is not beneficial to swap the
2420 int LocalSwapBenefits = -1;
2421 unsigned Op1Idx = 1;
2422 if (BinOp->getOperand(Op1Idx) == Op0) {
2424 LocalSwapBenefits = 1;
2426 if (BinOp->getOperand(Op1Idx) != Op1)
2428 GlobalSwapBenefits += LocalSwapBenefits;
2430 return GlobalSwapBenefits > 0;
2433 /// \brief Check that one use is in the same block as the definition and all
2434 /// other uses are in blocks dominated by a given block
2436 /// \param DI Definition
2438 /// \param DB Block that must dominate all uses of \p DI outside
2439 /// the parent block
2440 /// \return true when \p UI is the only use of \p DI in the parent block
2441 /// and all other uses of \p DI are in blocks dominated by \p DB.
2443 bool InstCombiner::dominatesAllUses(const Instruction *DI,
2444 const Instruction *UI,
2445 const BasicBlock *DB) const {
2446 assert(DI && UI && "Instruction not defined\n");
2447 if (DI->getParent() != UI->getParent())
2449 // DominatorTree available?
2452 for (const User *U : DI->users()) {
2453 auto *Usr = cast<Instruction>(U);
2454 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
2461 /// true when the instruction sequence within a block is select-cmp-br.
2463 static bool isChainSelectCmpBranch(const SelectInst *SI) {
2464 const BasicBlock *BB = SI->getParent();
2467 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
2468 if (!BI || BI->getNumSuccessors() != 2)
2470 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
2471 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
2477 /// \brief True when a select result is replaced by one of its operands
2478 /// in select-icmp sequence. This will eventually result in the elimination
2481 /// \param SI Select instruction
2482 /// \param Icmp Compare instruction
2483 /// \param CI1 'true' when first select operand is equal to RHSC of Icmp
2484 /// \param CI2 'true' when second select operand is equal to RHSC of Icmp
2487 /// - The replacement is global and requires dominator information
2488 /// - The caller is responsible for the actual replacement
2493 /// %4 = select i1 %3, %C* %0, %C* null
2494 /// %5 = icmp eq %C* %4, null
2495 /// br i1 %5, label %9, label %7
2497 /// ; <label>:7 ; preds = %entry
2498 /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
2501 /// can be transformed to
2503 /// %5 = icmp eq %C* %0, null
2504 /// %6 = select i1 %3, i1 %5, i1 true
2505 /// br i1 %6, label %9, label %7
2507 /// ; <label>:7 ; preds = %entry
2508 /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
2510 /// Similar when the first operand of the select is a constant or/and
2511 /// the compare is for not equal rather than equal.
2513 /// FIXME: Currently the function considers equal compares only. It should be
2514 /// possbile to extend it to not equal compares also.
2516 bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
2517 const ICmpInst *Icmp,
2518 const ConstantInt *CI1,
2519 const ConstantInt *CI2) {
2520 if (isChainSelectCmpBranch(SI) && Icmp->isEquality()) {
2521 // Code sequence is select - icmp.[eq|ne] - br
2522 unsigned ReplaceWithOpd = 0;
2523 if (CI1 && !CI1->isZero())
2524 // The first constant operand of the select and the RHS of
2525 // the compare match, so try to substitute
2526 // the select results with its second operand
2528 // %4 = select i1 %3, %C* null, %C* %0
2529 // %5 = icmp eq %C* %4, null
2530 // ==> could replace select with second operand
2532 else if (CI2 && !CI2->isZero())
2533 // Similar when the second operand of the select is a constant
2535 // %4 = select i1 %3, %C* %0, %C* null
2536 // %5 = icmp eq %C* %4, null
2537 // ==> could replace select with first operand
2539 if (ReplaceWithOpd) {
2540 // Replace select with operand on else path for EQ compares.
2541 // Replace select with operand on then path for NE compares.
2543 Icmp->getPredicate() == ICmpInst::ICMP_EQ
2544 ? SI->getParent()->getTerminator()->getSuccessor(1)
2545 : SI->getParent()->getTerminator()->getSuccessor(0);
2546 if (InstCombiner::dominatesAllUses(SI, Icmp, Succ)) {
2547 SI->replaceAllUsesWith(SI->getOperand(ReplaceWithOpd));
2555 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2556 bool Changed = false;
2557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2558 unsigned Op0Cplxity = getComplexity(Op0);
2559 unsigned Op1Cplxity = getComplexity(Op1);
2561 /// Orders the operands of the compare so that they are listed from most
2562 /// complex to least complex. This puts constants before unary operators,
2563 /// before binary operators.
2564 if (Op0Cplxity < Op1Cplxity ||
2565 (Op0Cplxity == Op1Cplxity &&
2566 swapMayExposeCSEOpportunities(Op0, Op1))) {
2568 std::swap(Op0, Op1);
2572 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AT))
2573 return ReplaceInstUsesWith(I, V);
2575 // comparing -val or val with non-zero is the same as just comparing val
2576 // ie, abs(val) != 0 -> val != 0
2577 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2579 Value *Cond, *SelectTrue, *SelectFalse;
2580 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
2581 m_Value(SelectFalse)))) {
2582 if (Value *V = dyn_castNegVal(SelectTrue)) {
2583 if (V == SelectFalse)
2584 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2586 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2587 if (V == SelectTrue)
2588 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2593 Type *Ty = Op0->getType();
2595 // icmp's with boolean values can always be turned into bitwise operations
2596 if (Ty->isIntegerTy(1)) {
2597 switch (I.getPredicate()) {
2598 default: llvm_unreachable("Invalid icmp instruction!");
2599 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2600 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2601 return BinaryOperator::CreateNot(Xor);
2603 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2604 return BinaryOperator::CreateXor(Op0, Op1);
2606 case ICmpInst::ICMP_UGT:
2607 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2609 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2610 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2611 return BinaryOperator::CreateAnd(Not, Op1);
2613 case ICmpInst::ICMP_SGT:
2614 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2616 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2617 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2618 return BinaryOperator::CreateAnd(Not, Op0);
2620 case ICmpInst::ICMP_UGE:
2621 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2623 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2624 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2625 return BinaryOperator::CreateOr(Not, Op1);
2627 case ICmpInst::ICMP_SGE:
2628 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2630 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2631 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2632 return BinaryOperator::CreateOr(Not, Op0);
2637 unsigned BitWidth = 0;
2638 if (Ty->isIntOrIntVectorTy())
2639 BitWidth = Ty->getScalarSizeInBits();
2640 else if (DL) // Pointers require DL info to get their size.
2641 BitWidth = DL->getTypeSizeInBits(Ty->getScalarType());
2643 bool isSignBit = false;
2645 // See if we are doing a comparison with a constant.
2646 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2647 Value *A = nullptr, *B = nullptr;
2649 // Match the following pattern, which is a common idiom when writing
2650 // overflow-safe integer arithmetic function. The source performs an
2651 // addition in wider type, and explicitly checks for overflow using
2652 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2653 // sadd_with_overflow intrinsic.
2655 // TODO: This could probably be generalized to handle other overflow-safe
2656 // operations if we worked out the formulas to compute the appropriate
2660 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
2662 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
2663 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2664 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
2665 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
2669 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2670 if (I.isEquality() && CI->isZero() &&
2671 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2672 // (icmp cond A B) if cond is equality
2673 return new ICmpInst(I.getPredicate(), A, B);
2676 // If we have an icmp le or icmp ge instruction, turn it into the
2677 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2678 // them being folded in the code below. The SimplifyICmpInst code has
2679 // already handled the edge cases for us, so we just assert on them.
2680 switch (I.getPredicate()) {
2682 case ICmpInst::ICMP_ULE:
2683 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2684 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
2685 Builder->getInt(CI->getValue()+1));
2686 case ICmpInst::ICMP_SLE:
2687 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2688 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2689 Builder->getInt(CI->getValue()+1));
2690 case ICmpInst::ICMP_UGE:
2691 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
2692 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
2693 Builder->getInt(CI->getValue()-1));
2694 case ICmpInst::ICMP_SGE:
2695 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
2696 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2697 Builder->getInt(CI->getValue()-1));
2700 // (icmp eq/ne (ashr/lshr const2, A), const1)
2701 if (I.isEquality()) {
2703 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
2704 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
2705 return FoldICmpCstShrCst(I, Op0, A, CI, CI2);
2709 // If this comparison is a normal comparison, it demands all
2710 // bits, if it is a sign bit comparison, it only demands the sign bit.
2712 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2715 // See if we can fold the comparison based on range information we can get
2716 // by checking whether bits are known to be zero or one in the input.
2717 if (BitWidth != 0) {
2718 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2719 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2721 if (SimplifyDemandedBits(I.getOperandUse(0),
2722 DemandedBitsLHSMask(I, BitWidth, isSignBit),
2723 Op0KnownZero, Op0KnownOne, 0))
2725 if (SimplifyDemandedBits(I.getOperandUse(1),
2726 APInt::getAllOnesValue(BitWidth),
2727 Op1KnownZero, Op1KnownOne, 0))
2730 // Given the known and unknown bits, compute a range that the LHS could be
2731 // in. Compute the Min, Max and RHS values based on the known bits. For the
2732 // EQ and NE we use unsigned values.
2733 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2734 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2736 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2738 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2741 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2743 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2747 // If Min and Max are known to be the same, then SimplifyDemandedBits
2748 // figured out that the LHS is a constant. Just constant fold this now so
2749 // that code below can assume that Min != Max.
2750 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2751 return new ICmpInst(I.getPredicate(),
2752 ConstantInt::get(Op0->getType(), Op0Min), Op1);
2753 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2754 return new ICmpInst(I.getPredicate(), Op0,
2755 ConstantInt::get(Op1->getType(), Op1Min));
2757 // Based on the range information we know about the LHS, see if we can
2758 // simplify this comparison. For example, (x&4) < 8 is always true.
2759 switch (I.getPredicate()) {
2760 default: llvm_unreachable("Unknown icmp opcode!");
2761 case ICmpInst::ICMP_EQ: {
2762 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2763 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2765 // If all bits are known zero except for one, then we know at most one
2766 // bit is set. If the comparison is against zero, then this is a check
2767 // to see if *that* bit is set.
2768 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2769 if (~Op1KnownZero == 0) {
2770 // If the LHS is an AND with the same constant, look through it.
2771 Value *LHS = nullptr;
2772 ConstantInt *LHSC = nullptr;
2773 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2774 LHSC->getValue() != Op0KnownZeroInverted)
2777 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2778 // then turn "((1 << x)&8) == 0" into "x != 3".
2779 // or turn "((1 << x)&7) == 0" into "x > 2".
2781 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2782 APInt ValToCheck = Op0KnownZeroInverted;
2783 if (ValToCheck.isPowerOf2()) {
2784 unsigned CmpVal = ValToCheck.countTrailingZeros();
2785 return new ICmpInst(ICmpInst::ICMP_NE, X,
2786 ConstantInt::get(X->getType(), CmpVal));
2787 } else if ((++ValToCheck).isPowerOf2()) {
2788 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
2789 return new ICmpInst(ICmpInst::ICMP_UGT, X,
2790 ConstantInt::get(X->getType(), CmpVal));
2794 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2795 // then turn "((8 >>u x)&1) == 0" into "x != 3".
2797 if (Op0KnownZeroInverted == 1 &&
2798 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2799 return new ICmpInst(ICmpInst::ICMP_NE, X,
2800 ConstantInt::get(X->getType(),
2801 CI->countTrailingZeros()));
2806 case ICmpInst::ICMP_NE: {
2807 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2808 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2810 // If all bits are known zero except for one, then we know at most one
2811 // bit is set. If the comparison is against zero, then this is a check
2812 // to see if *that* bit is set.
2813 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2814 if (~Op1KnownZero == 0) {
2815 // If the LHS is an AND with the same constant, look through it.
2816 Value *LHS = nullptr;
2817 ConstantInt *LHSC = nullptr;
2818 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2819 LHSC->getValue() != Op0KnownZeroInverted)
2822 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2823 // then turn "((1 << x)&8) != 0" into "x == 3".
2824 // or turn "((1 << x)&7) != 0" into "x < 3".
2826 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2827 APInt ValToCheck = Op0KnownZeroInverted;
2828 if (ValToCheck.isPowerOf2()) {
2829 unsigned CmpVal = ValToCheck.countTrailingZeros();
2830 return new ICmpInst(ICmpInst::ICMP_EQ, X,
2831 ConstantInt::get(X->getType(), CmpVal));
2832 } else if ((++ValToCheck).isPowerOf2()) {
2833 unsigned CmpVal = ValToCheck.countTrailingZeros();
2834 return new ICmpInst(ICmpInst::ICMP_ULT, X,
2835 ConstantInt::get(X->getType(), CmpVal));
2839 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2840 // then turn "((8 >>u x)&1) != 0" into "x == 3".
2842 if (Op0KnownZeroInverted == 1 &&
2843 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2844 return new ICmpInst(ICmpInst::ICMP_EQ, X,
2845 ConstantInt::get(X->getType(),
2846 CI->countTrailingZeros()));
2851 case ICmpInst::ICMP_ULT:
2852 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
2853 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2854 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
2855 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2856 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2857 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2858 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2859 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2860 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2861 Builder->getInt(CI->getValue()-1));
2863 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2864 if (CI->isMinValue(true))
2865 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2866 Constant::getAllOnesValue(Op0->getType()));
2869 case ICmpInst::ICMP_UGT:
2870 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
2871 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2872 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
2873 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2875 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2876 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2877 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2878 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2879 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2880 Builder->getInt(CI->getValue()+1));
2882 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2883 if (CI->isMaxValue(true))
2884 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2885 Constant::getNullValue(Op0->getType()));
2888 case ICmpInst::ICMP_SLT:
2889 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
2890 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2891 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
2892 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2893 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2894 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2895 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2896 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2897 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2898 Builder->getInt(CI->getValue()-1));
2901 case ICmpInst::ICMP_SGT:
2902 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
2903 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2904 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
2905 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2907 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2908 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2909 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2910 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2911 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2912 Builder->getInt(CI->getValue()+1));
2915 case ICmpInst::ICMP_SGE:
2916 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2917 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
2918 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2919 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
2920 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2922 case ICmpInst::ICMP_SLE:
2923 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2924 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
2925 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2926 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
2927 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2929 case ICmpInst::ICMP_UGE:
2930 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2931 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
2932 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2933 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
2934 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2936 case ICmpInst::ICMP_ULE:
2937 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2938 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
2939 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2940 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
2941 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2945 // Turn a signed comparison into an unsigned one if both operands
2946 // are known to have the same sign.
2948 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2949 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2950 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2953 // Test if the ICmpInst instruction is used exclusively by a select as
2954 // part of a minimum or maximum operation. If so, refrain from doing
2955 // any other folding. This helps out other analyses which understand
2956 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2957 // and CodeGen. And in this case, at least one of the comparison
2958 // operands has at least one user besides the compare (the select),
2959 // which would often largely negate the benefit of folding anyway.
2961 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
2962 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2963 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2966 // See if we are doing a comparison between a constant and an instruction that
2967 // can be folded into the comparison.
2968 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2969 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2970 // instruction, see if that instruction also has constants so that the
2971 // instruction can be folded into the icmp
2972 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2973 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2977 // Handle icmp with constant (but not simple integer constant) RHS
2978 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2979 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2980 switch (LHSI->getOpcode()) {
2981 case Instruction::GetElementPtr:
2982 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2983 if (RHSC->isNullValue() &&
2984 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2985 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2986 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2988 case Instruction::PHI:
2989 // Only fold icmp into the PHI if the phi and icmp are in the same
2990 // block. If in the same block, we're encouraging jump threading. If
2991 // not, we are just pessimizing the code by making an i1 phi.
2992 if (LHSI->getParent() == I.getParent())
2993 if (Instruction *NV = FoldOpIntoPhi(I))
2996 case Instruction::Select: {
2997 // If either operand of the select is a constant, we can fold the
2998 // comparison into the select arms, which will cause one to be
2999 // constant folded and the select turned into a bitwise or.
3000 Value *Op1 = nullptr, *Op2 = nullptr;
3001 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
3002 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3003 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
3004 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3006 // We only want to perform this transformation if it will not lead to
3007 // additional code. This is true if either both sides of the select
3008 // fold to a constant (in which case the icmp is replaced with a select
3009 // which will usually simplify) or this is the only user of the
3010 // select (in which case we are trading a select+icmp for a simpler
3011 // select+icmp) or all uses of the select can be replaced based on
3012 // dominance information ("Global cases").
3013 bool Transform = false;
3016 else if (Op1 || Op2) {
3017 if (LHSI->hasOneUse())
3021 Transform = replacedSelectWithOperand(
3022 cast<SelectInst>(LHSI), &I, dyn_cast_or_null<ConstantInt>(Op1),
3023 dyn_cast_or_null<ConstantInt>(Op2));
3027 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3030 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3032 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3036 case Instruction::IntToPtr:
3037 // icmp pred inttoptr(X), null -> icmp pred X, 0
3038 if (RHSC->isNullValue() && DL &&
3039 DL->getIntPtrType(RHSC->getType()) ==
3040 LHSI->getOperand(0)->getType())
3041 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3042 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3045 case Instruction::Load:
3046 // Try to optimize things like "A[i] > 4" to index computations.
3047 if (GetElementPtrInst *GEP =
3048 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3049 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3050 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3051 !cast<LoadInst>(LHSI)->isVolatile())
3052 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3059 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3060 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3061 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3063 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3064 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3065 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3068 // Test to see if the operands of the icmp are casted versions of other
3069 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3071 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
3072 if (Op0->getType()->isPointerTy() &&
3073 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
3074 // We keep moving the cast from the left operand over to the right
3075 // operand, where it can often be eliminated completely.
3076 Op0 = CI->getOperand(0);
3078 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3079 // so eliminate it as well.
3080 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3081 Op1 = CI2->getOperand(0);
3083 // If Op1 is a constant, we can fold the cast into the constant.
3084 if (Op0->getType() != Op1->getType()) {
3085 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3086 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3088 // Otherwise, cast the RHS right before the icmp
3089 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3092 return new ICmpInst(I.getPredicate(), Op0, Op1);
3096 if (isa<CastInst>(Op0)) {
3097 // Handle the special case of: icmp (cast bool to X), <cst>
3098 // This comes up when you have code like
3101 // For generality, we handle any zero-extension of any operand comparison
3102 // with a constant or another cast from the same type.
3103 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3104 if (Instruction *R = visitICmpInstWithCastAndCast(I))
3108 // Special logic for binary operators.
3109 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3110 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3112 CmpInst::Predicate Pred = I.getPredicate();
3113 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3114 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3115 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3116 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3117 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3118 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3119 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3120 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3121 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3123 // Analyze the case when either Op0 or Op1 is an add instruction.
3124 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
3125 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3126 if (BO0 && BO0->getOpcode() == Instruction::Add)
3127 A = BO0->getOperand(0), B = BO0->getOperand(1);
3128 if (BO1 && BO1->getOpcode() == Instruction::Add)
3129 C = BO1->getOperand(0), D = BO1->getOperand(1);
3131 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3132 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3133 return new ICmpInst(Pred, A == Op1 ? B : A,
3134 Constant::getNullValue(Op1->getType()));
3136 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3137 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3138 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3141 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
3142 if (A && C && (A == C || A == D || B == C || B == D) &&
3143 NoOp0WrapProblem && NoOp1WrapProblem &&
3144 // Try not to increase register pressure.
3145 BO0->hasOneUse() && BO1->hasOneUse()) {
3146 // Determine Y and Z in the form icmp (X+Y), (X+Z).
3149 // C + B == C + D -> B == D
3152 } else if (A == D) {
3153 // D + B == C + D -> B == C
3156 } else if (B == C) {
3157 // A + C == C + D -> A == D
3162 // A + D == C + D -> A == C
3166 return new ICmpInst(Pred, Y, Z);
3169 // icmp slt (X + -1), Y -> icmp sle X, Y
3170 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3171 match(B, m_AllOnes()))
3172 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3174 // icmp sge (X + -1), Y -> icmp sgt X, Y
3175 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3176 match(B, m_AllOnes()))
3177 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3179 // icmp sle (X + 1), Y -> icmp slt X, Y
3180 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3182 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3184 // icmp sgt (X + 1), Y -> icmp sge X, Y
3185 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3187 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3189 // if C1 has greater magnitude than C2:
3190 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3191 // s.t. C3 = C1 - C2
3193 // if C2 has greater magnitude than C1:
3194 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3195 // s.t. C3 = C2 - C1
3196 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3197 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3198 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3199 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3200 const APInt &AP1 = C1->getValue();
3201 const APInt &AP2 = C2->getValue();
3202 if (AP1.isNegative() == AP2.isNegative()) {
3203 APInt AP1Abs = C1->getValue().abs();
3204 APInt AP2Abs = C2->getValue().abs();
3205 if (AP1Abs.uge(AP2Abs)) {
3206 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3207 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3208 return new ICmpInst(Pred, NewAdd, C);
3210 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3211 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3212 return new ICmpInst(Pred, A, NewAdd);
3218 // Analyze the case when either Op0 or Op1 is a sub instruction.
3219 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
3220 A = nullptr; B = nullptr; C = nullptr; D = nullptr;
3221 if (BO0 && BO0->getOpcode() == Instruction::Sub)
3222 A = BO0->getOperand(0), B = BO0->getOperand(1);
3223 if (BO1 && BO1->getOpcode() == Instruction::Sub)
3224 C = BO1->getOperand(0), D = BO1->getOperand(1);
3226 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3227 if (A == Op1 && NoOp0WrapProblem)
3228 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3230 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3231 if (C == Op0 && NoOp1WrapProblem)
3232 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3234 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
3235 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3236 // Try not to increase register pressure.
3237 BO0->hasOneUse() && BO1->hasOneUse())
3238 return new ICmpInst(Pred, A, C);
3240 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3241 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3242 // Try not to increase register pressure.
3243 BO0->hasOneUse() && BO1->hasOneUse())
3244 return new ICmpInst(Pred, D, B);
3246 // icmp (0-X) < cst --> x > -cst
3247 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3249 if (match(BO0, m_Neg(m_Value(X))))
3250 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3251 if (!RHSC->isMinValue(/*isSigned=*/true))
3252 return new ICmpInst(I.getSwappedPredicate(), X,
3253 ConstantExpr::getNeg(RHSC));
3256 BinaryOperator *SRem = nullptr;
3257 // icmp (srem X, Y), Y
3258 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3259 Op1 == BO0->getOperand(1))
3261 // icmp Y, (srem X, Y)
3262 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3263 Op0 == BO1->getOperand(1))
3266 // We don't check hasOneUse to avoid increasing register pressure because
3267 // the value we use is the same value this instruction was already using.
3268 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3270 case ICmpInst::ICMP_EQ:
3271 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3272 case ICmpInst::ICMP_NE:
3273 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3274 case ICmpInst::ICMP_SGT:
3275 case ICmpInst::ICMP_SGE:
3276 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3277 Constant::getAllOnesValue(SRem->getType()));
3278 case ICmpInst::ICMP_SLT:
3279 case ICmpInst::ICMP_SLE:
3280 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3281 Constant::getNullValue(SRem->getType()));
3285 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
3286 BO0->hasOneUse() && BO1->hasOneUse() &&
3287 BO0->getOperand(1) == BO1->getOperand(1)) {
3288 switch (BO0->getOpcode()) {
3290 case Instruction::Add:
3291 case Instruction::Sub:
3292 case Instruction::Xor:
3293 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3294 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3295 BO1->getOperand(0));
3296 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3297 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3298 if (CI->getValue().isSignBit()) {
3299 ICmpInst::Predicate Pred = I.isSigned()
3300 ? I.getUnsignedPredicate()
3301 : I.getSignedPredicate();
3302 return new ICmpInst(Pred, BO0->getOperand(0),
3303 BO1->getOperand(0));
3306 if (CI->isMaxValue(true)) {
3307 ICmpInst::Predicate Pred = I.isSigned()
3308 ? I.getUnsignedPredicate()
3309 : I.getSignedPredicate();
3310 Pred = I.getSwappedPredicate(Pred);
3311 return new ICmpInst(Pred, BO0->getOperand(0),
3312 BO1->getOperand(0));
3316 case Instruction::Mul:
3317 if (!I.isEquality())
3320 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3321 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3322 // Mask = -1 >> count-trailing-zeros(Cst).
3323 if (!CI->isZero() && !CI->isOne()) {
3324 const APInt &AP = CI->getValue();
3325 ConstantInt *Mask = ConstantInt::get(I.getContext(),
3326 APInt::getLowBitsSet(AP.getBitWidth(),
3328 AP.countTrailingZeros()));
3329 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
3330 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
3331 return new ICmpInst(I.getPredicate(), And1, And2);
3335 case Instruction::UDiv:
3336 case Instruction::LShr:
3340 case Instruction::SDiv:
3341 case Instruction::AShr:
3342 if (!BO0->isExact() || !BO1->isExact())
3344 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3345 BO1->getOperand(0));
3346 case Instruction::Shl: {
3347 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3348 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3351 if (!NSW && I.isSigned())
3353 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3354 BO1->getOperand(0));
3361 // Transform (A & ~B) == 0 --> (A & B) != 0
3362 // and (A & ~B) != 0 --> (A & B) == 0
3363 // if A is a power of 2.
3364 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
3365 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A, false,
3368 return new ICmpInst(I.getInversePredicate(),
3369 Builder->CreateAnd(A, B),
3372 // ~x < ~y --> y < x
3373 // ~x < cst --> ~cst < x
3374 if (match(Op0, m_Not(m_Value(A)))) {
3375 if (match(Op1, m_Not(m_Value(B))))
3376 return new ICmpInst(I.getPredicate(), B, A);
3377 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3378 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
3381 // (a+b) <u a --> llvm.uadd.with.overflow.
3382 // (a+b) <u b --> llvm.uadd.with.overflow.
3383 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
3384 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
3385 (Op1 == A || Op1 == B))
3386 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
3389 // a >u (a+b) --> llvm.uadd.with.overflow.
3390 // b >u (a+b) --> llvm.uadd.with.overflow.
3391 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
3392 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
3393 (Op0 == A || Op0 == B))
3394 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
3397 // (zext a) * (zext b) --> llvm.umul.with.overflow.
3398 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3399 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
3402 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3403 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
3408 if (I.isEquality()) {
3409 Value *A, *B, *C, *D;
3411 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3412 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3413 Value *OtherVal = A == Op1 ? B : A;
3414 return new ICmpInst(I.getPredicate(), OtherVal,
3415 Constant::getNullValue(A->getType()));
3418 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3419 // A^c1 == C^c2 --> A == C^(c1^c2)
3420 ConstantInt *C1, *C2;
3421 if (match(B, m_ConstantInt(C1)) &&
3422 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
3423 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
3424 Value *Xor = Builder->CreateXor(C, NC);
3425 return new ICmpInst(I.getPredicate(), A, Xor);
3428 // A^B == A^D -> B == D
3429 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
3430 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
3431 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
3432 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
3436 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3437 (A == Op0 || B == Op0)) {
3438 // A == (A^B) -> B == 0
3439 Value *OtherVal = A == Op0 ? B : A;
3440 return new ICmpInst(I.getPredicate(), OtherVal,
3441 Constant::getNullValue(A->getType()));
3444 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
3445 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
3446 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
3447 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
3450 X = B; Y = D; Z = A;
3451 } else if (A == D) {
3452 X = B; Y = C; Z = A;
3453 } else if (B == C) {
3454 X = A; Y = D; Z = B;
3455 } else if (B == D) {
3456 X = A; Y = C; Z = B;
3459 if (X) { // Build (X^Y) & Z
3460 Op1 = Builder->CreateXor(X, Y);
3461 Op1 = Builder->CreateAnd(Op1, Z);
3462 I.setOperand(0, Op1);
3463 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3468 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
3469 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
3471 if ((Op0->hasOneUse() &&
3472 match(Op0, m_ZExt(m_Value(A))) &&
3473 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3474 (Op1->hasOneUse() &&
3475 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3476 match(Op1, m_ZExt(m_Value(A))))) {
3477 APInt Pow2 = Cst1->getValue() + 1;
3478 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3479 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3480 return new ICmpInst(I.getPredicate(), A,
3481 Builder->CreateTrunc(B, A->getType()));
3484 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3485 // For lshr and ashr pairs.
3486 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3487 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3488 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3489 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3490 unsigned TypeBits = Cst1->getBitWidth();
3491 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3492 if (ShAmt < TypeBits && ShAmt != 0) {
3493 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
3494 ? ICmpInst::ICMP_UGE
3495 : ICmpInst::ICMP_ULT;
3496 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3497 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3498 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
3502 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3503 // "icmp (and X, mask), cst"
3505 if (Op0->hasOneUse() &&
3506 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
3507 m_ConstantInt(ShAmt))))) &&
3508 match(Op1, m_ConstantInt(Cst1)) &&
3509 // Only do this when A has multiple uses. This is most important to do
3510 // when it exposes other optimizations.
3512 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
3514 if (ShAmt < ASize) {
3516 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3519 APInt CmpV = Cst1->getValue().zext(ASize);
3522 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3523 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3529 Value *X; ConstantInt *Cst;
3531 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
3532 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
3535 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
3536 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
3538 return Changed ? &I : nullptr;
3541 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
3543 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3546 if (!isa<ConstantFP>(RHSC)) return nullptr;
3547 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
3549 // Get the width of the mantissa. We don't want to hack on conversions that
3550 // might lose information from the integer, e.g. "i64 -> float"
3551 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
3552 if (MantissaWidth == -1) return nullptr; // Unknown.
3554 // Check to see that the input is converted from an integer type that is small
3555 // enough that preserves all bits. TODO: check here for "known" sign bits.
3556 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3557 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
3559 // If this is a uitofp instruction, we need an extra bit to hold the sign.
3560 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3564 // If the conversion would lose info, don't hack on this.
3565 if ((int)InputSize > MantissaWidth)
3568 // Otherwise, we can potentially simplify the comparison. We know that it
3569 // will always come through as an integer value and we know the constant is
3570 // not a NAN (it would have been previously simplified).
3571 assert(!RHS.isNaN() && "NaN comparison not already folded!");
3573 ICmpInst::Predicate Pred;
3574 switch (I.getPredicate()) {
3575 default: llvm_unreachable("Unexpected predicate!");
3576 case FCmpInst::FCMP_UEQ:
3577 case FCmpInst::FCMP_OEQ:
3578 Pred = ICmpInst::ICMP_EQ;
3580 case FCmpInst::FCMP_UGT:
3581 case FCmpInst::FCMP_OGT:
3582 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3584 case FCmpInst::FCMP_UGE:
3585 case FCmpInst::FCMP_OGE:
3586 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3588 case FCmpInst::FCMP_ULT:
3589 case FCmpInst::FCMP_OLT:
3590 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3592 case FCmpInst::FCMP_ULE:
3593 case FCmpInst::FCMP_OLE:
3594 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3596 case FCmpInst::FCMP_UNE:
3597 case FCmpInst::FCMP_ONE:
3598 Pred = ICmpInst::ICMP_NE;
3600 case FCmpInst::FCMP_ORD:
3601 return ReplaceInstUsesWith(I, Builder->getTrue());
3602 case FCmpInst::FCMP_UNO:
3603 return ReplaceInstUsesWith(I, Builder->getFalse());
3606 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
3608 // Now we know that the APFloat is a normal number, zero or inf.
3610 // See if the FP constant is too large for the integer. For example,
3611 // comparing an i8 to 300.0.
3612 unsigned IntWidth = IntTy->getScalarSizeInBits();
3615 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3616 // and large values.
3617 APFloat SMax(RHS.getSemantics());
3618 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3619 APFloat::rmNearestTiesToEven);
3620 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3621 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3622 Pred == ICmpInst::ICMP_SLE)
3623 return ReplaceInstUsesWith(I, Builder->getTrue());
3624 return ReplaceInstUsesWith(I, Builder->getFalse());
3627 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3628 // +INF and large values.
3629 APFloat UMax(RHS.getSemantics());
3630 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3631 APFloat::rmNearestTiesToEven);
3632 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3633 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3634 Pred == ICmpInst::ICMP_ULE)
3635 return ReplaceInstUsesWith(I, Builder->getTrue());
3636 return ReplaceInstUsesWith(I, Builder->getFalse());
3641 // See if the RHS value is < SignedMin.
3642 APFloat SMin(RHS.getSemantics());
3643 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3644 APFloat::rmNearestTiesToEven);
3645 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3646 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3647 Pred == ICmpInst::ICMP_SGE)
3648 return ReplaceInstUsesWith(I, Builder->getTrue());
3649 return ReplaceInstUsesWith(I, Builder->getFalse());
3652 // See if the RHS value is < UnsignedMin.
3653 APFloat SMin(RHS.getSemantics());
3654 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3655 APFloat::rmNearestTiesToEven);
3656 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3657 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3658 Pred == ICmpInst::ICMP_UGE)
3659 return ReplaceInstUsesWith(I, Builder->getTrue());
3660 return ReplaceInstUsesWith(I, Builder->getFalse());
3664 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3665 // [0, UMAX], but it may still be fractional. See if it is fractional by
3666 // casting the FP value to the integer value and back, checking for equality.
3667 // Don't do this for zero, because -0.0 is not fractional.
3668 Constant *RHSInt = LHSUnsigned
3669 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3670 : ConstantExpr::getFPToSI(RHSC, IntTy);
3671 if (!RHS.isZero()) {
3672 bool Equal = LHSUnsigned
3673 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3674 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3676 // If we had a comparison against a fractional value, we have to adjust
3677 // the compare predicate and sometimes the value. RHSC is rounded towards
3678 // zero at this point.
3680 default: llvm_unreachable("Unexpected integer comparison!");
3681 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
3682 return ReplaceInstUsesWith(I, Builder->getTrue());
3683 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
3684 return ReplaceInstUsesWith(I, Builder->getFalse());
3685 case ICmpInst::ICMP_ULE:
3686 // (float)int <= 4.4 --> int <= 4
3687 // (float)int <= -4.4 --> false
3688 if (RHS.isNegative())
3689 return ReplaceInstUsesWith(I, Builder->getFalse());
3691 case ICmpInst::ICMP_SLE:
3692 // (float)int <= 4.4 --> int <= 4
3693 // (float)int <= -4.4 --> int < -4
3694 if (RHS.isNegative())
3695 Pred = ICmpInst::ICMP_SLT;
3697 case ICmpInst::ICMP_ULT:
3698 // (float)int < -4.4 --> false
3699 // (float)int < 4.4 --> int <= 4
3700 if (RHS.isNegative())
3701 return ReplaceInstUsesWith(I, Builder->getFalse());
3702 Pred = ICmpInst::ICMP_ULE;
3704 case ICmpInst::ICMP_SLT:
3705 // (float)int < -4.4 --> int < -4
3706 // (float)int < 4.4 --> int <= 4
3707 if (!RHS.isNegative())
3708 Pred = ICmpInst::ICMP_SLE;
3710 case ICmpInst::ICMP_UGT:
3711 // (float)int > 4.4 --> int > 4
3712 // (float)int > -4.4 --> true
3713 if (RHS.isNegative())
3714 return ReplaceInstUsesWith(I, Builder->getTrue());
3716 case ICmpInst::ICMP_SGT:
3717 // (float)int > 4.4 --> int > 4
3718 // (float)int > -4.4 --> int >= -4
3719 if (RHS.isNegative())
3720 Pred = ICmpInst::ICMP_SGE;
3722 case ICmpInst::ICMP_UGE:
3723 // (float)int >= -4.4 --> true
3724 // (float)int >= 4.4 --> int > 4
3725 if (RHS.isNegative())
3726 return ReplaceInstUsesWith(I, Builder->getTrue());
3727 Pred = ICmpInst::ICMP_UGT;
3729 case ICmpInst::ICMP_SGE:
3730 // (float)int >= -4.4 --> int >= -4
3731 // (float)int >= 4.4 --> int > 4
3732 if (!RHS.isNegative())
3733 Pred = ICmpInst::ICMP_SGT;
3739 // Lower this FP comparison into an appropriate integer version of the
3741 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3744 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3745 bool Changed = false;
3747 /// Orders the operands of the compare so that they are listed from most
3748 /// complex to least complex. This puts constants before unary operators,
3749 /// before binary operators.
3750 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3755 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3757 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AT))
3758 return ReplaceInstUsesWith(I, V);
3760 // Simplify 'fcmp pred X, X'
3762 switch (I.getPredicate()) {
3763 default: llvm_unreachable("Unknown predicate!");
3764 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3765 case FCmpInst::FCMP_ULT: // True if unordered or less than
3766 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3767 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3768 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3769 I.setPredicate(FCmpInst::FCMP_UNO);
3770 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3773 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3774 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3775 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3776 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3777 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3778 I.setPredicate(FCmpInst::FCMP_ORD);
3779 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3784 // Handle fcmp with constant RHS
3785 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3786 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3787 switch (LHSI->getOpcode()) {
3788 case Instruction::FPExt: {
3789 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3790 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3791 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3795 const fltSemantics *Sem;
3796 // FIXME: This shouldn't be here.
3797 if (LHSExt->getSrcTy()->isHalfTy())
3798 Sem = &APFloat::IEEEhalf;
3799 else if (LHSExt->getSrcTy()->isFloatTy())
3800 Sem = &APFloat::IEEEsingle;
3801 else if (LHSExt->getSrcTy()->isDoubleTy())
3802 Sem = &APFloat::IEEEdouble;
3803 else if (LHSExt->getSrcTy()->isFP128Ty())
3804 Sem = &APFloat::IEEEquad;
3805 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3806 Sem = &APFloat::x87DoubleExtended;
3807 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3808 Sem = &APFloat::PPCDoubleDouble;
3813 APFloat F = RHSF->getValueAPF();
3814 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3816 // Avoid lossy conversions and denormals. Zero is a special case
3817 // that's OK to convert.
3821 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3822 APFloat::cmpLessThan) || Fabs.isZero()))
3824 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3825 ConstantFP::get(RHSC->getContext(), F));
3828 case Instruction::PHI:
3829 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3830 // block. If in the same block, we're encouraging jump threading. If
3831 // not, we are just pessimizing the code by making an i1 phi.
3832 if (LHSI->getParent() == I.getParent())
3833 if (Instruction *NV = FoldOpIntoPhi(I))
3836 case Instruction::SIToFP:
3837 case Instruction::UIToFP:
3838 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3841 case Instruction::FSub: {
3842 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3844 if (match(LHSI, m_FNeg(m_Value(Op))))
3845 return new FCmpInst(I.getSwappedPredicate(), Op,
3846 ConstantExpr::getFNeg(RHSC));
3849 case Instruction::Load:
3850 if (GetElementPtrInst *GEP =
3851 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3852 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3853 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3854 !cast<LoadInst>(LHSI)->isVolatile())
3855 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3859 case Instruction::Call: {
3860 CallInst *CI = cast<CallInst>(LHSI);
3862 // Various optimization for fabs compared with zero.
3863 if (RHSC->isNullValue() && CI->getCalledFunction() &&
3864 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3866 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3867 Func == LibFunc::fabsl) {
3868 switch (I.getPredicate()) {
3870 // fabs(x) < 0 --> false
3871 case FCmpInst::FCMP_OLT:
3872 return ReplaceInstUsesWith(I, Builder->getFalse());
3873 // fabs(x) > 0 --> x != 0
3874 case FCmpInst::FCMP_OGT:
3875 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3877 // fabs(x) <= 0 --> x == 0
3878 case FCmpInst::FCMP_OLE:
3879 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3881 // fabs(x) >= 0 --> !isnan(x)
3882 case FCmpInst::FCMP_OGE:
3883 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3885 // fabs(x) == 0 --> x == 0
3886 // fabs(x) != 0 --> x != 0
3887 case FCmpInst::FCMP_OEQ:
3888 case FCmpInst::FCMP_UEQ:
3889 case FCmpInst::FCMP_ONE:
3890 case FCmpInst::FCMP_UNE:
3891 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3900 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
3902 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
3903 return new FCmpInst(I.getSwappedPredicate(), X, Y);
3905 // fcmp (fpext x), (fpext y) -> fcmp x, y
3906 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3907 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3908 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3909 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3910 RHSExt->getOperand(0));
3912 return Changed ? &I : nullptr;