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