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