1 //===- InstCombineCompares.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitICmp and visitFCmp functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/CaptureTracking.h"
18 #include "llvm/Analysis/CmpInstAnalysis.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/VectorUtils.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/Support/KnownBits.h"
28 #include "llvm/Transforms/InstCombine/InstCombiner.h"
29 
30 using namespace llvm;
31 using namespace PatternMatch;
32 
33 #define DEBUG_TYPE "instcombine"
34 
35 // How many times is a select replaced by one of its operands?
36 STATISTIC(NumSel, "Number of select opts");
37 
38 
39 /// Compute Result = In1+In2, returning true if the result overflowed for this
40 /// type.
41 static bool addWithOverflow(APInt &Result, const APInt &In1,
42                             const APInt &In2, bool IsSigned = false) {
43   bool Overflow;
44   if (IsSigned)
45     Result = In1.sadd_ov(In2, Overflow);
46   else
47     Result = In1.uadd_ov(In2, Overflow);
48 
49   return Overflow;
50 }
51 
52 /// Compute Result = In1-In2, returning true if the result overflowed for this
53 /// type.
54 static bool subWithOverflow(APInt &Result, const APInt &In1,
55                             const APInt &In2, bool IsSigned = false) {
56   bool Overflow;
57   if (IsSigned)
58     Result = In1.ssub_ov(In2, Overflow);
59   else
60     Result = In1.usub_ov(In2, Overflow);
61 
62   return Overflow;
63 }
64 
65 /// Given an icmp instruction, return true if any use of this comparison is a
66 /// branch on sign bit comparison.
67 static bool hasBranchUse(ICmpInst &I) {
68   for (auto *U : I.users())
69     if (isa<BranchInst>(U))
70       return true;
71   return false;
72 }
73 
74 /// Returns true if the exploded icmp can be expressed as a signed comparison
75 /// to zero and updates the predicate accordingly.
76 /// The signedness of the comparison is preserved.
77 /// TODO: Refactor with decomposeBitTestICmp()?
78 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
79   if (!ICmpInst::isSigned(Pred))
80     return false;
81 
82   if (C.isZero())
83     return ICmpInst::isRelational(Pred);
84 
85   if (C.isOne()) {
86     if (Pred == ICmpInst::ICMP_SLT) {
87       Pred = ICmpInst::ICMP_SLE;
88       return true;
89     }
90   } else if (C.isAllOnes()) {
91     if (Pred == ICmpInst::ICMP_SGT) {
92       Pred = ICmpInst::ICMP_SGE;
93       return true;
94     }
95   }
96 
97   return false;
98 }
99 
100 /// This is called when we see this pattern:
101 ///   cmp pred (load (gep GV, ...)), cmpcst
102 /// where GV is a global variable with a constant initializer. Try to simplify
103 /// this into some simple computation that does not need the load. For example
104 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
105 ///
106 /// If AndCst is non-null, then the loaded value is masked with that constant
107 /// before doing the comparison. This handles cases like "A[i]&4 == 0".
108 Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
109     LoadInst *LI, GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI,
110     ConstantInt *AndCst) {
111   if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||
112       GV->getValueType() != GEP->getSourceElementType() ||
113       !GV->isConstant() || !GV->hasDefinitiveInitializer())
114     return nullptr;
115 
116   Constant *Init = GV->getInitializer();
117   if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
118     return nullptr;
119 
120   uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
121   // Don't blow up on huge arrays.
122   if (ArrayElementCount > MaxArraySizeForCombine)
123     return nullptr;
124 
125   // There are many forms of this optimization we can handle, for now, just do
126   // the simple index into a single-dimensional array.
127   //
128   // Require: GEP GV, 0, i {{, constant indices}}
129   if (GEP->getNumOperands() < 3 ||
130       !isa<ConstantInt>(GEP->getOperand(1)) ||
131       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
132       isa<Constant>(GEP->getOperand(2)))
133     return nullptr;
134 
135   // Check that indices after the variable are constants and in-range for the
136   // type they index.  Collect the indices.  This is typically for arrays of
137   // structs.
138   SmallVector<unsigned, 4> LaterIndices;
139 
140   Type *EltTy = Init->getType()->getArrayElementType();
141   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
142     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
143     if (!Idx) return nullptr;  // Variable index.
144 
145     uint64_t IdxVal = Idx->getZExtValue();
146     if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
147 
148     if (StructType *STy = dyn_cast<StructType>(EltTy))
149       EltTy = STy->getElementType(IdxVal);
150     else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
151       if (IdxVal >= ATy->getNumElements()) return nullptr;
152       EltTy = ATy->getElementType();
153     } else {
154       return nullptr; // Unknown type.
155     }
156 
157     LaterIndices.push_back(IdxVal);
158   }
159 
160   enum { Overdefined = -3, Undefined = -2 };
161 
162   // Variables for our state machines.
163 
164   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
165   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
166   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
167   // undefined, otherwise set to the first true element.  SecondTrueElement is
168   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
169   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
170 
171   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
172   // form "i != 47 & i != 87".  Same state transitions as for true elements.
173   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
174 
175   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
176   /// define a state machine that triggers for ranges of values that the index
177   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
178   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
179   /// index in the range (inclusive).  We use -2 for undefined here because we
180   /// use relative comparisons and don't want 0-1 to match -1.
181   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
182 
183   // MagicBitvector - This is a magic bitvector where we set a bit if the
184   // comparison is true for element 'i'.  If there are 64 elements or less in
185   // the array, this will fully represent all the comparison results.
186   uint64_t MagicBitvector = 0;
187 
188   // Scan the array and see if one of our patterns matches.
189   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
190   for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
191     Constant *Elt = Init->getAggregateElement(i);
192     if (!Elt) return nullptr;
193 
194     // If this is indexing an array of structures, get the structure element.
195     if (!LaterIndices.empty()) {
196       Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices);
197       if (!Elt)
198         return nullptr;
199     }
200 
201     // If the element is masked, handle it.
202     if (AndCst) {
203       Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
204       if (!Elt)
205         return nullptr;
206     }
207 
208     // Find out if the comparison would be true or false for the i'th element.
209     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
210                                                   CompareRHS, DL, &TLI);
211     // If the result is undef for this element, ignore it.
212     if (isa<UndefValue>(C)) {
213       // Extend range state machines to cover this element in case there is an
214       // undef in the middle of the range.
215       if (TrueRangeEnd == (int)i-1)
216         TrueRangeEnd = i;
217       if (FalseRangeEnd == (int)i-1)
218         FalseRangeEnd = i;
219       continue;
220     }
221 
222     // If we can't compute the result for any of the elements, we have to give
223     // up evaluating the entire conditional.
224     if (!isa<ConstantInt>(C)) return nullptr;
225 
226     // Otherwise, we know if the comparison is true or false for this element,
227     // update our state machines.
228     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
229 
230     // State machine for single/double/range index comparison.
231     if (IsTrueForElt) {
232       // Update the TrueElement state machine.
233       if (FirstTrueElement == Undefined)
234         FirstTrueElement = TrueRangeEnd = i;  // First true element.
235       else {
236         // Update double-compare state machine.
237         if (SecondTrueElement == Undefined)
238           SecondTrueElement = i;
239         else
240           SecondTrueElement = Overdefined;
241 
242         // Update range state machine.
243         if (TrueRangeEnd == (int)i-1)
244           TrueRangeEnd = i;
245         else
246           TrueRangeEnd = Overdefined;
247       }
248     } else {
249       // Update the FalseElement state machine.
250       if (FirstFalseElement == Undefined)
251         FirstFalseElement = FalseRangeEnd = i; // First false element.
252       else {
253         // Update double-compare state machine.
254         if (SecondFalseElement == Undefined)
255           SecondFalseElement = i;
256         else
257           SecondFalseElement = Overdefined;
258 
259         // Update range state machine.
260         if (FalseRangeEnd == (int)i-1)
261           FalseRangeEnd = i;
262         else
263           FalseRangeEnd = Overdefined;
264       }
265     }
266 
267     // If this element is in range, update our magic bitvector.
268     if (i < 64 && IsTrueForElt)
269       MagicBitvector |= 1ULL << i;
270 
271     // If all of our states become overdefined, bail out early.  Since the
272     // predicate is expensive, only check it every 8 elements.  This is only
273     // really useful for really huge arrays.
274     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
275         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
276         FalseRangeEnd == Overdefined)
277       return nullptr;
278   }
279 
280   // Now that we've scanned the entire array, emit our new comparison(s).  We
281   // order the state machines in complexity of the generated code.
282   Value *Idx = GEP->getOperand(2);
283 
284   // If the index is larger than the pointer offset size of the target, truncate
285   // the index down like the GEP would do implicitly.  We don't have to do this
286   // for an inbounds GEP because the index can't be out of range.
287   if (!GEP->isInBounds()) {
288     Type *PtrIdxTy = DL.getIndexType(GEP->getType());
289     unsigned OffsetSize = PtrIdxTy->getIntegerBitWidth();
290     if (Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > OffsetSize)
291       Idx = Builder.CreateTrunc(Idx, PtrIdxTy);
292   }
293 
294   // If inbounds keyword is not present, Idx * ElementSize can overflow.
295   // Let's assume that ElementSize is 2 and the wanted value is at offset 0.
296   // Then, there are two possible values for Idx to match offset 0:
297   // 0x00..00, 0x80..00.
298   // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
299   // comparison is false if Idx was 0x80..00.
300   // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
301   unsigned ElementSize =
302       DL.getTypeAllocSize(Init->getType()->getArrayElementType());
303   auto MaskIdx = [&](Value *Idx) {
304     if (!GEP->isInBounds() && llvm::countr_zero(ElementSize) != 0) {
305       Value *Mask = ConstantInt::get(Idx->getType(), -1);
306       Mask = Builder.CreateLShr(Mask, llvm::countr_zero(ElementSize));
307       Idx = Builder.CreateAnd(Idx, Mask);
308     }
309     return Idx;
310   };
311 
312   // If the comparison is only true for one or two elements, emit direct
313   // comparisons.
314   if (SecondTrueElement != Overdefined) {
315     Idx = MaskIdx(Idx);
316     // None true -> false.
317     if (FirstTrueElement == Undefined)
318       return replaceInstUsesWith(ICI, Builder.getFalse());
319 
320     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
321 
322     // True for one element -> 'i == 47'.
323     if (SecondTrueElement == Undefined)
324       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
325 
326     // True for two elements -> 'i == 47 | i == 72'.
327     Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
328     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
329     Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
330     return BinaryOperator::CreateOr(C1, C2);
331   }
332 
333   // If the comparison is only false for one or two elements, emit direct
334   // comparisons.
335   if (SecondFalseElement != Overdefined) {
336     Idx = MaskIdx(Idx);
337     // None false -> true.
338     if (FirstFalseElement == Undefined)
339       return replaceInstUsesWith(ICI, Builder.getTrue());
340 
341     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
342 
343     // False for one element -> 'i != 47'.
344     if (SecondFalseElement == Undefined)
345       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
346 
347     // False for two elements -> 'i != 47 & i != 72'.
348     Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
349     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
350     Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
351     return BinaryOperator::CreateAnd(C1, C2);
352   }
353 
354   // If the comparison can be replaced with a range comparison for the elements
355   // where it is true, emit the range check.
356   if (TrueRangeEnd != Overdefined) {
357     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
358     Idx = MaskIdx(Idx);
359 
360     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
361     if (FirstTrueElement) {
362       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
363       Idx = Builder.CreateAdd(Idx, Offs);
364     }
365 
366     Value *End = ConstantInt::get(Idx->getType(),
367                                   TrueRangeEnd-FirstTrueElement+1);
368     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
369   }
370 
371   // False range check.
372   if (FalseRangeEnd != Overdefined) {
373     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
374     Idx = MaskIdx(Idx);
375     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
376     if (FirstFalseElement) {
377       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
378       Idx = Builder.CreateAdd(Idx, Offs);
379     }
380 
381     Value *End = ConstantInt::get(Idx->getType(),
382                                   FalseRangeEnd-FirstFalseElement);
383     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
384   }
385 
386   // If a magic bitvector captures the entire comparison state
387   // of this load, replace it with computation that does:
388   //   ((magic_cst >> i) & 1) != 0
389   {
390     Type *Ty = nullptr;
391 
392     // Look for an appropriate type:
393     // - The type of Idx if the magic fits
394     // - The smallest fitting legal type
395     if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
396       Ty = Idx->getType();
397     else
398       Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
399 
400     if (Ty) {
401       Idx = MaskIdx(Idx);
402       Value *V = Builder.CreateIntCast(Idx, Ty, false);
403       V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
404       V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
405       return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
406     }
407   }
408 
409   return nullptr;
410 }
411 
412 /// Returns true if we can rewrite Start as a GEP with pointer Base
413 /// and some integer offset. The nodes that need to be re-written
414 /// for this transformation will be added to Explored.
415 static bool canRewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
416                                   const DataLayout &DL,
417                                   SetVector<Value *> &Explored) {
418   SmallVector<Value *, 16> WorkList(1, Start);
419   Explored.insert(Base);
420 
421   // The following traversal gives us an order which can be used
422   // when doing the final transformation. Since in the final
423   // transformation we create the PHI replacement instructions first,
424   // we don't have to get them in any particular order.
425   //
426   // However, for other instructions we will have to traverse the
427   // operands of an instruction first, which means that we have to
428   // do a post-order traversal.
429   while (!WorkList.empty()) {
430     SetVector<PHINode *> PHIs;
431 
432     while (!WorkList.empty()) {
433       if (Explored.size() >= 100)
434         return false;
435 
436       Value *V = WorkList.back();
437 
438       if (Explored.contains(V)) {
439         WorkList.pop_back();
440         continue;
441       }
442 
443       if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
444           !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
445         // We've found some value that we can't explore which is different from
446         // the base. Therefore we can't do this transformation.
447         return false;
448 
449       if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
450         auto *CI = cast<CastInst>(V);
451         if (!CI->isNoopCast(DL))
452           return false;
453 
454         if (!Explored.contains(CI->getOperand(0)))
455           WorkList.push_back(CI->getOperand(0));
456       }
457 
458       if (auto *GEP = dyn_cast<GEPOperator>(V)) {
459         // We're limiting the GEP to having one index. This will preserve
460         // the original pointer type. We could handle more cases in the
461         // future.
462         if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
463             GEP->getSourceElementType() != ElemTy)
464           return false;
465 
466         if (!Explored.contains(GEP->getOperand(0)))
467           WorkList.push_back(GEP->getOperand(0));
468       }
469 
470       if (WorkList.back() == V) {
471         WorkList.pop_back();
472         // We've finished visiting this node, mark it as such.
473         Explored.insert(V);
474       }
475 
476       if (auto *PN = dyn_cast<PHINode>(V)) {
477         // We cannot transform PHIs on unsplittable basic blocks.
478         if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
479           return false;
480         Explored.insert(PN);
481         PHIs.insert(PN);
482       }
483     }
484 
485     // Explore the PHI nodes further.
486     for (auto *PN : PHIs)
487       for (Value *Op : PN->incoming_values())
488         if (!Explored.contains(Op))
489           WorkList.push_back(Op);
490   }
491 
492   // Make sure that we can do this. Since we can't insert GEPs in a basic
493   // block before a PHI node, we can't easily do this transformation if
494   // we have PHI node users of transformed instructions.
495   for (Value *Val : Explored) {
496     for (Value *Use : Val->uses()) {
497 
498       auto *PHI = dyn_cast<PHINode>(Use);
499       auto *Inst = dyn_cast<Instruction>(Val);
500 
501       if (Inst == Base || Inst == PHI || !Inst || !PHI ||
502           !Explored.contains(PHI))
503         continue;
504 
505       if (PHI->getParent() == Inst->getParent())
506         return false;
507     }
508   }
509   return true;
510 }
511 
512 // Sets the appropriate insert point on Builder where we can add
513 // a replacement Instruction for V (if that is possible).
514 static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
515                               bool Before = true) {
516   if (auto *PHI = dyn_cast<PHINode>(V)) {
517     Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
518     return;
519   }
520   if (auto *I = dyn_cast<Instruction>(V)) {
521     if (!Before)
522       I = &*std::next(I->getIterator());
523     Builder.SetInsertPoint(I);
524     return;
525   }
526   if (auto *A = dyn_cast<Argument>(V)) {
527     // Set the insertion point in the entry block.
528     BasicBlock &Entry = A->getParent()->getEntryBlock();
529     Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
530     return;
531   }
532   // Otherwise, this is a constant and we don't need to set a new
533   // insertion point.
534   assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
535 }
536 
537 /// Returns a re-written value of Start as an indexed GEP using Base as a
538 /// pointer.
539 static Value *rewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
540                                  const DataLayout &DL,
541                                  SetVector<Value *> &Explored,
542                                  InstCombiner &IC) {
543   // Perform all the substitutions. This is a bit tricky because we can
544   // have cycles in our use-def chains.
545   // 1. Create the PHI nodes without any incoming values.
546   // 2. Create all the other values.
547   // 3. Add the edges for the PHI nodes.
548   // 4. Emit GEPs to get the original pointers.
549   // 5. Remove the original instructions.
550   Type *IndexType = IntegerType::get(
551       Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
552 
553   DenseMap<Value *, Value *> NewInsts;
554   NewInsts[Base] = ConstantInt::getNullValue(IndexType);
555 
556   // Create the new PHI nodes, without adding any incoming values.
557   for (Value *Val : Explored) {
558     if (Val == Base)
559       continue;
560     // Create empty phi nodes. This avoids cyclic dependencies when creating
561     // the remaining instructions.
562     if (auto *PHI = dyn_cast<PHINode>(Val))
563       NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
564                                       PHI->getName() + ".idx", PHI);
565   }
566   IRBuilder<> Builder(Base->getContext());
567 
568   // Create all the other instructions.
569   for (Value *Val : Explored) {
570 
571     if (NewInsts.contains(Val))
572       continue;
573 
574     if (auto *CI = dyn_cast<CastInst>(Val)) {
575       // Don't get rid of the intermediate variable here; the store can grow
576       // the map which will invalidate the reference to the input value.
577       Value *V = NewInsts[CI->getOperand(0)];
578       NewInsts[CI] = V;
579       continue;
580     }
581     if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
582       Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
583                                                   : GEP->getOperand(1);
584       setInsertionPoint(Builder, GEP);
585       // Indices might need to be sign extended. GEPs will magically do
586       // this, but we need to do it ourselves here.
587       if (Index->getType()->getScalarSizeInBits() !=
588           NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
589         Index = Builder.CreateSExtOrTrunc(
590             Index, NewInsts[GEP->getOperand(0)]->getType(),
591             GEP->getOperand(0)->getName() + ".sext");
592       }
593 
594       auto *Op = NewInsts[GEP->getOperand(0)];
595       if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
596         NewInsts[GEP] = Index;
597       else
598         NewInsts[GEP] = Builder.CreateNSWAdd(
599             Op, Index, GEP->getOperand(0)->getName() + ".add");
600       continue;
601     }
602     if (isa<PHINode>(Val))
603       continue;
604 
605     llvm_unreachable("Unexpected instruction type");
606   }
607 
608   // Add the incoming values to the PHI nodes.
609   for (Value *Val : Explored) {
610     if (Val == Base)
611       continue;
612     // All the instructions have been created, we can now add edges to the
613     // phi nodes.
614     if (auto *PHI = dyn_cast<PHINode>(Val)) {
615       PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
616       for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
617         Value *NewIncoming = PHI->getIncomingValue(I);
618 
619         if (NewInsts.contains(NewIncoming))
620           NewIncoming = NewInsts[NewIncoming];
621 
622         NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
623       }
624     }
625   }
626 
627   PointerType *PtrTy =
628       ElemTy->getPointerTo(Start->getType()->getPointerAddressSpace());
629   for (Value *Val : Explored) {
630     if (Val == Base)
631       continue;
632 
633     // Depending on the type, for external users we have to emit
634     // a GEP or a GEP + ptrtoint.
635     setInsertionPoint(Builder, Val, false);
636 
637     // Cast base to the expected type.
638     Value *NewVal = Builder.CreateBitOrPointerCast(
639         Base, PtrTy, Start->getName() + "to.ptr");
640     NewVal = Builder.CreateInBoundsGEP(ElemTy, NewVal, ArrayRef(NewInsts[Val]),
641                                        Val->getName() + ".ptr");
642     NewVal = Builder.CreateBitOrPointerCast(
643         NewVal, Val->getType(), Val->getName() + ".conv");
644     IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
645     // Add old instruction to worklist for DCE. We don't directly remove it
646     // here because the original compare is one of the users.
647     IC.addToWorklist(cast<Instruction>(Val));
648   }
649 
650   return NewInsts[Start];
651 }
652 
653 /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
654 /// the input Value as a constant indexed GEP. Returns a pair containing
655 /// the GEPs Pointer and Index.
656 static std::pair<Value *, Value *>
657 getAsConstantIndexedAddress(Type *ElemTy, Value *V, const DataLayout &DL) {
658   Type *IndexType = IntegerType::get(V->getContext(),
659                                      DL.getIndexTypeSizeInBits(V->getType()));
660 
661   Constant *Index = ConstantInt::getNullValue(IndexType);
662   while (true) {
663     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
664       // We accept only inbouds GEPs here to exclude the possibility of
665       // overflow.
666       if (!GEP->isInBounds())
667         break;
668       if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
669           GEP->getSourceElementType() == ElemTy) {
670         V = GEP->getOperand(0);
671         Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
672         Index = ConstantExpr::getAdd(
673             Index, ConstantExpr::getSExtOrTrunc(GEPIndex, IndexType));
674         continue;
675       }
676       break;
677     }
678     if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
679       if (!CI->isNoopCast(DL))
680         break;
681       V = CI->getOperand(0);
682       continue;
683     }
684     if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
685       if (!CI->isNoopCast(DL))
686         break;
687       V = CI->getOperand(0);
688       continue;
689     }
690     break;
691   }
692   return {V, Index};
693 }
694 
695 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
696 /// We can look through PHIs, GEPs and casts in order to determine a common base
697 /// between GEPLHS and RHS.
698 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
699                                               ICmpInst::Predicate Cond,
700                                               const DataLayout &DL,
701                                               InstCombiner &IC) {
702   // FIXME: Support vector of pointers.
703   if (GEPLHS->getType()->isVectorTy())
704     return nullptr;
705 
706   if (!GEPLHS->hasAllConstantIndices())
707     return nullptr;
708 
709   Type *ElemTy = GEPLHS->getSourceElementType();
710   Value *PtrBase, *Index;
711   std::tie(PtrBase, Index) = getAsConstantIndexedAddress(ElemTy, GEPLHS, DL);
712 
713   // The set of nodes that will take part in this transformation.
714   SetVector<Value *> Nodes;
715 
716   if (!canRewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes))
717     return nullptr;
718 
719   // We know we can re-write this as
720   //  ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
721   // Since we've only looked through inbouds GEPs we know that we
722   // can't have overflow on either side. We can therefore re-write
723   // this as:
724   //   OFFSET1 cmp OFFSET2
725   Value *NewRHS = rewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes, IC);
726 
727   // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
728   // GEP having PtrBase as the pointer base, and has returned in NewRHS the
729   // offset. Since Index is the offset of LHS to the base pointer, we will now
730   // compare the offsets instead of comparing the pointers.
731   return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
732 }
733 
734 /// Fold comparisons between a GEP instruction and something else. At this point
735 /// we know that the GEP is on the LHS of the comparison.
736 Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
737                                            ICmpInst::Predicate Cond,
738                                            Instruction &I) {
739   // Don't transform signed compares of GEPs into index compares. Even if the
740   // GEP is inbounds, the final add of the base pointer can have signed overflow
741   // and would change the result of the icmp.
742   // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
743   // the maximum signed value for the pointer type.
744   if (ICmpInst::isSigned(Cond))
745     return nullptr;
746 
747   // Look through bitcasts and addrspacecasts. We do not however want to remove
748   // 0 GEPs.
749   if (!isa<GetElementPtrInst>(RHS))
750     RHS = RHS->stripPointerCasts();
751 
752   Value *PtrBase = GEPLHS->getOperand(0);
753   if (PtrBase == RHS && (GEPLHS->isInBounds() || ICmpInst::isEquality(Cond))) {
754     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
755     Value *Offset = EmitGEPOffset(GEPLHS);
756     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
757                         Constant::getNullValue(Offset->getType()));
758   }
759 
760   if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
761       isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
762       !NullPointerIsDefined(I.getFunction(),
763                             RHS->getType()->getPointerAddressSpace())) {
764     // For most address spaces, an allocation can't be placed at null, but null
765     // itself is treated as a 0 size allocation in the in bounds rules.  Thus,
766     // the only valid inbounds address derived from null, is null itself.
767     // Thus, we have four cases to consider:
768     // 1) Base == nullptr, Offset == 0 -> inbounds, null
769     // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
770     // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
771     // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
772     //
773     // (Note if we're indexing a type of size 0, that simply collapses into one
774     //  of the buckets above.)
775     //
776     // In general, we're allowed to make values less poison (i.e. remove
777     //   sources of full UB), so in this case, we just select between the two
778     //   non-poison cases (1 and 4 above).
779     //
780     // For vectors, we apply the same reasoning on a per-lane basis.
781     auto *Base = GEPLHS->getPointerOperand();
782     if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
783       auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
784       Base = Builder.CreateVectorSplat(EC, Base);
785     }
786     return new ICmpInst(Cond, Base,
787                         ConstantExpr::getPointerBitCastOrAddrSpaceCast(
788                             cast<Constant>(RHS), Base->getType()));
789   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
790     // If the base pointers are different, but the indices are the same, just
791     // compare the base pointer.
792     if (PtrBase != GEPRHS->getOperand(0)) {
793       bool IndicesTheSame =
794           GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
795           GEPLHS->getPointerOperand()->getType() ==
796               GEPRHS->getPointerOperand()->getType() &&
797           GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
798       if (IndicesTheSame)
799         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
800           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
801             IndicesTheSame = false;
802             break;
803           }
804 
805       // If all indices are the same, just compare the base pointers.
806       Type *BaseType = GEPLHS->getOperand(0)->getType();
807       if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
808         return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
809 
810       // If we're comparing GEPs with two base pointers that only differ in type
811       // and both GEPs have only constant indices or just one use, then fold
812       // the compare with the adjusted indices.
813       // FIXME: Support vector of pointers.
814       if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
815           (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
816           (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
817           PtrBase->stripPointerCasts() ==
818               GEPRHS->getOperand(0)->stripPointerCasts() &&
819           !GEPLHS->getType()->isVectorTy()) {
820         Value *LOffset = EmitGEPOffset(GEPLHS);
821         Value *ROffset = EmitGEPOffset(GEPRHS);
822 
823         // If we looked through an addrspacecast between different sized address
824         // spaces, the LHS and RHS pointers are different sized
825         // integers. Truncate to the smaller one.
826         Type *LHSIndexTy = LOffset->getType();
827         Type *RHSIndexTy = ROffset->getType();
828         if (LHSIndexTy != RHSIndexTy) {
829           if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
830               RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
831             ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
832           } else
833             LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
834         }
835 
836         Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),
837                                         LOffset, ROffset);
838         return replaceInstUsesWith(I, Cmp);
839       }
840 
841       // Otherwise, the base pointers are different and the indices are
842       // different. Try convert this to an indexed compare by looking through
843       // PHIs/casts.
844       return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
845     }
846 
847     // If one of the GEPs has all zero indices, recurse.
848     // FIXME: Handle vector of pointers.
849     if (!GEPLHS->getType()->isVectorTy() && GEPLHS->hasAllZeroIndices())
850       return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
851                          ICmpInst::getSwappedPredicate(Cond), I);
852 
853     // If the other GEP has all zero indices, recurse.
854     // FIXME: Handle vector of pointers.
855     if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices())
856       return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
857 
858     bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
859     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
860         GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
861       // If the GEPs only differ by one index, compare it.
862       unsigned NumDifferences = 0;  // Keep track of # differences.
863       unsigned DiffOperand = 0;     // The operand that differs.
864       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
865         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
866           Type *LHSType = GEPLHS->getOperand(i)->getType();
867           Type *RHSType = GEPRHS->getOperand(i)->getType();
868           // FIXME: Better support for vector of pointers.
869           if (LHSType->getPrimitiveSizeInBits() !=
870                    RHSType->getPrimitiveSizeInBits() ||
871               (GEPLHS->getType()->isVectorTy() &&
872                (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
873             // Irreconcilable differences.
874             NumDifferences = 2;
875             break;
876           }
877 
878           if (NumDifferences++) break;
879           DiffOperand = i;
880         }
881 
882       if (NumDifferences == 0)   // SAME GEP?
883         return replaceInstUsesWith(I, // No comparison is needed here.
884           ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
885 
886       else if (NumDifferences == 1 && GEPsInBounds) {
887         Value *LHSV = GEPLHS->getOperand(DiffOperand);
888         Value *RHSV = GEPRHS->getOperand(DiffOperand);
889         // Make sure we do a signed comparison here.
890         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
891       }
892     }
893 
894     // Only lower this if the icmp is the only user of the GEP or if we expect
895     // the result to fold to a constant!
896     if ((GEPsInBounds || CmpInst::isEquality(Cond)) &&
897         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
898         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
899       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
900       Value *L = EmitGEPOffset(GEPLHS);
901       Value *R = EmitGEPOffset(GEPRHS);
902       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
903     }
904   }
905 
906   // Try convert this to an indexed compare by looking through PHIs/casts as a
907   // last resort.
908   return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
909 }
910 
911 bool InstCombinerImpl::foldAllocaCmp(AllocaInst *Alloca) {
912   // It would be tempting to fold away comparisons between allocas and any
913   // pointer not based on that alloca (e.g. an argument). However, even
914   // though such pointers cannot alias, they can still compare equal.
915   //
916   // But LLVM doesn't specify where allocas get their memory, so if the alloca
917   // doesn't escape we can argue that it's impossible to guess its value, and we
918   // can therefore act as if any such guesses are wrong.
919   //
920   // However, we need to ensure that this folding is consistent: We can't fold
921   // one comparison to false, and then leave a different comparison against the
922   // same value alone (as it might evaluate to true at runtime, leading to a
923   // contradiction). As such, this code ensures that all comparisons are folded
924   // at the same time, and there are no other escapes.
925 
926   struct CmpCaptureTracker : public CaptureTracker {
927     AllocaInst *Alloca;
928     bool Captured = false;
929     /// The value of the map is a bit mask of which icmp operands the alloca is
930     /// used in.
931     SmallMapVector<ICmpInst *, unsigned, 4> ICmps;
932 
933     CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
934 
935     void tooManyUses() override { Captured = true; }
936 
937     bool captured(const Use *U) override {
938       auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
939       // We need to check that U is based *only* on the alloca, and doesn't
940       // have other contributions from a select/phi operand.
941       // TODO: We could check whether getUnderlyingObjects() reduces to one
942       // object, which would allow looking through phi nodes.
943       if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
944         // Collect equality icmps of the alloca, and don't treat them as
945         // captures.
946         auto Res = ICmps.insert({ICmp, 0});
947         Res.first->second |= 1u << U->getOperandNo();
948         return false;
949       }
950 
951       Captured = true;
952       return true;
953     }
954   };
955 
956   CmpCaptureTracker Tracker(Alloca);
957   PointerMayBeCaptured(Alloca, &Tracker);
958   if (Tracker.Captured)
959     return false;
960 
961   bool Changed = false;
962   for (auto [ICmp, Operands] : Tracker.ICmps) {
963     switch (Operands) {
964     case 1:
965     case 2: {
966       // The alloca is only used in one icmp operand. Assume that the
967       // equality is false.
968       auto *Res = ConstantInt::get(
969           ICmp->getType(), ICmp->getPredicate() == ICmpInst::ICMP_NE);
970       replaceInstUsesWith(*ICmp, Res);
971       eraseInstFromFunction(*ICmp);
972       Changed = true;
973       break;
974     }
975     case 3:
976       // Both icmp operands are based on the alloca, so this is comparing
977       // pointer offsets, without leaking any information about the address
978       // of the alloca. Ignore such comparisons.
979       break;
980     default:
981       llvm_unreachable("Cannot happen");
982     }
983   }
984 
985   return Changed;
986 }
987 
988 /// Fold "icmp pred (X+C), X".
989 Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
990                                                   ICmpInst::Predicate Pred) {
991   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
992   // so the values can never be equal.  Similarly for all other "or equals"
993   // operators.
994   assert(!!C && "C should not be zero!");
995 
996   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
997   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
998   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
999   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1000     Constant *R = ConstantInt::get(X->getType(),
1001                                    APInt::getMaxValue(C.getBitWidth()) - C);
1002     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1003   }
1004 
1005   // (X+1) >u X        --> X <u (0-1)        --> X != 255
1006   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
1007   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
1008   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
1009     return new ICmpInst(ICmpInst::ICMP_ULT, X,
1010                         ConstantInt::get(X->getType(), -C));
1011 
1012   APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
1013 
1014   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
1015   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
1016   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
1017   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
1018   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
1019   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
1020   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1021     return new ICmpInst(ICmpInst::ICMP_SGT, X,
1022                         ConstantInt::get(X->getType(), SMax - C));
1023 
1024   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
1025   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
1026   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1027   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1028   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
1029   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
1030 
1031   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
1032   return new ICmpInst(ICmpInst::ICMP_SLT, X,
1033                       ConstantInt::get(X->getType(), SMax - (C - 1)));
1034 }
1035 
1036 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1037 /// (icmp eq/ne A, Log2(AP2/AP1)) ->
1038 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
1039 Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
1040                                                      const APInt &AP1,
1041                                                      const APInt &AP2) {
1042   assert(I.isEquality() && "Cannot fold icmp gt/lt");
1043 
1044   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1045     if (I.getPredicate() == I.ICMP_NE)
1046       Pred = CmpInst::getInversePredicate(Pred);
1047     return new ICmpInst(Pred, LHS, RHS);
1048   };
1049 
1050   // Don't bother doing any work for cases which InstSimplify handles.
1051   if (AP2.isZero())
1052     return nullptr;
1053 
1054   bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1055   if (IsAShr) {
1056     if (AP2.isAllOnes())
1057       return nullptr;
1058     if (AP2.isNegative() != AP1.isNegative())
1059       return nullptr;
1060     if (AP2.sgt(AP1))
1061       return nullptr;
1062   }
1063 
1064   if (!AP1)
1065     // 'A' must be large enough to shift out the highest set bit.
1066     return getICmp(I.ICMP_UGT, A,
1067                    ConstantInt::get(A->getType(), AP2.logBase2()));
1068 
1069   if (AP1 == AP2)
1070     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1071 
1072   int Shift;
1073   if (IsAShr && AP1.isNegative())
1074     Shift = AP1.countl_one() - AP2.countl_one();
1075   else
1076     Shift = AP1.countl_zero() - AP2.countl_zero();
1077 
1078   if (Shift > 0) {
1079     if (IsAShr && AP1 == AP2.ashr(Shift)) {
1080       // There are multiple solutions if we are comparing against -1 and the LHS
1081       // of the ashr is not a power of two.
1082       if (AP1.isAllOnes() && !AP2.isPowerOf2())
1083         return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1084       return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1085     } else if (AP1 == AP2.lshr(Shift)) {
1086       return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1087     }
1088   }
1089 
1090   // Shifting const2 will never be equal to const1.
1091   // FIXME: This should always be handled by InstSimplify?
1092   auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1093   return replaceInstUsesWith(I, TorF);
1094 }
1095 
1096 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1097 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1098 Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
1099                                                      const APInt &AP1,
1100                                                      const APInt &AP2) {
1101   assert(I.isEquality() && "Cannot fold icmp gt/lt");
1102 
1103   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1104     if (I.getPredicate() == I.ICMP_NE)
1105       Pred = CmpInst::getInversePredicate(Pred);
1106     return new ICmpInst(Pred, LHS, RHS);
1107   };
1108 
1109   // Don't bother doing any work for cases which InstSimplify handles.
1110   if (AP2.isZero())
1111     return nullptr;
1112 
1113   unsigned AP2TrailingZeros = AP2.countr_zero();
1114 
1115   if (!AP1 && AP2TrailingZeros != 0)
1116     return getICmp(
1117         I.ICMP_UGE, A,
1118         ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1119 
1120   if (AP1 == AP2)
1121     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1122 
1123   // Get the distance between the lowest bits that are set.
1124   int Shift = AP1.countr_zero() - AP2TrailingZeros;
1125 
1126   if (Shift > 0 && AP2.shl(Shift) == AP1)
1127     return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1128 
1129   // Shifting const2 will never be equal to const1.
1130   // FIXME: This should always be handled by InstSimplify?
1131   auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1132   return replaceInstUsesWith(I, TorF);
1133 }
1134 
1135 /// The caller has matched a pattern of the form:
1136 ///   I = icmp ugt (add (add A, B), CI2), CI1
1137 /// If this is of the form:
1138 ///   sum = a + b
1139 ///   if (sum+128 >u 255)
1140 /// Then replace it with llvm.sadd.with.overflow.i8.
1141 ///
1142 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1143                                           ConstantInt *CI2, ConstantInt *CI1,
1144                                           InstCombinerImpl &IC) {
1145   // The transformation we're trying to do here is to transform this into an
1146   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1147   // with a narrower add, and discard the add-with-constant that is part of the
1148   // range check (if we can't eliminate it, this isn't profitable).
1149 
1150   // In order to eliminate the add-with-constant, the compare can be its only
1151   // use.
1152   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1153   if (!AddWithCst->hasOneUse())
1154     return nullptr;
1155 
1156   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1157   if (!CI2->getValue().isPowerOf2())
1158     return nullptr;
1159   unsigned NewWidth = CI2->getValue().countr_zero();
1160   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1161     return nullptr;
1162 
1163   // The width of the new add formed is 1 more than the bias.
1164   ++NewWidth;
1165 
1166   // Check to see that CI1 is an all-ones value with NewWidth bits.
1167   if (CI1->getBitWidth() == NewWidth ||
1168       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1169     return nullptr;
1170 
1171   // This is only really a signed overflow check if the inputs have been
1172   // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1173   // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1174   if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth ||
1175       IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth)
1176     return nullptr;
1177 
1178   // In order to replace the original add with a narrower
1179   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1180   // and truncates that discard the high bits of the add.  Verify that this is
1181   // the case.
1182   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1183   for (User *U : OrigAdd->users()) {
1184     if (U == AddWithCst)
1185       continue;
1186 
1187     // Only accept truncates for now.  We would really like a nice recursive
1188     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1189     // chain to see which bits of a value are actually demanded.  If the
1190     // original add had another add which was then immediately truncated, we
1191     // could still do the transformation.
1192     TruncInst *TI = dyn_cast<TruncInst>(U);
1193     if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1194       return nullptr;
1195   }
1196 
1197   // If the pattern matches, truncate the inputs to the narrower type and
1198   // use the sadd_with_overflow intrinsic to efficiently compute both the
1199   // result and the overflow bit.
1200   Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1201   Function *F = Intrinsic::getDeclaration(
1202       I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1203 
1204   InstCombiner::BuilderTy &Builder = IC.Builder;
1205 
1206   // Put the new code above the original add, in case there are any uses of the
1207   // add between the add and the compare.
1208   Builder.SetInsertPoint(OrigAdd);
1209 
1210   Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1211   Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1212   CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1213   Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1214   Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1215 
1216   // The inner add was the result of the narrow add, zero extended to the
1217   // wider type.  Replace it with the result computed by the intrinsic.
1218   IC.replaceInstUsesWith(*OrigAdd, ZExt);
1219   IC.eraseInstFromFunction(*OrigAdd);
1220 
1221   // The original icmp gets replaced with the overflow value.
1222   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1223 }
1224 
1225 /// If we have:
1226 ///   icmp eq/ne (urem/srem %x, %y), 0
1227 /// iff %y is a power-of-two, we can replace this with a bit test:
1228 ///   icmp eq/ne (and %x, (add %y, -1)), 0
1229 Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1230   // This fold is only valid for equality predicates.
1231   if (!I.isEquality())
1232     return nullptr;
1233   ICmpInst::Predicate Pred;
1234   Value *X, *Y, *Zero;
1235   if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1236                         m_CombineAnd(m_Zero(), m_Value(Zero)))))
1237     return nullptr;
1238   if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
1239     return nullptr;
1240   // This may increase instruction count, we don't enforce that Y is a constant.
1241   Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1242   Value *Masked = Builder.CreateAnd(X, Mask);
1243   return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1244 }
1245 
1246 /// Fold equality-comparison between zero and any (maybe truncated) right-shift
1247 /// by one-less-than-bitwidth into a sign test on the original value.
1248 Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
1249   Instruction *Val;
1250   ICmpInst::Predicate Pred;
1251   if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1252     return nullptr;
1253 
1254   Value *X;
1255   Type *XTy;
1256 
1257   Constant *C;
1258   if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1259     XTy = X->getType();
1260     unsigned XBitWidth = XTy->getScalarSizeInBits();
1261     if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1262                                      APInt(XBitWidth, XBitWidth - 1))))
1263       return nullptr;
1264   } else if (isa<BinaryOperator>(Val) &&
1265              (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1266                   cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1267                   /*AnalyzeForSignBitExtraction=*/true))) {
1268     XTy = X->getType();
1269   } else
1270     return nullptr;
1271 
1272   return ICmpInst::Create(Instruction::ICmp,
1273                           Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1274                                                     : ICmpInst::ICMP_SLT,
1275                           X, ConstantInt::getNullValue(XTy));
1276 }
1277 
1278 // Handle  icmp pred X, 0
1279 Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
1280   CmpInst::Predicate Pred = Cmp.getPredicate();
1281   if (!match(Cmp.getOperand(1), m_Zero()))
1282     return nullptr;
1283 
1284   // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1285   if (Pred == ICmpInst::ICMP_SGT) {
1286     Value *A, *B;
1287     if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1288       if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT))
1289         return new ICmpInst(Pred, B, Cmp.getOperand(1));
1290       if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT))
1291         return new ICmpInst(Pred, A, Cmp.getOperand(1));
1292     }
1293   }
1294 
1295   if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))
1296     return New;
1297 
1298   // Given:
1299   //   icmp eq/ne (urem %x, %y), 0
1300   // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1301   //   icmp eq/ne %x, 0
1302   Value *X, *Y;
1303   if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1304       ICmpInst::isEquality(Pred)) {
1305     KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1306     KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1307     if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1308       return new ICmpInst(Pred, X, Cmp.getOperand(1));
1309   }
1310 
1311   // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1312   // odd/non-zero/there is no overflow.
1313   if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1314       ICmpInst::isEquality(Pred)) {
1315 
1316     KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1317     // if X % 2 != 0
1318     //    (icmp eq/ne Y)
1319     if (XKnown.countMaxTrailingZeros() == 0)
1320       return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1321 
1322     KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1323     // if Y % 2 != 0
1324     //    (icmp eq/ne X)
1325     if (YKnown.countMaxTrailingZeros() == 0)
1326       return new ICmpInst(Pred, X, Cmp.getOperand(1));
1327 
1328     auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1329     if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1330       const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1331       // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1332       // but to avoid unnecessary work, first just if this is an obvious case.
1333 
1334       // if X non-zero and NoOverflow(X * Y)
1335       //    (icmp eq/ne Y)
1336       if (!XKnown.One.isZero() || isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
1337         return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1338 
1339       // if Y non-zero and NoOverflow(X * Y)
1340       //    (icmp eq/ne X)
1341       if (!YKnown.One.isZero() || isKnownNonZero(Y, DL, 0, Q.AC, Q.CxtI, Q.DT))
1342         return new ICmpInst(Pred, X, Cmp.getOperand(1));
1343     }
1344     // Note, we are skipping cases:
1345     //      if Y % 2 != 0 AND X % 2 != 0
1346     //          (false/true)
1347     //      if X non-zero and Y non-zero and NoOverflow(X * Y)
1348     //          (false/true)
1349     // Those can be simplified later as we would have already replaced the (icmp
1350     // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1351     // will fold to a constant elsewhere.
1352   }
1353   return nullptr;
1354 }
1355 
1356 /// Fold icmp Pred X, C.
1357 /// TODO: This code structure does not make sense. The saturating add fold
1358 /// should be moved to some other helper and extended as noted below (it is also
1359 /// possible that code has been made unnecessary - do we canonicalize IR to
1360 /// overflow/saturating intrinsics or not?).
1361 Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
1362   // Match the following pattern, which is a common idiom when writing
1363   // overflow-safe integer arithmetic functions. The source performs an addition
1364   // in wider type and explicitly checks for overflow using comparisons against
1365   // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1366   //
1367   // TODO: This could probably be generalized to handle other overflow-safe
1368   // operations if we worked out the formulas to compute the appropriate magic
1369   // constants.
1370   //
1371   // sum = a + b
1372   // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
1373   CmpInst::Predicate Pred = Cmp.getPredicate();
1374   Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1375   Value *A, *B;
1376   ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1377   if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1378       match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1379     if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1380       return Res;
1381 
1382   // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1383   Constant *C = dyn_cast<Constant>(Op1);
1384   if (!C)
1385     return nullptr;
1386 
1387   if (auto *Phi = dyn_cast<PHINode>(Op0))
1388     if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) {
1389       SmallVector<Constant *> Ops;
1390       for (Value *V : Phi->incoming_values()) {
1391         Constant *Res =
1392             ConstantFoldCompareInstOperands(Pred, cast<Constant>(V), C, DL);
1393         if (!Res)
1394           return nullptr;
1395         Ops.push_back(Res);
1396       }
1397       Builder.SetInsertPoint(Phi);
1398       PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1399       for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1400         NewPhi->addIncoming(V, Pred);
1401       return replaceInstUsesWith(Cmp, NewPhi);
1402     }
1403 
1404   return nullptr;
1405 }
1406 
1407 /// Canonicalize icmp instructions based on dominating conditions.
1408 Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1409   // This is a cheap/incomplete check for dominance - just match a single
1410   // predecessor with a conditional branch.
1411   BasicBlock *CmpBB = Cmp.getParent();
1412   BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1413   if (!DomBB)
1414     return nullptr;
1415 
1416   Value *DomCond;
1417   BasicBlock *TrueBB, *FalseBB;
1418   if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1419     return nullptr;
1420 
1421   assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
1422          "Predecessor block does not point to successor?");
1423 
1424   // The branch should get simplified. Don't bother simplifying this condition.
1425   if (TrueBB == FalseBB)
1426     return nullptr;
1427 
1428   // We already checked simple implication in InstSimplify, only handle complex
1429   // cases here.
1430 
1431   CmpInst::Predicate Pred = Cmp.getPredicate();
1432   Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1433   ICmpInst::Predicate DomPred;
1434   const APInt *C, *DomC;
1435   if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) &&
1436       match(Y, m_APInt(C))) {
1437     // We have 2 compares of a variable with constants. Calculate the constant
1438     // ranges of those compares to see if we can transform the 2nd compare:
1439     // DomBB:
1440     //   DomCond = icmp DomPred X, DomC
1441     //   br DomCond, CmpBB, FalseBB
1442     // CmpBB:
1443     //   Cmp = icmp Pred X, C
1444     ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, *C);
1445     ConstantRange DominatingCR =
1446         (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC)
1447                           : ConstantRange::makeExactICmpRegion(
1448                                 CmpInst::getInversePredicate(DomPred), *DomC);
1449     ConstantRange Intersection = DominatingCR.intersectWith(CR);
1450     ConstantRange Difference = DominatingCR.difference(CR);
1451     if (Intersection.isEmptySet())
1452       return replaceInstUsesWith(Cmp, Builder.getFalse());
1453     if (Difference.isEmptySet())
1454       return replaceInstUsesWith(Cmp, Builder.getTrue());
1455 
1456     // Canonicalizing a sign bit comparison that gets used in a branch,
1457     // pessimizes codegen by generating branch on zero instruction instead
1458     // of a test and branch. So we avoid canonicalizing in such situations
1459     // because test and branch instruction has better branch displacement
1460     // than compare and branch instruction.
1461     bool UnusedBit;
1462     bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1463     if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1464       return nullptr;
1465 
1466     // Avoid an infinite loop with min/max canonicalization.
1467     // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1468     if (Cmp.hasOneUse() &&
1469         match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1470       return nullptr;
1471 
1472     if (const APInt *EqC = Intersection.getSingleElement())
1473       return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1474     if (const APInt *NeC = Difference.getSingleElement())
1475       return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1476   }
1477 
1478   return nullptr;
1479 }
1480 
1481 /// Fold icmp (trunc X), C.
1482 Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
1483                                                      TruncInst *Trunc,
1484                                                      const APInt &C) {
1485   ICmpInst::Predicate Pred = Cmp.getPredicate();
1486   Value *X = Trunc->getOperand(0);
1487   if (C.isOne() && C.getBitWidth() > 1) {
1488     // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1489     Value *V = nullptr;
1490     if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1491       return new ICmpInst(ICmpInst::ICMP_SLT, V,
1492                           ConstantInt::get(V->getType(), 1));
1493   }
1494 
1495   Type *SrcTy = X->getType();
1496   unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1497            SrcBits = SrcTy->getScalarSizeInBits();
1498 
1499   // TODO: Handle any shifted constant by subtracting trailing zeros.
1500   // TODO: Handle non-equality predicates.
1501   Value *Y;
1502   if (Cmp.isEquality() && match(X, m_Shl(m_One(), m_Value(Y)))) {
1503     // (trunc (1 << Y) to iN) == 0 --> Y u>= N
1504     // (trunc (1 << Y) to iN) != 0 --> Y u<  N
1505     if (C.isZero()) {
1506       auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1507       return new ICmpInst(NewPred, Y, ConstantInt::get(SrcTy, DstBits));
1508     }
1509     // (trunc (1 << Y) to iN) == 2**C --> Y == C
1510     // (trunc (1 << Y) to iN) != 2**C --> Y != C
1511     if (C.isPowerOf2())
1512       return new ICmpInst(Pred, Y, ConstantInt::get(SrcTy, C.logBase2()));
1513   }
1514 
1515   if (Cmp.isEquality() && Trunc->hasOneUse()) {
1516     // Canonicalize to a mask and wider compare if the wide type is suitable:
1517     // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1518     if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1519       Constant *Mask =
1520           ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1521       Value *And = Builder.CreateAnd(X, Mask);
1522       Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1523       return new ICmpInst(Pred, And, WideC);
1524     }
1525 
1526     // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1527     // of the high bits truncated out of x are known.
1528     KnownBits Known = computeKnownBits(X, 0, &Cmp);
1529 
1530     // If all the high bits are known, we can do this xform.
1531     if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1532       // Pull in the high bits from known-ones set.
1533       APInt NewRHS = C.zext(SrcBits);
1534       NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1535       return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1536     }
1537   }
1538 
1539   // Look through truncated right-shift of the sign-bit for a sign-bit check:
1540   // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0  --> ShOp <  0
1541   // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1542   Value *ShOp;
1543   const APInt *ShAmtC;
1544   bool TrueIfSigned;
1545   if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1546       match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) &&
1547       DstBits == SrcBits - ShAmtC->getZExtValue()) {
1548     return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1549                                        ConstantInt::getNullValue(SrcTy))
1550                         : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1551                                        ConstantInt::getAllOnesValue(SrcTy));
1552   }
1553 
1554   return nullptr;
1555 }
1556 
1557 /// Fold icmp (xor X, Y), C.
1558 Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
1559                                                    BinaryOperator *Xor,
1560                                                    const APInt &C) {
1561   if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1562     return I;
1563 
1564   Value *X = Xor->getOperand(0);
1565   Value *Y = Xor->getOperand(1);
1566   const APInt *XorC;
1567   if (!match(Y, m_APInt(XorC)))
1568     return nullptr;
1569 
1570   // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1571   // fold the xor.
1572   ICmpInst::Predicate Pred = Cmp.getPredicate();
1573   bool TrueIfSigned = false;
1574   if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1575 
1576     // If the sign bit of the XorCst is not set, there is no change to
1577     // the operation, just stop using the Xor.
1578     if (!XorC->isNegative())
1579       return replaceOperand(Cmp, 0, X);
1580 
1581     // Emit the opposite comparison.
1582     if (TrueIfSigned)
1583       return new ICmpInst(ICmpInst::ICMP_SGT, X,
1584                           ConstantInt::getAllOnesValue(X->getType()));
1585     else
1586       return new ICmpInst(ICmpInst::ICMP_SLT, X,
1587                           ConstantInt::getNullValue(X->getType()));
1588   }
1589 
1590   if (Xor->hasOneUse()) {
1591     // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1592     if (!Cmp.isEquality() && XorC->isSignMask()) {
1593       Pred = Cmp.getFlippedSignednessPredicate();
1594       return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1595     }
1596 
1597     // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1598     if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1599       Pred = Cmp.getFlippedSignednessPredicate();
1600       Pred = Cmp.getSwappedPredicate(Pred);
1601       return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1602     }
1603   }
1604 
1605   // Mask constant magic can eliminate an 'xor' with unsigned compares.
1606   if (Pred == ICmpInst::ICMP_UGT) {
1607     // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1608     if (*XorC == ~C && (C + 1).isPowerOf2())
1609       return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1610     // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1611     if (*XorC == C && (C + 1).isPowerOf2())
1612       return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1613   }
1614   if (Pred == ICmpInst::ICMP_ULT) {
1615     // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1616     if (*XorC == -C && C.isPowerOf2())
1617       return new ICmpInst(ICmpInst::ICMP_UGT, X,
1618                           ConstantInt::get(X->getType(), ~C));
1619     // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1620     if (*XorC == C && (-C).isPowerOf2())
1621       return new ICmpInst(ICmpInst::ICMP_UGT, X,
1622                           ConstantInt::get(X->getType(), ~C));
1623   }
1624   return nullptr;
1625 }
1626 
1627 /// For power-of-2 C:
1628 /// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1629 /// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1630 Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
1631                                                      BinaryOperator *Xor,
1632                                                      const APInt &C) {
1633   CmpInst::Predicate Pred = Cmp.getPredicate();
1634   APInt PowerOf2;
1635   if (Pred == ICmpInst::ICMP_ULT)
1636     PowerOf2 = C;
1637   else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1638     PowerOf2 = C + 1;
1639   else
1640     return nullptr;
1641   if (!PowerOf2.isPowerOf2())
1642     return nullptr;
1643   Value *X;
1644   const APInt *ShiftC;
1645   if (!match(Xor, m_OneUse(m_c_Xor(m_Value(X),
1646                                    m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1647     return nullptr;
1648   uint64_t Shift = ShiftC->getLimitedValue();
1649   Type *XType = X->getType();
1650   if (Shift == 0 || PowerOf2.isMinSignedValue())
1651     return nullptr;
1652   Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1653   APInt Bound =
1654       Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1655   return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1656 }
1657 
1658 /// Fold icmp (and (sh X, Y), C2), C1.
1659 Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
1660                                                 BinaryOperator *And,
1661                                                 const APInt &C1,
1662                                                 const APInt &C2) {
1663   BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1664   if (!Shift || !Shift->isShift())
1665     return nullptr;
1666 
1667   // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1668   // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1669   // code produced by the clang front-end, for bitfield access.
1670   // This seemingly simple opportunity to fold away a shift turns out to be
1671   // rather complicated. See PR17827 for details.
1672   unsigned ShiftOpcode = Shift->getOpcode();
1673   bool IsShl = ShiftOpcode == Instruction::Shl;
1674   const APInt *C3;
1675   if (match(Shift->getOperand(1), m_APInt(C3))) {
1676     APInt NewAndCst, NewCmpCst;
1677     bool AnyCmpCstBitsShiftedOut;
1678     if (ShiftOpcode == Instruction::Shl) {
1679       // For a left shift, we can fold if the comparison is not signed. We can
1680       // also fold a signed comparison if the mask value and comparison value
1681       // are not negative. These constraints may not be obvious, but we can
1682       // prove that they are correct using an SMT solver.
1683       if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1684         return nullptr;
1685 
1686       NewCmpCst = C1.lshr(*C3);
1687       NewAndCst = C2.lshr(*C3);
1688       AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1689     } else if (ShiftOpcode == Instruction::LShr) {
1690       // For a logical right shift, we can fold if the comparison is not signed.
1691       // We can also fold a signed comparison if the shifted mask value and the
1692       // shifted comparison value are not negative. These constraints may not be
1693       // obvious, but we can prove that they are correct using an SMT solver.
1694       NewCmpCst = C1.shl(*C3);
1695       NewAndCst = C2.shl(*C3);
1696       AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1697       if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1698         return nullptr;
1699     } else {
1700       // For an arithmetic shift, check that both constants don't use (in a
1701       // signed sense) the top bits being shifted out.
1702       assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1703       NewCmpCst = C1.shl(*C3);
1704       NewAndCst = C2.shl(*C3);
1705       AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1706       if (NewAndCst.ashr(*C3) != C2)
1707         return nullptr;
1708     }
1709 
1710     if (AnyCmpCstBitsShiftedOut) {
1711       // If we shifted bits out, the fold is not going to work out. As a
1712       // special case, check to see if this means that the result is always
1713       // true or false now.
1714       if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1715         return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1716       if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1717         return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1718     } else {
1719       Value *NewAnd = Builder.CreateAnd(
1720           Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1721       return new ICmpInst(Cmp.getPredicate(),
1722           NewAnd, ConstantInt::get(And->getType(), NewCmpCst));
1723     }
1724   }
1725 
1726   // Turn ((X >> Y) & C2) == 0  into  (X & (C2 << Y)) == 0.  The latter is
1727   // preferable because it allows the C2 << Y expression to be hoisted out of a
1728   // loop if Y is invariant and X is not.
1729   if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1730       !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1731     // Compute C2 << Y.
1732     Value *NewShift =
1733         IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1734               : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1735 
1736     // Compute X & (C2 << Y).
1737     Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1738     return replaceOperand(Cmp, 0, NewAnd);
1739   }
1740 
1741   return nullptr;
1742 }
1743 
1744 /// Fold icmp (and X, C2), C1.
1745 Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
1746                                                      BinaryOperator *And,
1747                                                      const APInt &C1) {
1748   bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1749 
1750   // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1751   // TODO: We canonicalize to the longer form for scalars because we have
1752   // better analysis/folds for icmp, and codegen may be better with icmp.
1753   if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&
1754       match(And->getOperand(1), m_One()))
1755     return new TruncInst(And->getOperand(0), Cmp.getType());
1756 
1757   const APInt *C2;
1758   Value *X;
1759   if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1760     return nullptr;
1761 
1762   // Don't perform the following transforms if the AND has multiple uses
1763   if (!And->hasOneUse())
1764     return nullptr;
1765 
1766   if (Cmp.isEquality() && C1.isZero()) {
1767     // Restrict this fold to single-use 'and' (PR10267).
1768     // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1769     if (C2->isSignMask()) {
1770       Constant *Zero = Constant::getNullValue(X->getType());
1771       auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1772       return new ICmpInst(NewPred, X, Zero);
1773     }
1774 
1775     APInt NewC2 = *C2;
1776     KnownBits Know = computeKnownBits(And->getOperand(0), 0, And);
1777     // Set high zeros of C2 to allow matching negated power-of-2.
1778     NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1779                                         Know.countMinLeadingZeros());
1780 
1781     // Restrict this fold only for single-use 'and' (PR10267).
1782     // ((%x & C) == 0) --> %x u< (-C)  iff (-C) is power of two.
1783     if (NewC2.isNegatedPowerOf2()) {
1784       Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1785       auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1786       return new ICmpInst(NewPred, X, NegBOC);
1787     }
1788   }
1789 
1790   // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1791   // the input width without changing the value produced, eliminate the cast:
1792   //
1793   // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1794   //
1795   // We can do this transformation if the constants do not have their sign bits
1796   // set or if it is an equality comparison. Extending a relational comparison
1797   // when we're checking the sign bit would not work.
1798   Value *W;
1799   if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1800       (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1801     // TODO: Is this a good transform for vectors? Wider types may reduce
1802     // throughput. Should this transform be limited (even for scalars) by using
1803     // shouldChangeType()?
1804     if (!Cmp.getType()->isVectorTy()) {
1805       Type *WideType = W->getType();
1806       unsigned WideScalarBits = WideType->getScalarSizeInBits();
1807       Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1808       Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1809       Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1810       return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1811     }
1812   }
1813 
1814   if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1815     return I;
1816 
1817   // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1818   // (icmp pred (and A, (or (shl 1, B), 1), 0))
1819   //
1820   // iff pred isn't signed
1821   if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1822       match(And->getOperand(1), m_One())) {
1823     Constant *One = cast<Constant>(And->getOperand(1));
1824     Value *Or = And->getOperand(0);
1825     Value *A, *B, *LShr;
1826     if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1827         match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1828       unsigned UsesRemoved = 0;
1829       if (And->hasOneUse())
1830         ++UsesRemoved;
1831       if (Or->hasOneUse())
1832         ++UsesRemoved;
1833       if (LShr->hasOneUse())
1834         ++UsesRemoved;
1835 
1836       // Compute A & ((1 << B) | 1)
1837       unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1838       if (UsesRemoved >= RequireUsesRemoved) {
1839         Value *NewOr =
1840             Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1841                                                /*HasNUW=*/true),
1842                              One, Or->getName());
1843         Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1844         return replaceOperand(Cmp, 0, NewAnd);
1845       }
1846     }
1847   }
1848 
1849   return nullptr;
1850 }
1851 
1852 /// Fold icmp (and X, Y), C.
1853 Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
1854                                                    BinaryOperator *And,
1855                                                    const APInt &C) {
1856   if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1857     return I;
1858 
1859   const ICmpInst::Predicate Pred = Cmp.getPredicate();
1860   bool TrueIfNeg;
1861   if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1862     // ((X - 1) & ~X) <  0 --> X == 0
1863     // ((X - 1) & ~X) >= 0 --> X != 0
1864     Value *X;
1865     if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1866         match(And->getOperand(1), m_Not(m_Specific(X)))) {
1867       auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1868       return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1869     }
1870     // (X & X) <  0 --> X == MinSignedC
1871     // (X & X) > -1 --> X != MinSignedC
1872     if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1873       Constant *MinSignedC = ConstantInt::get(
1874           X->getType(),
1875           APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1876       auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1877       return new ICmpInst(NewPred, X, MinSignedC);
1878     }
1879   }
1880 
1881   // TODO: These all require that Y is constant too, so refactor with the above.
1882 
1883   // Try to optimize things like "A[i] & 42 == 0" to index computations.
1884   Value *X = And->getOperand(0);
1885   Value *Y = And->getOperand(1);
1886   if (auto *C2 = dyn_cast<ConstantInt>(Y))
1887     if (auto *LI = dyn_cast<LoadInst>(X))
1888       if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1889         if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1890           if (Instruction *Res =
1891                   foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2))
1892             return Res;
1893 
1894   if (!Cmp.isEquality())
1895     return nullptr;
1896 
1897   // X & -C == -C -> X >  u ~C
1898   // X & -C != -C -> X <= u ~C
1899   //   iff C is a power of 2
1900   if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1901     auto NewPred =
1902         Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
1903     return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1904   }
1905 
1906   // If we are testing the intersection of 2 select-of-nonzero-constants with no
1907   // common bits set, it's the same as checking if exactly one select condition
1908   // is set:
1909   // ((A ? TC : FC) & (B ? TC : FC)) == 0 --> xor A, B
1910   // ((A ? TC : FC) & (B ? TC : FC)) != 0 --> not(xor A, B)
1911   // TODO: Generalize for non-constant values.
1912   // TODO: Handle signed/unsigned predicates.
1913   // TODO: Handle other bitwise logic connectors.
1914   // TODO: Extend to handle a non-zero compare constant.
1915   if (C.isZero() && (Pred == CmpInst::ICMP_EQ || And->hasOneUse())) {
1916     assert(Cmp.isEquality() && "Not expecting non-equality predicates");
1917     Value *A, *B;
1918     const APInt *TC, *FC;
1919     if (match(X, m_Select(m_Value(A), m_APInt(TC), m_APInt(FC))) &&
1920         match(Y,
1921               m_Select(m_Value(B), m_SpecificInt(*TC), m_SpecificInt(*FC))) &&
1922         !TC->isZero() && !FC->isZero() && !TC->intersects(*FC)) {
1923       Value *R = Builder.CreateXor(A, B);
1924       if (Pred == CmpInst::ICMP_NE)
1925         R = Builder.CreateNot(R);
1926       return replaceInstUsesWith(Cmp, R);
1927     }
1928   }
1929 
1930   // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1931   // ((zext i1 X) & Y) != 0 -->  ((trunc Y) & X)
1932   // ((zext i1 X) & Y) == 1 -->  ((trunc Y) & X)
1933   // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1934   if (match(And, m_OneUse(m_c_And(m_OneUse(m_ZExt(m_Value(X))), m_Value(Y)))) &&
1935       X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
1936     Value *TruncY = Builder.CreateTrunc(Y, X->getType());
1937     if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1938       Value *And = Builder.CreateAnd(TruncY, X);
1939       return BinaryOperator::CreateNot(And);
1940     }
1941     return BinaryOperator::CreateAnd(TruncY, X);
1942   }
1943 
1944   return nullptr;
1945 }
1946 
1947 /// Fold icmp eq/ne (or (xor (X1, X2), xor(X3, X4))), 0.
1948 static Value *foldICmpOrXorChain(ICmpInst &Cmp, BinaryOperator *Or,
1949                                  InstCombiner::BuilderTy &Builder) {
1950   // Are we using xors to bitwise check for a pair or pairs of (in)equalities?
1951   // Convert to a shorter form that has more potential to be folded even
1952   // further.
1953   // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4)
1954   // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4)
1955   // ((X1 ^ X2) || (X3 ^ X4) || (X5 ^ X6)) == 0 -->
1956   // (X1 == X2) && (X3 == X4) && (X5 == X6)
1957   // ((X1 ^ X2) || (X3 ^ X4) || (X5 ^ X6)) != 0 -->
1958   // (X1 != X2) || (X3 != X4) || (X5 != X6)
1959   // TODO: Implement for sub
1960   SmallVector<std::pair<Value *, Value *>, 2> CmpValues;
1961   SmallVector<Value *, 16> WorkList(1, Or);
1962 
1963   while (!WorkList.empty()) {
1964     auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
1965       Value *Lhs, *Rhs;
1966 
1967       if (match(OrOperatorArgument,
1968                 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
1969         CmpValues.emplace_back(Lhs, Rhs);
1970       } else {
1971         WorkList.push_back(OrOperatorArgument);
1972       }
1973     };
1974 
1975     Value *CurrentValue = WorkList.pop_back_val();
1976     Value *OrOperatorLhs, *OrOperatorRhs;
1977 
1978     if (!match(CurrentValue,
1979                m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
1980       return nullptr;
1981     }
1982 
1983     MatchOrOperatorArgument(OrOperatorRhs);
1984     MatchOrOperatorArgument(OrOperatorLhs);
1985   }
1986 
1987   ICmpInst::Predicate Pred = Cmp.getPredicate();
1988   auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1989   Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
1990                                      CmpValues.rbegin()->second);
1991 
1992   for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
1993     Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
1994     LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
1995   }
1996 
1997   return LhsCmp;
1998 }
1999 
2000 /// Fold icmp (or X, Y), C.
2001 Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
2002                                                   BinaryOperator *Or,
2003                                                   const APInt &C) {
2004   ICmpInst::Predicate Pred = Cmp.getPredicate();
2005   if (C.isOne()) {
2006     // icmp slt signum(V) 1 --> icmp slt V, 1
2007     Value *V = nullptr;
2008     if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2009       return new ICmpInst(ICmpInst::ICMP_SLT, V,
2010                           ConstantInt::get(V->getType(), 1));
2011   }
2012 
2013   Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2014   const APInt *MaskC;
2015   if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2016     if (*MaskC == C && (C + 1).isPowerOf2()) {
2017       // X | C == C --> X <=u C
2018       // X | C != C --> X  >u C
2019       //   iff C+1 is a power of 2 (C is a bitmask of the low bits)
2020       Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
2021       return new ICmpInst(Pred, OrOp0, OrOp1);
2022     }
2023 
2024     // More general: canonicalize 'equality with set bits mask' to
2025     // 'equality with clear bits mask'.
2026     // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2027     // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2028     if (Or->hasOneUse()) {
2029       Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2030       Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2031       return new ICmpInst(Pred, And, NewC);
2032     }
2033   }
2034 
2035   // (X | (X-1)) s<  0 --> X s< 1
2036   // (X | (X-1)) s> -1 --> X s> 0
2037   Value *X;
2038   bool TrueIfSigned;
2039   if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2040       match(Or, m_c_Or(m_Add(m_Value(X), m_AllOnes()), m_Deferred(X)))) {
2041     auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2042     Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2043     return new ICmpInst(NewPred, X, NewC);
2044   }
2045 
2046   const APInt *OrC;
2047   // icmp(X | OrC, C) --> icmp(X, 0)
2048   if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2049     switch (Pred) {
2050     // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2051     case ICmpInst::ICMP_SLT:
2052     // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2053     case ICmpInst::ICMP_SGE:
2054       if (OrC->sge(C))
2055         return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2056       break;
2057     // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2058     case ICmpInst::ICMP_SLE:
2059     // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2060     case ICmpInst::ICMP_SGT:
2061       if (OrC->sgt(C))
2062         return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(Pred), X,
2063                             ConstantInt::getNullValue(X->getType()));
2064       break;
2065     default:
2066       break;
2067     }
2068   }
2069 
2070   if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2071     return nullptr;
2072 
2073   Value *P, *Q;
2074   if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
2075     // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2076     // -> and (icmp eq P, null), (icmp eq Q, null).
2077     Value *CmpP =
2078         Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2079     Value *CmpQ =
2080         Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2081     auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2082     return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2083   }
2084 
2085   if (Value *V = foldICmpOrXorChain(Cmp, Or, Builder))
2086     return replaceInstUsesWith(Cmp, V);
2087 
2088   return nullptr;
2089 }
2090 
2091 /// Fold icmp (mul X, Y), C.
2092 Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
2093                                                    BinaryOperator *Mul,
2094                                                    const APInt &C) {
2095   ICmpInst::Predicate Pred = Cmp.getPredicate();
2096   Type *MulTy = Mul->getType();
2097   Value *X = Mul->getOperand(0);
2098 
2099   // If there's no overflow:
2100   // X * X == 0 --> X == 0
2101   // X * X != 0 --> X != 0
2102   if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
2103       (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
2104     return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2105 
2106   const APInt *MulC;
2107   if (!match(Mul->getOperand(1), m_APInt(MulC)))
2108     return nullptr;
2109 
2110   // If this is a test of the sign bit and the multiply is sign-preserving with
2111   // a constant operand, use the multiply LHS operand instead:
2112   // (X * +MulC) < 0 --> X < 0
2113   // (X * -MulC) < 0 --> X > 0
2114   if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2115     if (MulC->isNegative())
2116       Pred = ICmpInst::getSwappedPredicate(Pred);
2117     return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2118   }
2119 
2120   if (MulC->isZero())
2121     return nullptr;
2122 
2123   // If the multiply does not wrap or the constant is odd, try to divide the
2124   // compare constant by the multiplication factor.
2125   if (Cmp.isEquality()) {
2126     // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2127     if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2128       Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2129       return new ICmpInst(Pred, X, NewC);
2130     }
2131 
2132     // C % MulC == 0 is weaker than we could use if MulC is odd because it
2133     // correct to transform if MulC * N == C including overflow. I.e with i8
2134     // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2135     // miss that case.
2136     if (C.urem(*MulC).isZero()) {
2137       // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2138       // (mul X, OddC) eq/ne N * C --> X eq/ne N
2139       if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2140         Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2141         return new ICmpInst(Pred, X, NewC);
2142       }
2143     }
2144   }
2145 
2146   // With a matching no-overflow guarantee, fold the constants:
2147   // (X * MulC) < C --> X < (C / MulC)
2148   // (X * MulC) > C --> X > (C / MulC)
2149   // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2150   Constant *NewC = nullptr;
2151   if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2152     // MININT / -1 --> overflow.
2153     if (C.isMinSignedValue() && MulC->isAllOnes())
2154       return nullptr;
2155     if (MulC->isNegative())
2156       Pred = ICmpInst::getSwappedPredicate(Pred);
2157 
2158     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2159       NewC = ConstantInt::get(
2160           MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::UP));
2161     } else {
2162       assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2163              "Unexpected predicate");
2164       NewC = ConstantInt::get(
2165           MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::DOWN));
2166     }
2167   } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2168     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2169       NewC = ConstantInt::get(
2170           MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::UP));
2171     } else {
2172       assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2173              "Unexpected predicate");
2174       NewC = ConstantInt::get(
2175           MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::DOWN));
2176     }
2177   }
2178 
2179   return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2180 }
2181 
2182 /// Fold icmp (shl 1, Y), C.
2183 static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
2184                                    const APInt &C) {
2185   Value *Y;
2186   if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
2187     return nullptr;
2188 
2189   Type *ShiftType = Shl->getType();
2190   unsigned TypeBits = C.getBitWidth();
2191   bool CIsPowerOf2 = C.isPowerOf2();
2192   ICmpInst::Predicate Pred = Cmp.getPredicate();
2193   if (Cmp.isUnsigned()) {
2194     // (1 << Y) pred C -> Y pred Log2(C)
2195     if (!CIsPowerOf2) {
2196       // (1 << Y) <  30 -> Y <= 4
2197       // (1 << Y) <= 30 -> Y <= 4
2198       // (1 << Y) >= 30 -> Y >  4
2199       // (1 << Y) >  30 -> Y >  4
2200       if (Pred == ICmpInst::ICMP_ULT)
2201         Pred = ICmpInst::ICMP_ULE;
2202       else if (Pred == ICmpInst::ICMP_UGE)
2203         Pred = ICmpInst::ICMP_UGT;
2204     }
2205 
2206     unsigned CLog2 = C.logBase2();
2207     return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2208   } else if (Cmp.isSigned()) {
2209     Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2210     // (1 << Y) >  0 -> Y != 31
2211     // (1 << Y) >  C -> Y != 31 if C is negative.
2212     if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2213       return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2214 
2215     // (1 << Y) <  0 -> Y == 31
2216     // (1 << Y) <  1 -> Y == 31
2217     // (1 << Y) <  C -> Y == 31 if C is negative and not signed min.
2218     // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2219     if (Pred == ICmpInst::ICMP_SLT && (C-1).sle(0))
2220       return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2221   }
2222 
2223   return nullptr;
2224 }
2225 
2226 /// Fold icmp (shl X, Y), C.
2227 Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
2228                                                    BinaryOperator *Shl,
2229                                                    const APInt &C) {
2230   const APInt *ShiftVal;
2231   if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2232     return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2233 
2234   ICmpInst::Predicate Pred = Cmp.getPredicate();
2235   // (icmp pred (shl nuw&nsw X, Y), Csle0)
2236   //      -> (icmp pred X, Csle0)
2237   //
2238   // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2239   // so X's must be what is used.
2240   if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2241     return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2242 
2243   // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2244   //      -> (icmp eq/ne X, 0)
2245   if (ICmpInst::isEquality(Pred) && C.isZero() &&
2246       (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2247     return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2248 
2249   // (icmp slt (shl nsw X, Y), 0/1)
2250   //      -> (icmp slt X, 0/1)
2251   // (icmp sgt (shl nsw X, Y), 0/-1)
2252   //      -> (icmp sgt X, 0/-1)
2253   //
2254   // NB: sge/sle with a constant will canonicalize to sgt/slt.
2255   if (Shl->hasNoSignedWrap() &&
2256       (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2257     if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2258       return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2259 
2260   const APInt *ShiftAmt;
2261   if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2262     return foldICmpShlOne(Cmp, Shl, C);
2263 
2264   // Check that the shift amount is in range. If not, don't perform undefined
2265   // shifts. When the shift is visited, it will be simplified.
2266   unsigned TypeBits = C.getBitWidth();
2267   if (ShiftAmt->uge(TypeBits))
2268     return nullptr;
2269 
2270   Value *X = Shl->getOperand(0);
2271   Type *ShType = Shl->getType();
2272 
2273   // NSW guarantees that we are only shifting out sign bits from the high bits,
2274   // so we can ASHR the compare constant without needing a mask and eliminate
2275   // the shift.
2276   if (Shl->hasNoSignedWrap()) {
2277     if (Pred == ICmpInst::ICMP_SGT) {
2278       // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2279       APInt ShiftedC = C.ashr(*ShiftAmt);
2280       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2281     }
2282     if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2283         C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2284       APInt ShiftedC = C.ashr(*ShiftAmt);
2285       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2286     }
2287     if (Pred == ICmpInst::ICMP_SLT) {
2288       // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2289       // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2290       // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2291       // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2292       assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2293       APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2294       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2295     }
2296   }
2297 
2298   // NUW guarantees that we are only shifting out zero bits from the high bits,
2299   // so we can LSHR the compare constant without needing a mask and eliminate
2300   // the shift.
2301   if (Shl->hasNoUnsignedWrap()) {
2302     if (Pred == ICmpInst::ICMP_UGT) {
2303       // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2304       APInt ShiftedC = C.lshr(*ShiftAmt);
2305       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2306     }
2307     if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2308         C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2309       APInt ShiftedC = C.lshr(*ShiftAmt);
2310       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2311     }
2312     if (Pred == ICmpInst::ICMP_ULT) {
2313       // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2314       // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2315       // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2316       // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2317       assert(C.ugt(0) && "ult 0 should have been eliminated");
2318       APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2319       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2320     }
2321   }
2322 
2323   if (Cmp.isEquality() && Shl->hasOneUse()) {
2324     // Strength-reduce the shift into an 'and'.
2325     Constant *Mask = ConstantInt::get(
2326         ShType,
2327         APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2328     Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2329     Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2330     return new ICmpInst(Pred, And, LShrC);
2331   }
2332 
2333   // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2334   bool TrueIfSigned = false;
2335   if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2336     // (X << 31) <s 0  --> (X & 1) != 0
2337     Constant *Mask = ConstantInt::get(
2338         ShType,
2339         APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2340     Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2341     return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2342                         And, Constant::getNullValue(ShType));
2343   }
2344 
2345   // Simplify 'shl' inequality test into 'and' equality test.
2346   if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2347     // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2348     if ((C + 1).isPowerOf2() &&
2349         (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2350       Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2351       return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2352                                                      : ICmpInst::ICMP_NE,
2353                           And, Constant::getNullValue(ShType));
2354     }
2355     // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2356     if (C.isPowerOf2() &&
2357         (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2358       Value *And =
2359           Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2360       return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2361                                                      : ICmpInst::ICMP_NE,
2362                           And, Constant::getNullValue(ShType));
2363     }
2364   }
2365 
2366   // Transform (icmp pred iM (shl iM %v, N), C)
2367   // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2368   // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2369   // This enables us to get rid of the shift in favor of a trunc that may be
2370   // free on the target. It has the additional benefit of comparing to a
2371   // smaller constant that may be more target-friendly.
2372   unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2373   if (Shl->hasOneUse() && Amt != 0 && C.countr_zero() >= Amt &&
2374       DL.isLegalInteger(TypeBits - Amt)) {
2375     Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2376     if (auto *ShVTy = dyn_cast<VectorType>(ShType))
2377       TruncTy = VectorType::get(TruncTy, ShVTy->getElementCount());
2378     Constant *NewC =
2379         ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2380     return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2381   }
2382 
2383   return nullptr;
2384 }
2385 
2386 /// Fold icmp ({al}shr X, Y), C.
2387 Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
2388                                                    BinaryOperator *Shr,
2389                                                    const APInt &C) {
2390   // An exact shr only shifts out zero bits, so:
2391   // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2392   Value *X = Shr->getOperand(0);
2393   CmpInst::Predicate Pred = Cmp.getPredicate();
2394   if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2395     return new ICmpInst(Pred, X, Cmp.getOperand(1));
2396 
2397   bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2398   const APInt *ShiftValC;
2399   if (match(X, m_APInt(ShiftValC))) {
2400     if (Cmp.isEquality())
2401       return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2402 
2403     // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2404     // (ShiftValC >> Y) <s  0 --> Y == 0 with ShiftValC < 0
2405     bool TrueIfSigned;
2406     if (!IsAShr && ShiftValC->isNegative() &&
2407         isSignBitCheck(Pred, C, TrueIfSigned))
2408       return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2409                           Shr->getOperand(1),
2410                           ConstantInt::getNullValue(X->getType()));
2411 
2412     // If the shifted constant is a power-of-2, test the shift amount directly:
2413     // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2414     // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2415     if (!IsAShr && ShiftValC->isPowerOf2() &&
2416         (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2417       bool IsUGT = Pred == CmpInst::ICMP_UGT;
2418       assert(ShiftValC->uge(C) && "Expected simplify of compare");
2419       assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2420 
2421       unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2422       unsigned ShiftLZ = ShiftValC->countl_zero();
2423       Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2424       auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2425       return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2426     }
2427   }
2428 
2429   const APInt *ShiftAmtC;
2430   if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2431     return nullptr;
2432 
2433   // Check that the shift amount is in range. If not, don't perform undefined
2434   // shifts. When the shift is visited it will be simplified.
2435   unsigned TypeBits = C.getBitWidth();
2436   unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2437   if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2438     return nullptr;
2439 
2440   bool IsExact = Shr->isExact();
2441   Type *ShrTy = Shr->getType();
2442   // TODO: If we could guarantee that InstSimplify would handle all of the
2443   // constant-value-based preconditions in the folds below, then we could assert
2444   // those conditions rather than checking them. This is difficult because of
2445   // undef/poison (PR34838).
2446   if (IsAShr) {
2447     if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2448       // When ShAmtC can be shifted losslessly:
2449       // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2450       // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2451       APInt ShiftedC = C.shl(ShAmtVal);
2452       if (ShiftedC.ashr(ShAmtVal) == C)
2453         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2454     }
2455     if (Pred == CmpInst::ICMP_SGT) {
2456       // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2457       APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2458       if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2459           (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2460         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2461     }
2462     if (Pred == CmpInst::ICMP_UGT) {
2463       // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2464       // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2465       // clause accounts for that pattern.
2466       APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2467       if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2468           (C + 1).shl(ShAmtVal).isMinSignedValue())
2469         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2470     }
2471 
2472     // If the compare constant has significant bits above the lowest sign-bit,
2473     // then convert an unsigned cmp to a test of the sign-bit:
2474     // (ashr X, ShiftC) u> C --> X s< 0
2475     // (ashr X, ShiftC) u< C --> X s> -1
2476     if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2477       if (Pred == CmpInst::ICMP_UGT) {
2478         return new ICmpInst(CmpInst::ICMP_SLT, X,
2479                             ConstantInt::getNullValue(ShrTy));
2480       }
2481       if (Pred == CmpInst::ICMP_ULT) {
2482         return new ICmpInst(CmpInst::ICMP_SGT, X,
2483                             ConstantInt::getAllOnesValue(ShrTy));
2484       }
2485     }
2486   } else {
2487     if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2488       // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2489       // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2490       APInt ShiftedC = C.shl(ShAmtVal);
2491       if (ShiftedC.lshr(ShAmtVal) == C)
2492         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2493     }
2494     if (Pred == CmpInst::ICMP_UGT) {
2495       // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2496       APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2497       if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2498         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2499     }
2500   }
2501 
2502   if (!Cmp.isEquality())
2503     return nullptr;
2504 
2505   // Handle equality comparisons of shift-by-constant.
2506 
2507   // If the comparison constant changes with the shift, the comparison cannot
2508   // succeed (bits of the comparison constant cannot match the shifted value).
2509   // This should be known by InstSimplify and already be folded to true/false.
2510   assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2511           (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2512          "Expected icmp+shr simplify did not occur.");
2513 
2514   // If the bits shifted out are known zero, compare the unshifted value:
2515   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
2516   if (Shr->isExact())
2517     return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2518 
2519   if (C.isZero()) {
2520     // == 0 is u< 1.
2521     if (Pred == CmpInst::ICMP_EQ)
2522       return new ICmpInst(CmpInst::ICMP_ULT, X,
2523                           ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal)));
2524     else
2525       return new ICmpInst(CmpInst::ICMP_UGT, X,
2526                           ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1));
2527   }
2528 
2529   if (Shr->hasOneUse()) {
2530     // Canonicalize the shift into an 'and':
2531     // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2532     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2533     Constant *Mask = ConstantInt::get(ShrTy, Val);
2534     Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2535     return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2536   }
2537 
2538   return nullptr;
2539 }
2540 
2541 Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
2542                                                     BinaryOperator *SRem,
2543                                                     const APInt &C) {
2544   // Match an 'is positive' or 'is negative' comparison of remainder by a
2545   // constant power-of-2 value:
2546   // (X % pow2C) sgt/slt 0
2547   const ICmpInst::Predicate Pred = Cmp.getPredicate();
2548   if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2549       Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2550     return nullptr;
2551 
2552   // TODO: The one-use check is standard because we do not typically want to
2553   //       create longer instruction sequences, but this might be a special-case
2554   //       because srem is not good for analysis or codegen.
2555   if (!SRem->hasOneUse())
2556     return nullptr;
2557 
2558   const APInt *DivisorC;
2559   if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2560     return nullptr;
2561 
2562   // For cmp_sgt/cmp_slt only zero valued C is handled.
2563   // For cmp_eq/cmp_ne only positive valued C is handled.
2564   if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2565        !C.isZero()) ||
2566       ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2567        !C.isStrictlyPositive()))
2568     return nullptr;
2569 
2570   // Mask off the sign bit and the modulo bits (low-bits).
2571   Type *Ty = SRem->getType();
2572   APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2573   Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2574   Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2575 
2576   if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2577     return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2578 
2579   // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2580   // bit is set. Example:
2581   // (i8 X % 32) s> 0 --> (X & 159) s> 0
2582   if (Pred == ICmpInst::ICMP_SGT)
2583     return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2584 
2585   // For 'is negative?' check that the sign-bit is set and at least 1 masked
2586   // bit is set. Example:
2587   // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2588   return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2589 }
2590 
2591 /// Fold icmp (udiv X, Y), C.
2592 Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
2593                                                     BinaryOperator *UDiv,
2594                                                     const APInt &C) {
2595   ICmpInst::Predicate Pred = Cmp.getPredicate();
2596   Value *X = UDiv->getOperand(0);
2597   Value *Y = UDiv->getOperand(1);
2598   Type *Ty = UDiv->getType();
2599 
2600   const APInt *C2;
2601   if (!match(X, m_APInt(C2)))
2602     return nullptr;
2603 
2604   assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2605 
2606   // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2607   if (Pred == ICmpInst::ICMP_UGT) {
2608     assert(!C.isMaxValue() &&
2609            "icmp ugt X, UINT_MAX should have been simplified already.");
2610     return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2611                         ConstantInt::get(Ty, C2->udiv(C + 1)));
2612   }
2613 
2614   // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2615   if (Pred == ICmpInst::ICMP_ULT) {
2616     assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2617     return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2618                         ConstantInt::get(Ty, C2->udiv(C)));
2619   }
2620 
2621   return nullptr;
2622 }
2623 
2624 /// Fold icmp ({su}div X, Y), C.
2625 Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
2626                                                    BinaryOperator *Div,
2627                                                    const APInt &C) {
2628   ICmpInst::Predicate Pred = Cmp.getPredicate();
2629   Value *X = Div->getOperand(0);
2630   Value *Y = Div->getOperand(1);
2631   Type *Ty = Div->getType();
2632   bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2633 
2634   // If unsigned division and the compare constant is bigger than
2635   // UMAX/2 (negative), there's only one pair of values that satisfies an
2636   // equality check, so eliminate the division:
2637   // (X u/ Y) == C --> (X == C) && (Y == 1)
2638   // (X u/ Y) != C --> (X != C) || (Y != 1)
2639   // Similarly, if signed division and the compare constant is exactly SMIN:
2640   // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2641   // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2642   if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2643       (!DivIsSigned || C.isMinSignedValue()))   {
2644     Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2645     Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2646     auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2647     return BinaryOperator::Create(Logic, XBig, YOne);
2648   }
2649 
2650   // Fold: icmp pred ([us]div X, C2), C -> range test
2651   // Fold this div into the comparison, producing a range check.
2652   // Determine, based on the divide type, what the range is being
2653   // checked.  If there is an overflow on the low or high side, remember
2654   // it, otherwise compute the range [low, hi) bounding the new value.
2655   // See: InsertRangeTest above for the kinds of replacements possible.
2656   const APInt *C2;
2657   if (!match(Y, m_APInt(C2)))
2658     return nullptr;
2659 
2660   // FIXME: If the operand types don't match the type of the divide
2661   // then don't attempt this transform. The code below doesn't have the
2662   // logic to deal with a signed divide and an unsigned compare (and
2663   // vice versa). This is because (x /s C2) <s C  produces different
2664   // results than (x /s C2) <u C or (x /u C2) <s C or even
2665   // (x /u C2) <u C.  Simply casting the operands and result won't
2666   // work. :(  The if statement below tests that condition and bails
2667   // if it finds it.
2668   if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2669     return nullptr;
2670 
2671   // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2672   // INT_MIN will also fail if the divisor is 1. Although folds of all these
2673   // division-by-constant cases should be present, we can not assert that they
2674   // have happened before we reach this icmp instruction.
2675   if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2676     return nullptr;
2677 
2678   // Compute Prod = C * C2. We are essentially solving an equation of
2679   // form X / C2 = C. We solve for X by multiplying C2 and C.
2680   // By solving for X, we can turn this into a range check instead of computing
2681   // a divide.
2682   APInt Prod = C * *C2;
2683 
2684   // Determine if the product overflows by seeing if the product is not equal to
2685   // the divide. Make sure we do the same kind of divide as in the LHS
2686   // instruction that we're folding.
2687   bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2688 
2689   // If the division is known to be exact, then there is no remainder from the
2690   // divide, so the covered range size is unit, otherwise it is the divisor.
2691   APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2692 
2693   // Figure out the interval that is being checked.  For example, a comparison
2694   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2695   // Compute this interval based on the constants involved and the signedness of
2696   // the compare/divide.  This computes a half-open interval, keeping track of
2697   // whether either value in the interval overflows.  After analysis each
2698   // overflow variable is set to 0 if it's corresponding bound variable is valid
2699   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2700   int LoOverflow = 0, HiOverflow = 0;
2701   APInt LoBound, HiBound;
2702 
2703   if (!DivIsSigned) { // udiv
2704     // e.g. X/5 op 3  --> [15, 20)
2705     LoBound = Prod;
2706     HiOverflow = LoOverflow = ProdOV;
2707     if (!HiOverflow) {
2708       // If this is not an exact divide, then many values in the range collapse
2709       // to the same result value.
2710       HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2711     }
2712   } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2713     if (C.isZero()) {                    // (X / pos) op 0
2714       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
2715       LoBound = -(RangeSize - 1);
2716       HiBound = RangeSize;
2717     } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2718       LoBound = Prod;                    // e.g.   X/5 op 3 --> [15, 20)
2719       HiOverflow = LoOverflow = ProdOV;
2720       if (!HiOverflow)
2721         HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2722     } else { // (X / pos) op neg
2723       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
2724       HiBound = Prod + 1;
2725       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2726       if (!LoOverflow) {
2727         APInt DivNeg = -RangeSize;
2728         LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2729       }
2730     }
2731   } else if (C2->isNegative()) { // Divisor is < 0.
2732     if (Div->isExact())
2733       RangeSize.negate();
2734     if (C.isZero()) { // (X / neg) op 0
2735       // e.g. X/-5 op 0  --> [-4, 5)
2736       LoBound = RangeSize + 1;
2737       HiBound = -RangeSize;
2738       if (HiBound == *C2) { // -INTMIN = INTMIN
2739         HiOverflow = 1;     // [INTMIN+1, overflow)
2740         HiBound = APInt();  // e.g. X/INTMIN = 0 --> X > INTMIN
2741       }
2742     } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2743       // e.g. X/-5 op 3  --> [-19, -14)
2744       HiBound = Prod + 1;
2745       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2746       if (!LoOverflow)
2747         LoOverflow =
2748             addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2749     } else {          // (X / neg) op neg
2750       LoBound = Prod; // e.g. X/-5 op -3  --> [15, 20)
2751       LoOverflow = HiOverflow = ProdOV;
2752       if (!HiOverflow)
2753         HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2754     }
2755 
2756     // Dividing by a negative swaps the condition.  LT <-> GT
2757     Pred = ICmpInst::getSwappedPredicate(Pred);
2758   }
2759 
2760   switch (Pred) {
2761   default:
2762     llvm_unreachable("Unhandled icmp predicate!");
2763   case ICmpInst::ICMP_EQ:
2764     if (LoOverflow && HiOverflow)
2765       return replaceInstUsesWith(Cmp, Builder.getFalse());
2766     if (HiOverflow)
2767       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2768                           X, ConstantInt::get(Ty, LoBound));
2769     if (LoOverflow)
2770       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2771                           X, ConstantInt::get(Ty, HiBound));
2772     return replaceInstUsesWith(
2773         Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2774   case ICmpInst::ICMP_NE:
2775     if (LoOverflow && HiOverflow)
2776       return replaceInstUsesWith(Cmp, Builder.getTrue());
2777     if (HiOverflow)
2778       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2779                           X, ConstantInt::get(Ty, LoBound));
2780     if (LoOverflow)
2781       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2782                           X, ConstantInt::get(Ty, HiBound));
2783     return replaceInstUsesWith(
2784         Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2785   case ICmpInst::ICMP_ULT:
2786   case ICmpInst::ICMP_SLT:
2787     if (LoOverflow == +1) // Low bound is greater than input range.
2788       return replaceInstUsesWith(Cmp, Builder.getTrue());
2789     if (LoOverflow == -1) // Low bound is less than input range.
2790       return replaceInstUsesWith(Cmp, Builder.getFalse());
2791     return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
2792   case ICmpInst::ICMP_UGT:
2793   case ICmpInst::ICMP_SGT:
2794     if (HiOverflow == +1) // High bound greater than input range.
2795       return replaceInstUsesWith(Cmp, Builder.getFalse());
2796     if (HiOverflow == -1) // High bound less than input range.
2797       return replaceInstUsesWith(Cmp, Builder.getTrue());
2798     if (Pred == ICmpInst::ICMP_UGT)
2799       return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
2800     return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
2801   }
2802 
2803   return nullptr;
2804 }
2805 
2806 /// Fold icmp (sub X, Y), C.
2807 Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
2808                                                    BinaryOperator *Sub,
2809                                                    const APInt &C) {
2810   Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2811   ICmpInst::Predicate Pred = Cmp.getPredicate();
2812   Type *Ty = Sub->getType();
2813 
2814   // (SubC - Y) == C) --> Y == (SubC - C)
2815   // (SubC - Y) != C) --> Y != (SubC - C)
2816   Constant *SubC;
2817   if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
2818     return new ICmpInst(Pred, Y,
2819                         ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
2820   }
2821 
2822   // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2823   const APInt *C2;
2824   APInt SubResult;
2825   ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2826   bool HasNSW = Sub->hasNoSignedWrap();
2827   bool HasNUW = Sub->hasNoUnsignedWrap();
2828   if (match(X, m_APInt(C2)) &&
2829       ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2830       !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2831     return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
2832 
2833   // X - Y == 0 --> X == Y.
2834   // X - Y != 0 --> X != Y.
2835   // TODO: We allow this with multiple uses as long as the other uses are not
2836   //       in phis. The phi use check is guarding against a codegen regression
2837   //       for a loop test. If the backend could undo this (and possibly
2838   //       subsequent transforms), we would not need this hack.
2839   if (Cmp.isEquality() && C.isZero() &&
2840       none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
2841     return new ICmpInst(Pred, X, Y);
2842 
2843   // The following transforms are only worth it if the only user of the subtract
2844   // is the icmp.
2845   // TODO: This is an artificial restriction for all of the transforms below
2846   //       that only need a single replacement icmp. Can these use the phi test
2847   //       like the transform above here?
2848   if (!Sub->hasOneUse())
2849     return nullptr;
2850 
2851   if (Sub->hasNoSignedWrap()) {
2852     // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2853     if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
2854       return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
2855 
2856     // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2857     if (Pred == ICmpInst::ICMP_SGT && C.isZero())
2858       return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2859 
2860     // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2861     if (Pred == ICmpInst::ICMP_SLT && C.isZero())
2862       return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2863 
2864     // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2865     if (Pred == ICmpInst::ICMP_SLT && C.isOne())
2866       return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2867   }
2868 
2869   if (!match(X, m_APInt(C2)))
2870     return nullptr;
2871 
2872   // C2 - Y <u C -> (Y | (C - 1)) == C2
2873   //   iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2874   if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
2875       (*C2 & (C - 1)) == (C - 1))
2876     return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
2877 
2878   // C2 - Y >u C -> (Y | C) != C2
2879   //   iff C2 & C == C and C + 1 is a power of 2
2880   if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
2881     return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
2882 
2883   // We have handled special cases that reduce.
2884   // Canonicalize any remaining sub to add as:
2885   // (C2 - Y) > C --> (Y + ~C2) < ~C
2886   Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
2887                                  HasNUW, HasNSW);
2888   return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
2889 }
2890 
2891 /// Fold icmp (add X, Y), C.
2892 Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
2893                                                    BinaryOperator *Add,
2894                                                    const APInt &C) {
2895   Value *Y = Add->getOperand(1);
2896   const APInt *C2;
2897   if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
2898     return nullptr;
2899 
2900   // Fold icmp pred (add X, C2), C.
2901   Value *X = Add->getOperand(0);
2902   Type *Ty = Add->getType();
2903   const CmpInst::Predicate Pred = Cmp.getPredicate();
2904 
2905   // If the add does not wrap, we can always adjust the compare by subtracting
2906   // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
2907   // are canonicalized to SGT/SLT/UGT/ULT.
2908   if ((Add->hasNoSignedWrap() &&
2909        (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
2910       (Add->hasNoUnsignedWrap() &&
2911        (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
2912     bool Overflow;
2913     APInt NewC =
2914         Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
2915     // If there is overflow, the result must be true or false.
2916     // TODO: Can we assert there is no overflow because InstSimplify always
2917     // handles those cases?
2918     if (!Overflow)
2919       // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2920       return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2921   }
2922 
2923   auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
2924   const APInt &Upper = CR.getUpper();
2925   const APInt &Lower = CR.getLower();
2926   if (Cmp.isSigned()) {
2927     if (Lower.isSignMask())
2928       return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
2929     if (Upper.isSignMask())
2930       return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
2931   } else {
2932     if (Lower.isMinValue())
2933       return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
2934     if (Upper.isMinValue())
2935       return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
2936   }
2937 
2938   // This set of folds is intentionally placed after folds that use no-wrapping
2939   // flags because those folds are likely better for later analysis/codegen.
2940   const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
2941   const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
2942 
2943   // Fold compare with offset to opposite sign compare if it eliminates offset:
2944   // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
2945   if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
2946     return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
2947 
2948   // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
2949   if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
2950     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
2951 
2952   // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
2953   if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
2954     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
2955 
2956   // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
2957   if (Pred == CmpInst::ICMP_SLT && C == *C2)
2958     return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
2959 
2960   // (X + -1) <u C --> X <=u C (if X is never null)
2961   if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
2962     const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
2963     if (llvm::isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
2964       return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
2965   }
2966 
2967   if (!Add->hasOneUse())
2968     return nullptr;
2969 
2970   // X+C <u C2 -> (X & -C2) == C
2971   //   iff C & (C2-1) == 0
2972   //       C2 is a power of 2
2973   if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
2974     return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
2975                         ConstantExpr::getNeg(cast<Constant>(Y)));
2976 
2977   // X+C >u C2 -> (X & ~C2) != C
2978   //   iff C & C2 == 0
2979   //       C2+1 is a power of 2
2980   if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
2981     return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
2982                         ConstantExpr::getNeg(cast<Constant>(Y)));
2983 
2984   // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
2985   // to the ult form.
2986   // X+C2 >u C -> X+(C2-C-1) <u ~C
2987   if (Pred == ICmpInst::ICMP_UGT)
2988     return new ICmpInst(ICmpInst::ICMP_ULT,
2989                         Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
2990                         ConstantInt::get(Ty, ~C));
2991 
2992   return nullptr;
2993 }
2994 
2995 bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
2996                                                Value *&RHS, ConstantInt *&Less,
2997                                                ConstantInt *&Equal,
2998                                                ConstantInt *&Greater) {
2999   // TODO: Generalize this to work with other comparison idioms or ensure
3000   // they get canonicalized into this form.
3001 
3002   // select i1 (a == b),
3003   //        i32 Equal,
3004   //        i32 (select i1 (a < b), i32 Less, i32 Greater)
3005   // where Equal, Less and Greater are placeholders for any three constants.
3006   ICmpInst::Predicate PredA;
3007   if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3008       !ICmpInst::isEquality(PredA))
3009     return false;
3010   Value *EqualVal = SI->getTrueValue();
3011   Value *UnequalVal = SI->getFalseValue();
3012   // We still can get non-canonical predicate here, so canonicalize.
3013   if (PredA == ICmpInst::ICMP_NE)
3014     std::swap(EqualVal, UnequalVal);
3015   if (!match(EqualVal, m_ConstantInt(Equal)))
3016     return false;
3017   ICmpInst::Predicate PredB;
3018   Value *LHS2, *RHS2;
3019   if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3020                                   m_ConstantInt(Less), m_ConstantInt(Greater))))
3021     return false;
3022   // We can get predicate mismatch here, so canonicalize if possible:
3023   // First, ensure that 'LHS' match.
3024   if (LHS2 != LHS) {
3025     // x sgt y <--> y slt x
3026     std::swap(LHS2, RHS2);
3027     PredB = ICmpInst::getSwappedPredicate(PredB);
3028   }
3029   if (LHS2 != LHS)
3030     return false;
3031   // We also need to canonicalize 'RHS'.
3032   if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3033     // x sgt C-1  <-->  x sge C  <-->  not(x slt C)
3034     auto FlippedStrictness =
3035         InstCombiner::getFlippedStrictnessPredicateAndConstant(
3036             PredB, cast<Constant>(RHS2));
3037     if (!FlippedStrictness)
3038       return false;
3039     assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3040            "basic correctness failure");
3041     RHS2 = FlippedStrictness->second;
3042     // And kind-of perform the result swap.
3043     std::swap(Less, Greater);
3044     PredB = ICmpInst::ICMP_SLT;
3045   }
3046   return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3047 }
3048 
3049 Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
3050                                                       SelectInst *Select,
3051                                                       ConstantInt *C) {
3052 
3053   assert(C && "Cmp RHS should be a constant int!");
3054   // If we're testing a constant value against the result of a three way
3055   // comparison, the result can be expressed directly in terms of the
3056   // original values being compared.  Note: We could possibly be more
3057   // aggressive here and remove the hasOneUse test. The original select is
3058   // really likely to simplify or sink when we remove a test of the result.
3059   Value *OrigLHS, *OrigRHS;
3060   ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3061   if (Cmp.hasOneUse() &&
3062       matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3063                               C3GreaterThan)) {
3064     assert(C1LessThan && C2Equal && C3GreaterThan);
3065 
3066     bool TrueWhenLessThan =
3067         ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
3068             ->isAllOnesValue();
3069     bool TrueWhenEqual =
3070         ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
3071             ->isAllOnesValue();
3072     bool TrueWhenGreaterThan =
3073         ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
3074             ->isAllOnesValue();
3075 
3076     // This generates the new instruction that will replace the original Cmp
3077     // Instruction. Instead of enumerating the various combinations when
3078     // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3079     // false, we rely on chaining of ORs and future passes of InstCombine to
3080     // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3081 
3082     // When none of the three constants satisfy the predicate for the RHS (C),
3083     // the entire original Cmp can be simplified to a false.
3084     Value *Cond = Builder.getFalse();
3085     if (TrueWhenLessThan)
3086       Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT,
3087                                                        OrigLHS, OrigRHS));
3088     if (TrueWhenEqual)
3089       Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ,
3090                                                        OrigLHS, OrigRHS));
3091     if (TrueWhenGreaterThan)
3092       Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT,
3093                                                        OrigLHS, OrigRHS));
3094 
3095     return replaceInstUsesWith(Cmp, Cond);
3096   }
3097   return nullptr;
3098 }
3099 
3100 Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
3101   auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3102   if (!Bitcast)
3103     return nullptr;
3104 
3105   ICmpInst::Predicate Pred = Cmp.getPredicate();
3106   Value *Op1 = Cmp.getOperand(1);
3107   Value *BCSrcOp = Bitcast->getOperand(0);
3108   Type *SrcType = Bitcast->getSrcTy();
3109   Type *DstType = Bitcast->getType();
3110 
3111   // Make sure the bitcast doesn't change between scalar and vector and
3112   // doesn't change the number of vector elements.
3113   if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3114       SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3115     // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3116     Value *X;
3117     if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3118       // icmp  eq (bitcast (sitofp X)), 0 --> icmp  eq X, 0
3119       // icmp  ne (bitcast (sitofp X)), 0 --> icmp  ne X, 0
3120       // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3121       // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3122       if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3123            Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3124           match(Op1, m_Zero()))
3125         return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3126 
3127       // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3128       if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3129         return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3130 
3131       // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3132       if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3133         return new ICmpInst(Pred, X,
3134                             ConstantInt::getAllOnesValue(X->getType()));
3135     }
3136 
3137     // Zero-equality checks are preserved through unsigned floating-point casts:
3138     // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3139     // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3140     if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3141       if (Cmp.isEquality() && match(Op1, m_Zero()))
3142         return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3143 
3144     // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3145     // the FP extend/truncate because that cast does not change the sign-bit.
3146     // This is true for all standard IEEE-754 types and the X86 80-bit type.
3147     // The sign-bit is always the most significant bit in those types.
3148     const APInt *C;
3149     bool TrueIfSigned;
3150     if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse() &&
3151         isSignBitCheck(Pred, *C, TrueIfSigned)) {
3152       if (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3153           match(BCSrcOp, m_FPTrunc(m_Value(X)))) {
3154         // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3155         // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3156         Type *XType = X->getType();
3157 
3158         // We can't currently handle Power style floating point operations here.
3159         if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3160           Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3161           if (auto *XVTy = dyn_cast<VectorType>(XType))
3162             NewType = VectorType::get(NewType, XVTy->getElementCount());
3163           Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3164           if (TrueIfSigned)
3165             return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3166                                 ConstantInt::getNullValue(NewType));
3167           else
3168             return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3169                                 ConstantInt::getAllOnesValue(NewType));
3170         }
3171       }
3172     }
3173   }
3174 
3175   // Test to see if the operands of the icmp are casted versions of other
3176   // values. If the ptr->ptr cast can be stripped off both arguments, do so.
3177   if (DstType->isPointerTy() && (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
3178     // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3179     // so eliminate it as well.
3180     if (auto *BC2 = dyn_cast<BitCastInst>(Op1))
3181       Op1 = BC2->getOperand(0);
3182 
3183     Op1 = Builder.CreateBitCast(Op1, SrcType);
3184     return new ICmpInst(Pred, BCSrcOp, Op1);
3185   }
3186 
3187   const APInt *C;
3188   if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3189       !SrcType->isIntOrIntVectorTy())
3190     return nullptr;
3191 
3192   // If this is checking if all elements of a vector compare are set or not,
3193   // invert the casted vector equality compare and test if all compare
3194   // elements are clear or not. Compare against zero is generally easier for
3195   // analysis and codegen.
3196   // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3197   // Example: are all elements equal? --> are zero elements not equal?
3198   // TODO: Try harder to reduce compare of 2 freely invertible operands?
3199   if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse() &&
3200       isFreeToInvert(BCSrcOp, BCSrcOp->hasOneUse())) {
3201     Value *Cast = Builder.CreateBitCast(Builder.CreateNot(BCSrcOp), DstType);
3202     return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3203   }
3204 
3205   // If this is checking if all elements of an extended vector are clear or not,
3206   // compare in a narrow type to eliminate the extend:
3207   // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3208   Value *X;
3209   if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3210       match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3211     if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3212       Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3213       Value *NewCast = Builder.CreateBitCast(X, NewType);
3214       return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3215     }
3216   }
3217 
3218   // Folding: icmp <pred> iN X, C
3219   //  where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3220   //    and C is a splat of a K-bit pattern
3221   //    and SC is a constant vector = <C', C', C', ..., C'>
3222   // Into:
3223   //   %E = extractelement <M x iK> %vec, i32 C'
3224   //   icmp <pred> iK %E, trunc(C)
3225   Value *Vec;
3226   ArrayRef<int> Mask;
3227   if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3228     // Check whether every element of Mask is the same constant
3229     if (all_equal(Mask)) {
3230       auto *VecTy = cast<VectorType>(SrcType);
3231       auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3232       if (C->isSplat(EltTy->getBitWidth())) {
3233         // Fold the icmp based on the value of C
3234         // If C is M copies of an iK sized bit pattern,
3235         // then:
3236         //   =>  %E = extractelement <N x iK> %vec, i32 Elem
3237         //       icmp <pred> iK %SplatVal, <pattern>
3238         Value *Elem = Builder.getInt32(Mask[0]);
3239         Value *Extract = Builder.CreateExtractElement(Vec, Elem);
3240         Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3241         return new ICmpInst(Pred, Extract, NewC);
3242       }
3243     }
3244   }
3245   return nullptr;
3246 }
3247 
3248 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3249 /// where X is some kind of instruction.
3250 Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
3251   const APInt *C;
3252 
3253   if (match(Cmp.getOperand(1), m_APInt(C))) {
3254     if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3255       if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3256         return I;
3257 
3258     if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3259       // For now, we only support constant integers while folding the
3260       // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3261       // similar to the cases handled by binary ops above.
3262       if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3263         if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3264           return I;
3265 
3266     if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3267       if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3268         return I;
3269 
3270     if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3271       if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
3272         return I;
3273 
3274     // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3275     // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3276     // TODO: This checks one-use, but that is not strictly necessary.
3277     Value *Cmp0 = Cmp.getOperand(0);
3278     Value *X, *Y;
3279     if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3280         (match(Cmp0,
3281                m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
3282                    m_Value(X), m_Value(Y)))) ||
3283          match(Cmp0,
3284                m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
3285                    m_Value(X), m_Value(Y))))))
3286       return new ICmpInst(Cmp.getPredicate(), X, Y);
3287   }
3288 
3289   if (match(Cmp.getOperand(1), m_APIntAllowUndef(C)))
3290     return foldICmpInstWithConstantAllowUndef(Cmp, *C);
3291 
3292   return nullptr;
3293 }
3294 
3295 /// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3296 /// icmp eq/ne BO, C.
3297 Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
3298     ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3299   // TODO: Some of these folds could work with arbitrary constants, but this
3300   // function is limited to scalar and vector splat constants.
3301   if (!Cmp.isEquality())
3302     return nullptr;
3303 
3304   ICmpInst::Predicate Pred = Cmp.getPredicate();
3305   bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3306   Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3307   Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3308 
3309   switch (BO->getOpcode()) {
3310   case Instruction::SRem:
3311     // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3312     if (C.isZero() && BO->hasOneUse()) {
3313       const APInt *BOC;
3314       if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3315         Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3316         return new ICmpInst(Pred, NewRem,
3317                             Constant::getNullValue(BO->getType()));
3318       }
3319     }
3320     break;
3321   case Instruction::Add: {
3322     // (A + C2) == C --> A == (C - C2)
3323     // (A + C2) != C --> A != (C - C2)
3324     // TODO: Remove the one-use limitation? See discussion in D58633.
3325     if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3326       if (BO->hasOneUse())
3327         return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3328     } else if (C.isZero()) {
3329       // Replace ((add A, B) != 0) with (A != -B) if A or B is
3330       // efficiently invertible, or if the add has just this one use.
3331       if (Value *NegVal = dyn_castNegVal(BOp1))
3332         return new ICmpInst(Pred, BOp0, NegVal);
3333       if (Value *NegVal = dyn_castNegVal(BOp0))
3334         return new ICmpInst(Pred, NegVal, BOp1);
3335       if (BO->hasOneUse()) {
3336         Value *Neg = Builder.CreateNeg(BOp1);
3337         Neg->takeName(BO);
3338         return new ICmpInst(Pred, BOp0, Neg);
3339       }
3340     }
3341     break;
3342   }
3343   case Instruction::Xor:
3344     if (BO->hasOneUse()) {
3345       if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3346         // For the xor case, we can xor two constants together, eliminating
3347         // the explicit xor.
3348         return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3349       } else if (C.isZero()) {
3350         // Replace ((xor A, B) != 0) with (A != B)
3351         return new ICmpInst(Pred, BOp0, BOp1);
3352       }
3353     }
3354     break;
3355   case Instruction::Or: {
3356     const APInt *BOC;
3357     if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3358       // Comparing if all bits outside of a constant mask are set?
3359       // Replace (X | C) == -1 with (X & ~C) == ~C.
3360       // This removes the -1 constant.
3361       Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
3362       Value *And = Builder.CreateAnd(BOp0, NotBOC);
3363       return new ICmpInst(Pred, And, NotBOC);
3364     }
3365     break;
3366   }
3367   case Instruction::UDiv:
3368   case Instruction::SDiv:
3369     if (BO->isExact()) {
3370       // div exact X, Y eq/ne 0 -> X eq/ne 0
3371       // div exact X, Y eq/ne 1 -> X eq/ne Y
3372       // div exact X, Y eq/ne C ->
3373       //    if Y * C never-overflow && OneUse:
3374       //      -> Y * C eq/ne X
3375       if (C.isZero())
3376         return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3377       else if (C.isOne())
3378         return new ICmpInst(Pred, BOp0, BOp1);
3379       else if (BO->hasOneUse()) {
3380         OverflowResult OR = computeOverflow(
3381             Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3382             Cmp.getOperand(1), BO);
3383         if (OR == OverflowResult::NeverOverflows) {
3384           Value *YC =
3385               Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3386           return new ICmpInst(Pred, YC, BOp0);
3387         }
3388       }
3389     }
3390     if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3391       // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3392       auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3393       return new ICmpInst(NewPred, BOp1, BOp0);
3394     }
3395     break;
3396   default:
3397     break;
3398   }
3399   return nullptr;
3400 }
3401 
3402 static Instruction *foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs,
3403                                       const APInt &CRhs,
3404                                       InstCombiner::BuilderTy &Builder,
3405                                       const SimplifyQuery &Q) {
3406   assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3407          "Non-ctpop intrin in ctpop fold");
3408   if (!CtpopLhs->hasOneUse())
3409     return nullptr;
3410 
3411   // Power of 2 test:
3412   //    isPow2OrZero : ctpop(X) u< 2
3413   //    isPow2       : ctpop(X) == 1
3414   //    NotPow2OrZero: ctpop(X) u> 1
3415   //    NotPow2      : ctpop(X) != 1
3416   // If we know any bit of X can be folded to:
3417   //    IsPow2       : X & (~Bit) == 0
3418   //    NotPow2      : X & (~Bit) != 0
3419   const ICmpInst::Predicate Pred = I.getPredicate();
3420   if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3421       (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3422     Value *Op = CtpopLhs->getArgOperand(0);
3423     KnownBits OpKnown = computeKnownBits(Op, Q.DL,
3424                                          /*Depth*/ 0, Q.AC, Q.CxtI, Q.DT);
3425     // No need to check for count > 1, that should be already constant folded.
3426     if (OpKnown.countMinPopulation() == 1) {
3427       Value *And = Builder.CreateAnd(
3428           Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3429       return new ICmpInst(
3430           (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3431               ? ICmpInst::ICMP_EQ
3432               : ICmpInst::ICMP_NE,
3433           And, Constant::getNullValue(Op->getType()));
3434     }
3435   }
3436 
3437   return nullptr;
3438 }
3439 
3440 /// Fold an equality icmp with LLVM intrinsic and constant operand.
3441 Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
3442     ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3443   Type *Ty = II->getType();
3444   unsigned BitWidth = C.getBitWidth();
3445   const ICmpInst::Predicate Pred = Cmp.getPredicate();
3446 
3447   switch (II->getIntrinsicID()) {
3448   case Intrinsic::abs:
3449     // abs(A) == 0  ->  A == 0
3450     // abs(A) == INT_MIN  ->  A == INT_MIN
3451     if (C.isZero() || C.isMinSignedValue())
3452       return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3453     break;
3454 
3455   case Intrinsic::bswap:
3456     // bswap(A) == C  ->  A == bswap(C)
3457     return new ICmpInst(Pred, II->getArgOperand(0),
3458                         ConstantInt::get(Ty, C.byteSwap()));
3459 
3460   case Intrinsic::bitreverse:
3461     // bitreverse(A) == C  ->  A == bitreverse(C)
3462     return new ICmpInst(Pred, II->getArgOperand(0),
3463                         ConstantInt::get(Ty, C.reverseBits()));
3464 
3465   case Intrinsic::ctlz:
3466   case Intrinsic::cttz: {
3467     // ctz(A) == bitwidth(A)  ->  A == 0 and likewise for !=
3468     if (C == BitWidth)
3469       return new ICmpInst(Pred, II->getArgOperand(0),
3470                           ConstantInt::getNullValue(Ty));
3471 
3472     // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3473     // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3474     // Limit to one use to ensure we don't increase instruction count.
3475     unsigned Num = C.getLimitedValue(BitWidth);
3476     if (Num != BitWidth && II->hasOneUse()) {
3477       bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3478       APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3479                                : APInt::getHighBitsSet(BitWidth, Num + 1);
3480       APInt Mask2 = IsTrailing
3481         ? APInt::getOneBitSet(BitWidth, Num)
3482         : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3483       return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3484                           ConstantInt::get(Ty, Mask2));
3485     }
3486     break;
3487   }
3488 
3489   case Intrinsic::ctpop: {
3490     // popcount(A) == 0  ->  A == 0 and likewise for !=
3491     // popcount(A) == bitwidth(A)  ->  A == -1 and likewise for !=
3492     bool IsZero = C.isZero();
3493     if (IsZero || C == BitWidth)
3494       return new ICmpInst(Pred, II->getArgOperand(0),
3495                           IsZero ? Constant::getNullValue(Ty)
3496                                  : Constant::getAllOnesValue(Ty));
3497 
3498     break;
3499   }
3500 
3501   case Intrinsic::fshl:
3502   case Intrinsic::fshr:
3503     if (II->getArgOperand(0) == II->getArgOperand(1)) {
3504       const APInt *RotAmtC;
3505       // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3506       // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3507       if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3508         return new ICmpInst(Pred, II->getArgOperand(0),
3509                             II->getIntrinsicID() == Intrinsic::fshl
3510                                 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3511                                 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3512     }
3513     break;
3514 
3515   case Intrinsic::umax:
3516   case Intrinsic::uadd_sat: {
3517     // uadd.sat(a, b) == 0  ->  (a | b) == 0
3518     // umax(a, b) == 0  ->  (a | b) == 0
3519     if (C.isZero() && II->hasOneUse()) {
3520       Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
3521       return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3522     }
3523     break;
3524   }
3525 
3526   case Intrinsic::ssub_sat:
3527     // ssub.sat(a, b) == 0 -> a == b
3528     if (C.isZero())
3529       return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
3530     break;
3531   case Intrinsic::usub_sat: {
3532     // usub.sat(a, b) == 0  ->  a <= b
3533     if (C.isZero()) {
3534       ICmpInst::Predicate NewPred =
3535           Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3536       return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
3537     }
3538     break;
3539   }
3540   default:
3541     break;
3542   }
3543 
3544   return nullptr;
3545 }
3546 
3547 /// Fold an icmp with LLVM intrinsics
3548 static Instruction *
3549 foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp,
3550                                InstCombiner::BuilderTy &Builder) {
3551   assert(Cmp.isEquality());
3552 
3553   ICmpInst::Predicate Pred = Cmp.getPredicate();
3554   Value *Op0 = Cmp.getOperand(0);
3555   Value *Op1 = Cmp.getOperand(1);
3556   const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3557   const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3558   if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3559     return nullptr;
3560 
3561   switch (IIOp0->getIntrinsicID()) {
3562   case Intrinsic::bswap:
3563   case Intrinsic::bitreverse:
3564     // If both operands are byte-swapped or bit-reversed, just compare the
3565     // original values.
3566     return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3567   case Intrinsic::fshl:
3568   case Intrinsic::fshr: {
3569     // If both operands are rotated by same amount, just compare the
3570     // original values.
3571     if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3572       break;
3573     if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3574       break;
3575     if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
3576       return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3577 
3578     // rotate(X, AmtX) == rotate(Y, AmtY)
3579     //  -> rotate(X, AmtX - AmtY) == Y
3580     // Do this if either both rotates have one use or if only one has one use
3581     // and AmtX/AmtY are constants.
3582     unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
3583     if (OneUses == 2 ||
3584         (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
3585          match(IIOp1->getOperand(2), m_ImmConstant()))) {
3586       Value *SubAmt =
3587           Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
3588       Value *CombinedRotate = Builder.CreateIntrinsic(
3589           Op0->getType(), IIOp0->getIntrinsicID(),
3590           {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
3591       return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
3592     }
3593   } break;
3594   default:
3595     break;
3596   }
3597 
3598   return nullptr;
3599 }
3600 
3601 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3602 /// where X is some kind of instruction and C is AllowUndef.
3603 /// TODO: Move more folds which allow undef to this function.
3604 Instruction *
3605 InstCombinerImpl::foldICmpInstWithConstantAllowUndef(ICmpInst &Cmp,
3606                                                      const APInt &C) {
3607   const ICmpInst::Predicate Pred = Cmp.getPredicate();
3608   if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3609     switch (II->getIntrinsicID()) {
3610     default:
3611       break;
3612     case Intrinsic::fshl:
3613     case Intrinsic::fshr:
3614       if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
3615         // (rot X, ?) == 0/-1 --> X == 0/-1
3616         if (C.isZero() || C.isAllOnes())
3617           return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
3618       }
3619       break;
3620     }
3621   }
3622 
3623   return nullptr;
3624 }
3625 
3626 /// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
3627 Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
3628                                                          BinaryOperator *BO,
3629                                                          const APInt &C) {
3630   switch (BO->getOpcode()) {
3631   case Instruction::Xor:
3632     if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
3633       return I;
3634     break;
3635   case Instruction::And:
3636     if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
3637       return I;
3638     break;
3639   case Instruction::Or:
3640     if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
3641       return I;
3642     break;
3643   case Instruction::Mul:
3644     if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
3645       return I;
3646     break;
3647   case Instruction::Shl:
3648     if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
3649       return I;
3650     break;
3651   case Instruction::LShr:
3652   case Instruction::AShr:
3653     if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
3654       return I;
3655     break;
3656   case Instruction::SRem:
3657     if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
3658       return I;
3659     break;
3660   case Instruction::UDiv:
3661     if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
3662       return I;
3663     [[fallthrough]];
3664   case Instruction::SDiv:
3665     if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
3666       return I;
3667     break;
3668   case Instruction::Sub:
3669     if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
3670       return I;
3671     break;
3672   case Instruction::Add:
3673     if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
3674       return I;
3675     break;
3676   default:
3677     break;
3678   }
3679 
3680   // TODO: These folds could be refactored to be part of the above calls.
3681   return foldICmpBinOpEqualityWithConstant(Cmp, BO, C);
3682 }
3683 
3684 static Instruction *
3685 foldICmpUSubSatOrUAddSatWithConstant(ICmpInst::Predicate Pred,
3686                                      SaturatingInst *II, const APInt &C,
3687                                      InstCombiner::BuilderTy &Builder) {
3688   // This transform may end up producing more than one instruction for the
3689   // intrinsic, so limit it to one user of the intrinsic.
3690   if (!II->hasOneUse())
3691     return nullptr;
3692 
3693   // Let Y        = [add/sub]_sat(X, C) pred C2
3694   //     SatVal   = The saturating value for the operation
3695   //     WillWrap = Whether or not the operation will underflow / overflow
3696   // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
3697   // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
3698   //
3699   // When (SatVal pred C2) is true, then
3700   //    Y = WillWrap ? true : ((X binop C) pred C2)
3701   // => Y = WillWrap || ((X binop C) pred C2)
3702   // else
3703   //    Y =  WillWrap ? false : ((X binop C) pred C2)
3704   // => Y = !WillWrap ?  ((X binop C) pred C2) : false
3705   // => Y = !WillWrap && ((X binop C) pred C2)
3706   Value *Op0 = II->getOperand(0);
3707   Value *Op1 = II->getOperand(1);
3708 
3709   const APInt *COp1;
3710   // This transform only works when the intrinsic has an integral constant or
3711   // splat vector as the second operand.
3712   if (!match(Op1, m_APInt(COp1)))
3713     return nullptr;
3714 
3715   APInt SatVal;
3716   switch (II->getIntrinsicID()) {
3717   default:
3718     llvm_unreachable(
3719         "This function only works with usub_sat and uadd_sat for now!");
3720   case Intrinsic::uadd_sat:
3721     SatVal = APInt::getAllOnes(C.getBitWidth());
3722     break;
3723   case Intrinsic::usub_sat:
3724     SatVal = APInt::getZero(C.getBitWidth());
3725     break;
3726   }
3727 
3728   // Check (SatVal pred C2)
3729   bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
3730 
3731   // !WillWrap.
3732   ConstantRange C1 = ConstantRange::makeExactNoWrapRegion(
3733       II->getBinaryOp(), *COp1, II->getNoWrapKind());
3734 
3735   // WillWrap.
3736   if (SatValCheck)
3737     C1 = C1.inverse();
3738 
3739   ConstantRange C2 = ConstantRange::makeExactICmpRegion(Pred, C);
3740   if (II->getBinaryOp() == Instruction::Add)
3741     C2 = C2.sub(*COp1);
3742   else
3743     C2 = C2.add(*COp1);
3744 
3745   Instruction::BinaryOps CombiningOp =
3746       SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
3747 
3748   std::optional<ConstantRange> Combination;
3749   if (CombiningOp == Instruction::BinaryOps::Or)
3750     Combination = C1.exactUnionWith(C2);
3751   else /* CombiningOp == Instruction::BinaryOps::And */
3752     Combination = C1.exactIntersectWith(C2);
3753 
3754   if (!Combination)
3755     return nullptr;
3756 
3757   CmpInst::Predicate EquivPred;
3758   APInt EquivInt;
3759   APInt EquivOffset;
3760 
3761   Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3762 
3763   return new ICmpInst(
3764       EquivPred,
3765       Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
3766       ConstantInt::get(Op1->getType(), EquivInt));
3767 }
3768 
3769 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
3770 Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
3771                                                              IntrinsicInst *II,
3772                                                              const APInt &C) {
3773   ICmpInst::Predicate Pred = Cmp.getPredicate();
3774 
3775   // Handle folds that apply for any kind of icmp.
3776   switch (II->getIntrinsicID()) {
3777   default:
3778     break;
3779   case Intrinsic::uadd_sat:
3780   case Intrinsic::usub_sat:
3781     if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
3782             Pred, cast<SaturatingInst>(II), C, Builder))
3783       return Folded;
3784     break;
3785   case Intrinsic::ctpop: {
3786     const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3787     if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
3788       return R;
3789   } break;
3790   }
3791 
3792   if (Cmp.isEquality())
3793     return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
3794 
3795   Type *Ty = II->getType();
3796   unsigned BitWidth = C.getBitWidth();
3797   switch (II->getIntrinsicID()) {
3798   case Intrinsic::ctpop: {
3799     // (ctpop X > BitWidth - 1) --> X == -1
3800     Value *X = II->getArgOperand(0);
3801     if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
3802       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
3803                              ConstantInt::getAllOnesValue(Ty));
3804     // (ctpop X < BitWidth) --> X != -1
3805     if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
3806       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
3807                              ConstantInt::getAllOnesValue(Ty));
3808     break;
3809   }
3810   case Intrinsic::ctlz: {
3811     // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
3812     if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3813       unsigned Num = C.getLimitedValue();
3814       APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3815       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
3816                              II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3817     }
3818 
3819     // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
3820     if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3821       unsigned Num = C.getLimitedValue();
3822       APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);
3823       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
3824                              II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3825     }
3826     break;
3827   }
3828   case Intrinsic::cttz: {
3829     // Limit to one use to ensure we don't increase instruction count.
3830     if (!II->hasOneUse())
3831       return nullptr;
3832 
3833     // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
3834     if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3835       APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
3836       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
3837                              Builder.CreateAnd(II->getArgOperand(0), Mask),
3838                              ConstantInt::getNullValue(Ty));
3839     }
3840 
3841     // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
3842     if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3843       APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
3844       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
3845                              Builder.CreateAnd(II->getArgOperand(0), Mask),
3846                              ConstantInt::getNullValue(Ty));
3847     }
3848     break;
3849   }
3850   case Intrinsic::ssub_sat:
3851     // ssub.sat(a, b) spred 0 -> a spred b
3852     if (ICmpInst::isSigned(Pred)) {
3853       if (C.isZero())
3854         return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
3855       // X s<= 0 is cannonicalized to X s< 1
3856       if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3857         return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
3858                             II->getArgOperand(1));
3859       // X s>= 0 is cannonicalized to X s> -1
3860       if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3861         return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
3862                             II->getArgOperand(1));
3863     }
3864     break;
3865   default:
3866     break;
3867   }
3868 
3869   return nullptr;
3870 }
3871 
3872 /// Handle icmp with constant (but not simple integer constant) RHS.
3873 Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
3874   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3875   Constant *RHSC = dyn_cast<Constant>(Op1);
3876   Instruction *LHSI = dyn_cast<Instruction>(Op0);
3877   if (!RHSC || !LHSI)
3878     return nullptr;
3879 
3880   switch (LHSI->getOpcode()) {
3881   case Instruction::GetElementPtr:
3882     // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3883     if (RHSC->isNullValue() &&
3884         cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3885       return new ICmpInst(
3886           I.getPredicate(), LHSI->getOperand(0),
3887           Constant::getNullValue(LHSI->getOperand(0)->getType()));
3888     break;
3889   case Instruction::PHI:
3890     // Only fold icmp into the PHI if the phi and icmp are in the same
3891     // block.  If in the same block, we're encouraging jump threading.  If
3892     // not, we are just pessimizing the code by making an i1 phi.
3893     if (LHSI->getParent() == I.getParent())
3894       if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3895         return NV;
3896     break;
3897   case Instruction::IntToPtr:
3898     // icmp pred inttoptr(X), null -> icmp pred X, 0
3899     if (RHSC->isNullValue() &&
3900         DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3901       return new ICmpInst(
3902           I.getPredicate(), LHSI->getOperand(0),
3903           Constant::getNullValue(LHSI->getOperand(0)->getType()));
3904     break;
3905 
3906   case Instruction::Load:
3907     // Try to optimize things like "A[i] > 4" to index computations.
3908     if (GetElementPtrInst *GEP =
3909             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
3910       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3911         if (Instruction *Res =
3912                 foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I))
3913           return Res;
3914     break;
3915   }
3916 
3917   return nullptr;
3918 }
3919 
3920 Instruction *InstCombinerImpl::foldSelectICmp(ICmpInst::Predicate Pred,
3921                                               SelectInst *SI, Value *RHS,
3922                                               const ICmpInst &I) {
3923   // Try to fold the comparison into the select arms, which will cause the
3924   // select to be converted into a logical and/or.
3925   auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
3926     if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
3927       return Res;
3928     if (std::optional<bool> Impl = isImpliedCondition(
3929             SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
3930       return ConstantInt::get(I.getType(), *Impl);
3931     return nullptr;
3932   };
3933 
3934   ConstantInt *CI = nullptr;
3935   Value *Op1 = SimplifyOp(SI->getOperand(1), true);
3936   if (Op1)
3937     CI = dyn_cast<ConstantInt>(Op1);
3938 
3939   Value *Op2 = SimplifyOp(SI->getOperand(2), false);
3940   if (Op2)
3941     CI = dyn_cast<ConstantInt>(Op2);
3942 
3943   // We only want to perform this transformation if it will not lead to
3944   // additional code. This is true if either both sides of the select
3945   // fold to a constant (in which case the icmp is replaced with a select
3946   // which will usually simplify) or this is the only user of the
3947   // select (in which case we are trading a select+icmp for a simpler
3948   // select+icmp) or all uses of the select can be replaced based on
3949   // dominance information ("Global cases").
3950   bool Transform = false;
3951   if (Op1 && Op2)
3952     Transform = true;
3953   else if (Op1 || Op2) {
3954     // Local case
3955     if (SI->hasOneUse())
3956       Transform = true;
3957     // Global cases
3958     else if (CI && !CI->isZero())
3959       // When Op1 is constant try replacing select with second operand.
3960       // Otherwise Op2 is constant and try replacing select with first
3961       // operand.
3962       Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
3963   }
3964   if (Transform) {
3965     if (!Op1)
3966       Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
3967     if (!Op2)
3968       Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
3969     return SelectInst::Create(SI->getOperand(0), Op1, Op2);
3970   }
3971 
3972   return nullptr;
3973 }
3974 
3975 /// Some comparisons can be simplified.
3976 /// In this case, we are looking for comparisons that look like
3977 /// a check for a lossy truncation.
3978 /// Folds:
3979 ///   icmp SrcPred (x & Mask), x    to    icmp DstPred x, Mask
3980 /// Where Mask is some pattern that produces all-ones in low bits:
3981 ///    (-1 >> y)
3982 ///    ((-1 << y) >> y)     <- non-canonical, has extra uses
3983 ///   ~(-1 << y)
3984 ///    ((1 << y) + (-1))    <- non-canonical, has extra uses
3985 /// The Mask can be a constant, too.
3986 /// For some predicates, the operands are commutative.
3987 /// For others, x can only be on a specific side.
3988 static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I,
3989                                           InstCombiner::BuilderTy &Builder) {
3990   ICmpInst::Predicate SrcPred;
3991   Value *X, *M, *Y;
3992   auto m_VariableMask = m_CombineOr(
3993       m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())),
3994                   m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
3995       m_CombineOr(m_LShr(m_AllOnes(), m_Value()),
3996                   m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y))));
3997   auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
3998   if (!match(&I, m_c_ICmp(SrcPred,
3999                           m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)),
4000                           m_Deferred(X))))
4001     return nullptr;
4002 
4003   ICmpInst::Predicate DstPred;
4004   switch (SrcPred) {
4005   case ICmpInst::Predicate::ICMP_EQ:
4006     //  x & (-1 >> y) == x    ->    x u<= (-1 >> y)
4007     DstPred = ICmpInst::Predicate::ICMP_ULE;
4008     break;
4009   case ICmpInst::Predicate::ICMP_NE:
4010     //  x & (-1 >> y) != x    ->    x u> (-1 >> y)
4011     DstPred = ICmpInst::Predicate::ICMP_UGT;
4012     break;
4013   case ICmpInst::Predicate::ICMP_ULT:
4014     //  x & (-1 >> y) u< x    ->    x u> (-1 >> y)
4015     //  x u> x & (-1 >> y)    ->    x u> (-1 >> y)
4016     DstPred = ICmpInst::Predicate::ICMP_UGT;
4017     break;
4018   case ICmpInst::Predicate::ICMP_UGE:
4019     //  x & (-1 >> y) u>= x    ->    x u<= (-1 >> y)
4020     //  x u<= x & (-1 >> y)    ->    x u<= (-1 >> y)
4021     DstPred = ICmpInst::Predicate::ICMP_ULE;
4022     break;
4023   case ICmpInst::Predicate::ICMP_SLT:
4024     //  x & (-1 >> y) s< x    ->    x s> (-1 >> y)
4025     //  x s> x & (-1 >> y)    ->    x s> (-1 >> y)
4026     if (!match(M, m_Constant())) // Can not do this fold with non-constant.
4027       return nullptr;
4028     if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
4029       return nullptr;
4030     DstPred = ICmpInst::Predicate::ICMP_SGT;
4031     break;
4032   case ICmpInst::Predicate::ICMP_SGE:
4033     //  x & (-1 >> y) s>= x    ->    x s<= (-1 >> y)
4034     //  x s<= x & (-1 >> y)    ->    x s<= (-1 >> y)
4035     if (!match(M, m_Constant())) // Can not do this fold with non-constant.
4036       return nullptr;
4037     if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
4038       return nullptr;
4039     DstPred = ICmpInst::Predicate::ICMP_SLE;
4040     break;
4041   case ICmpInst::Predicate::ICMP_SGT:
4042   case ICmpInst::Predicate::ICMP_SLE:
4043     return nullptr;
4044   case ICmpInst::Predicate::ICMP_UGT:
4045   case ICmpInst::Predicate::ICMP_ULE:
4046     llvm_unreachable("Instsimplify took care of commut. variant");
4047     break;
4048   default:
4049     llvm_unreachable("All possible folds are handled.");
4050   }
4051 
4052   // The mask value may be a vector constant that has undefined elements. But it
4053   // may not be safe to propagate those undefs into the new compare, so replace
4054   // those elements by copying an existing, defined, and safe scalar constant.
4055   Type *OpTy = M->getType();
4056   auto *VecC = dyn_cast<Constant>(M);
4057   auto *OpVTy = dyn_cast<FixedVectorType>(OpTy);
4058   if (OpVTy && VecC && VecC->containsUndefOrPoisonElement()) {
4059     Constant *SafeReplacementConstant = nullptr;
4060     for (unsigned i = 0, e = OpVTy->getNumElements(); i != e; ++i) {
4061       if (!isa<UndefValue>(VecC->getAggregateElement(i))) {
4062         SafeReplacementConstant = VecC->getAggregateElement(i);
4063         break;
4064       }
4065     }
4066     assert(SafeReplacementConstant && "Failed to find undef replacement");
4067     M = Constant::replaceUndefsWith(VecC, SafeReplacementConstant);
4068   }
4069 
4070   return Builder.CreateICmp(DstPred, X, M);
4071 }
4072 
4073 /// Some comparisons can be simplified.
4074 /// In this case, we are looking for comparisons that look like
4075 /// a check for a lossy signed truncation.
4076 /// Folds:   (MaskedBits is a constant.)
4077 ///   ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4078 /// Into:
4079 ///   (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4080 /// Where  KeptBits = bitwidth(%x) - MaskedBits
4081 static Value *
4082 foldICmpWithTruncSignExtendedVal(ICmpInst &I,
4083                                  InstCombiner::BuilderTy &Builder) {
4084   ICmpInst::Predicate SrcPred;
4085   Value *X;
4086   const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4087   // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4088   if (!match(&I, m_c_ICmp(SrcPred,
4089                           m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)),
4090                                           m_APInt(C1))),
4091                           m_Deferred(X))))
4092     return nullptr;
4093 
4094   // Potential handling of non-splats: for each element:
4095   //  * if both are undef, replace with constant 0.
4096   //    Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4097   //  * if both are not undef, and are different, bailout.
4098   //  * else, only one is undef, then pick the non-undef one.
4099 
4100   // The shift amount must be equal.
4101   if (*C0 != *C1)
4102     return nullptr;
4103   const APInt &MaskedBits = *C0;
4104   assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4105 
4106   ICmpInst::Predicate DstPred;
4107   switch (SrcPred) {
4108   case ICmpInst::Predicate::ICMP_EQ:
4109     // ((%x << MaskedBits) a>> MaskedBits) == %x
4110     //   =>
4111     // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4112     DstPred = ICmpInst::Predicate::ICMP_ULT;
4113     break;
4114   case ICmpInst::Predicate::ICMP_NE:
4115     // ((%x << MaskedBits) a>> MaskedBits) != %x
4116     //   =>
4117     // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4118     DstPred = ICmpInst::Predicate::ICMP_UGE;
4119     break;
4120   // FIXME: are more folds possible?
4121   default:
4122     return nullptr;
4123   }
4124 
4125   auto *XType = X->getType();
4126   const unsigned XBitWidth = XType->getScalarSizeInBits();
4127   const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4128   assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4129 
4130   // KeptBits = bitwidth(%x) - MaskedBits
4131   const APInt KeptBits = BitWidth - MaskedBits;
4132   assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4133   // ICmpCst = (1 << KeptBits)
4134   const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4135   assert(ICmpCst.isPowerOf2());
4136   // AddCst = (1 << (KeptBits-1))
4137   const APInt AddCst = ICmpCst.lshr(1);
4138   assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4139 
4140   // T0 = add %x, AddCst
4141   Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4142   // T1 = T0 DstPred ICmpCst
4143   Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4144 
4145   return T1;
4146 }
4147 
4148 // Given pattern:
4149 //   icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4150 // we should move shifts to the same hand of 'and', i.e. rewrite as
4151 //   icmp eq/ne (and (x shift (Q+K)), y), 0  iff (Q+K) u< bitwidth(x)
4152 // We are only interested in opposite logical shifts here.
4153 // One of the shifts can be truncated.
4154 // If we can, we want to end up creating 'lshr' shift.
4155 static Value *
4156 foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
4157                                            InstCombiner::BuilderTy &Builder) {
4158   if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4159       !I.getOperand(0)->hasOneUse())
4160     return nullptr;
4161 
4162   auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4163 
4164   // Look for an 'and' of two logical shifts, one of which may be truncated.
4165   // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4166   Instruction *XShift, *MaybeTruncation, *YShift;
4167   if (!match(
4168           I.getOperand(0),
4169           m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4170                   m_CombineAnd(m_TruncOrSelf(m_CombineAnd(
4171                                    m_AnyLogicalShift, m_Instruction(YShift))),
4172                                m_Instruction(MaybeTruncation)))))
4173     return nullptr;
4174 
4175   // We potentially looked past 'trunc', but only when matching YShift,
4176   // therefore YShift must have the widest type.
4177   Instruction *WidestShift = YShift;
4178   // Therefore XShift must have the shallowest type.
4179   // Or they both have identical types if there was no truncation.
4180   Instruction *NarrowestShift = XShift;
4181 
4182   Type *WidestTy = WidestShift->getType();
4183   Type *NarrowestTy = NarrowestShift->getType();
4184   assert(NarrowestTy == I.getOperand(0)->getType() &&
4185          "We did not look past any shifts while matching XShift though.");
4186   bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4187 
4188   // If YShift is a 'lshr', swap the shifts around.
4189   if (match(YShift, m_LShr(m_Value(), m_Value())))
4190     std::swap(XShift, YShift);
4191 
4192   // The shifts must be in opposite directions.
4193   auto XShiftOpcode = XShift->getOpcode();
4194   if (XShiftOpcode == YShift->getOpcode())
4195     return nullptr; // Do not care about same-direction shifts here.
4196 
4197   Value *X, *XShAmt, *Y, *YShAmt;
4198   match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4199   match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4200 
4201   // If one of the values being shifted is a constant, then we will end with
4202   // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4203   // however, we will need to ensure that we won't increase instruction count.
4204   if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4205     // At least one of the hands of the 'and' should be one-use shift.
4206     if (!match(I.getOperand(0),
4207                m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4208       return nullptr;
4209     if (HadTrunc) {
4210       // Due to the 'trunc', we will need to widen X. For that either the old
4211       // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4212       if (!MaybeTruncation->hasOneUse() &&
4213           !NarrowestShift->getOperand(1)->hasOneUse())
4214         return nullptr;
4215     }
4216   }
4217 
4218   // We have two shift amounts from two different shifts. The types of those
4219   // shift amounts may not match. If that's the case let's bailout now.
4220   if (XShAmt->getType() != YShAmt->getType())
4221     return nullptr;
4222 
4223   // As input, we have the following pattern:
4224   //   icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4225   // We want to rewrite that as:
4226   //   icmp eq/ne (and (x shift (Q+K)), y), 0  iff (Q+K) u< bitwidth(x)
4227   // While we know that originally (Q+K) would not overflow
4228   // (because  2 * (N-1) u<= iN -1), we have looked past extensions of
4229   // shift amounts. so it may now overflow in smaller bitwidth.
4230   // To ensure that does not happen, we need to ensure that the total maximal
4231   // shift amount is still representable in that smaller bit width.
4232   unsigned MaximalPossibleTotalShiftAmount =
4233       (WidestTy->getScalarSizeInBits() - 1) +
4234       (NarrowestTy->getScalarSizeInBits() - 1);
4235   APInt MaximalRepresentableShiftAmount =
4236       APInt::getAllOnes(XShAmt->getType()->getScalarSizeInBits());
4237   if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
4238     return nullptr;
4239 
4240   // Can we fold (XShAmt+YShAmt) ?
4241   auto *NewShAmt = dyn_cast_or_null<Constant>(
4242       simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
4243                       /*isNUW=*/false, SQ.getWithInstruction(&I)));
4244   if (!NewShAmt)
4245     return nullptr;
4246   NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy);
4247   unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4248 
4249   // Is the new shift amount smaller than the bit width?
4250   // FIXME: could also rely on ConstantRange.
4251   if (!match(NewShAmt,
4252              m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
4253                                 APInt(WidestBitWidth, WidestBitWidth))))
4254     return nullptr;
4255 
4256   // An extra legality check is needed if we had trunc-of-lshr.
4257   if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
4258     auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4259                     WidestShift]() {
4260       // It isn't obvious whether it's worth it to analyze non-constants here.
4261       // Also, let's basically give up on non-splat cases, pessimizing vectors.
4262       // If *any* of these preconditions matches we can perform the fold.
4263       Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4264                                     ? NewShAmt->getSplatValue()
4265                                     : NewShAmt;
4266       // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4267       if (NewShAmtSplat &&
4268           (NewShAmtSplat->isNullValue() ||
4269            NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4270         return true;
4271       // We consider *min* leading zeros so a single outlier
4272       // blocks the transform as opposed to allowing it.
4273       if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
4274         KnownBits Known = computeKnownBits(C, SQ.DL);
4275         unsigned MinLeadZero = Known.countMinLeadingZeros();
4276         // If the value being shifted has at most lowest bit set we can fold.
4277         unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4278         if (MaxActiveBits <= 1)
4279           return true;
4280         // Precondition:  NewShAmt u<= countLeadingZeros(C)
4281         if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
4282           return true;
4283       }
4284       if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
4285         KnownBits Known = computeKnownBits(C, SQ.DL);
4286         unsigned MinLeadZero = Known.countMinLeadingZeros();
4287         // If the value being shifted has at most lowest bit set we can fold.
4288         unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4289         if (MaxActiveBits <= 1)
4290           return true;
4291         // Precondition:  ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
4292         if (NewShAmtSplat) {
4293           APInt AdjNewShAmt =
4294               (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
4295           if (AdjNewShAmt.ule(MinLeadZero))
4296             return true;
4297         }
4298       }
4299       return false; // Can't tell if it's ok.
4300     };
4301     if (!CanFold())
4302       return nullptr;
4303   }
4304 
4305   // All good, we can do this fold.
4306   X = Builder.CreateZExt(X, WidestTy);
4307   Y = Builder.CreateZExt(Y, WidestTy);
4308   // The shift is the same that was for X.
4309   Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4310                   ? Builder.CreateLShr(X, NewShAmt)
4311                   : Builder.CreateShl(X, NewShAmt);
4312   Value *T1 = Builder.CreateAnd(T0, Y);
4313   return Builder.CreateICmp(I.getPredicate(), T1,
4314                             Constant::getNullValue(WidestTy));
4315 }
4316 
4317 /// Fold
4318 ///   (-1 u/ x) u< y
4319 ///   ((x * y) ?/ x) != y
4320 /// to
4321 ///   @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4322 /// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4323 /// will mean that we are looking for the opposite answer.
4324 Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
4325   ICmpInst::Predicate Pred;
4326   Value *X, *Y;
4327   Instruction *Mul;
4328   Instruction *Div;
4329   bool NeedNegation;
4330   // Look for: (-1 u/ x) u</u>= y
4331   if (!I.isEquality() &&
4332       match(&I, m_c_ICmp(Pred,
4333                          m_CombineAnd(m_OneUse(m_UDiv(m_AllOnes(), m_Value(X))),
4334                                       m_Instruction(Div)),
4335                          m_Value(Y)))) {
4336     Mul = nullptr;
4337 
4338     // Are we checking that overflow does not happen, or does happen?
4339     switch (Pred) {
4340     case ICmpInst::Predicate::ICMP_ULT:
4341       NeedNegation = false;
4342       break; // OK
4343     case ICmpInst::Predicate::ICMP_UGE:
4344       NeedNegation = true;
4345       break; // OK
4346     default:
4347       return nullptr; // Wrong predicate.
4348     }
4349   } else // Look for: ((x * y) / x) !=/== y
4350       if (I.isEquality() &&
4351           match(&I,
4352                 m_c_ICmp(Pred, m_Value(Y),
4353                          m_CombineAnd(
4354                              m_OneUse(m_IDiv(m_CombineAnd(m_c_Mul(m_Deferred(Y),
4355                                                                   m_Value(X)),
4356                                                           m_Instruction(Mul)),
4357                                              m_Deferred(X))),
4358                              m_Instruction(Div))))) {
4359     NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4360   } else
4361     return nullptr;
4362 
4363   BuilderTy::InsertPointGuard Guard(Builder);
4364   // If the pattern included (x * y), we'll want to insert new instructions
4365   // right before that original multiplication so that we can replace it.
4366   bool MulHadOtherUses = Mul && !Mul->hasOneUse();
4367   if (MulHadOtherUses)
4368     Builder.SetInsertPoint(Mul);
4369 
4370   Function *F = Intrinsic::getDeclaration(I.getModule(),
4371                                           Div->getOpcode() == Instruction::UDiv
4372                                               ? Intrinsic::umul_with_overflow
4373                                               : Intrinsic::smul_with_overflow,
4374                                           X->getType());
4375   CallInst *Call = Builder.CreateCall(F, {X, Y}, "mul");
4376 
4377   // If the multiplication was used elsewhere, to ensure that we don't leave
4378   // "duplicate" instructions, replace uses of that original multiplication
4379   // with the multiplication result from the with.overflow intrinsic.
4380   if (MulHadOtherUses)
4381     replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
4382 
4383   Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
4384   if (NeedNegation) // This technically increases instruction count.
4385     Res = Builder.CreateNot(Res, "mul.not.ov");
4386 
4387   // If we replaced the mul, erase it. Do this after all uses of Builder,
4388   // as the mul is used as insertion point.
4389   if (MulHadOtherUses)
4390     eraseInstFromFunction(*Mul);
4391 
4392   return Res;
4393 }
4394 
4395 static Instruction *foldICmpXNegX(ICmpInst &I,
4396                                   InstCombiner::BuilderTy &Builder) {
4397   CmpInst::Predicate Pred;
4398   Value *X;
4399   if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
4400 
4401     if (ICmpInst::isSigned(Pred))
4402       Pred = ICmpInst::getSwappedPredicate(Pred);
4403     else if (ICmpInst::isUnsigned(Pred))
4404       Pred = ICmpInst::getSignedPredicate(Pred);
4405     // else for equality-comparisons just keep the predicate.
4406 
4407     return ICmpInst::Create(Instruction::ICmp, Pred, X,
4408                             Constant::getNullValue(X->getType()), I.getName());
4409   }
4410 
4411   // A value is not equal to its negation unless that value is 0 or
4412   // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
4413   if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
4414       ICmpInst::isEquality(Pred)) {
4415     Type *Ty = X->getType();
4416     uint32_t BitWidth = Ty->getScalarSizeInBits();
4417     Constant *MaxSignedVal =
4418         ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
4419     Value *And = Builder.CreateAnd(X, MaxSignedVal);
4420     Constant *Zero = Constant::getNullValue(Ty);
4421     return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
4422   }
4423 
4424   return nullptr;
4425 }
4426 
4427 static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,
4428                                   InstCombinerImpl &IC) {
4429   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
4430   // Normalize xor operand as operand 0.
4431   CmpInst::Predicate Pred = I.getPredicate();
4432   if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
4433     std::swap(Op0, Op1);
4434     Pred = ICmpInst::getSwappedPredicate(Pred);
4435   }
4436   if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
4437     return nullptr;
4438 
4439   // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
4440   // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
4441   // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
4442   // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
4443   CmpInst::Predicate PredOut = CmpInst::getStrictPredicate(Pred);
4444   if (PredOut != Pred &&
4445       isKnownNonZero(A, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4446     return new ICmpInst(PredOut, Op0, Op1);
4447 
4448   return nullptr;
4449 }
4450 
4451 /// Try to fold icmp (binop), X or icmp X, (binop).
4452 /// TODO: A large part of this logic is duplicated in InstSimplify's
4453 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
4454 /// duplication.
4455 Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
4456                                              const SimplifyQuery &SQ) {
4457   const SimplifyQuery Q = SQ.getWithInstruction(&I);
4458   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4459 
4460   // Special logic for binary operators.
4461   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
4462   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
4463   if (!BO0 && !BO1)
4464     return nullptr;
4465 
4466   if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
4467     return NewICmp;
4468 
4469   const CmpInst::Predicate Pred = I.getPredicate();
4470   Value *X;
4471 
4472   // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
4473   // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
4474   if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
4475       (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
4476     return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
4477   // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
4478   if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
4479       (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
4480     return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
4481 
4482   {
4483     // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
4484     Constant *C;
4485     if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
4486                                   m_ImmConstant(C)))) &&
4487         (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
4488       Constant *C2 = ConstantExpr::getNot(C);
4489       return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
4490     }
4491     // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
4492     if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
4493                                   m_ImmConstant(C)))) &&
4494         (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
4495       Constant *C2 = ConstantExpr::getNot(C);
4496       return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
4497     }
4498   }
4499 
4500   {
4501     // Similar to above: an unsigned overflow comparison may use offset + mask:
4502     // ((Op1 + C) & C) u<  Op1 --> Op1 != 0
4503     // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
4504     // Op0 u>  ((Op0 + C) & C) --> Op0 != 0
4505     // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
4506     BinaryOperator *BO;
4507     const APInt *C;
4508     if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
4509         match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4510         match(BO, m_Add(m_Specific(Op1), m_SpecificIntAllowUndef(*C)))) {
4511       CmpInst::Predicate NewPred =
4512           Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
4513       Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4514       return new ICmpInst(NewPred, Op1, Zero);
4515     }
4516 
4517     if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
4518         match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4519         match(BO, m_Add(m_Specific(Op0), m_SpecificIntAllowUndef(*C)))) {
4520       CmpInst::Predicate NewPred =
4521           Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
4522       Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4523       return new ICmpInst(NewPred, Op0, Zero);
4524     }
4525   }
4526 
4527   bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
4528   if (BO0 && isa<OverflowingBinaryOperator>(BO0))
4529     NoOp0WrapProblem =
4530         ICmpInst::isEquality(Pred) ||
4531         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
4532         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
4533   if (BO1 && isa<OverflowingBinaryOperator>(BO1))
4534     NoOp1WrapProblem =
4535         ICmpInst::isEquality(Pred) ||
4536         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
4537         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
4538 
4539   // Analyze the case when either Op0 or Op1 is an add instruction.
4540   // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
4541   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
4542   if (BO0 && BO0->getOpcode() == Instruction::Add) {
4543     A = BO0->getOperand(0);
4544     B = BO0->getOperand(1);
4545   }
4546   if (BO1 && BO1->getOpcode() == Instruction::Add) {
4547     C = BO1->getOperand(0);
4548     D = BO1->getOperand(1);
4549   }
4550 
4551   // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
4552   // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
4553   if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
4554     return new ICmpInst(Pred, A == Op1 ? B : A,
4555                         Constant::getNullValue(Op1->getType()));
4556 
4557   // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
4558   // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
4559   if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
4560     return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
4561                         C == Op0 ? D : C);
4562 
4563   // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
4564   if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
4565       NoOp1WrapProblem) {
4566     // Determine Y and Z in the form icmp (X+Y), (X+Z).
4567     Value *Y, *Z;
4568     if (A == C) {
4569       // C + B == C + D  ->  B == D
4570       Y = B;
4571       Z = D;
4572     } else if (A == D) {
4573       // D + B == C + D  ->  B == C
4574       Y = B;
4575       Z = C;
4576     } else if (B == C) {
4577       // A + C == C + D  ->  A == D
4578       Y = A;
4579       Z = D;
4580     } else {
4581       assert(B == D);
4582       // A + D == C + D  ->  A == C
4583       Y = A;
4584       Z = C;
4585     }
4586     return new ICmpInst(Pred, Y, Z);
4587   }
4588 
4589   // icmp slt (A + -1), Op1 -> icmp sle A, Op1
4590   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
4591       match(B, m_AllOnes()))
4592     return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
4593 
4594   // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
4595   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
4596       match(B, m_AllOnes()))
4597     return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
4598 
4599   // icmp sle (A + 1), Op1 -> icmp slt A, Op1
4600   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
4601     return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
4602 
4603   // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
4604   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
4605     return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
4606 
4607   // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
4608   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
4609       match(D, m_AllOnes()))
4610     return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
4611 
4612   // icmp sle Op0, (C + -1) -> icmp slt Op0, C
4613   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
4614       match(D, m_AllOnes()))
4615     return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
4616 
4617   // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
4618   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
4619     return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
4620 
4621   // icmp slt Op0, (C + 1) -> icmp sle Op0, C
4622   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
4623     return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
4624 
4625   // TODO: The subtraction-related identities shown below also hold, but
4626   // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
4627   // wouldn't happen even if they were implemented.
4628   //
4629   // icmp ult (A - 1), Op1 -> icmp ule A, Op1
4630   // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
4631   // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
4632   // icmp ule Op0, (C - 1) -> icmp ult Op0, C
4633 
4634   // icmp ule (A + 1), Op0 -> icmp ult A, Op1
4635   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
4636     return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
4637 
4638   // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
4639   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
4640     return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
4641 
4642   // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
4643   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
4644     return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
4645 
4646   // icmp ult Op0, (C + 1) -> icmp ule Op0, C
4647   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
4648     return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
4649 
4650   // if C1 has greater magnitude than C2:
4651   //  icmp (A + C1), (C + C2) -> icmp (A + C3), C
4652   //  s.t. C3 = C1 - C2
4653   //
4654   // if C2 has greater magnitude than C1:
4655   //  icmp (A + C1), (C + C2) -> icmp A, (C + C3)
4656   //  s.t. C3 = C2 - C1
4657   if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
4658       (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
4659     const APInt *AP1, *AP2;
4660     // TODO: Support non-uniform vectors.
4661     // TODO: Allow undef passthrough if B AND D's element is undef.
4662     if (match(B, m_APIntAllowUndef(AP1)) && match(D, m_APIntAllowUndef(AP2)) &&
4663         AP1->isNegative() == AP2->isNegative()) {
4664       APInt AP1Abs = AP1->abs();
4665       APInt AP2Abs = AP2->abs();
4666       if (AP1Abs.uge(AP2Abs)) {
4667         APInt Diff = *AP1 - *AP2;
4668         bool HasNUW = BO0->hasNoUnsignedWrap() && Diff.ule(*AP1);
4669         bool HasNSW = BO0->hasNoSignedWrap();
4670         Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
4671         Value *NewAdd = Builder.CreateAdd(A, C3, "", HasNUW, HasNSW);
4672         return new ICmpInst(Pred, NewAdd, C);
4673       } else {
4674         APInt Diff = *AP2 - *AP1;
4675         bool HasNUW = BO1->hasNoUnsignedWrap() && Diff.ule(*AP2);
4676         bool HasNSW = BO1->hasNoSignedWrap();
4677         Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
4678         Value *NewAdd = Builder.CreateAdd(C, C3, "", HasNUW, HasNSW);
4679         return new ICmpInst(Pred, A, NewAdd);
4680       }
4681     }
4682     Constant *Cst1, *Cst2;
4683     if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
4684         ICmpInst::isEquality(Pred)) {
4685       Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
4686       Value *NewAdd = Builder.CreateAdd(C, Diff);
4687       return new ICmpInst(Pred, A, NewAdd);
4688     }
4689   }
4690 
4691   // Analyze the case when either Op0 or Op1 is a sub instruction.
4692   // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
4693   A = nullptr;
4694   B = nullptr;
4695   C = nullptr;
4696   D = nullptr;
4697   if (BO0 && BO0->getOpcode() == Instruction::Sub) {
4698     A = BO0->getOperand(0);
4699     B = BO0->getOperand(1);
4700   }
4701   if (BO1 && BO1->getOpcode() == Instruction::Sub) {
4702     C = BO1->getOperand(0);
4703     D = BO1->getOperand(1);
4704   }
4705 
4706   // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
4707   if (A == Op1 && NoOp0WrapProblem)
4708     return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
4709   // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
4710   if (C == Op0 && NoOp1WrapProblem)
4711     return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
4712 
4713   // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
4714   // (A - B) u>/u<= A --> B u>/u<= A
4715   if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
4716     return new ICmpInst(Pred, B, A);
4717   // C u</u>= (C - D) --> C u</u>= D
4718   if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
4719     return new ICmpInst(Pred, C, D);
4720   // (A - B) u>=/u< A --> B u>/u<= A  iff B != 0
4721   if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
4722       isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4723     return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A);
4724   // C u<=/u> (C - D) --> C u</u>= D  iff B != 0
4725   if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
4726       isKnownNonZero(D, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4727     return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D);
4728 
4729   // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
4730   if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
4731     return new ICmpInst(Pred, A, C);
4732 
4733   // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
4734   if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
4735     return new ICmpInst(Pred, D, B);
4736 
4737   // icmp (0-X) < cst --> x > -cst
4738   if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
4739     Value *X;
4740     if (match(BO0, m_Neg(m_Value(X))))
4741       if (Constant *RHSC = dyn_cast<Constant>(Op1))
4742         if (RHSC->isNotMinSignedValue())
4743           return new ICmpInst(I.getSwappedPredicate(), X,
4744                               ConstantExpr::getNeg(RHSC));
4745   }
4746 
4747   if (Instruction * R = foldICmpXorXX(I, Q, *this))
4748     return R;
4749 
4750   {
4751     // Try to remove shared multiplier from comparison:
4752     // X * Z u{lt/le/gt/ge}/eq/ne Y * Z
4753     Value *X, *Y, *Z;
4754     if (Pred == ICmpInst::getUnsignedPredicate(Pred) &&
4755         ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
4756           match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
4757          (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
4758           match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))))) {
4759       bool NonZero;
4760       if (ICmpInst::isEquality(Pred)) {
4761         KnownBits ZKnown = computeKnownBits(Z, 0, &I);
4762         // if Z % 2 != 0
4763         //    X * Z eq/ne Y * Z -> X eq/ne Y
4764         if (ZKnown.countMaxTrailingZeros() == 0)
4765           return new ICmpInst(Pred, X, Y);
4766         NonZero = !ZKnown.One.isZero() ||
4767                   isKnownNonZero(Z, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
4768         // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
4769         //    X * Z eq/ne Y * Z -> X eq/ne Y
4770         if (NonZero && BO0 && BO1 && BO0->hasNoSignedWrap() &&
4771             BO1->hasNoSignedWrap())
4772           return new ICmpInst(Pred, X, Y);
4773       } else
4774         NonZero = isKnownNonZero(Z, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
4775 
4776       // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
4777       //    X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
4778       if (NonZero && BO0 && BO1 && BO0->hasNoUnsignedWrap() &&
4779           BO1->hasNoUnsignedWrap())
4780         return new ICmpInst(Pred, X, Y);
4781     }
4782   }
4783 
4784   BinaryOperator *SRem = nullptr;
4785   // icmp (srem X, Y), Y
4786   if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
4787     SRem = BO0;
4788   // icmp Y, (srem X, Y)
4789   else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4790            Op0 == BO1->getOperand(1))
4791     SRem = BO1;
4792   if (SRem) {
4793     // We don't check hasOneUse to avoid increasing register pressure because
4794     // the value we use is the same value this instruction was already using.
4795     switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4796     default:
4797       break;
4798     case ICmpInst::ICMP_EQ:
4799       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4800     case ICmpInst::ICMP_NE:
4801       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4802     case ICmpInst::ICMP_SGT:
4803     case ICmpInst::ICMP_SGE:
4804       return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4805                           Constant::getAllOnesValue(SRem->getType()));
4806     case ICmpInst::ICMP_SLT:
4807     case ICmpInst::ICMP_SLE:
4808       return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4809                           Constant::getNullValue(SRem->getType()));
4810     }
4811   }
4812 
4813   if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
4814       BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
4815     switch (BO0->getOpcode()) {
4816     default:
4817       break;
4818     case Instruction::Add:
4819     case Instruction::Sub:
4820     case Instruction::Xor: {
4821       if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4822         return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4823 
4824       const APInt *C;
4825       if (match(BO0->getOperand(1), m_APInt(C))) {
4826         // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
4827         if (C->isSignMask()) {
4828           ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4829           return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4830         }
4831 
4832         // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
4833         if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
4834           ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4835           NewPred = I.getSwappedPredicate(NewPred);
4836           return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4837         }
4838       }
4839       break;
4840     }
4841     case Instruction::Mul: {
4842       if (!I.isEquality())
4843         break;
4844 
4845       const APInt *C;
4846       if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
4847           !C->isOne()) {
4848         // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
4849         // Mask = -1 >> count-trailing-zeros(C).
4850         if (unsigned TZs = C->countr_zero()) {
4851           Constant *Mask = ConstantInt::get(
4852               BO0->getType(),
4853               APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
4854           Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
4855           Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
4856           return new ICmpInst(Pred, And1, And2);
4857         }
4858       }
4859       break;
4860     }
4861     case Instruction::UDiv:
4862     case Instruction::LShr:
4863       if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
4864         break;
4865       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4866 
4867     case Instruction::SDiv:
4868       if (!I.isEquality() || !BO0->isExact() || !BO1->isExact())
4869         break;
4870       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4871 
4872     case Instruction::AShr:
4873       if (!BO0->isExact() || !BO1->isExact())
4874         break;
4875       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4876 
4877     case Instruction::Shl: {
4878       bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4879       bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4880       if (!NUW && !NSW)
4881         break;
4882       if (!NSW && I.isSigned())
4883         break;
4884       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4885     }
4886     }
4887   }
4888 
4889   if (BO0) {
4890     // Transform  A & (L - 1) `ult` L --> L != 0
4891     auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4892     auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
4893 
4894     if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
4895       auto *Zero = Constant::getNullValue(BO0->getType());
4896       return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4897     }
4898   }
4899 
4900   // For unsigned predicates / eq / ne:
4901   // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
4902   // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
4903   if (!ICmpInst::isSigned(Pred)) {
4904     if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
4905       return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
4906                           Constant::getNullValue(Op1->getType()));
4907     else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
4908       return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
4909                           Constant::getNullValue(Op0->getType()), Op0);
4910   }
4911 
4912   if (Value *V = foldMultiplicationOverflowCheck(I))
4913     return replaceInstUsesWith(I, V);
4914 
4915   if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder))
4916     return replaceInstUsesWith(I, V);
4917 
4918   if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
4919     return replaceInstUsesWith(I, V);
4920 
4921   if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
4922     return replaceInstUsesWith(I, V);
4923 
4924   return nullptr;
4925 }
4926 
4927 /// Fold icmp Pred min|max(X, Y), X.
4928 static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) {
4929   ICmpInst::Predicate Pred = Cmp.getPredicate();
4930   Value *Op0 = Cmp.getOperand(0);
4931   Value *X = Cmp.getOperand(1);
4932 
4933   // Canonicalize minimum or maximum operand to LHS of the icmp.
4934   if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) ||
4935       match(X, m_c_SMax(m_Specific(Op0), m_Value())) ||
4936       match(X, m_c_UMin(m_Specific(Op0), m_Value())) ||
4937       match(X, m_c_UMax(m_Specific(Op0), m_Value()))) {
4938     std::swap(Op0, X);
4939     Pred = Cmp.getSwappedPredicate();
4940   }
4941 
4942   Value *Y;
4943   if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) {
4944     // smin(X, Y)  == X --> X s<= Y
4945     // smin(X, Y) s>= X --> X s<= Y
4946     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE)
4947       return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
4948 
4949     // smin(X, Y) != X --> X s> Y
4950     // smin(X, Y) s< X --> X s> Y
4951     if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT)
4952       return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
4953 
4954     // These cases should be handled in InstSimplify:
4955     // smin(X, Y) s<= X --> true
4956     // smin(X, Y) s> X --> false
4957     return nullptr;
4958   }
4959 
4960   if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) {
4961     // smax(X, Y)  == X --> X s>= Y
4962     // smax(X, Y) s<= X --> X s>= Y
4963     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE)
4964       return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
4965 
4966     // smax(X, Y) != X --> X s< Y
4967     // smax(X, Y) s> X --> X s< Y
4968     if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT)
4969       return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
4970 
4971     // These cases should be handled in InstSimplify:
4972     // smax(X, Y) s>= X --> true
4973     // smax(X, Y) s< X --> false
4974     return nullptr;
4975   }
4976 
4977   if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) {
4978     // umin(X, Y)  == X --> X u<= Y
4979     // umin(X, Y) u>= X --> X u<= Y
4980     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE)
4981       return new ICmpInst(ICmpInst::ICMP_ULE, X, Y);
4982 
4983     // umin(X, Y) != X --> X u> Y
4984     // umin(X, Y) u< X --> X u> Y
4985     if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT)
4986       return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
4987 
4988     // These cases should be handled in InstSimplify:
4989     // umin(X, Y) u<= X --> true
4990     // umin(X, Y) u> X --> false
4991     return nullptr;
4992   }
4993 
4994   if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) {
4995     // umax(X, Y)  == X --> X u>= Y
4996     // umax(X, Y) u<= X --> X u>= Y
4997     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE)
4998       return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
4999 
5000     // umax(X, Y) != X --> X u< Y
5001     // umax(X, Y) u> X --> X u< Y
5002     if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT)
5003       return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
5004 
5005     // These cases should be handled in InstSimplify:
5006     // umax(X, Y) u>= X --> true
5007     // umax(X, Y) u< X --> false
5008     return nullptr;
5009   }
5010 
5011   return nullptr;
5012 }
5013 
5014 // Canonicalize checking for a power-of-2-or-zero value:
5015 static Instruction *foldICmpPow2Test(ICmpInst &I,
5016                                      InstCombiner::BuilderTy &Builder) {
5017   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5018   const CmpInst::Predicate Pred = I.getPredicate();
5019   Value *A = nullptr;
5020   bool CheckIs;
5021   if (I.isEquality()) {
5022     // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
5023     // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
5024     if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
5025                                      m_Deferred(A)))) ||
5026         !match(Op1, m_ZeroInt()))
5027       A = nullptr;
5028 
5029     // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
5030     // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
5031     if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
5032       A = Op1;
5033     else if (match(Op1,
5034                    m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))
5035       A = Op0;
5036 
5037     CheckIs = Pred == ICmpInst::ICMP_EQ;
5038   } else if (ICmpInst::isUnsigned(Pred)) {
5039     // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
5040     // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
5041 
5042     if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5043         match(Op0, m_OneUse(m_c_Xor(m_Add(m_Specific(Op1), m_AllOnes()),
5044                                     m_Specific(Op1))))) {
5045       A = Op1;
5046       CheckIs = Pred == ICmpInst::ICMP_UGE;
5047     } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5048                match(Op1, m_OneUse(m_c_Xor(m_Add(m_Specific(Op0), m_AllOnes()),
5049                                            m_Specific(Op0))))) {
5050       A = Op0;
5051       CheckIs = Pred == ICmpInst::ICMP_ULE;
5052     }
5053   }
5054 
5055   if (A) {
5056     Type *Ty = A->getType();
5057     CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
5058     return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
5059                                   ConstantInt::get(Ty, 2))
5060                    : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
5061                                   ConstantInt::get(Ty, 1));
5062   }
5063 
5064   return nullptr;
5065 }
5066 
5067 Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
5068   if (!I.isEquality())
5069     return nullptr;
5070 
5071   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5072   const CmpInst::Predicate Pred = I.getPredicate();
5073   Value *A, *B, *C, *D;
5074   if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5075     if (A == Op1 || B == Op1) { // (A^B) == A  ->  B == 0
5076       Value *OtherVal = A == Op1 ? B : A;
5077       return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
5078     }
5079 
5080     if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5081       // A^c1 == C^c2 --> A == C^(c1^c2)
5082       ConstantInt *C1, *C2;
5083       if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
5084           Op1->hasOneUse()) {
5085         Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
5086         Value *Xor = Builder.CreateXor(C, NC);
5087         return new ICmpInst(Pred, A, Xor);
5088       }
5089 
5090       // A^B == A^D -> B == D
5091       if (A == C)
5092         return new ICmpInst(Pred, B, D);
5093       if (A == D)
5094         return new ICmpInst(Pred, B, C);
5095       if (B == C)
5096         return new ICmpInst(Pred, A, D);
5097       if (B == D)
5098         return new ICmpInst(Pred, A, C);
5099     }
5100   }
5101 
5102   // canoncalize:
5103   // (icmp eq/ne (and X, C), X)
5104   //    -> (icmp eq/ne (and X, ~C), 0)
5105   {
5106     Constant *CMask;
5107     A = nullptr;
5108     if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_ImmConstant(CMask)))))
5109       A = Op1;
5110     else if (match(Op1, m_OneUse(m_And(m_Specific(Op0), m_ImmConstant(CMask)))))
5111       A = Op0;
5112     if (A)
5113       return new ICmpInst(Pred, Builder.CreateAnd(A, Builder.CreateNot(CMask)),
5114                           Constant::getNullValue(A->getType()));
5115   }
5116 
5117   if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
5118     // A == (A^B)  ->  B == 0
5119     Value *OtherVal = A == Op0 ? B : A;
5120     return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
5121   }
5122 
5123   // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5124   if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
5125       match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
5126     Value *X = nullptr, *Y = nullptr, *Z = nullptr;
5127 
5128     if (A == C) {
5129       X = B;
5130       Y = D;
5131       Z = A;
5132     } else if (A == D) {
5133       X = B;
5134       Y = C;
5135       Z = A;
5136     } else if (B == C) {
5137       X = A;
5138       Y = D;
5139       Z = B;
5140     } else if (B == D) {
5141       X = A;
5142       Y = C;
5143       Z = B;
5144     }
5145 
5146     if (X) { // Build (X^Y) & Z
5147       Op1 = Builder.CreateXor(X, Y);
5148       Op1 = Builder.CreateAnd(Op1, Z);
5149       return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
5150     }
5151   }
5152 
5153   {
5154     // Similar to above, but specialized for constant because invert is needed:
5155     // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
5156     Value *X, *Y;
5157     Constant *C;
5158     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
5159         match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
5160       Value *Xor = Builder.CreateXor(X, Y);
5161       Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
5162       return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
5163     }
5164   }
5165 
5166   if (match(Op1, m_ZExt(m_Value(A))) &&
5167       (Op0->hasOneUse() || Op1->hasOneUse())) {
5168     // (B & (Pow2C-1)) == zext A --> A == trunc B
5169     // (B & (Pow2C-1)) != zext A --> A != trunc B
5170     const APInt *MaskC;
5171     if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
5172         MaskC->countr_one() == A->getType()->getScalarSizeInBits())
5173       return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
5174   }
5175 
5176   // Test if 2 values have different or same signbits:
5177   // (X u>> BitWidth - 1) == zext (Y s> -1) --> (X ^ Y) < 0
5178   // (X u>> BitWidth - 1) != zext (Y s> -1) --> (X ^ Y) > -1
5179   // (X s>> BitWidth - 1) == sext (Y s> -1) --> (X ^ Y) < 0
5180   // (X s>> BitWidth - 1) != sext (Y s> -1) --> (X ^ Y) > -1
5181   Instruction *ExtI;
5182   if (match(Op1, m_CombineAnd(m_Instruction(ExtI), m_ZExtOrSExt(m_Value(A)))) &&
5183       (Op0->hasOneUse() || Op1->hasOneUse())) {
5184     unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
5185     Instruction *ShiftI;
5186     Value *X, *Y;
5187     ICmpInst::Predicate Pred2;
5188     if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
5189                                 m_Shr(m_Value(X),
5190                                       m_SpecificIntAllowUndef(OpWidth - 1)))) &&
5191         match(A, m_ICmp(Pred2, m_Value(Y), m_AllOnes())) &&
5192         Pred2 == ICmpInst::ICMP_SGT && X->getType() == Y->getType()) {
5193       unsigned ExtOpc = ExtI->getOpcode();
5194       unsigned ShiftOpc = ShiftI->getOpcode();
5195       if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
5196           (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
5197         Value *Xor = Builder.CreateXor(X, Y, "xor.signbits");
5198         Value *R = (Pred == ICmpInst::ICMP_EQ) ? Builder.CreateIsNeg(Xor)
5199                                                : Builder.CreateIsNotNeg(Xor);
5200         return replaceInstUsesWith(I, R);
5201       }
5202     }
5203   }
5204 
5205   // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
5206   // For lshr and ashr pairs.
5207   const APInt *AP1, *AP2;
5208   if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
5209        match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowUndef(AP2))))) ||
5210       (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
5211        match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowUndef(AP2)))))) {
5212     if (AP1 != AP2)
5213       return nullptr;
5214     unsigned TypeBits = AP1->getBitWidth();
5215     unsigned ShAmt = AP1->getLimitedValue(TypeBits);
5216     if (ShAmt < TypeBits && ShAmt != 0) {
5217       ICmpInst::Predicate NewPred =
5218           Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5219       Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
5220       APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
5221       return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
5222     }
5223   }
5224 
5225   // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
5226   ConstantInt *Cst1;
5227   if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
5228       match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
5229     unsigned TypeBits = Cst1->getBitWidth();
5230     unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
5231     if (ShAmt < TypeBits && ShAmt != 0) {
5232       Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
5233       APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
5234       Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
5235                                       I.getName() + ".mask");
5236       return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
5237     }
5238   }
5239 
5240   // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
5241   // "icmp (and X, mask), cst"
5242   uint64_t ShAmt = 0;
5243   if (Op0->hasOneUse() &&
5244       match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
5245       match(Op1, m_ConstantInt(Cst1)) &&
5246       // Only do this when A has multiple uses.  This is most important to do
5247       // when it exposes other optimizations.
5248       !A->hasOneUse()) {
5249     unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
5250 
5251     if (ShAmt < ASize) {
5252       APInt MaskV =
5253           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
5254       MaskV <<= ShAmt;
5255 
5256       APInt CmpV = Cst1->getValue().zext(ASize);
5257       CmpV <<= ShAmt;
5258 
5259       Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
5260       return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
5261     }
5262   }
5263 
5264   if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(I, Builder))
5265     return ICmp;
5266 
5267   // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks the
5268   // top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s INT_MAX",
5269   // which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a few steps
5270   // of instcombine.
5271   unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5272   if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
5273       match(Op1, m_Trunc(m_LShr(m_Specific(A), m_SpecificInt(BitWidth)))) &&
5274       A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
5275       (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
5276     APInt C = APInt::getOneBitSet(BitWidth * 2, BitWidth - 1);
5277     Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
5278     return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
5279                                                   : ICmpInst::ICMP_UGE,
5280                         Add, ConstantInt::get(A->getType(), C.shl(1)));
5281   }
5282 
5283   // Canonicalize:
5284   // Assume B_Pow2 != 0
5285   // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
5286   // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
5287   if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
5288       isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, 0, &I))
5289     return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
5290                         ConstantInt::getNullValue(Op0->getType()));
5291 
5292   if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
5293       isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, 0, &I))
5294     return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
5295                         ConstantInt::getNullValue(Op1->getType()));
5296 
5297   // Canonicalize:
5298   // icmp eq/ne X, OneUse(rotate-right(X))
5299   //    -> icmp eq/ne X, rotate-left(X)
5300   // We generally try to convert rotate-right -> rotate-left, this just
5301   // canonicalizes another case.
5302   CmpInst::Predicate PredUnused = Pred;
5303   if (match(&I, m_c_ICmp(PredUnused, m_Value(A),
5304                          m_OneUse(m_Intrinsic<Intrinsic::fshr>(
5305                              m_Deferred(A), m_Deferred(A), m_Value(B))))))
5306     return new ICmpInst(
5307         Pred, A,
5308         Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
5309 
5310   return nullptr;
5311 }
5312 
5313 Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {
5314   ICmpInst::Predicate Pred = ICmp.getPredicate();
5315   Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
5316 
5317   // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
5318   // The trunc masks high bits while the compare may effectively mask low bits.
5319   Value *X;
5320   const APInt *C;
5321   if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
5322     return nullptr;
5323 
5324   // This matches patterns corresponding to tests of the signbit as well as:
5325   // (trunc X) u< C --> (X & -C) == 0 (are all masked-high-bits clear?)
5326   // (trunc X) u> C --> (X & ~C) != 0 (are any masked-high-bits set?)
5327   APInt Mask;
5328   if (decomposeBitTestICmp(Op0, Op1, Pred, X, Mask, true /* WithTrunc */)) {
5329     Value *And = Builder.CreateAnd(X, Mask);
5330     Constant *Zero = ConstantInt::getNullValue(X->getType());
5331     return new ICmpInst(Pred, And, Zero);
5332   }
5333 
5334   unsigned SrcBits = X->getType()->getScalarSizeInBits();
5335   if (Pred == ICmpInst::ICMP_ULT && C->isNegatedPowerOf2()) {
5336     // If C is a negative power-of-2 (high-bit mask):
5337     // (trunc X) u< C --> (X & C) != C (are any masked-high-bits clear?)
5338     Constant *MaskC = ConstantInt::get(X->getType(), C->zext(SrcBits));
5339     Value *And = Builder.CreateAnd(X, MaskC);
5340     return new ICmpInst(ICmpInst::ICMP_NE, And, MaskC);
5341   }
5342 
5343   if (Pred == ICmpInst::ICMP_UGT && (~*C).isPowerOf2()) {
5344     // If C is not-of-power-of-2 (one clear bit):
5345     // (trunc X) u> C --> (X & (C+1)) == C+1 (are all masked-high-bits set?)
5346     Constant *MaskC = ConstantInt::get(X->getType(), (*C + 1).zext(SrcBits));
5347     Value *And = Builder.CreateAnd(X, MaskC);
5348     return new ICmpInst(ICmpInst::ICMP_EQ, And, MaskC);
5349   }
5350 
5351   if (auto *II = dyn_cast<IntrinsicInst>(X)) {
5352     if (II->getIntrinsicID() == Intrinsic::cttz ||
5353         II->getIntrinsicID() == Intrinsic::ctlz) {
5354       unsigned MaxRet = SrcBits;
5355       // If the "is_zero_poison" argument is set, then we know at least
5356       // one bit is set in the input, so the result is always at least one
5357       // less than the full bitwidth of that input.
5358       if (match(II->getArgOperand(1), m_One()))
5359         MaxRet--;
5360 
5361       // Make sure the destination is wide enough to hold the largest output of
5362       // the intrinsic.
5363       if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
5364         if (Instruction *I =
5365                 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
5366           return I;
5367     }
5368   }
5369 
5370   return nullptr;
5371 }
5372 
5373 Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
5374   assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
5375   auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
5376   Value *X;
5377   if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
5378     return nullptr;
5379 
5380   bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
5381   bool IsSignedCmp = ICmp.isSigned();
5382 
5383   // icmp Pred (ext X), (ext Y)
5384   Value *Y;
5385   if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
5386     bool IsZext0 = isa<ZExtOperator>(ICmp.getOperand(0));
5387     bool IsZext1 = isa<ZExtOperator>(ICmp.getOperand(1));
5388 
5389     if (IsZext0 != IsZext1) {
5390         // If X and Y and both i1
5391         // (icmp eq/ne (zext X) (sext Y))
5392         //      eq -> (icmp eq (or X, Y), 0)
5393         //      ne -> (icmp ne (or X, Y), 0)
5394       if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
5395           Y->getType()->isIntOrIntVectorTy(1))
5396         return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
5397                             Constant::getNullValue(X->getType()));
5398 
5399       // If we have mismatched casts, treat the zext of a non-negative source as
5400       // a sext to simulate matching casts. Otherwise, we are done.
5401       // TODO: Can we handle some predicates (equality) without non-negative?
5402       if ((IsZext0 && isKnownNonNegative(X, DL, 0, &AC, &ICmp, &DT)) ||
5403           (IsZext1 && isKnownNonNegative(Y, DL, 0, &AC, &ICmp, &DT)))
5404         IsSignedExt = true;
5405       else
5406         return nullptr;
5407     }
5408 
5409     // Not an extension from the same type?
5410     Type *XTy = X->getType(), *YTy = Y->getType();
5411     if (XTy != YTy) {
5412       // One of the casts must have one use because we are creating a new cast.
5413       if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
5414         return nullptr;
5415       // Extend the narrower operand to the type of the wider operand.
5416       CastInst::CastOps CastOpcode =
5417           IsSignedExt ? Instruction::SExt : Instruction::ZExt;
5418       if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
5419         X = Builder.CreateCast(CastOpcode, X, YTy);
5420       else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
5421         Y = Builder.CreateCast(CastOpcode, Y, XTy);
5422       else
5423         return nullptr;
5424     }
5425 
5426     // (zext X) == (zext Y) --> X == Y
5427     // (sext X) == (sext Y) --> X == Y
5428     if (ICmp.isEquality())
5429       return new ICmpInst(ICmp.getPredicate(), X, Y);
5430 
5431     // A signed comparison of sign extended values simplifies into a
5432     // signed comparison.
5433     if (IsSignedCmp && IsSignedExt)
5434       return new ICmpInst(ICmp.getPredicate(), X, Y);
5435 
5436     // The other three cases all fold into an unsigned comparison.
5437     return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
5438   }
5439 
5440   // Below here, we are only folding a compare with constant.
5441   auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
5442   if (!C)
5443     return nullptr;
5444 
5445   // Compute the constant that would happen if we truncated to SrcTy then
5446   // re-extended to DestTy.
5447   Type *SrcTy = CastOp0->getSrcTy();
5448   Type *DestTy = CastOp0->getDestTy();
5449   Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
5450   Constant *Res2 = ConstantExpr::getCast(CastOp0->getOpcode(), Res1, DestTy);
5451 
5452   // If the re-extended constant didn't change...
5453   if (Res2 == C) {
5454     if (ICmp.isEquality())
5455       return new ICmpInst(ICmp.getPredicate(), X, Res1);
5456 
5457     // A signed comparison of sign extended values simplifies into a
5458     // signed comparison.
5459     if (IsSignedExt && IsSignedCmp)
5460       return new ICmpInst(ICmp.getPredicate(), X, Res1);
5461 
5462     // The other three cases all fold into an unsigned comparison.
5463     return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res1);
5464   }
5465 
5466   // The re-extended constant changed, partly changed (in the case of a vector),
5467   // or could not be determined to be equal (in the case of a constant
5468   // expression), so the constant cannot be represented in the shorter type.
5469   // All the cases that fold to true or false will have already been handled
5470   // by simplifyICmpInst, so only deal with the tricky case.
5471   if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
5472     return nullptr;
5473 
5474   // Is source op positive?
5475   // icmp ult (sext X), C --> icmp sgt X, -1
5476   if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
5477     return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy));
5478 
5479   // Is source op negative?
5480   // icmp ugt (sext X), C --> icmp slt X, 0
5481   assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
5482   return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));
5483 }
5484 
5485 /// Handle icmp (cast x), (cast or constant).
5486 Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
5487   // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
5488   // icmp compares only pointer's value.
5489   // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
5490   Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
5491   Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
5492   if (SimplifiedOp0 || SimplifiedOp1)
5493     return new ICmpInst(ICmp.getPredicate(),
5494                         SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
5495                         SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
5496 
5497   auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
5498   if (!CastOp0)
5499     return nullptr;
5500   if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
5501     return nullptr;
5502 
5503   Value *Op0Src = CastOp0->getOperand(0);
5504   Type *SrcTy = CastOp0->getSrcTy();
5505   Type *DestTy = CastOp0->getDestTy();
5506 
5507   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5508   // integer type is the same size as the pointer type.
5509   auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) {
5510     if (isa<VectorType>(SrcTy)) {
5511       SrcTy = cast<VectorType>(SrcTy)->getElementType();
5512       DestTy = cast<VectorType>(DestTy)->getElementType();
5513     }
5514     return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth();
5515   };
5516   if (CastOp0->getOpcode() == Instruction::PtrToInt &&
5517       CompatibleSizes(SrcTy, DestTy)) {
5518     Value *NewOp1 = nullptr;
5519     if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
5520       Value *PtrSrc = PtrToIntOp1->getOperand(0);
5521       if (PtrSrc->getType()->getPointerAddressSpace() ==
5522           Op0Src->getType()->getPointerAddressSpace()) {
5523         NewOp1 = PtrToIntOp1->getOperand(0);
5524         // If the pointer types don't match, insert a bitcast.
5525         if (Op0Src->getType() != NewOp1->getType())
5526           NewOp1 = Builder.CreateBitCast(NewOp1, Op0Src->getType());
5527       }
5528     } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
5529       NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5530     }
5531 
5532     if (NewOp1)
5533       return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
5534   }
5535 
5536   if (Instruction *R = foldICmpWithTrunc(ICmp))
5537     return R;
5538 
5539   return foldICmpWithZextOrSext(ICmp);
5540 }
5541 
5542 static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned) {
5543   switch (BinaryOp) {
5544     default:
5545       llvm_unreachable("Unsupported binary op");
5546     case Instruction::Add:
5547     case Instruction::Sub:
5548       return match(RHS, m_Zero());
5549     case Instruction::Mul:
5550       return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
5551              match(RHS, m_One());
5552   }
5553 }
5554 
5555 OverflowResult
5556 InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
5557                                   bool IsSigned, Value *LHS, Value *RHS,
5558                                   Instruction *CxtI) const {
5559   switch (BinaryOp) {
5560     default:
5561       llvm_unreachable("Unsupported binary op");
5562     case Instruction::Add:
5563       if (IsSigned)
5564         return computeOverflowForSignedAdd(LHS, RHS, CxtI);
5565       else
5566         return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
5567     case Instruction::Sub:
5568       if (IsSigned)
5569         return computeOverflowForSignedSub(LHS, RHS, CxtI);
5570       else
5571         return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
5572     case Instruction::Mul:
5573       if (IsSigned)
5574         return computeOverflowForSignedMul(LHS, RHS, CxtI);
5575       else
5576         return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
5577   }
5578 }
5579 
5580 bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
5581                                              bool IsSigned, Value *LHS,
5582                                              Value *RHS, Instruction &OrigI,
5583                                              Value *&Result,
5584                                              Constant *&Overflow) {
5585   if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
5586     std::swap(LHS, RHS);
5587 
5588   // If the overflow check was an add followed by a compare, the insertion point
5589   // may be pointing to the compare.  We want to insert the new instructions
5590   // before the add in case there are uses of the add between the add and the
5591   // compare.
5592   Builder.SetInsertPoint(&OrigI);
5593 
5594   Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
5595   if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
5596     OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
5597 
5598   if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
5599     Result = LHS;
5600     Overflow = ConstantInt::getFalse(OverflowTy);
5601     return true;
5602   }
5603 
5604   switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
5605     case OverflowResult::MayOverflow:
5606       return false;
5607     case OverflowResult::AlwaysOverflowsLow:
5608     case OverflowResult::AlwaysOverflowsHigh:
5609       Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
5610       Result->takeName(&OrigI);
5611       Overflow = ConstantInt::getTrue(OverflowTy);
5612       return true;
5613     case OverflowResult::NeverOverflows:
5614       Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
5615       Result->takeName(&OrigI);
5616       Overflow = ConstantInt::getFalse(OverflowTy);
5617       if (auto *Inst = dyn_cast<Instruction>(Result)) {
5618         if (IsSigned)
5619           Inst->setHasNoSignedWrap();
5620         else
5621           Inst->setHasNoUnsignedWrap();
5622       }
5623       return true;
5624   }
5625 
5626   llvm_unreachable("Unexpected overflow result");
5627 }
5628 
5629 /// Recognize and process idiom involving test for multiplication
5630 /// overflow.
5631 ///
5632 /// The caller has matched a pattern of the form:
5633 ///   I = cmp u (mul(zext A, zext B), V
5634 /// The function checks if this is a test for overflow and if so replaces
5635 /// multiplication with call to 'mul.with.overflow' intrinsic.
5636 ///
5637 /// \param I Compare instruction.
5638 /// \param MulVal Result of 'mult' instruction.  It is one of the arguments of
5639 ///               the compare instruction.  Must be of integer type.
5640 /// \param OtherVal The other argument of compare instruction.
5641 /// \returns Instruction which must replace the compare instruction, NULL if no
5642 ///          replacement required.
5643 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
5644                                          Value *OtherVal,
5645                                          InstCombinerImpl &IC) {
5646   // Don't bother doing this transformation for pointers, don't do it for
5647   // vectors.
5648   if (!isa<IntegerType>(MulVal->getType()))
5649     return nullptr;
5650 
5651   assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
5652   assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
5653   auto *MulInstr = dyn_cast<Instruction>(MulVal);
5654   if (!MulInstr)
5655     return nullptr;
5656   assert(MulInstr->getOpcode() == Instruction::Mul);
5657 
5658   auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
5659        *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
5660   assert(LHS->getOpcode() == Instruction::ZExt);
5661   assert(RHS->getOpcode() == Instruction::ZExt);
5662   Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
5663 
5664   // Calculate type and width of the result produced by mul.with.overflow.
5665   Type *TyA = A->getType(), *TyB = B->getType();
5666   unsigned WidthA = TyA->getPrimitiveSizeInBits(),
5667            WidthB = TyB->getPrimitiveSizeInBits();
5668   unsigned MulWidth;
5669   Type *MulType;
5670   if (WidthB > WidthA) {
5671     MulWidth = WidthB;
5672     MulType = TyB;
5673   } else {
5674     MulWidth = WidthA;
5675     MulType = TyA;
5676   }
5677 
5678   // In order to replace the original mul with a narrower mul.with.overflow,
5679   // all uses must ignore upper bits of the product.  The number of used low
5680   // bits must be not greater than the width of mul.with.overflow.
5681   if (MulVal->hasNUsesOrMore(2))
5682     for (User *U : MulVal->users()) {
5683       if (U == &I)
5684         continue;
5685       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
5686         // Check if truncation ignores bits above MulWidth.
5687         unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
5688         if (TruncWidth > MulWidth)
5689           return nullptr;
5690       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
5691         // Check if AND ignores bits above MulWidth.
5692         if (BO->getOpcode() != Instruction::And)
5693           return nullptr;
5694         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5695           const APInt &CVal = CI->getValue();
5696           if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
5697             return nullptr;
5698         } else {
5699           // In this case we could have the operand of the binary operation
5700           // being defined in another block, and performing the replacement
5701           // could break the dominance relation.
5702           return nullptr;
5703         }
5704       } else {
5705         // Other uses prohibit this transformation.
5706         return nullptr;
5707       }
5708     }
5709 
5710   // Recognize patterns
5711   switch (I.getPredicate()) {
5712   case ICmpInst::ICMP_EQ:
5713   case ICmpInst::ICMP_NE:
5714     // Recognize pattern:
5715     //   mulval = mul(zext A, zext B)
5716     //   cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
5717     ConstantInt *CI;
5718     Value *ValToMask;
5719     if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
5720       if (ValToMask != MulVal)
5721         return nullptr;
5722       const APInt &CVal = CI->getValue() + 1;
5723       if (CVal.isPowerOf2()) {
5724         unsigned MaskWidth = CVal.logBase2();
5725         if (MaskWidth == MulWidth)
5726           break; // Recognized
5727       }
5728     }
5729     return nullptr;
5730 
5731   case ICmpInst::ICMP_UGT:
5732     // Recognize pattern:
5733     //   mulval = mul(zext A, zext B)
5734     //   cmp ugt mulval, max
5735     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
5736       APInt MaxVal = APInt::getMaxValue(MulWidth);
5737       MaxVal = MaxVal.zext(CI->getBitWidth());
5738       if (MaxVal.eq(CI->getValue()))
5739         break; // Recognized
5740     }
5741     return nullptr;
5742 
5743   case ICmpInst::ICMP_UGE:
5744     // Recognize pattern:
5745     //   mulval = mul(zext A, zext B)
5746     //   cmp uge mulval, max+1
5747     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
5748       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
5749       if (MaxVal.eq(CI->getValue()))
5750         break; // Recognized
5751     }
5752     return nullptr;
5753 
5754   case ICmpInst::ICMP_ULE:
5755     // Recognize pattern:
5756     //   mulval = mul(zext A, zext B)
5757     //   cmp ule mulval, max
5758     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
5759       APInt MaxVal = APInt::getMaxValue(MulWidth);
5760       MaxVal = MaxVal.zext(CI->getBitWidth());
5761       if (MaxVal.eq(CI->getValue()))
5762         break; // Recognized
5763     }
5764     return nullptr;
5765 
5766   case ICmpInst::ICMP_ULT:
5767     // Recognize pattern:
5768     //   mulval = mul(zext A, zext B)
5769     //   cmp ule mulval, max + 1
5770     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
5771       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
5772       if (MaxVal.eq(CI->getValue()))
5773         break; // Recognized
5774     }
5775     return nullptr;
5776 
5777   default:
5778     return nullptr;
5779   }
5780 
5781   InstCombiner::BuilderTy &Builder = IC.Builder;
5782   Builder.SetInsertPoint(MulInstr);
5783 
5784   // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
5785   Value *MulA = A, *MulB = B;
5786   if (WidthA < MulWidth)
5787     MulA = Builder.CreateZExt(A, MulType);
5788   if (WidthB < MulWidth)
5789     MulB = Builder.CreateZExt(B, MulType);
5790   Function *F = Intrinsic::getDeclaration(
5791       I.getModule(), Intrinsic::umul_with_overflow, MulType);
5792   CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul");
5793   IC.addToWorklist(MulInstr);
5794 
5795   // If there are uses of mul result other than the comparison, we know that
5796   // they are truncation or binary AND. Change them to use result of
5797   // mul.with.overflow and adjust properly mask/size.
5798   if (MulVal->hasNUsesOrMore(2)) {
5799     Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
5800     for (User *U : make_early_inc_range(MulVal->users())) {
5801       if (U == &I || U == OtherVal)
5802         continue;
5803       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
5804         if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
5805           IC.replaceInstUsesWith(*TI, Mul);
5806         else
5807           TI->setOperand(0, Mul);
5808       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
5809         assert(BO->getOpcode() == Instruction::And);
5810         // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
5811         ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
5812         APInt ShortMask = CI->getValue().trunc(MulWidth);
5813         Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
5814         Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
5815         IC.replaceInstUsesWith(*BO, Zext);
5816       } else {
5817         llvm_unreachable("Unexpected Binary operation");
5818       }
5819       IC.addToWorklist(cast<Instruction>(U));
5820     }
5821   }
5822   if (isa<Instruction>(OtherVal))
5823     IC.addToWorklist(cast<Instruction>(OtherVal));
5824 
5825   // The original icmp gets replaced with the overflow value, maybe inverted
5826   // depending on predicate.
5827   bool Inverse = false;
5828   switch (I.getPredicate()) {
5829   case ICmpInst::ICMP_NE:
5830     break;
5831   case ICmpInst::ICMP_EQ:
5832     Inverse = true;
5833     break;
5834   case ICmpInst::ICMP_UGT:
5835   case ICmpInst::ICMP_UGE:
5836     if (I.getOperand(0) == MulVal)
5837       break;
5838     Inverse = true;
5839     break;
5840   case ICmpInst::ICMP_ULT:
5841   case ICmpInst::ICMP_ULE:
5842     if (I.getOperand(1) == MulVal)
5843       break;
5844     Inverse = true;
5845     break;
5846   default:
5847     llvm_unreachable("Unexpected predicate");
5848   }
5849   if (Inverse) {
5850     Value *Res = Builder.CreateExtractValue(Call, 1);
5851     return BinaryOperator::CreateNot(Res);
5852   }
5853 
5854   return ExtractValueInst::Create(Call, 1);
5855 }
5856 
5857 /// When performing a comparison against a constant, it is possible that not all
5858 /// the bits in the LHS are demanded. This helper method computes the mask that
5859 /// IS demanded.
5860 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
5861   const APInt *RHS;
5862   if (!match(I.getOperand(1), m_APInt(RHS)))
5863     return APInt::getAllOnes(BitWidth);
5864 
5865   // If this is a normal comparison, it demands all bits. If it is a sign bit
5866   // comparison, it only demands the sign bit.
5867   bool UnusedBit;
5868   if (InstCombiner::isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
5869     return APInt::getSignMask(BitWidth);
5870 
5871   switch (I.getPredicate()) {
5872   // For a UGT comparison, we don't care about any bits that
5873   // correspond to the trailing ones of the comparand.  The value of these
5874   // bits doesn't impact the outcome of the comparison, because any value
5875   // greater than the RHS must differ in a bit higher than these due to carry.
5876   case ICmpInst::ICMP_UGT:
5877     return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
5878 
5879   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
5880   // Any value less than the RHS must differ in a higher bit because of carries.
5881   case ICmpInst::ICMP_ULT:
5882     return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
5883 
5884   default:
5885     return APInt::getAllOnes(BitWidth);
5886   }
5887 }
5888 
5889 /// Check that one use is in the same block as the definition and all
5890 /// other uses are in blocks dominated by a given block.
5891 ///
5892 /// \param DI Definition
5893 /// \param UI Use
5894 /// \param DB Block that must dominate all uses of \p DI outside
5895 ///           the parent block
5896 /// \return true when \p UI is the only use of \p DI in the parent block
5897 /// and all other uses of \p DI are in blocks dominated by \p DB.
5898 ///
5899 bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
5900                                         const Instruction *UI,
5901                                         const BasicBlock *DB) const {
5902   assert(DI && UI && "Instruction not defined\n");
5903   // Ignore incomplete definitions.
5904   if (!DI->getParent())
5905     return false;
5906   // DI and UI must be in the same block.
5907   if (DI->getParent() != UI->getParent())
5908     return false;
5909   // Protect from self-referencing blocks.
5910   if (DI->getParent() == DB)
5911     return false;
5912   for (const User *U : DI->users()) {
5913     auto *Usr = cast<Instruction>(U);
5914     if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
5915       return false;
5916   }
5917   return true;
5918 }
5919 
5920 /// Return true when the instruction sequence within a block is select-cmp-br.
5921 static bool isChainSelectCmpBranch(const SelectInst *SI) {
5922   const BasicBlock *BB = SI->getParent();
5923   if (!BB)
5924     return false;
5925   auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
5926   if (!BI || BI->getNumSuccessors() != 2)
5927     return false;
5928   auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
5929   if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
5930     return false;
5931   return true;
5932 }
5933 
5934 /// True when a select result is replaced by one of its operands
5935 /// in select-icmp sequence. This will eventually result in the elimination
5936 /// of the select.
5937 ///
5938 /// \param SI    Select instruction
5939 /// \param Icmp  Compare instruction
5940 /// \param SIOpd Operand that replaces the select
5941 ///
5942 /// Notes:
5943 /// - The replacement is global and requires dominator information
5944 /// - The caller is responsible for the actual replacement
5945 ///
5946 /// Example:
5947 ///
5948 /// entry:
5949 ///  %4 = select i1 %3, %C* %0, %C* null
5950 ///  %5 = icmp eq %C* %4, null
5951 ///  br i1 %5, label %9, label %7
5952 ///  ...
5953 ///  ; <label>:7                                       ; preds = %entry
5954 ///  %8 = getelementptr inbounds %C* %4, i64 0, i32 0
5955 ///  ...
5956 ///
5957 /// can be transformed to
5958 ///
5959 ///  %5 = icmp eq %C* %0, null
5960 ///  %6 = select i1 %3, i1 %5, i1 true
5961 ///  br i1 %6, label %9, label %7
5962 ///  ...
5963 ///  ; <label>:7                                       ; preds = %entry
5964 ///  %8 = getelementptr inbounds %C* %0, i64 0, i32 0  // replace by %0!
5965 ///
5966 /// Similar when the first operand of the select is a constant or/and
5967 /// the compare is for not equal rather than equal.
5968 ///
5969 /// NOTE: The function is only called when the select and compare constants
5970 /// are equal, the optimization can work only for EQ predicates. This is not a
5971 /// major restriction since a NE compare should be 'normalized' to an equal
5972 /// compare, which usually happens in the combiner and test case
5973 /// select-cmp-br.ll checks for it.
5974 bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
5975                                                  const ICmpInst *Icmp,
5976                                                  const unsigned SIOpd) {
5977   assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
5978   if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
5979     BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
5980     // The check for the single predecessor is not the best that can be
5981     // done. But it protects efficiently against cases like when SI's
5982     // home block has two successors, Succ and Succ1, and Succ1 predecessor
5983     // of Succ. Then SI can't be replaced by SIOpd because the use that gets
5984     // replaced can be reached on either path. So the uniqueness check
5985     // guarantees that the path all uses of SI (outside SI's parent) are on
5986     // is disjoint from all other paths out of SI. But that information
5987     // is more expensive to compute, and the trade-off here is in favor
5988     // of compile-time. It should also be noticed that we check for a single
5989     // predecessor and not only uniqueness. This to handle the situation when
5990     // Succ and Succ1 points to the same basic block.
5991     if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
5992       NumSel++;
5993       SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
5994       return true;
5995     }
5996   }
5997   return false;
5998 }
5999 
6000 /// Try to fold the comparison based on range information we can get by checking
6001 /// whether bits are known to be zero or one in the inputs.
6002 Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
6003   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6004   Type *Ty = Op0->getType();
6005   ICmpInst::Predicate Pred = I.getPredicate();
6006 
6007   // Get scalar or pointer size.
6008   unsigned BitWidth = Ty->isIntOrIntVectorTy()
6009                           ? Ty->getScalarSizeInBits()
6010                           : DL.getPointerTypeSizeInBits(Ty->getScalarType());
6011 
6012   if (!BitWidth)
6013     return nullptr;
6014 
6015   KnownBits Op0Known(BitWidth);
6016   KnownBits Op1Known(BitWidth);
6017 
6018   if (SimplifyDemandedBits(&I, 0,
6019                            getDemandedBitsLHSMask(I, BitWidth),
6020                            Op0Known, 0))
6021     return &I;
6022 
6023   if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, 0))
6024     return &I;
6025 
6026   // Given the known and unknown bits, compute a range that the LHS could be
6027   // in.  Compute the Min, Max and RHS values based on the known bits. For the
6028   // EQ and NE we use unsigned values.
6029   APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6030   APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6031   if (I.isSigned()) {
6032     Op0Min = Op0Known.getSignedMinValue();
6033     Op0Max = Op0Known.getSignedMaxValue();
6034     Op1Min = Op1Known.getSignedMinValue();
6035     Op1Max = Op1Known.getSignedMaxValue();
6036   } else {
6037     Op0Min = Op0Known.getMinValue();
6038     Op0Max = Op0Known.getMaxValue();
6039     Op1Min = Op1Known.getMinValue();
6040     Op1Max = Op1Known.getMaxValue();
6041   }
6042 
6043   // If Min and Max are known to be the same, then SimplifyDemandedBits figured
6044   // out that the LHS or RHS is a constant. Constant fold this now, so that
6045   // code below can assume that Min != Max.
6046   if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6047     return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1);
6048   if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6049     return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min));
6050 
6051   // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
6052   // min/max canonical compare with some other compare. That could lead to
6053   // conflict with select canonicalization and infinite looping.
6054   // FIXME: This constraint may go away if min/max intrinsics are canonical.
6055   auto isMinMaxCmp = [&](Instruction &Cmp) {
6056     if (!Cmp.hasOneUse())
6057       return false;
6058     Value *A, *B;
6059     SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
6060     if (!SelectPatternResult::isMinOrMax(SPF))
6061       return false;
6062     return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
6063            match(Op1, m_MaxOrMin(m_Value(), m_Value()));
6064   };
6065   if (!isMinMaxCmp(I)) {
6066     switch (Pred) {
6067     default:
6068       break;
6069     case ICmpInst::ICMP_ULT: {
6070       if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6071         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6072       const APInt *CmpC;
6073       if (match(Op1, m_APInt(CmpC))) {
6074         // A <u C -> A == C-1 if min(A)+1 == C
6075         if (*CmpC == Op0Min + 1)
6076           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6077                               ConstantInt::get(Op1->getType(), *CmpC - 1));
6078         // X <u C --> X == 0, if the number of zero bits in the bottom of X
6079         // exceeds the log2 of C.
6080         if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
6081           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6082                               Constant::getNullValue(Op1->getType()));
6083       }
6084       break;
6085     }
6086     case ICmpInst::ICMP_UGT: {
6087       if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6088         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6089       const APInt *CmpC;
6090       if (match(Op1, m_APInt(CmpC))) {
6091         // A >u C -> A == C+1 if max(a)-1 == C
6092         if (*CmpC == Op0Max - 1)
6093           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6094                               ConstantInt::get(Op1->getType(), *CmpC + 1));
6095         // X >u C --> X != 0, if the number of zero bits in the bottom of X
6096         // exceeds the log2 of C.
6097         if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
6098           return new ICmpInst(ICmpInst::ICMP_NE, Op0,
6099                               Constant::getNullValue(Op1->getType()));
6100       }
6101       break;
6102     }
6103     case ICmpInst::ICMP_SLT: {
6104       if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6105         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6106       const APInt *CmpC;
6107       if (match(Op1, m_APInt(CmpC))) {
6108         if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
6109           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6110                               ConstantInt::get(Op1->getType(), *CmpC - 1));
6111       }
6112       break;
6113     }
6114     case ICmpInst::ICMP_SGT: {
6115       if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6116         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6117       const APInt *CmpC;
6118       if (match(Op1, m_APInt(CmpC))) {
6119         if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
6120           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6121                               ConstantInt::get(Op1->getType(), *CmpC + 1));
6122       }
6123       break;
6124     }
6125     }
6126   }
6127 
6128   // Based on the range information we know about the LHS, see if we can
6129   // simplify this comparison.  For example, (x&4) < 8 is always true.
6130   switch (Pred) {
6131   default:
6132     llvm_unreachable("Unknown icmp opcode!");
6133   case ICmpInst::ICMP_EQ:
6134   case ICmpInst::ICMP_NE: {
6135     if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6136       return replaceInstUsesWith(
6137           I, ConstantInt::getBool(I.getType(), Pred == CmpInst::ICMP_NE));
6138 
6139     // If all bits are known zero except for one, then we know at most one bit
6140     // is set. If the comparison is against zero, then this is a check to see if
6141     // *that* bit is set.
6142     APInt Op0KnownZeroInverted = ~Op0Known.Zero;
6143     if (Op1Known.isZero()) {
6144       // If the LHS is an AND with the same constant, look through it.
6145       Value *LHS = nullptr;
6146       const APInt *LHSC;
6147       if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
6148           *LHSC != Op0KnownZeroInverted)
6149         LHS = Op0;
6150 
6151       Value *X;
6152       const APInt *C1;
6153       if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
6154         Type *XTy = X->getType();
6155         unsigned Log2C1 = C1->countr_zero();
6156         APInt C2 = Op0KnownZeroInverted;
6157         APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
6158         if (C2Pow2.isPowerOf2()) {
6159           // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
6160           // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
6161           // ((C1 << X) & C2) != 0 -> X  < (Log2(C2+C1) - Log2(C1))
6162           unsigned Log2C2 = C2Pow2.countr_zero();
6163           auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
6164           auto NewPred =
6165               Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
6166           return new ICmpInst(NewPred, X, CmpC);
6167         }
6168       }
6169     }
6170 
6171     // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
6172     if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
6173         (Op0Known & Op1Known) == Op0Known)
6174       return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6175                           ConstantInt::getNullValue(Op1->getType()));
6176     break;
6177   }
6178   case ICmpInst::ICMP_ULT: {
6179     if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6180       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6181     if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6182       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6183     break;
6184   }
6185   case ICmpInst::ICMP_UGT: {
6186     if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6187       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6188     if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6189       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6190     break;
6191   }
6192   case ICmpInst::ICMP_SLT: {
6193     if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6194       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6195     if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6196       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6197     break;
6198   }
6199   case ICmpInst::ICMP_SGT: {
6200     if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6201       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6202     if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6203       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6204     break;
6205   }
6206   case ICmpInst::ICMP_SGE:
6207     assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6208     if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6209       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6210     if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6211       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6212     if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
6213       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6214     break;
6215   case ICmpInst::ICMP_SLE:
6216     assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6217     if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6218       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6219     if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6220       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6221     if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
6222       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6223     break;
6224   case ICmpInst::ICMP_UGE:
6225     assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6226     if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6227       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6228     if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6229       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6230     if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
6231       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6232     break;
6233   case ICmpInst::ICMP_ULE:
6234     assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6235     if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6236       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6237     if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6238       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6239     if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
6240       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6241     break;
6242   }
6243 
6244   // Turn a signed comparison into an unsigned one if both operands are known to
6245   // have the same sign.
6246   if (I.isSigned() &&
6247       ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
6248        (Op0Known.One.isNegative() && Op1Known.One.isNegative())))
6249     return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6250 
6251   return nullptr;
6252 }
6253 
6254 /// If one operand of an icmp is effectively a bool (value range of {0,1}),
6255 /// then try to reduce patterns based on that limit.
6256 Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
6257   Value *X, *Y;
6258   ICmpInst::Predicate Pred;
6259 
6260   // X must be 0 and bool must be true for "ULT":
6261   // X <u (zext i1 Y) --> (X == 0) & Y
6262   if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
6263       Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
6264     return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
6265 
6266   // X must be 0 or bool must be true for "ULE":
6267   // X <=u (sext i1 Y) --> (X == 0) | Y
6268   if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
6269       Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
6270     return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
6271 
6272   const APInt *C;
6273   if (match(I.getOperand(0), m_c_Add(m_ZExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
6274       match(I.getOperand(1), m_APInt(C)) &&
6275       X->getType()->isIntOrIntVectorTy(1) &&
6276       Y->getType()->isIntOrIntVectorTy(1)) {
6277     unsigned BitWidth = C->getBitWidth();
6278     Pred = I.getPredicate();
6279     APInt Zero = APInt::getZero(BitWidth);
6280     APInt MinusOne = APInt::getAllOnes(BitWidth);
6281     APInt One(BitWidth, 1);
6282     if ((C->sgt(Zero) && Pred == ICmpInst::ICMP_SGT) ||
6283         (C->slt(Zero) && Pred == ICmpInst::ICMP_SLT))
6284       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6285     if ((C->sgt(One) && Pred == ICmpInst::ICMP_SLT) ||
6286         (C->slt(MinusOne) && Pred == ICmpInst::ICMP_SGT))
6287       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6288 
6289     if (I.getOperand(0)->hasOneUse()) {
6290       APInt NewC = *C;
6291       // canonicalize predicate to eq/ne
6292       if ((*C == Zero && Pred == ICmpInst::ICMP_SLT) ||
6293           (*C != Zero && *C != MinusOne && Pred == ICmpInst::ICMP_UGT)) {
6294         // x s< 0 in [-1, 1] --> x == -1
6295         // x u> 1(or any const !=0 !=-1) in [-1, 1] --> x == -1
6296         NewC = MinusOne;
6297         Pred = ICmpInst::ICMP_EQ;
6298       } else if ((*C == MinusOne && Pred == ICmpInst::ICMP_SGT) ||
6299                  (*C != Zero && *C != One && Pred == ICmpInst::ICMP_ULT)) {
6300         // x s> -1 in [-1, 1] --> x != -1
6301         // x u< -1 in [-1, 1] --> x != -1
6302         Pred = ICmpInst::ICMP_NE;
6303       } else if (*C == Zero && Pred == ICmpInst::ICMP_SGT) {
6304         // x s> 0 in [-1, 1] --> x == 1
6305         NewC = One;
6306         Pred = ICmpInst::ICMP_EQ;
6307       } else if (*C == One && Pred == ICmpInst::ICMP_SLT) {
6308         // x s< 1 in [-1, 1] --> x != 1
6309         Pred = ICmpInst::ICMP_NE;
6310       }
6311 
6312       if (NewC == MinusOne) {
6313         if (Pred == ICmpInst::ICMP_EQ)
6314           return BinaryOperator::CreateAnd(Builder.CreateNot(X), Y);
6315         if (Pred == ICmpInst::ICMP_NE)
6316           return BinaryOperator::CreateOr(X, Builder.CreateNot(Y));
6317       } else if (NewC == One) {
6318         if (Pred == ICmpInst::ICMP_EQ)
6319           return BinaryOperator::CreateAnd(X, Builder.CreateNot(Y));
6320         if (Pred == ICmpInst::ICMP_NE)
6321           return BinaryOperator::CreateOr(Builder.CreateNot(X), Y);
6322       }
6323     }
6324   }
6325 
6326   return nullptr;
6327 }
6328 
6329 std::optional<std::pair<CmpInst::Predicate, Constant *>>
6330 InstCombiner::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred,
6331                                                        Constant *C) {
6332   assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) &&
6333          "Only for relational integer predicates.");
6334 
6335   Type *Type = C->getType();
6336   bool IsSigned = ICmpInst::isSigned(Pred);
6337 
6338   CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred);
6339   bool WillIncrement =
6340       UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
6341 
6342   // Check if the constant operand can be safely incremented/decremented
6343   // without overflowing/underflowing.
6344   auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) {
6345     return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);
6346   };
6347 
6348   Constant *SafeReplacementConstant = nullptr;
6349   if (auto *CI = dyn_cast<ConstantInt>(C)) {
6350     // Bail out if the constant can't be safely incremented/decremented.
6351     if (!ConstantIsOk(CI))
6352       return std::nullopt;
6353   } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
6354     unsigned NumElts = FVTy->getNumElements();
6355     for (unsigned i = 0; i != NumElts; ++i) {
6356       Constant *Elt = C->getAggregateElement(i);
6357       if (!Elt)
6358         return std::nullopt;
6359 
6360       if (isa<UndefValue>(Elt))
6361         continue;
6362 
6363       // Bail out if we can't determine if this constant is min/max or if we
6364       // know that this constant is min/max.
6365       auto *CI = dyn_cast<ConstantInt>(Elt);
6366       if (!CI || !ConstantIsOk(CI))
6367         return std::nullopt;
6368 
6369       if (!SafeReplacementConstant)
6370         SafeReplacementConstant = CI;
6371     }
6372   } else {
6373     // ConstantExpr?
6374     return std::nullopt;
6375   }
6376 
6377   // It may not be safe to change a compare predicate in the presence of
6378   // undefined elements, so replace those elements with the first safe constant
6379   // that we found.
6380   // TODO: in case of poison, it is safe; let's replace undefs only.
6381   if (C->containsUndefOrPoisonElement()) {
6382     assert(SafeReplacementConstant && "Replacement constant not set");
6383     C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
6384   }
6385 
6386   CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred);
6387 
6388   // Increment or decrement the constant.
6389   Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
6390   Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
6391 
6392   return std::make_pair(NewPred, NewC);
6393 }
6394 
6395 /// If we have an icmp le or icmp ge instruction with a constant operand, turn
6396 /// it into the appropriate icmp lt or icmp gt instruction. This transform
6397 /// allows them to be folded in visitICmpInst.
6398 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
6399   ICmpInst::Predicate Pred = I.getPredicate();
6400   if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
6401       InstCombiner::isCanonicalPredicate(Pred))
6402     return nullptr;
6403 
6404   Value *Op0 = I.getOperand(0);
6405   Value *Op1 = I.getOperand(1);
6406   auto *Op1C = dyn_cast<Constant>(Op1);
6407   if (!Op1C)
6408     return nullptr;
6409 
6410   auto FlippedStrictness =
6411       InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
6412   if (!FlippedStrictness)
6413     return nullptr;
6414 
6415   return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
6416 }
6417 
6418 /// If we have a comparison with a non-canonical predicate, if we can update
6419 /// all the users, invert the predicate and adjust all the users.
6420 CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
6421   // Is the predicate already canonical?
6422   CmpInst::Predicate Pred = I.getPredicate();
6423   if (InstCombiner::isCanonicalPredicate(Pred))
6424     return nullptr;
6425 
6426   // Can all users be adjusted to predicate inversion?
6427   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
6428     return nullptr;
6429 
6430   // Ok, we can canonicalize comparison!
6431   // Let's first invert the comparison's predicate.
6432   I.setPredicate(CmpInst::getInversePredicate(Pred));
6433   I.setName(I.getName() + ".not");
6434 
6435   // And, adapt users.
6436   freelyInvertAllUsersOf(&I);
6437 
6438   return &I;
6439 }
6440 
6441 /// Integer compare with boolean values can always be turned into bitwise ops.
6442 static Instruction *canonicalizeICmpBool(ICmpInst &I,
6443                                          InstCombiner::BuilderTy &Builder) {
6444   Value *A = I.getOperand(0), *B = I.getOperand(1);
6445   assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
6446 
6447   // A boolean compared to true/false can be simplified to Op0/true/false in
6448   // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
6449   // Cases not handled by InstSimplify are always 'not' of Op0.
6450   if (match(B, m_Zero())) {
6451     switch (I.getPredicate()) {
6452       case CmpInst::ICMP_EQ:  // A ==   0 -> !A
6453       case CmpInst::ICMP_ULE: // A <=u  0 -> !A
6454       case CmpInst::ICMP_SGE: // A >=s  0 -> !A
6455         return BinaryOperator::CreateNot(A);
6456       default:
6457         llvm_unreachable("ICmp i1 X, C not simplified as expected.");
6458     }
6459   } else if (match(B, m_One())) {
6460     switch (I.getPredicate()) {
6461       case CmpInst::ICMP_NE:  // A !=  1 -> !A
6462       case CmpInst::ICMP_ULT: // A <u  1 -> !A
6463       case CmpInst::ICMP_SGT: // A >s -1 -> !A
6464         return BinaryOperator::CreateNot(A);
6465       default:
6466         llvm_unreachable("ICmp i1 X, C not simplified as expected.");
6467     }
6468   }
6469 
6470   switch (I.getPredicate()) {
6471   default:
6472     llvm_unreachable("Invalid icmp instruction!");
6473   case ICmpInst::ICMP_EQ:
6474     // icmp eq i1 A, B -> ~(A ^ B)
6475     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
6476 
6477   case ICmpInst::ICMP_NE:
6478     // icmp ne i1 A, B -> A ^ B
6479     return BinaryOperator::CreateXor(A, B);
6480 
6481   case ICmpInst::ICMP_UGT:
6482     // icmp ugt -> icmp ult
6483     std::swap(A, B);
6484     [[fallthrough]];
6485   case ICmpInst::ICMP_ULT:
6486     // icmp ult i1 A, B -> ~A & B
6487     return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
6488 
6489   case ICmpInst::ICMP_SGT:
6490     // icmp sgt -> icmp slt
6491     std::swap(A, B);
6492     [[fallthrough]];
6493   case ICmpInst::ICMP_SLT:
6494     // icmp slt i1 A, B -> A & ~B
6495     return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
6496 
6497   case ICmpInst::ICMP_UGE:
6498     // icmp uge -> icmp ule
6499     std::swap(A, B);
6500     [[fallthrough]];
6501   case ICmpInst::ICMP_ULE:
6502     // icmp ule i1 A, B -> ~A | B
6503     return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
6504 
6505   case ICmpInst::ICMP_SGE:
6506     // icmp sge -> icmp sle
6507     std::swap(A, B);
6508     [[fallthrough]];
6509   case ICmpInst::ICMP_SLE:
6510     // icmp sle i1 A, B -> A | ~B
6511     return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
6512   }
6513 }
6514 
6515 // Transform pattern like:
6516 //   (1 << Y) u<= X  or  ~(-1 << Y) u<  X  or  ((1 << Y)+(-1)) u<  X
6517 //   (1 << Y) u>  X  or  ~(-1 << Y) u>= X  or  ((1 << Y)+(-1)) u>= X
6518 // Into:
6519 //   (X l>> Y) != 0
6520 //   (X l>> Y) == 0
6521 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
6522                                             InstCombiner::BuilderTy &Builder) {
6523   ICmpInst::Predicate Pred, NewPred;
6524   Value *X, *Y;
6525   if (match(&Cmp,
6526             m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
6527     switch (Pred) {
6528     case ICmpInst::ICMP_ULE:
6529       NewPred = ICmpInst::ICMP_NE;
6530       break;
6531     case ICmpInst::ICMP_UGT:
6532       NewPred = ICmpInst::ICMP_EQ;
6533       break;
6534     default:
6535       return nullptr;
6536     }
6537   } else if (match(&Cmp, m_c_ICmp(Pred,
6538                                   m_OneUse(m_CombineOr(
6539                                       m_Not(m_Shl(m_AllOnes(), m_Value(Y))),
6540                                       m_Add(m_Shl(m_One(), m_Value(Y)),
6541                                             m_AllOnes()))),
6542                                   m_Value(X)))) {
6543     // The variant with 'add' is not canonical, (the variant with 'not' is)
6544     // we only get it because it has extra uses, and can't be canonicalized,
6545 
6546     switch (Pred) {
6547     case ICmpInst::ICMP_ULT:
6548       NewPred = ICmpInst::ICMP_NE;
6549       break;
6550     case ICmpInst::ICMP_UGE:
6551       NewPred = ICmpInst::ICMP_EQ;
6552       break;
6553     default:
6554       return nullptr;
6555     }
6556   } else
6557     return nullptr;
6558 
6559   Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
6560   Constant *Zero = Constant::getNullValue(NewX->getType());
6561   return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
6562 }
6563 
6564 static Instruction *foldVectorCmp(CmpInst &Cmp,
6565                                   InstCombiner::BuilderTy &Builder) {
6566   const CmpInst::Predicate Pred = Cmp.getPredicate();
6567   Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
6568   Value *V1, *V2;
6569 
6570   auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
6571     Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
6572     if (auto *I = dyn_cast<Instruction>(V))
6573       I->copyIRFlags(&Cmp);
6574     Module *M = Cmp.getModule();
6575     Function *F = Intrinsic::getDeclaration(
6576         M, Intrinsic::experimental_vector_reverse, V->getType());
6577     return CallInst::Create(F, V);
6578   };
6579 
6580   if (match(LHS, m_VecReverse(m_Value(V1)))) {
6581     // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
6582     if (match(RHS, m_VecReverse(m_Value(V2))) &&
6583         (LHS->hasOneUse() || RHS->hasOneUse()))
6584       return createCmpReverse(Pred, V1, V2);
6585 
6586     // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
6587     if (LHS->hasOneUse() && isSplatValue(RHS))
6588       return createCmpReverse(Pred, V1, RHS);
6589   }
6590   // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
6591   else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
6592     return createCmpReverse(Pred, LHS, V2);
6593 
6594   ArrayRef<int> M;
6595   if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
6596     return nullptr;
6597 
6598   // If both arguments of the cmp are shuffles that use the same mask and
6599   // shuffle within a single vector, move the shuffle after the cmp:
6600   // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
6601   Type *V1Ty = V1->getType();
6602   if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
6603       V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
6604     Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
6605     return new ShuffleVectorInst(NewCmp, M);
6606   }
6607 
6608   // Try to canonicalize compare with splatted operand and splat constant.
6609   // TODO: We could generalize this for more than splats. See/use the code in
6610   //       InstCombiner::foldVectorBinop().
6611   Constant *C;
6612   if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
6613     return nullptr;
6614 
6615   // Length-changing splats are ok, so adjust the constants as needed:
6616   // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
6617   Constant *ScalarC = C->getSplatValue(/* AllowUndefs */ true);
6618   int MaskSplatIndex;
6619   if (ScalarC && match(M, m_SplatOrUndefMask(MaskSplatIndex))) {
6620     // We allow undefs in matching, but this transform removes those for safety.
6621     // Demanded elements analysis should be able to recover some/all of that.
6622     C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
6623                                  ScalarC);
6624     SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
6625     Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
6626     return new ShuffleVectorInst(NewCmp, NewM);
6627   }
6628 
6629   return nullptr;
6630 }
6631 
6632 // extract(uadd.with.overflow(A, B), 0) ult A
6633 //  -> extract(uadd.with.overflow(A, B), 1)
6634 static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
6635   CmpInst::Predicate Pred = I.getPredicate();
6636   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6637 
6638   Value *UAddOv;
6639   Value *A, *B;
6640   auto UAddOvResultPat = m_ExtractValue<0>(
6641       m_Intrinsic<Intrinsic::uadd_with_overflow>(m_Value(A), m_Value(B)));
6642   if (match(Op0, UAddOvResultPat) &&
6643       ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
6644        (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
6645         (match(A, m_One()) || match(B, m_One()))) ||
6646        (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
6647         (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
6648     // extract(uadd.with.overflow(A, B), 0) < A
6649     // extract(uadd.with.overflow(A, 1), 0) == 0
6650     // extract(uadd.with.overflow(A, -1), 0) != -1
6651     UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
6652   else if (match(Op1, UAddOvResultPat) &&
6653            Pred == ICmpInst::ICMP_UGT && (Op0 == A || Op0 == B))
6654     // A > extract(uadd.with.overflow(A, B), 0)
6655     UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
6656   else
6657     return nullptr;
6658 
6659   return ExtractValueInst::Create(UAddOv, 1);
6660 }
6661 
6662 static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
6663   if (!I.getOperand(0)->getType()->isPointerTy() ||
6664       NullPointerIsDefined(
6665           I.getParent()->getParent(),
6666           I.getOperand(0)->getType()->getPointerAddressSpace())) {
6667     return nullptr;
6668   }
6669   Instruction *Op;
6670   if (match(I.getOperand(0), m_Instruction(Op)) &&
6671       match(I.getOperand(1), m_Zero()) &&
6672       Op->isLaunderOrStripInvariantGroup()) {
6673     return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
6674                             Op->getOperand(0), I.getOperand(1));
6675   }
6676   return nullptr;
6677 }
6678 
6679 /// This function folds patterns produced by lowering of reduce idioms, such as
6680 /// llvm.vector.reduce.and which are lowered into instruction chains. This code
6681 /// attempts to generate fewer number of scalar comparisons instead of vector
6682 /// comparisons when possible.
6683 static Instruction *foldReductionIdiom(ICmpInst &I,
6684                                        InstCombiner::BuilderTy &Builder,
6685                                        const DataLayout &DL) {
6686   if (I.getType()->isVectorTy())
6687     return nullptr;
6688   ICmpInst::Predicate OuterPred, InnerPred;
6689   Value *LHS, *RHS;
6690 
6691   // Match lowering of @llvm.vector.reduce.and. Turn
6692   ///   %vec_ne = icmp ne <8 x i8> %lhs, %rhs
6693   ///   %scalar_ne = bitcast <8 x i1> %vec_ne to i8
6694   ///   %res = icmp <pred> i8 %scalar_ne, 0
6695   ///
6696   /// into
6697   ///
6698   ///   %lhs.scalar = bitcast <8 x i8> %lhs to i64
6699   ///   %rhs.scalar = bitcast <8 x i8> %rhs to i64
6700   ///   %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
6701   ///
6702   /// for <pred> in {ne, eq}.
6703   if (!match(&I, m_ICmp(OuterPred,
6704                         m_OneUse(m_BitCast(m_OneUse(
6705                             m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
6706                         m_Zero())))
6707     return nullptr;
6708   auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
6709   if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
6710     return nullptr;
6711   unsigned NumBits =
6712       LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
6713   // TODO: Relax this to "not wider than max legal integer type"?
6714   if (!DL.isLegalInteger(NumBits))
6715     return nullptr;
6716 
6717   if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
6718     auto *ScalarTy = Builder.getIntNTy(NumBits);
6719     LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
6720     RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
6721     return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
6722                             I.getName());
6723   }
6724 
6725   return nullptr;
6726 }
6727 
6728 Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
6729   bool Changed = false;
6730   const SimplifyQuery Q = SQ.getWithInstruction(&I);
6731   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6732   unsigned Op0Cplxity = getComplexity(Op0);
6733   unsigned Op1Cplxity = getComplexity(Op1);
6734 
6735   /// Orders the operands of the compare so that they are listed from most
6736   /// complex to least complex.  This puts constants before unary operators,
6737   /// before binary operators.
6738   if (Op0Cplxity < Op1Cplxity) {
6739     I.swapOperands();
6740     std::swap(Op0, Op1);
6741     Changed = true;
6742   }
6743 
6744   if (Value *V = simplifyICmpInst(I.getPredicate(), Op0, Op1, Q))
6745     return replaceInstUsesWith(I, V);
6746 
6747   // Comparing -val or val with non-zero is the same as just comparing val
6748   // ie, abs(val) != 0 -> val != 0
6749   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
6750     Value *Cond, *SelectTrue, *SelectFalse;
6751     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
6752                             m_Value(SelectFalse)))) {
6753       if (Value *V = dyn_castNegVal(SelectTrue)) {
6754         if (V == SelectFalse)
6755           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
6756       }
6757       else if (Value *V = dyn_castNegVal(SelectFalse)) {
6758         if (V == SelectTrue)
6759           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
6760       }
6761     }
6762   }
6763 
6764   if (Op0->getType()->isIntOrIntVectorTy(1))
6765     if (Instruction *Res = canonicalizeICmpBool(I, Builder))
6766       return Res;
6767 
6768   if (Instruction *Res = canonicalizeCmpWithConstant(I))
6769     return Res;
6770 
6771   if (Instruction *Res = canonicalizeICmpPredicate(I))
6772     return Res;
6773 
6774   if (Instruction *Res = foldICmpWithConstant(I))
6775     return Res;
6776 
6777   if (Instruction *Res = foldICmpWithDominatingICmp(I))
6778     return Res;
6779 
6780   if (Instruction *Res = foldICmpUsingBoolRange(I))
6781     return Res;
6782 
6783   if (Instruction *Res = foldICmpUsingKnownBits(I))
6784     return Res;
6785 
6786   // Test if the ICmpInst instruction is used exclusively by a select as
6787   // part of a minimum or maximum operation. If so, refrain from doing
6788   // any other folding. This helps out other analyses which understand
6789   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6790   // and CodeGen. And in this case, at least one of the comparison
6791   // operands has at least one user besides the compare (the select),
6792   // which would often largely negate the benefit of folding anyway.
6793   //
6794   // Do the same for the other patterns recognized by matchSelectPattern.
6795   if (I.hasOneUse())
6796     if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
6797       Value *A, *B;
6798       SelectPatternResult SPR = matchSelectPattern(SI, A, B);
6799       if (SPR.Flavor != SPF_UNKNOWN)
6800         return nullptr;
6801     }
6802 
6803   // Do this after checking for min/max to prevent infinite looping.
6804   if (Instruction *Res = foldICmpWithZero(I))
6805     return Res;
6806 
6807   // FIXME: We only do this after checking for min/max to prevent infinite
6808   // looping caused by a reverse canonicalization of these patterns for min/max.
6809   // FIXME: The organization of folds is a mess. These would naturally go into
6810   // canonicalizeCmpWithConstant(), but we can't move all of the above folds
6811   // down here after the min/max restriction.
6812   ICmpInst::Predicate Pred = I.getPredicate();
6813   const APInt *C;
6814   if (match(Op1, m_APInt(C))) {
6815     // For i32: x >u 2147483647 -> x <s 0  -> true if sign bit set
6816     if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
6817       Constant *Zero = Constant::getNullValue(Op0->getType());
6818       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
6819     }
6820 
6821     // For i32: x <u 2147483648 -> x >s -1  -> true if sign bit clear
6822     if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
6823       Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
6824       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
6825     }
6826   }
6827 
6828   // The folds in here may rely on wrapping flags and special constants, so
6829   // they can break up min/max idioms in some cases but not seemingly similar
6830   // patterns.
6831   // FIXME: It may be possible to enhance select folding to make this
6832   //        unnecessary. It may also be moot if we canonicalize to min/max
6833   //        intrinsics.
6834   if (Instruction *Res = foldICmpBinOp(I, Q))
6835     return Res;
6836 
6837   if (Instruction *Res = foldICmpInstWithConstant(I))
6838     return Res;
6839 
6840   // Try to match comparison as a sign bit test. Intentionally do this after
6841   // foldICmpInstWithConstant() to potentially let other folds to happen first.
6842   if (Instruction *New = foldSignBitTest(I))
6843     return New;
6844 
6845   if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
6846     return Res;
6847 
6848   // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
6849   if (auto *GEP = dyn_cast<GEPOperator>(Op0))
6850     if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
6851       return NI;
6852   if (auto *GEP = dyn_cast<GEPOperator>(Op1))
6853     if (Instruction *NI = foldGEPICmp(GEP, Op0, I.getSwappedPredicate(), I))
6854       return NI;
6855 
6856   if (auto *SI = dyn_cast<SelectInst>(Op0))
6857     if (Instruction *NI = foldSelectICmp(I.getPredicate(), SI, Op1, I))
6858       return NI;
6859   if (auto *SI = dyn_cast<SelectInst>(Op1))
6860     if (Instruction *NI = foldSelectICmp(I.getSwappedPredicate(), SI, Op0, I))
6861       return NI;
6862 
6863   // In case of a comparison with two select instructions having the same
6864   // condition, check whether one of the resulting branches can be simplified.
6865   // If so, just compare the other branch and select the appropriate result.
6866   // For example:
6867   //   %tmp1 = select i1 %cmp, i32 %y, i32 %x
6868   //   %tmp2 = select i1 %cmp, i32 %z, i32 %x
6869   //   %cmp2 = icmp slt i32 %tmp2, %tmp1
6870   // The icmp will result false for the false value of selects and the result
6871   // will depend upon the comparison of true values of selects if %cmp is
6872   // true. Thus, transform this into:
6873   //   %cmp = icmp slt i32 %y, %z
6874   //   %sel = select i1 %cond, i1 %cmp, i1 false
6875   // This handles similar cases to transform.
6876   {
6877     Value *Cond, *A, *B, *C, *D;
6878     if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
6879         match(Op1, m_Select(m_Specific(Cond), m_Value(C), m_Value(D))) &&
6880         (Op0->hasOneUse() || Op1->hasOneUse())) {
6881       // Check whether comparison of TrueValues can be simplified
6882       if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
6883         Value *NewICMP = Builder.CreateICmp(Pred, B, D);
6884         return SelectInst::Create(Cond, Res, NewICMP);
6885       }
6886       // Check whether comparison of FalseValues can be simplified
6887       if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
6888         Value *NewICMP = Builder.CreateICmp(Pred, A, C);
6889         return SelectInst::Create(Cond, NewICMP, Res);
6890       }
6891     }
6892   }
6893 
6894   // Try to optimize equality comparisons against alloca-based pointers.
6895   if (Op0->getType()->isPointerTy() && I.isEquality()) {
6896     assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
6897     if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
6898       if (foldAllocaCmp(Alloca))
6899         return nullptr;
6900     if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
6901       if (foldAllocaCmp(Alloca))
6902         return nullptr;
6903   }
6904 
6905   if (Instruction *Res = foldICmpBitCast(I))
6906     return Res;
6907 
6908   // TODO: Hoist this above the min/max bailout.
6909   if (Instruction *R = foldICmpWithCastOp(I))
6910     return R;
6911 
6912   if (Instruction *Res = foldICmpWithMinMax(I))
6913     return Res;
6914 
6915   {
6916     Value *A, *B;
6917     // Transform (A & ~B) == 0 --> (A & B) != 0
6918     // and       (A & ~B) != 0 --> (A & B) == 0
6919     // if A is a power of 2.
6920     if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
6921         match(Op1, m_Zero()) &&
6922         isKnownToBeAPowerOfTwo(A, false, 0, &I) && I.isEquality())
6923       return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(A, B),
6924                           Op1);
6925 
6926     // ~X < ~Y --> Y < X
6927     // ~X < C -->  X > ~C
6928     if (match(Op0, m_Not(m_Value(A)))) {
6929       if (match(Op1, m_Not(m_Value(B))))
6930         return new ICmpInst(I.getPredicate(), B, A);
6931 
6932       const APInt *C;
6933       if (match(Op1, m_APInt(C)))
6934         return new ICmpInst(I.getSwappedPredicate(), A,
6935                             ConstantInt::get(Op1->getType(), ~(*C)));
6936     }
6937 
6938     Instruction *AddI = nullptr;
6939     if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
6940                                      m_Instruction(AddI))) &&
6941         isa<IntegerType>(A->getType())) {
6942       Value *Result;
6943       Constant *Overflow;
6944       // m_UAddWithOverflow can match patterns that do not include  an explicit
6945       // "add" instruction, so check the opcode of the matched op.
6946       if (AddI->getOpcode() == Instruction::Add &&
6947           OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, A, B, *AddI,
6948                                 Result, Overflow)) {
6949         replaceInstUsesWith(*AddI, Result);
6950         eraseInstFromFunction(*AddI);
6951         return replaceInstUsesWith(I, Overflow);
6952       }
6953     }
6954 
6955     // (zext a) * (zext b)  --> llvm.umul.with.overflow.
6956     if (match(Op0, m_NUWMul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
6957       if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this))
6958         return R;
6959     }
6960     if (match(Op1, m_NUWMul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
6961       if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this))
6962         return R;
6963     }
6964   }
6965 
6966   if (Instruction *Res = foldICmpEquality(I))
6967     return Res;
6968 
6969   if (Instruction *Res = foldICmpPow2Test(I, Builder))
6970     return Res;
6971 
6972   if (Instruction *Res = foldICmpOfUAddOv(I))
6973     return Res;
6974 
6975   // The 'cmpxchg' instruction returns an aggregate containing the old value and
6976   // an i1 which indicates whether or not we successfully did the swap.
6977   //
6978   // Replace comparisons between the old value and the expected value with the
6979   // indicator that 'cmpxchg' returns.
6980   //
6981   // N.B.  This transform is only valid when the 'cmpxchg' is not permitted to
6982   // spuriously fail.  In those cases, the old value may equal the expected
6983   // value but it is possible for the swap to not occur.
6984   if (I.getPredicate() == ICmpInst::ICMP_EQ)
6985     if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
6986       if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
6987         if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
6988             !ACXI->isWeak())
6989           return ExtractValueInst::Create(ACXI, 1);
6990 
6991   {
6992     Value *X;
6993     const APInt *C;
6994     // icmp X+Cst, X
6995     if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
6996       return foldICmpAddOpConst(X, *C, I.getPredicate());
6997 
6998     // icmp X, X+Cst
6999     if (match(Op1, m_Add(m_Value(X), m_APInt(C))) && Op0 == X)
7000       return foldICmpAddOpConst(X, *C, I.getSwappedPredicate());
7001   }
7002 
7003   if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))
7004     return Res;
7005 
7006   if (I.getType()->isVectorTy())
7007     if (Instruction *Res = foldVectorCmp(I, Builder))
7008       return Res;
7009 
7010   if (Instruction *Res = foldICmpInvariantGroup(I))
7011     return Res;
7012 
7013   if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
7014     return Res;
7015 
7016   return Changed ? &I : nullptr;
7017 }
7018 
7019 /// Fold fcmp ([us]itofp x, cst) if possible.
7020 Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
7021                                                     Instruction *LHSI,
7022                                                     Constant *RHSC) {
7023   if (!isa<ConstantFP>(RHSC)) return nullptr;
7024   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
7025 
7026   // Get the width of the mantissa.  We don't want to hack on conversions that
7027   // might lose information from the integer, e.g. "i64 -> float"
7028   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
7029   if (MantissaWidth == -1) return nullptr;  // Unknown.
7030 
7031   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
7032 
7033   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
7034 
7035   if (I.isEquality()) {
7036     FCmpInst::Predicate P = I.getPredicate();
7037     bool IsExact = false;
7038     APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
7039     RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
7040 
7041     // If the floating point constant isn't an integer value, we know if we will
7042     // ever compare equal / not equal to it.
7043     if (!IsExact) {
7044       // TODO: Can never be -0.0 and other non-representable values
7045       APFloat RHSRoundInt(RHS);
7046       RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
7047       if (RHS != RHSRoundInt) {
7048         if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
7049           return replaceInstUsesWith(I, Builder.getFalse());
7050 
7051         assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
7052         return replaceInstUsesWith(I, Builder.getTrue());
7053       }
7054     }
7055 
7056     // TODO: If the constant is exactly representable, is it always OK to do
7057     // equality compares as integer?
7058   }
7059 
7060   // Check to see that the input is converted from an integer type that is small
7061   // enough that preserves all bits.  TODO: check here for "known" sign bits.
7062   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
7063   unsigned InputSize = IntTy->getScalarSizeInBits();
7064 
7065   // Following test does NOT adjust InputSize downwards for signed inputs,
7066   // because the most negative value still requires all the mantissa bits
7067   // to distinguish it from one less than that value.
7068   if ((int)InputSize > MantissaWidth) {
7069     // Conversion would lose accuracy. Check if loss can impact comparison.
7070     int Exp = ilogb(RHS);
7071     if (Exp == APFloat::IEK_Inf) {
7072       int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
7073       if (MaxExponent < (int)InputSize - !LHSUnsigned)
7074         // Conversion could create infinity.
7075         return nullptr;
7076     } else {
7077       // Note that if RHS is zero or NaN, then Exp is negative
7078       // and first condition is trivially false.
7079       if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
7080         // Conversion could affect comparison.
7081         return nullptr;
7082     }
7083   }
7084 
7085   // Otherwise, we can potentially simplify the comparison.  We know that it
7086   // will always come through as an integer value and we know the constant is
7087   // not a NAN (it would have been previously simplified).
7088   assert(!RHS.isNaN() && "NaN comparison not already folded!");
7089 
7090   ICmpInst::Predicate Pred;
7091   switch (I.getPredicate()) {
7092   default: llvm_unreachable("Unexpected predicate!");
7093   case FCmpInst::FCMP_UEQ:
7094   case FCmpInst::FCMP_OEQ:
7095     Pred = ICmpInst::ICMP_EQ;
7096     break;
7097   case FCmpInst::FCMP_UGT:
7098   case FCmpInst::FCMP_OGT:
7099     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
7100     break;
7101   case FCmpInst::FCMP_UGE:
7102   case FCmpInst::FCMP_OGE:
7103     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
7104     break;
7105   case FCmpInst::FCMP_ULT:
7106   case FCmpInst::FCMP_OLT:
7107     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
7108     break;
7109   case FCmpInst::FCMP_ULE:
7110   case FCmpInst::FCMP_OLE:
7111     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
7112     break;
7113   case FCmpInst::FCMP_UNE:
7114   case FCmpInst::FCMP_ONE:
7115     Pred = ICmpInst::ICMP_NE;
7116     break;
7117   case FCmpInst::FCMP_ORD:
7118     return replaceInstUsesWith(I, Builder.getTrue());
7119   case FCmpInst::FCMP_UNO:
7120     return replaceInstUsesWith(I, Builder.getFalse());
7121   }
7122 
7123   // Now we know that the APFloat is a normal number, zero or inf.
7124 
7125   // See if the FP constant is too large for the integer.  For example,
7126   // comparing an i8 to 300.0.
7127   unsigned IntWidth = IntTy->getScalarSizeInBits();
7128 
7129   if (!LHSUnsigned) {
7130     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
7131     // and large values.
7132     APFloat SMax(RHS.getSemantics());
7133     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
7134                           APFloat::rmNearestTiesToEven);
7135     if (SMax < RHS) { // smax < 13123.0
7136       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
7137           Pred == ICmpInst::ICMP_SLE)
7138         return replaceInstUsesWith(I, Builder.getTrue());
7139       return replaceInstUsesWith(I, Builder.getFalse());
7140     }
7141   } else {
7142     // If the RHS value is > UnsignedMax, fold the comparison. This handles
7143     // +INF and large values.
7144     APFloat UMax(RHS.getSemantics());
7145     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
7146                           APFloat::rmNearestTiesToEven);
7147     if (UMax < RHS) { // umax < 13123.0
7148       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
7149           Pred == ICmpInst::ICMP_ULE)
7150         return replaceInstUsesWith(I, Builder.getTrue());
7151       return replaceInstUsesWith(I, Builder.getFalse());
7152     }
7153   }
7154 
7155   if (!LHSUnsigned) {
7156     // See if the RHS value is < SignedMin.
7157     APFloat SMin(RHS.getSemantics());
7158     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
7159                           APFloat::rmNearestTiesToEven);
7160     if (SMin > RHS) { // smin > 12312.0
7161       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
7162           Pred == ICmpInst::ICMP_SGE)
7163         return replaceInstUsesWith(I, Builder.getTrue());
7164       return replaceInstUsesWith(I, Builder.getFalse());
7165     }
7166   } else {
7167     // See if the RHS value is < UnsignedMin.
7168     APFloat UMin(RHS.getSemantics());
7169     UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
7170                           APFloat::rmNearestTiesToEven);
7171     if (UMin > RHS) { // umin > 12312.0
7172       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
7173           Pred == ICmpInst::ICMP_UGE)
7174         return replaceInstUsesWith(I, Builder.getTrue());
7175       return replaceInstUsesWith(I, Builder.getFalse());
7176     }
7177   }
7178 
7179   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
7180   // [0, UMAX], but it may still be fractional.  See if it is fractional by
7181   // casting the FP value to the integer value and back, checking for equality.
7182   // Don't do this for zero, because -0.0 is not fractional.
7183   Constant *RHSInt = LHSUnsigned
7184     ? ConstantExpr::getFPToUI(RHSC, IntTy)
7185     : ConstantExpr::getFPToSI(RHSC, IntTy);
7186   if (!RHS.isZero()) {
7187     bool Equal = LHSUnsigned
7188       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
7189       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
7190     if (!Equal) {
7191       // If we had a comparison against a fractional value, we have to adjust
7192       // the compare predicate and sometimes the value.  RHSC is rounded towards
7193       // zero at this point.
7194       switch (Pred) {
7195       default: llvm_unreachable("Unexpected integer comparison!");
7196       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
7197         return replaceInstUsesWith(I, Builder.getTrue());
7198       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
7199         return replaceInstUsesWith(I, Builder.getFalse());
7200       case ICmpInst::ICMP_ULE:
7201         // (float)int <= 4.4   --> int <= 4
7202         // (float)int <= -4.4  --> false
7203         if (RHS.isNegative())
7204           return replaceInstUsesWith(I, Builder.getFalse());
7205         break;
7206       case ICmpInst::ICMP_SLE:
7207         // (float)int <= 4.4   --> int <= 4
7208         // (float)int <= -4.4  --> int < -4
7209         if (RHS.isNegative())
7210           Pred = ICmpInst::ICMP_SLT;
7211         break;
7212       case ICmpInst::ICMP_ULT:
7213         // (float)int < -4.4   --> false
7214         // (float)int < 4.4    --> int <= 4
7215         if (RHS.isNegative())
7216           return replaceInstUsesWith(I, Builder.getFalse());
7217         Pred = ICmpInst::ICMP_ULE;
7218         break;
7219       case ICmpInst::ICMP_SLT:
7220         // (float)int < -4.4   --> int < -4
7221         // (float)int < 4.4    --> int <= 4
7222         if (!RHS.isNegative())
7223           Pred = ICmpInst::ICMP_SLE;
7224         break;
7225       case ICmpInst::ICMP_UGT:
7226         // (float)int > 4.4    --> int > 4
7227         // (float)int > -4.4   --> true
7228         if (RHS.isNegative())
7229           return replaceInstUsesWith(I, Builder.getTrue());
7230         break;
7231       case ICmpInst::ICMP_SGT:
7232         // (float)int > 4.4    --> int > 4
7233         // (float)int > -4.4   --> int >= -4
7234         if (RHS.isNegative())
7235           Pred = ICmpInst::ICMP_SGE;
7236         break;
7237       case ICmpInst::ICMP_UGE:
7238         // (float)int >= -4.4   --> true
7239         // (float)int >= 4.4    --> int > 4
7240         if (RHS.isNegative())
7241           return replaceInstUsesWith(I, Builder.getTrue());
7242         Pred = ICmpInst::ICMP_UGT;
7243         break;
7244       case ICmpInst::ICMP_SGE:
7245         // (float)int >= -4.4   --> int >= -4
7246         // (float)int >= 4.4    --> int > 4
7247         if (!RHS.isNegative())
7248           Pred = ICmpInst::ICMP_SGT;
7249         break;
7250       }
7251     }
7252   }
7253 
7254   // Lower this FP comparison into an appropriate integer version of the
7255   // comparison.
7256   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
7257 }
7258 
7259 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
7260 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
7261                                               Constant *RHSC) {
7262   // When C is not 0.0 and infinities are not allowed:
7263   // (C / X) < 0.0 is a sign-bit test of X
7264   // (C / X) < 0.0 --> X < 0.0 (if C is positive)
7265   // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
7266   //
7267   // Proof:
7268   // Multiply (C / X) < 0.0 by X * X / C.
7269   // - X is non zero, if it is the flag 'ninf' is violated.
7270   // - C defines the sign of X * X * C. Thus it also defines whether to swap
7271   //   the predicate. C is also non zero by definition.
7272   //
7273   // Thus X * X / C is non zero and the transformation is valid. [qed]
7274 
7275   FCmpInst::Predicate Pred = I.getPredicate();
7276 
7277   // Check that predicates are valid.
7278   if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
7279       (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
7280     return nullptr;
7281 
7282   // Check that RHS operand is zero.
7283   if (!match(RHSC, m_AnyZeroFP()))
7284     return nullptr;
7285 
7286   // Check fastmath flags ('ninf').
7287   if (!LHSI->hasNoInfs() || !I.hasNoInfs())
7288     return nullptr;
7289 
7290   // Check the properties of the dividend. It must not be zero to avoid a
7291   // division by zero (see Proof).
7292   const APFloat *C;
7293   if (!match(LHSI->getOperand(0), m_APFloat(C)))
7294     return nullptr;
7295 
7296   if (C->isZero())
7297     return nullptr;
7298 
7299   // Get swapped predicate if necessary.
7300   if (C->isNegative())
7301     Pred = I.getSwappedPredicate();
7302 
7303   return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
7304 }
7305 
7306 /// Optimize fabs(X) compared with zero.
7307 static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
7308   Value *X;
7309   if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
7310     return nullptr;
7311 
7312   const APFloat *C;
7313   if (!match(I.getOperand(1), m_APFloat(C)))
7314     return nullptr;
7315 
7316   if (!C->isPosZero()) {
7317     if (!C->isSmallestNormalized())
7318       return nullptr;
7319 
7320     const Function *F = I.getFunction();
7321     DenormalMode Mode = F->getDenormalMode(C->getSemantics());
7322     if (Mode.Input == DenormalMode::PreserveSign ||
7323         Mode.Input == DenormalMode::PositiveZero) {
7324 
7325       auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
7326         Constant *Zero = ConstantFP::getZero(X->getType());
7327         return new FCmpInst(P, X, Zero, "", I);
7328       };
7329 
7330       switch (I.getPredicate()) {
7331       case FCmpInst::FCMP_OLT:
7332         // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
7333         return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
7334       case FCmpInst::FCMP_UGE:
7335         // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
7336         return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
7337       case FCmpInst::FCMP_OGE:
7338         // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
7339         return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
7340       case FCmpInst::FCMP_ULT:
7341         // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
7342         return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
7343       default:
7344         break;
7345       }
7346     }
7347 
7348     return nullptr;
7349   }
7350 
7351   auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
7352     I->setPredicate(P);
7353     return IC.replaceOperand(*I, 0, X);
7354   };
7355 
7356   switch (I.getPredicate()) {
7357   case FCmpInst::FCMP_UGE:
7358   case FCmpInst::FCMP_OLT:
7359     // fabs(X) >= 0.0 --> true
7360     // fabs(X) <  0.0 --> false
7361     llvm_unreachable("fcmp should have simplified");
7362 
7363   case FCmpInst::FCMP_OGT:
7364     // fabs(X) > 0.0 --> X != 0.0
7365     return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
7366 
7367   case FCmpInst::FCMP_UGT:
7368     // fabs(X) u> 0.0 --> X u!= 0.0
7369     return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
7370 
7371   case FCmpInst::FCMP_OLE:
7372     // fabs(X) <= 0.0 --> X == 0.0
7373     return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
7374 
7375   case FCmpInst::FCMP_ULE:
7376     // fabs(X) u<= 0.0 --> X u== 0.0
7377     return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
7378 
7379   case FCmpInst::FCMP_OGE:
7380     // fabs(X) >= 0.0 --> !isnan(X)
7381     assert(!I.hasNoNaNs() && "fcmp should have simplified");
7382     return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
7383 
7384   case FCmpInst::FCMP_ULT:
7385     // fabs(X) u< 0.0 --> isnan(X)
7386     assert(!I.hasNoNaNs() && "fcmp should have simplified");
7387     return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
7388 
7389   case FCmpInst::FCMP_OEQ:
7390   case FCmpInst::FCMP_UEQ:
7391   case FCmpInst::FCMP_ONE:
7392   case FCmpInst::FCMP_UNE:
7393   case FCmpInst::FCMP_ORD:
7394   case FCmpInst::FCMP_UNO:
7395     // Look through the fabs() because it doesn't change anything but the sign.
7396     // fabs(X) == 0.0 --> X == 0.0,
7397     // fabs(X) != 0.0 --> X != 0.0
7398     // isnan(fabs(X)) --> isnan(X)
7399     // !isnan(fabs(X) --> !isnan(X)
7400     return replacePredAndOp0(&I, I.getPredicate(), X);
7401 
7402   default:
7403     return nullptr;
7404   }
7405 }
7406 
7407 static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
7408   CmpInst::Predicate Pred = I.getPredicate();
7409   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7410 
7411   // Canonicalize fneg as Op1.
7412   if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
7413     std::swap(Op0, Op1);
7414     Pred = I.getSwappedPredicate();
7415   }
7416 
7417   if (!match(Op1, m_FNeg(m_Specific(Op0))))
7418     return nullptr;
7419 
7420   // Replace the negated operand with 0.0:
7421   // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
7422   Constant *Zero = ConstantFP::getZero(Op0->getType());
7423   return new FCmpInst(Pred, Op0, Zero, "", &I);
7424 }
7425 
7426 Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
7427   bool Changed = false;
7428 
7429   /// Orders the operands of the compare so that they are listed from most
7430   /// complex to least complex.  This puts constants before unary operators,
7431   /// before binary operators.
7432   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
7433     I.swapOperands();
7434     Changed = true;
7435   }
7436 
7437   const CmpInst::Predicate Pred = I.getPredicate();
7438   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7439   if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
7440                                   SQ.getWithInstruction(&I)))
7441     return replaceInstUsesWith(I, V);
7442 
7443   // Simplify 'fcmp pred X, X'
7444   Type *OpType = Op0->getType();
7445   assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
7446   if (Op0 == Op1) {
7447     switch (Pred) {
7448       default: break;
7449     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
7450     case FCmpInst::FCMP_ULT:    // True if unordered or less than
7451     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
7452     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
7453       // Canonicalize these to be 'fcmp uno %X, 0.0'.
7454       I.setPredicate(FCmpInst::FCMP_UNO);
7455       I.setOperand(1, Constant::getNullValue(OpType));
7456       return &I;
7457 
7458     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
7459     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
7460     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
7461     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
7462       // Canonicalize these to be 'fcmp ord %X, 0.0'.
7463       I.setPredicate(FCmpInst::FCMP_ORD);
7464       I.setOperand(1, Constant::getNullValue(OpType));
7465       return &I;
7466     }
7467   }
7468 
7469   // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
7470   // then canonicalize the operand to 0.0.
7471   if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
7472     if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, DL, &TLI, 0,
7473                                                       &AC, &I, &DT))
7474       return replaceOperand(I, 0, ConstantFP::getZero(OpType));
7475 
7476     if (!match(Op1, m_PosZeroFP()) &&
7477         isKnownNeverNaN(Op1, DL, &TLI, 0, &AC, &I, &DT))
7478       return replaceOperand(I, 1, ConstantFP::getZero(OpType));
7479   }
7480 
7481   // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
7482   Value *X, *Y;
7483   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
7484     return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
7485 
7486   if (Instruction *R = foldFCmpFNegCommonOp(I))
7487     return R;
7488 
7489   // Test if the FCmpInst instruction is used exclusively by a select as
7490   // part of a minimum or maximum operation. If so, refrain from doing
7491   // any other folding. This helps out other analyses which understand
7492   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7493   // and CodeGen. And in this case, at least one of the comparison
7494   // operands has at least one user besides the compare (the select),
7495   // which would often largely negate the benefit of folding anyway.
7496   if (I.hasOneUse())
7497     if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
7498       Value *A, *B;
7499       SelectPatternResult SPR = matchSelectPattern(SI, A, B);
7500       if (SPR.Flavor != SPF_UNKNOWN)
7501         return nullptr;
7502     }
7503 
7504   // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
7505   // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
7506   if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
7507     return replaceOperand(I, 1, ConstantFP::getZero(OpType));
7508 
7509   // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
7510   // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
7511   if (match(Op1, m_PosZeroFP()) &&
7512       match(Op0, m_OneUse(m_BitCast(m_Value(X)))) &&
7513       X->getType()->isVectorTy() == OpType->isVectorTy() &&
7514       X->getType()->getScalarSizeInBits() == OpType->getScalarSizeInBits()) {
7515     ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
7516     if (Pred == FCmpInst::FCMP_OEQ)
7517       IntPred = ICmpInst::ICMP_EQ;
7518     else if (Pred == FCmpInst::FCMP_UNE)
7519       IntPred = ICmpInst::ICMP_NE;
7520 
7521     if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
7522       Type *IntTy = X->getType();
7523       const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
7524       Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
7525       return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
7526     }
7527   }
7528 
7529   // Handle fcmp with instruction LHS and constant RHS.
7530   Instruction *LHSI;
7531   Constant *RHSC;
7532   if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
7533     switch (LHSI->getOpcode()) {
7534     case Instruction::PHI:
7535       // Only fold fcmp into the PHI if the phi and fcmp are in the same
7536       // block.  If in the same block, we're encouraging jump threading.  If
7537       // not, we are just pessimizing the code by making an i1 phi.
7538       if (LHSI->getParent() == I.getParent())
7539         if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
7540           return NV;
7541       break;
7542     case Instruction::SIToFP:
7543     case Instruction::UIToFP:
7544       if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
7545         return NV;
7546       break;
7547     case Instruction::FDiv:
7548       if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
7549         return NV;
7550       break;
7551     case Instruction::Load:
7552       if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
7553         if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
7554           if (Instruction *Res = foldCmpLoadFromIndexedGlobal(
7555                   cast<LoadInst>(LHSI), GEP, GV, I))
7556             return Res;
7557       break;
7558   }
7559   }
7560 
7561   if (Instruction *R = foldFabsWithFcmpZero(I, *this))
7562     return R;
7563 
7564   if (match(Op0, m_FNeg(m_Value(X)))) {
7565     // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
7566     Constant *C;
7567     if (match(Op1, m_Constant(C)))
7568       if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
7569         return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
7570   }
7571 
7572   if (match(Op0, m_FPExt(m_Value(X)))) {
7573     // fcmp (fpext X), (fpext Y) -> fcmp X, Y
7574     if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
7575       return new FCmpInst(Pred, X, Y, "", &I);
7576 
7577     const APFloat *C;
7578     if (match(Op1, m_APFloat(C))) {
7579       const fltSemantics &FPSem =
7580           X->getType()->getScalarType()->getFltSemantics();
7581       bool Lossy;
7582       APFloat TruncC = *C;
7583       TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);
7584 
7585       if (Lossy) {
7586         // X can't possibly equal the higher-precision constant, so reduce any
7587         // equality comparison.
7588         // TODO: Other predicates can be handled via getFCmpCode().
7589         switch (Pred) {
7590         case FCmpInst::FCMP_OEQ:
7591           // X is ordered and equal to an impossible constant --> false
7592           return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7593         case FCmpInst::FCMP_ONE:
7594           // X is ordered and not equal to an impossible constant --> ordered
7595           return new FCmpInst(FCmpInst::FCMP_ORD, X,
7596                               ConstantFP::getZero(X->getType()));
7597         case FCmpInst::FCMP_UEQ:
7598           // X is unordered or equal to an impossible constant --> unordered
7599           return new FCmpInst(FCmpInst::FCMP_UNO, X,
7600                               ConstantFP::getZero(X->getType()));
7601         case FCmpInst::FCMP_UNE:
7602           // X is unordered or not equal to an impossible constant --> true
7603           return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7604         default:
7605           break;
7606         }
7607       }
7608 
7609       // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
7610       // Avoid lossy conversions and denormals.
7611       // Zero is a special case that's OK to convert.
7612       APFloat Fabs = TruncC;
7613       Fabs.clearSign();
7614       if (!Lossy &&
7615           (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
7616         Constant *NewC = ConstantFP::get(X->getType(), TruncC);
7617         return new FCmpInst(Pred, X, NewC, "", &I);
7618       }
7619     }
7620   }
7621 
7622   // Convert a sign-bit test of an FP value into a cast and integer compare.
7623   // TODO: Simplify if the copysign constant is 0.0 or NaN.
7624   // TODO: Handle non-zero compare constants.
7625   // TODO: Handle other predicates.
7626   const APFloat *C;
7627   if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::copysign>(m_APFloat(C),
7628                                                            m_Value(X)))) &&
7629       match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
7630     Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
7631     if (auto *VecTy = dyn_cast<VectorType>(OpType))
7632       IntType = VectorType::get(IntType, VecTy->getElementCount());
7633 
7634     // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
7635     if (Pred == FCmpInst::FCMP_OLT) {
7636       Value *IntX = Builder.CreateBitCast(X, IntType);
7637       return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
7638                           ConstantInt::getNullValue(IntType));
7639     }
7640   }
7641 
7642   {
7643     Value *CanonLHS = nullptr, *CanonRHS = nullptr;
7644     match(Op0, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonLHS)));
7645     match(Op1, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonRHS)));
7646 
7647     // (canonicalize(x) == x) => (x == x)
7648     if (CanonLHS == Op1)
7649       return new FCmpInst(Pred, Op1, Op1, "", &I);
7650 
7651     // (x == canonicalize(x)) => (x == x)
7652     if (CanonRHS == Op0)
7653       return new FCmpInst(Pred, Op0, Op0, "", &I);
7654 
7655     // (canonicalize(x) == canonicalize(y)) => (x == y)
7656     if (CanonLHS && CanonRHS)
7657       return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
7658   }
7659 
7660   if (I.getType()->isVectorTy())
7661     if (Instruction *Res = foldVectorCmp(I, Builder))
7662       return Res;
7663 
7664   return Changed ? &I : nullptr;
7665 }
7666