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