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