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