Fix a serious typo in InstCombine's optimization of comparisons.
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineCompares.cpp
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 "InstCombine.h"
15 #include "llvm/IntrinsicInst.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Support/ConstantRange.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/PatternMatch.h"
23 using namespace llvm;
24 using namespace PatternMatch;
25
26 static ConstantInt *getOne(Constant *C) {
27   return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
28 }
29
30 /// AddOne - Add one to a ConstantInt
31 static Constant *AddOne(Constant *C) {
32   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
33 }
34 /// SubOne - Subtract one from a ConstantInt
35 static Constant *SubOne(Constant *C) {
36   return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
37 }
38
39 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
40   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
41 }
42
43 static bool HasAddOverflow(ConstantInt *Result,
44                            ConstantInt *In1, ConstantInt *In2,
45                            bool IsSigned) {
46   if (!IsSigned)
47     return Result->getValue().ult(In1->getValue());
48
49   if (In2->isNegative())
50     return Result->getValue().sgt(In1->getValue());
51   return Result->getValue().slt(In1->getValue());
52 }
53
54 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
55 /// overflowed for this type.
56 static bool AddWithOverflow(Constant *&Result, Constant *In1,
57                             Constant *In2, bool IsSigned = false) {
58   Result = ConstantExpr::getAdd(In1, In2);
59
60   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
61     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
62       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
63       if (HasAddOverflow(ExtractElement(Result, Idx),
64                          ExtractElement(In1, Idx),
65                          ExtractElement(In2, Idx),
66                          IsSigned))
67         return true;
68     }
69     return false;
70   }
71
72   return HasAddOverflow(cast<ConstantInt>(Result),
73                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
74                         IsSigned);
75 }
76
77 static bool HasSubOverflow(ConstantInt *Result,
78                            ConstantInt *In1, ConstantInt *In2,
79                            bool IsSigned) {
80   if (!IsSigned)
81     return Result->getValue().ugt(In1->getValue());
82
83   if (In2->isNegative())
84     return Result->getValue().slt(In1->getValue());
85
86   return Result->getValue().sgt(In1->getValue());
87 }
88
89 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
90 /// overflowed for this type.
91 static bool SubWithOverflow(Constant *&Result, Constant *In1,
92                             Constant *In2, bool IsSigned = false) {
93   Result = ConstantExpr::getSub(In1, In2);
94
95   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
96     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
97       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
98       if (HasSubOverflow(ExtractElement(Result, Idx),
99                          ExtractElement(In1, Idx),
100                          ExtractElement(In2, Idx),
101                          IsSigned))
102         return true;
103     }
104     return false;
105   }
106
107   return HasSubOverflow(cast<ConstantInt>(Result),
108                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
109                         IsSigned);
110 }
111
112 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
113 /// comparison only checks the sign bit.  If it only checks the sign bit, set
114 /// TrueIfSigned if the result of the comparison is true when the input value is
115 /// signed.
116 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
117                            bool &TrueIfSigned) {
118   switch (pred) {
119   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
120     TrueIfSigned = true;
121     return RHS->isZero();
122   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
123     TrueIfSigned = true;
124     return RHS->isAllOnesValue();
125   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
126     TrueIfSigned = false;
127     return RHS->isAllOnesValue();
128   case ICmpInst::ICMP_UGT:
129     // True if LHS u> RHS and RHS == high-bit-mask - 1
130     TrueIfSigned = true;
131     return RHS->isMaxValue(true);
132   case ICmpInst::ICMP_UGE:
133     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
134     TrueIfSigned = true;
135     return RHS->getValue().isSignBit();
136   default:
137     return false;
138   }
139 }
140
141 // isHighOnes - Return true if the constant is of the form 1+0+.
142 // This is the same as lowones(~X).
143 static bool isHighOnes(const ConstantInt *CI) {
144   return (~CI->getValue() + 1).isPowerOf2();
145 }
146
147 /// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
148 /// set of known zero and one bits, compute the maximum and minimum values that
149 /// could have the specified known zero and known one bits, returning them in
150 /// min/max.
151 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
152                                                    const APInt& KnownOne,
153                                                    APInt& Min, APInt& Max) {
154   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
155          KnownZero.getBitWidth() == Min.getBitWidth() &&
156          KnownZero.getBitWidth() == Max.getBitWidth() &&
157          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
158   APInt UnknownBits = ~(KnownZero|KnownOne);
159
160   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
161   // bit if it is unknown.
162   Min = KnownOne;
163   Max = KnownOne|UnknownBits;
164
165   if (UnknownBits.isNegative()) { // Sign bit is unknown
166     Min.setBit(Min.getBitWidth()-1);
167     Max.clearBit(Max.getBitWidth()-1);
168   }
169 }
170
171 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
172 // a set of known zero and one bits, compute the maximum and minimum values that
173 // could have the specified known zero and known one bits, returning them in
174 // min/max.
175 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
176                                                      const APInt &KnownOne,
177                                                      APInt &Min, APInt &Max) {
178   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
179          KnownZero.getBitWidth() == Min.getBitWidth() &&
180          KnownZero.getBitWidth() == Max.getBitWidth() &&
181          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
182   APInt UnknownBits = ~(KnownZero|KnownOne);
183
184   // The minimum value is when the unknown bits are all zeros.
185   Min = KnownOne;
186   // The maximum value is when the unknown bits are all ones.
187   Max = KnownOne|UnknownBits;
188 }
189
190
191
192 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
193 ///   cmp pred (load (gep GV, ...)), cmpcst
194 /// where GV is a global variable with a constant initializer.  Try to simplify
195 /// this into some simple computation that does not need the load.  For example
196 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
197 ///
198 /// If AndCst is non-null, then the loaded value is masked with that constant
199 /// before doing the comparison.  This handles cases like "A[i]&4 == 0".
200 Instruction *InstCombiner::
201 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
202                              CmpInst &ICI, ConstantInt *AndCst) {
203   // We need TD information to know the pointer size unless this is inbounds.
204   if (!GEP->isInBounds() && TD == 0) return 0;
205
206   Constant *Init = GV->getInitializer();
207   if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
208     return 0;
209   
210   uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
211   if (ArrayElementCount > 1024) return 0;  // Don't blow up on huge arrays.
212
213   // There are many forms of this optimization we can handle, for now, just do
214   // the simple index into a single-dimensional array.
215   //
216   // Require: GEP GV, 0, i {{, constant indices}}
217   if (GEP->getNumOperands() < 3 ||
218       !isa<ConstantInt>(GEP->getOperand(1)) ||
219       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
220       isa<Constant>(GEP->getOperand(2)))
221     return 0;
222
223   // Check that indices after the variable are constants and in-range for the
224   // type they index.  Collect the indices.  This is typically for arrays of
225   // structs.
226   SmallVector<unsigned, 4> LaterIndices;
227
228   Type *EltTy = Init->getType()->getArrayElementType();
229   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
230     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
231     if (Idx == 0) return 0;  // Variable index.
232
233     uint64_t IdxVal = Idx->getZExtValue();
234     if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
235
236     if (StructType *STy = dyn_cast<StructType>(EltTy))
237       EltTy = STy->getElementType(IdxVal);
238     else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
239       if (IdxVal >= ATy->getNumElements()) return 0;
240       EltTy = ATy->getElementType();
241     } else {
242       return 0; // Unknown type.
243     }
244
245     LaterIndices.push_back(IdxVal);
246   }
247
248   enum { Overdefined = -3, Undefined = -2 };
249
250   // Variables for our state machines.
251
252   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
253   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
254   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
255   // undefined, otherwise set to the first true element.  SecondTrueElement is
256   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
257   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
258
259   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
260   // form "i != 47 & i != 87".  Same state transitions as for true elements.
261   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
262
263   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
264   /// define a state machine that triggers for ranges of values that the index
265   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
266   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
267   /// index in the range (inclusive).  We use -2 for undefined here because we
268   /// use relative comparisons and don't want 0-1 to match -1.
269   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
270
271   // MagicBitvector - This is a magic bitvector where we set a bit if the
272   // comparison is true for element 'i'.  If there are 64 elements or less in
273   // the array, this will fully represent all the comparison results.
274   uint64_t MagicBitvector = 0;
275
276
277   // Scan the array and see if one of our patterns matches.
278   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
279   for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
280     Constant *Elt = Init->getAggregateElement(i);
281     if (Elt == 0) return 0;
282
283     // If this is indexing an array of structures, get the structure element.
284     if (!LaterIndices.empty())
285       Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
286
287     // If the element is masked, handle it.
288     if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
289
290     // Find out if the comparison would be true or false for the i'th element.
291     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
292                                                   CompareRHS, TD, TLI);
293     // If the result is undef for this element, ignore it.
294     if (isa<UndefValue>(C)) {
295       // Extend range state machines to cover this element in case there is an
296       // undef in the middle of the range.
297       if (TrueRangeEnd == (int)i-1)
298         TrueRangeEnd = i;
299       if (FalseRangeEnd == (int)i-1)
300         FalseRangeEnd = i;
301       continue;
302     }
303
304     // If we can't compute the result for any of the elements, we have to give
305     // up evaluating the entire conditional.
306     if (!isa<ConstantInt>(C)) return 0;
307
308     // Otherwise, we know if the comparison is true or false for this element,
309     // update our state machines.
310     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
311
312     // State machine for single/double/range index comparison.
313     if (IsTrueForElt) {
314       // Update the TrueElement state machine.
315       if (FirstTrueElement == Undefined)
316         FirstTrueElement = TrueRangeEnd = i;  // First true element.
317       else {
318         // Update double-compare state machine.
319         if (SecondTrueElement == Undefined)
320           SecondTrueElement = i;
321         else
322           SecondTrueElement = Overdefined;
323
324         // Update range state machine.
325         if (TrueRangeEnd == (int)i-1)
326           TrueRangeEnd = i;
327         else
328           TrueRangeEnd = Overdefined;
329       }
330     } else {
331       // Update the FalseElement state machine.
332       if (FirstFalseElement == Undefined)
333         FirstFalseElement = FalseRangeEnd = i; // First false element.
334       else {
335         // Update double-compare state machine.
336         if (SecondFalseElement == Undefined)
337           SecondFalseElement = i;
338         else
339           SecondFalseElement = Overdefined;
340
341         // Update range state machine.
342         if (FalseRangeEnd == (int)i-1)
343           FalseRangeEnd = i;
344         else
345           FalseRangeEnd = Overdefined;
346       }
347     }
348
349
350     // If this element is in range, update our magic bitvector.
351     if (i < 64 && IsTrueForElt)
352       MagicBitvector |= 1ULL << i;
353
354     // If all of our states become overdefined, bail out early.  Since the
355     // predicate is expensive, only check it every 8 elements.  This is only
356     // really useful for really huge arrays.
357     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
358         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
359         FalseRangeEnd == Overdefined)
360       return 0;
361   }
362
363   // Now that we've scanned the entire array, emit our new comparison(s).  We
364   // order the state machines in complexity of the generated code.
365   Value *Idx = GEP->getOperand(2);
366
367   // If the index is larger than the pointer size of the target, truncate the
368   // index down like the GEP would do implicitly.  We don't have to do this for
369   // an inbounds GEP because the index can't be out of range.
370   if (!GEP->isInBounds() &&
371       Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
372     Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
373
374   // If the comparison is only true for one or two elements, emit direct
375   // comparisons.
376   if (SecondTrueElement != Overdefined) {
377     // None true -> false.
378     if (FirstTrueElement == Undefined)
379       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
380
381     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
382
383     // True for one element -> 'i == 47'.
384     if (SecondTrueElement == Undefined)
385       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
386
387     // True for two elements -> 'i == 47 | i == 72'.
388     Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
389     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
390     Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
391     return BinaryOperator::CreateOr(C1, C2);
392   }
393
394   // If the comparison is only false for one or two elements, emit direct
395   // comparisons.
396   if (SecondFalseElement != Overdefined) {
397     // None false -> true.
398     if (FirstFalseElement == Undefined)
399       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
400
401     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
402
403     // False for one element -> 'i != 47'.
404     if (SecondFalseElement == Undefined)
405       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
406
407     // False for two elements -> 'i != 47 & i != 72'.
408     Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
409     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
410     Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
411     return BinaryOperator::CreateAnd(C1, C2);
412   }
413
414   // If the comparison can be replaced with a range comparison for the elements
415   // where it is true, emit the range check.
416   if (TrueRangeEnd != Overdefined) {
417     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
418
419     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
420     if (FirstTrueElement) {
421       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
422       Idx = Builder->CreateAdd(Idx, Offs);
423     }
424
425     Value *End = ConstantInt::get(Idx->getType(),
426                                   TrueRangeEnd-FirstTrueElement+1);
427     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
428   }
429
430   // False range check.
431   if (FalseRangeEnd != Overdefined) {
432     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
433     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
434     if (FirstFalseElement) {
435       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
436       Idx = Builder->CreateAdd(Idx, Offs);
437     }
438
439     Value *End = ConstantInt::get(Idx->getType(),
440                                   FalseRangeEnd-FirstFalseElement);
441     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
442   }
443
444
445   // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
446   // of this load, replace it with computation that does:
447   //   ((magic_cst >> i) & 1) != 0
448   if (ArrayElementCount <= 32 ||
449       (TD && ArrayElementCount <= 64 && TD->isLegalInteger(64))) {
450     Type *Ty;
451     if (ArrayElementCount <= 32)
452       Ty = Type::getInt32Ty(Init->getContext());
453     else
454       Ty = Type::getInt64Ty(Init->getContext());
455     Value *V = Builder->CreateIntCast(Idx, Ty, false);
456     V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
457     V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
458     return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
459   }
460
461   return 0;
462 }
463
464
465 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
466 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
467 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
468 /// be complex, and scales are involved.  The above expression would also be
469 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
470 /// This later form is less amenable to optimization though, and we are allowed
471 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
472 ///
473 /// If we can't emit an optimized form for this expression, this returns null.
474 ///
475 static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
476   TargetData &TD = *IC.getTargetData();
477   gep_type_iterator GTI = gep_type_begin(GEP);
478
479   // Check to see if this gep only has a single variable index.  If so, and if
480   // any constant indices are a multiple of its scale, then we can compute this
481   // in terms of the scale of the variable index.  For example, if the GEP
482   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
483   // because the expression will cross zero at the same point.
484   unsigned i, e = GEP->getNumOperands();
485   int64_t Offset = 0;
486   for (i = 1; i != e; ++i, ++GTI) {
487     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
488       // Compute the aggregate offset of constant indices.
489       if (CI->isZero()) continue;
490
491       // Handle a struct index, which adds its field offset to the pointer.
492       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
493         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
494       } else {
495         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
496         Offset += Size*CI->getSExtValue();
497       }
498     } else {
499       // Found our variable index.
500       break;
501     }
502   }
503
504   // If there are no variable indices, we must have a constant offset, just
505   // evaluate it the general way.
506   if (i == e) return 0;
507
508   Value *VariableIdx = GEP->getOperand(i);
509   // Determine the scale factor of the variable element.  For example, this is
510   // 4 if the variable index is into an array of i32.
511   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
512
513   // Verify that there are no other variable indices.  If so, emit the hard way.
514   for (++i, ++GTI; i != e; ++i, ++GTI) {
515     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
516     if (!CI) return 0;
517
518     // Compute the aggregate offset of constant indices.
519     if (CI->isZero()) continue;
520
521     // Handle a struct index, which adds its field offset to the pointer.
522     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
523       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
524     } else {
525       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
526       Offset += Size*CI->getSExtValue();
527     }
528   }
529
530   // Okay, we know we have a single variable index, which must be a
531   // pointer/array/vector index.  If there is no offset, life is simple, return
532   // the index.
533   unsigned IntPtrWidth = TD.getPointerSizeInBits();
534   if (Offset == 0) {
535     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
536     // we don't need to bother extending: the extension won't affect where the
537     // computation crosses zero.
538     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
539       Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
540       VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
541     }
542     return VariableIdx;
543   }
544
545   // Otherwise, there is an index.  The computation we will do will be modulo
546   // the pointer size, so get it.
547   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
548
549   Offset &= PtrSizeMask;
550   VariableScale &= PtrSizeMask;
551
552   // To do this transformation, any constant index must be a multiple of the
553   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
554   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
555   // multiple of the variable scale.
556   int64_t NewOffs = Offset / (int64_t)VariableScale;
557   if (Offset != NewOffs*(int64_t)VariableScale)
558     return 0;
559
560   // Okay, we can do this evaluation.  Start by converting the index to intptr.
561   Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
562   if (VariableIdx->getType() != IntPtrTy)
563     VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
564                                             true /*Signed*/);
565   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
566   return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
567 }
568
569 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
570 /// else.  At this point we know that the GEP is on the LHS of the comparison.
571 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
572                                        ICmpInst::Predicate Cond,
573                                        Instruction &I) {
574   // Don't transform signed compares of GEPs into index compares. Even if the
575   // GEP is inbounds, the final add of the base pointer can have signed overflow
576   // and would change the result of the icmp.
577   // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
578   // the maximum signed value for the pointer type.
579   if (ICmpInst::isSigned(Cond))
580     return 0;
581
582   // Look through bitcasts.
583   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
584     RHS = BCI->getOperand(0);
585
586   Value *PtrBase = GEPLHS->getOperand(0);
587   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
588     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
589     // This transformation (ignoring the base and scales) is valid because we
590     // know pointers can't overflow since the gep is inbounds.  See if we can
591     // output an optimized form.
592     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
593
594     // If not, synthesize the offset the hard way.
595     if (Offset == 0)
596       Offset = EmitGEPOffset(GEPLHS);
597     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
598                         Constant::getNullValue(Offset->getType()));
599   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
600     // If the base pointers are different, but the indices are the same, just
601     // compare the base pointer.
602     if (PtrBase != GEPRHS->getOperand(0)) {
603       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
604       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
605                         GEPRHS->getOperand(0)->getType();
606       if (IndicesTheSame)
607         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
608           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
609             IndicesTheSame = false;
610             break;
611           }
612
613       // If all indices are the same, just compare the base pointers.
614       if (IndicesTheSame)
615         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
616                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
617
618       // If we're comparing GEPs with two base pointers that only differ in type
619       // and both GEPs have only constant indices or just one use, then fold
620       // the compare with the adjusted indices.
621       if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
622           (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
623           (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
624           PtrBase->stripPointerCasts() ==
625             GEPRHS->getOperand(0)->stripPointerCasts()) {
626         Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
627                                          EmitGEPOffset(GEPLHS),
628                                          EmitGEPOffset(GEPRHS));
629         return ReplaceInstUsesWith(I, Cmp);
630       }
631
632       // Otherwise, the base pointers are different and the indices are
633       // different, bail out.
634       return 0;
635     }
636
637     // If one of the GEPs has all zero indices, recurse.
638     bool AllZeros = true;
639     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
640       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
641           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
642         AllZeros = false;
643         break;
644       }
645     if (AllZeros)
646       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
647                           ICmpInst::getSwappedPredicate(Cond), I);
648
649     // If the other GEP has all zero indices, recurse.
650     AllZeros = true;
651     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
652       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
653           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
654         AllZeros = false;
655         break;
656       }
657     if (AllZeros)
658       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
659
660     bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
661     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
662       // If the GEPs only differ by one index, compare it.
663       unsigned NumDifferences = 0;  // Keep track of # differences.
664       unsigned DiffOperand = 0;     // The operand that differs.
665       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
666         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
667           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
668                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
669             // Irreconcilable differences.
670             NumDifferences = 2;
671             break;
672           } else {
673             if (NumDifferences++) break;
674             DiffOperand = i;
675           }
676         }
677
678       if (NumDifferences == 0)   // SAME GEP?
679         return ReplaceInstUsesWith(I, // No comparison is needed here.
680                                ConstantInt::get(Type::getInt1Ty(I.getContext()),
681                                              ICmpInst::isTrueWhenEqual(Cond)));
682
683       else if (NumDifferences == 1 && GEPsInBounds) {
684         Value *LHSV = GEPLHS->getOperand(DiffOperand);
685         Value *RHSV = GEPRHS->getOperand(DiffOperand);
686         // Make sure we do a signed comparison here.
687         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
688       }
689     }
690
691     // Only lower this if the icmp is the only user of the GEP or if we expect
692     // the result to fold to a constant!
693     if (TD &&
694         GEPsInBounds &&
695         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
696         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
697       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
698       Value *L = EmitGEPOffset(GEPLHS);
699       Value *R = EmitGEPOffset(GEPRHS);
700       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
701     }
702   }
703   return 0;
704 }
705
706 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
707 Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
708                                             Value *X, ConstantInt *CI,
709                                             ICmpInst::Predicate Pred,
710                                             Value *TheAdd) {
711   // If we have X+0, exit early (simplifying logic below) and let it get folded
712   // elsewhere.   icmp X+0, X  -> icmp X, X
713   if (CI->isZero()) {
714     bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
715     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
716   }
717
718   // (X+4) == X -> false.
719   if (Pred == ICmpInst::ICMP_EQ)
720     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
721
722   // (X+4) != X -> true.
723   if (Pred == ICmpInst::ICMP_NE)
724     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
725
726   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
727   // so the values can never be equal.  Similarly for all other "or equals"
728   // operators.
729
730   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
731   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
732   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
733   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
734     Value *R =
735       ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
736     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
737   }
738
739   // (X+1) >u X        --> X <u (0-1)        --> X != 255
740   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
741   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
742   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
743     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
744
745   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
746   ConstantInt *SMax = ConstantInt::get(X->getContext(),
747                                        APInt::getSignedMaxValue(BitWidth));
748
749   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
750   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
751   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
752   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
753   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
754   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
755   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
756     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
757
758   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
759   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
760   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
761   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
762   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
763   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
764
765   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
766   Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
767   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
768 }
769
770 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
771 /// and CmpRHS are both known to be integer constants.
772 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
773                                           ConstantInt *DivRHS) {
774   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
775   const APInt &CmpRHSV = CmpRHS->getValue();
776
777   // FIXME: If the operand types don't match the type of the divide
778   // then don't attempt this transform. The code below doesn't have the
779   // logic to deal with a signed divide and an unsigned compare (and
780   // vice versa). This is because (x /s C1) <s C2  produces different
781   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
782   // (x /u C1) <u C2.  Simply casting the operands and result won't
783   // work. :(  The if statement below tests that condition and bails
784   // if it finds it.
785   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
786   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
787     return 0;
788   if (DivRHS->isZero())
789     return 0; // The ProdOV computation fails on divide by zero.
790   if (DivIsSigned && DivRHS->isAllOnesValue())
791     return 0; // The overflow computation also screws up here
792   if (DivRHS->isOne()) {
793     // This eliminates some funny cases with INT_MIN.
794     ICI.setOperand(0, DivI->getOperand(0));   // X/1 == X.
795     return &ICI;
796   }
797
798   // Compute Prod = CI * DivRHS. We are essentially solving an equation
799   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
800   // C2 (CI). By solving for X we can turn this into a range check
801   // instead of computing a divide.
802   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
803
804   // Determine if the product overflows by seeing if the product is
805   // not equal to the divide. Make sure we do the same kind of divide
806   // as in the LHS instruction that we're folding.
807   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
808                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
809
810   // Get the ICmp opcode
811   ICmpInst::Predicate Pred = ICI.getPredicate();
812
813   /// If the division is known to be exact, then there is no remainder from the
814   /// divide, so the covered range size is unit, otherwise it is the divisor.
815   ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
816
817   // Figure out the interval that is being checked.  For example, a comparison
818   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
819   // Compute this interval based on the constants involved and the signedness of
820   // the compare/divide.  This computes a half-open interval, keeping track of
821   // whether either value in the interval overflows.  After analysis each
822   // overflow variable is set to 0 if it's corresponding bound variable is valid
823   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
824   int LoOverflow = 0, HiOverflow = 0;
825   Constant *LoBound = 0, *HiBound = 0;
826
827   if (!DivIsSigned) {  // udiv
828     // e.g. X/5 op 3  --> [15, 20)
829     LoBound = Prod;
830     HiOverflow = LoOverflow = ProdOV;
831     if (!HiOverflow) {
832       // If this is not an exact divide, then many values in the range collapse
833       // to the same result value.
834       HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
835     }
836
837   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
838     if (CmpRHSV == 0) {       // (X / pos) op 0
839       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
840       LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
841       HiBound = RangeSize;
842     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
843       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
844       HiOverflow = LoOverflow = ProdOV;
845       if (!HiOverflow)
846         HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
847     } else {                       // (X / pos) op neg
848       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
849       HiBound = AddOne(Prod);
850       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
851       if (!LoOverflow) {
852         ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
853         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
854       }
855     }
856   } else if (DivRHS->isNegative()) { // Divisor is < 0.
857     if (DivI->isExact())
858       RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
859     if (CmpRHSV == 0) {       // (X / neg) op 0
860       // e.g. X/-5 op 0  --> [-4, 5)
861       LoBound = AddOne(RangeSize);
862       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
863       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
864         HiOverflow = 1;            // [INTMIN+1, overflow)
865         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
866       }
867     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
868       // e.g. X/-5 op 3  --> [-19, -14)
869       HiBound = AddOne(Prod);
870       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
871       if (!LoOverflow)
872         LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
873     } else {                       // (X / neg) op neg
874       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
875       LoOverflow = HiOverflow = ProdOV;
876       if (!HiOverflow)
877         HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
878     }
879
880     // Dividing by a negative swaps the condition.  LT <-> GT
881     Pred = ICmpInst::getSwappedPredicate(Pred);
882   }
883
884   Value *X = DivI->getOperand(0);
885   switch (Pred) {
886   default: llvm_unreachable("Unhandled icmp opcode!");
887   case ICmpInst::ICMP_EQ:
888     if (LoOverflow && HiOverflow)
889       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
890     if (HiOverflow)
891       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
892                           ICmpInst::ICMP_UGE, X, LoBound);
893     if (LoOverflow)
894       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
895                           ICmpInst::ICMP_ULT, X, HiBound);
896     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
897                                                     DivIsSigned, true));
898   case ICmpInst::ICMP_NE:
899     if (LoOverflow && HiOverflow)
900       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
901     if (HiOverflow)
902       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
903                           ICmpInst::ICMP_ULT, X, LoBound);
904     if (LoOverflow)
905       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
906                           ICmpInst::ICMP_UGE, X, HiBound);
907     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
908                                                     DivIsSigned, false));
909   case ICmpInst::ICMP_ULT:
910   case ICmpInst::ICMP_SLT:
911     if (LoOverflow == +1)   // Low bound is greater than input range.
912       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
913     if (LoOverflow == -1)   // Low bound is less than input range.
914       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
915     return new ICmpInst(Pred, X, LoBound);
916   case ICmpInst::ICMP_UGT:
917   case ICmpInst::ICMP_SGT:
918     if (HiOverflow == +1)       // High bound greater than input range.
919       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
920     if (HiOverflow == -1)       // High bound less than input range.
921       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
922     if (Pred == ICmpInst::ICMP_UGT)
923       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
924     return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
925   }
926 }
927
928 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
929 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
930                                           ConstantInt *ShAmt) {
931   const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
932
933   // Check that the shift amount is in range.  If not, don't perform
934   // undefined shifts.  When the shift is visited it will be
935   // simplified.
936   uint32_t TypeBits = CmpRHSV.getBitWidth();
937   uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
938   if (ShAmtVal >= TypeBits || ShAmtVal == 0)
939     return 0;
940
941   if (!ICI.isEquality()) {
942     // If we have an unsigned comparison and an ashr, we can't simplify this.
943     // Similarly for signed comparisons with lshr.
944     if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
945       return 0;
946
947     // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
948     // by a power of 2.  Since we already have logic to simplify these,
949     // transform to div and then simplify the resultant comparison.
950     if (Shr->getOpcode() == Instruction::AShr &&
951         (!Shr->isExact() || ShAmtVal == TypeBits - 1))
952       return 0;
953
954     // Revisit the shift (to delete it).
955     Worklist.Add(Shr);
956
957     Constant *DivCst =
958       ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
959
960     Value *Tmp =
961       Shr->getOpcode() == Instruction::AShr ?
962       Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
963       Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
964
965     ICI.setOperand(0, Tmp);
966
967     // If the builder folded the binop, just return it.
968     BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
969     if (TheDiv == 0)
970       return &ICI;
971
972     // Otherwise, fold this div/compare.
973     assert(TheDiv->getOpcode() == Instruction::SDiv ||
974            TheDiv->getOpcode() == Instruction::UDiv);
975
976     Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
977     assert(Res && "This div/cst should have folded!");
978     return Res;
979   }
980
981
982   // If we are comparing against bits always shifted out, the
983   // comparison cannot succeed.
984   APInt Comp = CmpRHSV << ShAmtVal;
985   ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
986   if (Shr->getOpcode() == Instruction::LShr)
987     Comp = Comp.lshr(ShAmtVal);
988   else
989     Comp = Comp.ashr(ShAmtVal);
990
991   if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
992     bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
993     Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
994                                      IsICMP_NE);
995     return ReplaceInstUsesWith(ICI, Cst);
996   }
997
998   // Otherwise, check to see if the bits shifted out are known to be zero.
999   // If so, we can compare against the unshifted value:
1000   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
1001   if (Shr->hasOneUse() && Shr->isExact())
1002     return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
1003
1004   if (Shr->hasOneUse()) {
1005     // Otherwise strength reduce the shift into an and.
1006     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1007     Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
1008
1009     Value *And = Builder->CreateAnd(Shr->getOperand(0),
1010                                     Mask, Shr->getName()+".mask");
1011     return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1012   }
1013   return 0;
1014 }
1015
1016
1017 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1018 ///
1019 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1020                                                           Instruction *LHSI,
1021                                                           ConstantInt *RHS) {
1022   const APInt &RHSV = RHS->getValue();
1023
1024   switch (LHSI->getOpcode()) {
1025   case Instruction::Trunc:
1026     if (ICI.isEquality() && LHSI->hasOneUse()) {
1027       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1028       // of the high bits truncated out of x are known.
1029       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1030              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1031       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1032       ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
1033
1034       // If all the high bits are known, we can do this xform.
1035       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1036         // Pull in the high bits from known-ones set.
1037         APInt NewRHS = RHS->getValue().zext(SrcBits);
1038         NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
1039         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1040                             ConstantInt::get(ICI.getContext(), NewRHS));
1041       }
1042     }
1043     break;
1044
1045   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
1046     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1047       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1048       // fold the xor.
1049       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1050           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1051         Value *CompareVal = LHSI->getOperand(0);
1052
1053         // If the sign bit of the XorCST is not set, there is no change to
1054         // the operation, just stop using the Xor.
1055         if (!XorCST->isNegative()) {
1056           ICI.setOperand(0, CompareVal);
1057           Worklist.Add(LHSI);
1058           return &ICI;
1059         }
1060
1061         // Was the old condition true if the operand is positive?
1062         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1063
1064         // If so, the new one isn't.
1065         isTrueIfPositive ^= true;
1066
1067         if (isTrueIfPositive)
1068           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1069                               SubOne(RHS));
1070         else
1071           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1072                               AddOne(RHS));
1073       }
1074
1075       if (LHSI->hasOneUse()) {
1076         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1077         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1078           const APInt &SignBit = XorCST->getValue();
1079           ICmpInst::Predicate Pred = ICI.isSigned()
1080                                          ? ICI.getUnsignedPredicate()
1081                                          : ICI.getSignedPredicate();
1082           return new ICmpInst(Pred, LHSI->getOperand(0),
1083                               ConstantInt::get(ICI.getContext(),
1084                                                RHSV ^ SignBit));
1085         }
1086
1087         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1088         if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
1089           const APInt &NotSignBit = XorCST->getValue();
1090           ICmpInst::Predicate Pred = ICI.isSigned()
1091                                          ? ICI.getUnsignedPredicate()
1092                                          : ICI.getSignedPredicate();
1093           Pred = ICI.getSwappedPredicate(Pred);
1094           return new ICmpInst(Pred, LHSI->getOperand(0),
1095                               ConstantInt::get(ICI.getContext(),
1096                                                RHSV ^ NotSignBit));
1097         }
1098       }
1099     }
1100     break;
1101   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
1102     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1103         LHSI->getOperand(0)->hasOneUse()) {
1104       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1105
1106       // If the LHS is an AND of a truncating cast, we can widen the
1107       // and/compare to be the input width without changing the value
1108       // produced, eliminating a cast.
1109       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1110         // We can do this transformation if either the AND constant does not
1111         // have its sign bit set or if it is an equality comparison.
1112         // Extending a relational comparison when we're checking the sign
1113         // bit would not work.
1114         if (ICI.isEquality() ||
1115             (!AndCST->isNegative() && RHSV.isNonNegative())) {
1116           Value *NewAnd =
1117             Builder->CreateAnd(Cast->getOperand(0),
1118                                ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1119           NewAnd->takeName(LHSI);
1120           return new ICmpInst(ICI.getPredicate(), NewAnd,
1121                               ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1122         }
1123       }
1124
1125       // If the LHS is an AND of a zext, and we have an equality compare, we can
1126       // shrink the and/compare to the smaller type, eliminating the cast.
1127       if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1128         IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1129         // Make sure we don't compare the upper bits, SimplifyDemandedBits
1130         // should fold the icmp to true/false in that case.
1131         if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1132           Value *NewAnd =
1133             Builder->CreateAnd(Cast->getOperand(0),
1134                                ConstantExpr::getTrunc(AndCST, Ty));
1135           NewAnd->takeName(LHSI);
1136           return new ICmpInst(ICI.getPredicate(), NewAnd,
1137                               ConstantExpr::getTrunc(RHS, Ty));
1138         }
1139       }
1140
1141       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1142       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1143       // happens a LOT in code produced by the C front-end, for bitfield
1144       // access.
1145       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1146       if (Shift && !Shift->isShift())
1147         Shift = 0;
1148
1149       ConstantInt *ShAmt;
1150       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1151       Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
1152       Type *AndTy = AndCST->getType();          // Type of the and.
1153
1154       // We can fold this as long as we can't shift unknown bits
1155       // into the mask.  This can only happen with signed shift
1156       // rights, as they sign-extend.
1157       if (ShAmt) {
1158         bool CanFold = Shift->isLogicalShift();
1159         if (!CanFold) {
1160           // To test for the bad case of the signed shr, see if any
1161           // of the bits shifted in could be tested after the mask.
1162           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1163           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
1164
1165           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
1166           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
1167                AndCST->getValue()) == 0)
1168             CanFold = true;
1169         }
1170
1171         if (CanFold) {
1172           Constant *NewCst;
1173           if (Shift->getOpcode() == Instruction::Shl)
1174             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1175           else
1176             NewCst = ConstantExpr::getShl(RHS, ShAmt);
1177
1178           // Check to see if we are shifting out any of the bits being
1179           // compared.
1180           if (ConstantExpr::get(Shift->getOpcode(),
1181                                        NewCst, ShAmt) != RHS) {
1182             // If we shifted bits out, the fold is not going to work out.
1183             // As a special case, check to see if this means that the
1184             // result is always true or false now.
1185             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1186               return ReplaceInstUsesWith(ICI,
1187                                        ConstantInt::getFalse(ICI.getContext()));
1188             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1189               return ReplaceInstUsesWith(ICI,
1190                                        ConstantInt::getTrue(ICI.getContext()));
1191           } else {
1192             ICI.setOperand(1, NewCst);
1193             Constant *NewAndCST;
1194             if (Shift->getOpcode() == Instruction::Shl)
1195               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1196             else
1197               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1198             LHSI->setOperand(1, NewAndCST);
1199             LHSI->setOperand(0, Shift->getOperand(0));
1200             Worklist.Add(Shift); // Shift is dead.
1201             return &ICI;
1202           }
1203         }
1204       }
1205
1206       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1207       // preferable because it allows the C<<Y expression to be hoisted out
1208       // of a loop if Y is invariant and X is not.
1209       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1210           ICI.isEquality() && !Shift->isArithmeticShift() &&
1211           !isa<Constant>(Shift->getOperand(0))) {
1212         // Compute C << Y.
1213         Value *NS;
1214         if (Shift->getOpcode() == Instruction::LShr) {
1215           NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
1216         } else {
1217           // Insert a logical shift.
1218           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
1219         }
1220
1221         // Compute X & (C << Y).
1222         Value *NewAnd =
1223           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1224
1225         ICI.setOperand(0, NewAnd);
1226         return &ICI;
1227       }
1228     }
1229
1230     // Try to optimize things like "A[i]&42 == 0" to index computations.
1231     if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1232       if (GetElementPtrInst *GEP =
1233           dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1234         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1235           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1236               !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1237             ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1238             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1239               return Res;
1240           }
1241     }
1242     break;
1243
1244   case Instruction::Or: {
1245     if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1246       break;
1247     Value *P, *Q;
1248     if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1249       // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1250       // -> and (icmp eq P, null), (icmp eq Q, null).
1251       Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1252                                         Constant::getNullValue(P->getType()));
1253       Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1254                                         Constant::getNullValue(Q->getType()));
1255       Instruction *Op;
1256       if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1257         Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1258       else
1259         Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1260       return Op;
1261     }
1262     break;
1263   }
1264
1265   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1266     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1267     if (!ShAmt) break;
1268
1269     uint32_t TypeBits = RHSV.getBitWidth();
1270
1271     // Check that the shift amount is in range.  If not, don't perform
1272     // undefined shifts.  When the shift is visited it will be
1273     // simplified.
1274     if (ShAmt->uge(TypeBits))
1275       break;
1276
1277     if (ICI.isEquality()) {
1278       // If we are comparing against bits always shifted out, the
1279       // comparison cannot succeed.
1280       Constant *Comp =
1281         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1282                                                                  ShAmt);
1283       if (Comp != RHS) {// Comparing against a bit that we know is zero.
1284         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1285         Constant *Cst =
1286           ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1287         return ReplaceInstUsesWith(ICI, Cst);
1288       }
1289
1290       // If the shift is NUW, then it is just shifting out zeros, no need for an
1291       // AND.
1292       if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1293         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1294                             ConstantExpr::getLShr(RHS, ShAmt));
1295
1296       if (LHSI->hasOneUse()) {
1297         // Otherwise strength reduce the shift into an and.
1298         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1299         Constant *Mask =
1300           ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
1301                                                        TypeBits-ShAmtVal));
1302
1303         Value *And =
1304           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1305         return new ICmpInst(ICI.getPredicate(), And,
1306                             ConstantExpr::getLShr(RHS, ShAmt));
1307       }
1308     }
1309
1310     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1311     bool TrueIfSigned = false;
1312     if (LHSI->hasOneUse() &&
1313         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1314       // (X << 31) <s 0  --> (X&1) != 0
1315       Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1316                                         APInt::getOneBitSet(TypeBits,
1317                                             TypeBits-ShAmt->getZExtValue()-1));
1318       Value *And =
1319         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1320       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1321                           And, Constant::getNullValue(And->getType()));
1322     }
1323     break;
1324   }
1325
1326   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
1327   case Instruction::AShr: {
1328     // Handle equality comparisons of shift-by-constant.
1329     BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1330     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1331       if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
1332         return Res;
1333     }
1334
1335     // Handle exact shr's.
1336     if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1337       if (RHSV.isMinValue())
1338         return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1339     }
1340     break;
1341   }
1342
1343   case Instruction::SDiv:
1344   case Instruction::UDiv:
1345     // Fold: icmp pred ([us]div X, C1), C2 -> range test
1346     // Fold this div into the comparison, producing a range check.
1347     // Determine, based on the divide type, what the range is being
1348     // checked.  If there is an overflow on the low or high side, remember
1349     // it, otherwise compute the range [low, hi) bounding the new value.
1350     // See: InsertRangeTest above for the kinds of replacements possible.
1351     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1352       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1353                                           DivRHS))
1354         return R;
1355     break;
1356
1357   case Instruction::Add:
1358     // Fold: icmp pred (add X, C1), C2
1359     if (!ICI.isEquality()) {
1360       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1361       if (!LHSC) break;
1362       const APInt &LHSV = LHSC->getValue();
1363
1364       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1365                             .subtract(LHSV);
1366
1367       if (ICI.isSigned()) {
1368         if (CR.getLower().isSignBit()) {
1369           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1370                               ConstantInt::get(ICI.getContext(),CR.getUpper()));
1371         } else if (CR.getUpper().isSignBit()) {
1372           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1373                               ConstantInt::get(ICI.getContext(),CR.getLower()));
1374         }
1375       } else {
1376         if (CR.getLower().isMinValue()) {
1377           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1378                               ConstantInt::get(ICI.getContext(),CR.getUpper()));
1379         } else if (CR.getUpper().isMinValue()) {
1380           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1381                               ConstantInt::get(ICI.getContext(),CR.getLower()));
1382         }
1383       }
1384     }
1385     break;
1386   }
1387
1388   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1389   if (ICI.isEquality()) {
1390     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1391
1392     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1393     // the second operand is a constant, simplify a bit.
1394     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1395       switch (BO->getOpcode()) {
1396       case Instruction::SRem:
1397         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1398         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1399           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1400           if (V.sgt(1) && V.isPowerOf2()) {
1401             Value *NewRem =
1402               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1403                                   BO->getName());
1404             return new ICmpInst(ICI.getPredicate(), NewRem,
1405                                 Constant::getNullValue(BO->getType()));
1406           }
1407         }
1408         break;
1409       case Instruction::Add:
1410         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1411         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1412           if (BO->hasOneUse())
1413             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1414                                 ConstantExpr::getSub(RHS, BOp1C));
1415         } else if (RHSV == 0) {
1416           // Replace ((add A, B) != 0) with (A != -B) if A or B is
1417           // efficiently invertible, or if the add has just this one use.
1418           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1419
1420           if (Value *NegVal = dyn_castNegVal(BOp1))
1421             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1422           if (Value *NegVal = dyn_castNegVal(BOp0))
1423             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1424           if (BO->hasOneUse()) {
1425             Value *Neg = Builder->CreateNeg(BOp1);
1426             Neg->takeName(BO);
1427             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1428           }
1429         }
1430         break;
1431       case Instruction::Xor:
1432         // For the xor case, we can xor two constants together, eliminating
1433         // the explicit xor.
1434         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1435           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1436                               ConstantExpr::getXor(RHS, BOC));
1437         } else if (RHSV == 0) {
1438           // Replace ((xor A, B) != 0) with (A != B)
1439           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1440                               BO->getOperand(1));
1441         }
1442         break;
1443       case Instruction::Sub:
1444         // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1445         if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1446           if (BO->hasOneUse())
1447             return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1448                                 ConstantExpr::getSub(BOp0C, RHS));
1449         } else if (RHSV == 0) {
1450           // Replace ((sub A, B) != 0) with (A != B)
1451           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1452                               BO->getOperand(1));
1453         }
1454         break;
1455       case Instruction::Or:
1456         // If bits are being or'd in that are not present in the constant we
1457         // are comparing against, then the comparison could never succeed!
1458         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1459           Constant *NotCI = ConstantExpr::getNot(RHS);
1460           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1461             return ReplaceInstUsesWith(ICI,
1462                              ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1463                                        isICMP_NE));
1464         }
1465         break;
1466
1467       case Instruction::And:
1468         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1469           // If bits are being compared against that are and'd out, then the
1470           // comparison can never succeed!
1471           if ((RHSV & ~BOC->getValue()) != 0)
1472             return ReplaceInstUsesWith(ICI,
1473                              ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1474                                        isICMP_NE));
1475
1476           // If we have ((X & C) == C), turn it into ((X & C) != 0).
1477           if (RHS == BOC && RHSV.isPowerOf2())
1478             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1479                                 ICmpInst::ICMP_NE, LHSI,
1480                                 Constant::getNullValue(RHS->getType()));
1481
1482           // Don't perform the following transforms if the AND has multiple uses
1483           if (!BO->hasOneUse())
1484             break;
1485
1486           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1487           if (BOC->getValue().isSignBit()) {
1488             Value *X = BO->getOperand(0);
1489             Constant *Zero = Constant::getNullValue(X->getType());
1490             ICmpInst::Predicate pred = isICMP_NE ?
1491               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1492             return new ICmpInst(pred, X, Zero);
1493           }
1494
1495           // ((X & ~7) == 0) --> X < 8
1496           if (RHSV == 0 && isHighOnes(BOC)) {
1497             Value *X = BO->getOperand(0);
1498             Constant *NegX = ConstantExpr::getNeg(BOC);
1499             ICmpInst::Predicate pred = isICMP_NE ?
1500               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1501             return new ICmpInst(pred, X, NegX);
1502           }
1503         }
1504       default: break;
1505       }
1506     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1507       // Handle icmp {eq|ne} <intrinsic>, intcst.
1508       switch (II->getIntrinsicID()) {
1509       case Intrinsic::bswap:
1510         Worklist.Add(II);
1511         ICI.setOperand(0, II->getArgOperand(0));
1512         ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1513         return &ICI;
1514       case Intrinsic::ctlz:
1515       case Intrinsic::cttz:
1516         // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
1517         if (RHSV == RHS->getType()->getBitWidth()) {
1518           Worklist.Add(II);
1519           ICI.setOperand(0, II->getArgOperand(0));
1520           ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1521           return &ICI;
1522         }
1523         break;
1524       case Intrinsic::ctpop:
1525         // popcount(A) == 0  ->  A == 0 and likewise for !=
1526         if (RHS->isZero()) {
1527           Worklist.Add(II);
1528           ICI.setOperand(0, II->getArgOperand(0));
1529           ICI.setOperand(1, RHS);
1530           return &ICI;
1531         }
1532         break;
1533       default:
1534         break;
1535       }
1536     }
1537   }
1538   return 0;
1539 }
1540
1541 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1542 /// We only handle extending casts so far.
1543 ///
1544 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1545   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1546   Value *LHSCIOp        = LHSCI->getOperand(0);
1547   Type *SrcTy     = LHSCIOp->getType();
1548   Type *DestTy    = LHSCI->getType();
1549   Value *RHSCIOp;
1550
1551   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1552   // integer type is the same size as the pointer type.
1553   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1554       TD->getPointerSizeInBits() ==
1555          cast<IntegerType>(DestTy)->getBitWidth()) {
1556     Value *RHSOp = 0;
1557     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1558       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1559     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1560       RHSOp = RHSC->getOperand(0);
1561       // If the pointer types don't match, insert a bitcast.
1562       if (LHSCIOp->getType() != RHSOp->getType())
1563         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1564     }
1565
1566     if (RHSOp)
1567       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1568   }
1569
1570   // The code below only handles extension cast instructions, so far.
1571   // Enforce this.
1572   if (LHSCI->getOpcode() != Instruction::ZExt &&
1573       LHSCI->getOpcode() != Instruction::SExt)
1574     return 0;
1575
1576   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1577   bool isSignedCmp = ICI.isSigned();
1578
1579   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1580     // Not an extension from the same type?
1581     RHSCIOp = CI->getOperand(0);
1582     if (RHSCIOp->getType() != LHSCIOp->getType())
1583       return 0;
1584
1585     // If the signedness of the two casts doesn't agree (i.e. one is a sext
1586     // and the other is a zext), then we can't handle this.
1587     if (CI->getOpcode() != LHSCI->getOpcode())
1588       return 0;
1589
1590     // Deal with equality cases early.
1591     if (ICI.isEquality())
1592       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1593
1594     // A signed comparison of sign extended values simplifies into a
1595     // signed comparison.
1596     if (isSignedCmp && isSignedExt)
1597       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1598
1599     // The other three cases all fold into an unsigned comparison.
1600     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1601   }
1602
1603   // If we aren't dealing with a constant on the RHS, exit early
1604   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1605   if (!CI)
1606     return 0;
1607
1608   // Compute the constant that would happen if we truncated to SrcTy then
1609   // reextended to DestTy.
1610   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1611   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1612                                                 Res1, DestTy);
1613
1614   // If the re-extended constant didn't change...
1615   if (Res2 == CI) {
1616     // Deal with equality cases early.
1617     if (ICI.isEquality())
1618       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1619
1620     // A signed comparison of sign extended values simplifies into a
1621     // signed comparison.
1622     if (isSignedExt && isSignedCmp)
1623       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1624
1625     // The other three cases all fold into an unsigned comparison.
1626     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1627   }
1628
1629   // The re-extended constant changed so the constant cannot be represented
1630   // in the shorter type. Consequently, we cannot emit a simple comparison.
1631   // All the cases that fold to true or false will have already been handled
1632   // by SimplifyICmpInst, so only deal with the tricky case.
1633
1634   if (isSignedCmp || !isSignedExt)
1635     return 0;
1636
1637   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1638   // should have been folded away previously and not enter in here.
1639
1640   // We're performing an unsigned comp with a sign extended value.
1641   // This is true if the input is >= 0. [aka >s -1]
1642   Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1643   Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1644
1645   // Finally, return the value computed.
1646   if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1647     return ReplaceInstUsesWith(ICI, Result);
1648
1649   assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1650   return BinaryOperator::CreateNot(Result);
1651 }
1652
1653 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1654 ///   I = icmp ugt (add (add A, B), CI2), CI1
1655 /// If this is of the form:
1656 ///   sum = a + b
1657 ///   if (sum+128 >u 255)
1658 /// Then replace it with llvm.sadd.with.overflow.i8.
1659 ///
1660 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1661                                           ConstantInt *CI2, ConstantInt *CI1,
1662                                           InstCombiner &IC) {
1663   // The transformation we're trying to do here is to transform this into an
1664   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1665   // with a narrower add, and discard the add-with-constant that is part of the
1666   // range check (if we can't eliminate it, this isn't profitable).
1667
1668   // In order to eliminate the add-with-constant, the compare can be its only
1669   // use.
1670   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1671   if (!AddWithCst->hasOneUse()) return 0;
1672
1673   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1674   if (!CI2->getValue().isPowerOf2()) return 0;
1675   unsigned NewWidth = CI2->getValue().countTrailingZeros();
1676   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1677
1678   // The width of the new add formed is 1 more than the bias.
1679   ++NewWidth;
1680
1681   // Check to see that CI1 is an all-ones value with NewWidth bits.
1682   if (CI1->getBitWidth() == NewWidth ||
1683       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1684     return 0;
1685
1686   // This is only really a signed overflow check if the inputs have been
1687   // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1688   // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1689   unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1690   if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1691       IC.ComputeNumSignBits(B) < NeededSignBits)
1692     return 0;
1693
1694   // In order to replace the original add with a narrower
1695   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1696   // and truncates that discard the high bits of the add.  Verify that this is
1697   // the case.
1698   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1699   for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1700        UI != E; ++UI) {
1701     if (*UI == AddWithCst) continue;
1702
1703     // Only accept truncates for now.  We would really like a nice recursive
1704     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1705     // chain to see which bits of a value are actually demanded.  If the
1706     // original add had another add which was then immediately truncated, we
1707     // could still do the transformation.
1708     TruncInst *TI = dyn_cast<TruncInst>(*UI);
1709     if (TI == 0 ||
1710         TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1711   }
1712
1713   // If the pattern matches, truncate the inputs to the narrower type and
1714   // use the sadd_with_overflow intrinsic to efficiently compute both the
1715   // result and the overflow bit.
1716   Module *M = I.getParent()->getParent()->getParent();
1717
1718   Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1719   Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1720                                        NewType);
1721
1722   InstCombiner::BuilderTy *Builder = IC.Builder;
1723
1724   // Put the new code above the original add, in case there are any uses of the
1725   // add between the add and the compare.
1726   Builder->SetInsertPoint(OrigAdd);
1727
1728   Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1729   Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1730   CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1731   Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1732   Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1733
1734   // The inner add was the result of the narrow add, zero extended to the
1735   // wider type.  Replace it with the result computed by the intrinsic.
1736   IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1737
1738   // The original icmp gets replaced with the overflow value.
1739   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1740 }
1741
1742 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1743                                      InstCombiner &IC) {
1744   // Don't bother doing this transformation for pointers, don't do it for
1745   // vectors.
1746   if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1747
1748   // If the add is a constant expr, then we don't bother transforming it.
1749   Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1750   if (OrigAdd == 0) return 0;
1751
1752   Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1753
1754   // Put the new code above the original add, in case there are any uses of the
1755   // add between the add and the compare.
1756   InstCombiner::BuilderTy *Builder = IC.Builder;
1757   Builder->SetInsertPoint(OrigAdd);
1758
1759   Module *M = I.getParent()->getParent()->getParent();
1760   Type *Ty = LHS->getType();
1761   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1762   CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1763   Value *Add = Builder->CreateExtractValue(Call, 0);
1764
1765   IC.ReplaceInstUsesWith(*OrigAdd, Add);
1766
1767   // The original icmp gets replaced with the overflow value.
1768   return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1769 }
1770
1771 // DemandedBitsLHSMask - When performing a comparison against a constant,
1772 // it is possible that not all the bits in the LHS are demanded.  This helper
1773 // method computes the mask that IS demanded.
1774 static APInt DemandedBitsLHSMask(ICmpInst &I,
1775                                  unsigned BitWidth, bool isSignCheck) {
1776   if (isSignCheck)
1777     return APInt::getSignBit(BitWidth);
1778
1779   ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1780   if (!CI) return APInt::getAllOnesValue(BitWidth);
1781   const APInt &RHS = CI->getValue();
1782
1783   switch (I.getPredicate()) {
1784   // For a UGT comparison, we don't care about any bits that
1785   // correspond to the trailing ones of the comparand.  The value of these
1786   // bits doesn't impact the outcome of the comparison, because any value
1787   // greater than the RHS must differ in a bit higher than these due to carry.
1788   case ICmpInst::ICMP_UGT: {
1789     unsigned trailingOnes = RHS.countTrailingOnes();
1790     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1791     return ~lowBitsSet;
1792   }
1793
1794   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1795   // Any value less than the RHS must differ in a higher bit because of carries.
1796   case ICmpInst::ICMP_ULT: {
1797     unsigned trailingZeros = RHS.countTrailingZeros();
1798     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1799     return ~lowBitsSet;
1800   }
1801
1802   default:
1803     return APInt::getAllOnesValue(BitWidth);
1804   }
1805
1806 }
1807
1808 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1809   bool Changed = false;
1810   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1811
1812   /// Orders the operands of the compare so that they are listed from most
1813   /// complex to least complex.  This puts constants before unary operators,
1814   /// before binary operators.
1815   if (getComplexity(Op0) < getComplexity(Op1)) {
1816     I.swapOperands();
1817     std::swap(Op0, Op1);
1818     Changed = true;
1819   }
1820
1821   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1822     return ReplaceInstUsesWith(I, V);
1823
1824   // comparing -val or val with non-zero is the same as just comparing val
1825   // ie, abs(val) != 0 -> val != 0
1826   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
1827   {
1828     Value *Cond, *SelectTrue, *SelectFalse;
1829     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
1830                             m_Value(SelectFalse)))) {
1831       if (Value *V = dyn_castNegVal(SelectTrue)) {
1832         if (V == SelectFalse)
1833           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
1834       }
1835       else if (Value *V = dyn_castNegVal(SelectFalse)) {
1836         if (V == SelectTrue)
1837           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
1838       }
1839     }
1840   }
1841
1842   Type *Ty = Op0->getType();
1843
1844   // icmp's with boolean values can always be turned into bitwise operations
1845   if (Ty->isIntegerTy(1)) {
1846     switch (I.getPredicate()) {
1847     default: llvm_unreachable("Invalid icmp instruction!");
1848     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
1849       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1850       return BinaryOperator::CreateNot(Xor);
1851     }
1852     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
1853       return BinaryOperator::CreateXor(Op0, Op1);
1854
1855     case ICmpInst::ICMP_UGT:
1856       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
1857       // FALL THROUGH
1858     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
1859       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1860       return BinaryOperator::CreateAnd(Not, Op1);
1861     }
1862     case ICmpInst::ICMP_SGT:
1863       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
1864       // FALL THROUGH
1865     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
1866       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1867       return BinaryOperator::CreateAnd(Not, Op0);
1868     }
1869     case ICmpInst::ICMP_UGE:
1870       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
1871       // FALL THROUGH
1872     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
1873       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1874       return BinaryOperator::CreateOr(Not, Op1);
1875     }
1876     case ICmpInst::ICMP_SGE:
1877       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
1878       // FALL THROUGH
1879     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
1880       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1881       return BinaryOperator::CreateOr(Not, Op0);
1882     }
1883     }
1884   }
1885
1886   unsigned BitWidth = 0;
1887   if (Ty->isIntOrIntVectorTy())
1888     BitWidth = Ty->getScalarSizeInBits();
1889   else if (TD)  // Pointers require TD info to get their size.
1890     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
1891
1892   bool isSignBit = false;
1893
1894   // See if we are doing a comparison with a constant.
1895   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1896     Value *A = 0, *B = 0;
1897
1898     // Match the following pattern, which is a common idiom when writing
1899     // overflow-safe integer arithmetic function.  The source performs an
1900     // addition in wider type, and explicitly checks for overflow using
1901     // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
1902     // sadd_with_overflow intrinsic.
1903     //
1904     // TODO: This could probably be generalized to handle other overflow-safe
1905     // operations if we worked out the formulas to compute the appropriate
1906     // magic constants.
1907     //
1908     // sum = a + b
1909     // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
1910     {
1911     ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
1912     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
1913         match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1914       if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
1915         return Res;
1916     }
1917
1918     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1919     if (I.isEquality() && CI->isZero() &&
1920         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1921       // (icmp cond A B) if cond is equality
1922       return new ICmpInst(I.getPredicate(), A, B);
1923     }
1924
1925     // If we have an icmp le or icmp ge instruction, turn it into the
1926     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
1927     // them being folded in the code below.  The SimplifyICmpInst code has
1928     // already handled the edge cases for us, so we just assert on them.
1929     switch (I.getPredicate()) {
1930     default: break;
1931     case ICmpInst::ICMP_ULE:
1932       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
1933       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1934                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
1935     case ICmpInst::ICMP_SLE:
1936       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
1937       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1938                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
1939     case ICmpInst::ICMP_UGE:
1940       assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
1941       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1942                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
1943     case ICmpInst::ICMP_SGE:
1944       assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
1945       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1946                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
1947     }
1948
1949     // If this comparison is a normal comparison, it demands all
1950     // bits, if it is a sign bit comparison, it only demands the sign bit.
1951     bool UnusedBit;
1952     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1953   }
1954
1955   // See if we can fold the comparison based on range information we can get
1956   // by checking whether bits are known to be zero or one in the input.
1957   if (BitWidth != 0) {
1958     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1959     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1960
1961     if (SimplifyDemandedBits(I.getOperandUse(0),
1962                              DemandedBitsLHSMask(I, BitWidth, isSignBit),
1963                              Op0KnownZero, Op0KnownOne, 0))
1964       return &I;
1965     if (SimplifyDemandedBits(I.getOperandUse(1),
1966                              APInt::getAllOnesValue(BitWidth),
1967                              Op1KnownZero, Op1KnownOne, 0))
1968       return &I;
1969
1970     // Given the known and unknown bits, compute a range that the LHS could be
1971     // in.  Compute the Min, Max and RHS values based on the known bits. For the
1972     // EQ and NE we use unsigned values.
1973     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1974     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1975     if (I.isSigned()) {
1976       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1977                                              Op0Min, Op0Max);
1978       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1979                                              Op1Min, Op1Max);
1980     } else {
1981       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1982                                                Op0Min, Op0Max);
1983       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1984                                                Op1Min, Op1Max);
1985     }
1986
1987     // If Min and Max are known to be the same, then SimplifyDemandedBits
1988     // figured out that the LHS is a constant.  Just constant fold this now so
1989     // that code below can assume that Min != Max.
1990     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1991       return new ICmpInst(I.getPredicate(),
1992                           ConstantInt::get(Op0->getType(), Op0Min), Op1);
1993     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1994       return new ICmpInst(I.getPredicate(), Op0,
1995                           ConstantInt::get(Op1->getType(), Op1Min));
1996
1997     // Based on the range information we know about the LHS, see if we can
1998     // simplify this comparison.  For example, (x&4) < 8 is always true.
1999     switch (I.getPredicate()) {
2000     default: llvm_unreachable("Unknown icmp opcode!");
2001     case ICmpInst::ICMP_EQ: {
2002       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2003         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2004
2005       // If all bits are known zero except for one, then we know at most one
2006       // bit is set.   If the comparison is against zero, then this is a check
2007       // to see if *that* bit is set.
2008       APInt Op0KnownZeroInverted = ~Op0KnownZero;
2009       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2010         // If the LHS is an AND with the same constant, look through it.
2011         Value *LHS = 0;
2012         ConstantInt *LHSC = 0;
2013         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2014             LHSC->getValue() != Op0KnownZeroInverted)
2015           LHS = Op0;
2016
2017         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2018         // then turn "((1 << x)&8) == 0" into "x != 3".
2019         Value *X = 0;
2020         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2021           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2022           return new ICmpInst(ICmpInst::ICMP_NE, X,
2023                               ConstantInt::get(X->getType(), CmpVal));
2024         }
2025
2026         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2027         // then turn "((8 >>u x)&1) == 0" into "x != 3".
2028         const APInt *CI;
2029         if (Op0KnownZeroInverted == 1 &&
2030             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2031           return new ICmpInst(ICmpInst::ICMP_NE, X,
2032                               ConstantInt::get(X->getType(),
2033                                                CI->countTrailingZeros()));
2034       }
2035
2036       break;
2037     }
2038     case ICmpInst::ICMP_NE: {
2039       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2040         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2041
2042       // If all bits are known zero except for one, then we know at most one
2043       // bit is set.   If the comparison is against zero, then this is a check
2044       // to see if *that* bit is set.
2045       APInt Op0KnownZeroInverted = ~Op0KnownZero;
2046       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2047         // If the LHS is an AND with the same constant, look through it.
2048         Value *LHS = 0;
2049         ConstantInt *LHSC = 0;
2050         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2051             LHSC->getValue() != Op0KnownZeroInverted)
2052           LHS = Op0;
2053
2054         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2055         // then turn "((1 << x)&8) != 0" into "x == 3".
2056         Value *X = 0;
2057         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2058           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2059           return new ICmpInst(ICmpInst::ICMP_EQ, X,
2060                               ConstantInt::get(X->getType(), CmpVal));
2061         }
2062
2063         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2064         // then turn "((8 >>u x)&1) != 0" into "x == 3".
2065         const APInt *CI;
2066         if (Op0KnownZeroInverted == 1 &&
2067             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2068           return new ICmpInst(ICmpInst::ICMP_EQ, X,
2069                               ConstantInt::get(X->getType(),
2070                                                CI->countTrailingZeros()));
2071       }
2072
2073       break;
2074     }
2075     case ICmpInst::ICMP_ULT:
2076       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
2077         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2078       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
2079         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2080       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
2081         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2082       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2083         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
2084           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2085                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
2086
2087         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
2088         if (CI->isMinValue(true))
2089           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2090                            Constant::getAllOnesValue(Op0->getType()));
2091       }
2092       break;
2093     case ICmpInst::ICMP_UGT:
2094       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
2095         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2096       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
2097         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2098
2099       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
2100         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2101       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2102         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
2103           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2104                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
2105
2106         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
2107         if (CI->isMaxValue(true))
2108           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2109                               Constant::getNullValue(Op0->getType()));
2110       }
2111       break;
2112     case ICmpInst::ICMP_SLT:
2113       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
2114         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2115       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
2116         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2117       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
2118         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2119       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2120         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
2121           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2122                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
2123       }
2124       break;
2125     case ICmpInst::ICMP_SGT:
2126       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
2127         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2128       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
2129         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2130
2131       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
2132         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2133       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2134         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
2135           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2136                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
2137       }
2138       break;
2139     case ICmpInst::ICMP_SGE:
2140       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2141       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
2142         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2143       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
2144         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2145       break;
2146     case ICmpInst::ICMP_SLE:
2147       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2148       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
2149         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2150       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
2151         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2152       break;
2153     case ICmpInst::ICMP_UGE:
2154       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2155       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
2156         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2157       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
2158         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2159       break;
2160     case ICmpInst::ICMP_ULE:
2161       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2162       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
2163         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2164       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
2165         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2166       break;
2167     }
2168
2169     // Turn a signed comparison into an unsigned one if both operands
2170     // are known to have the same sign.
2171     if (I.isSigned() &&
2172         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2173          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2174       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2175   }
2176
2177   // Test if the ICmpInst instruction is used exclusively by a select as
2178   // part of a minimum or maximum operation. If so, refrain from doing
2179   // any other folding. This helps out other analyses which understand
2180   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2181   // and CodeGen. And in this case, at least one of the comparison
2182   // operands has at least one user besides the compare (the select),
2183   // which would often largely negate the benefit of folding anyway.
2184   if (I.hasOneUse())
2185     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2186       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2187           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2188         return 0;
2189
2190   // See if we are doing a comparison between a constant and an instruction that
2191   // can be folded into the comparison.
2192   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2193     // Since the RHS is a ConstantInt (CI), if the left hand side is an
2194     // instruction, see if that instruction also has constants so that the
2195     // instruction can be folded into the icmp
2196     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2197       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2198         return Res;
2199   }
2200
2201   // Handle icmp with constant (but not simple integer constant) RHS
2202   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2203     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2204       switch (LHSI->getOpcode()) {
2205       case Instruction::GetElementPtr:
2206           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2207         if (RHSC->isNullValue() &&
2208             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2209           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2210                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
2211         break;
2212       case Instruction::PHI:
2213         // Only fold icmp into the PHI if the phi and icmp are in the same
2214         // block.  If in the same block, we're encouraging jump threading.  If
2215         // not, we are just pessimizing the code by making an i1 phi.
2216         if (LHSI->getParent() == I.getParent())
2217           if (Instruction *NV = FoldOpIntoPhi(I))
2218             return NV;
2219         break;
2220       case Instruction::Select: {
2221         // If either operand of the select is a constant, we can fold the
2222         // comparison into the select arms, which will cause one to be
2223         // constant folded and the select turned into a bitwise or.
2224         Value *Op1 = 0, *Op2 = 0;
2225         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2226           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2227         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2228           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2229
2230         // We only want to perform this transformation if it will not lead to
2231         // additional code. This is true if either both sides of the select
2232         // fold to a constant (in which case the icmp is replaced with a select
2233         // which will usually simplify) or this is the only user of the
2234         // select (in which case we are trading a select+icmp for a simpler
2235         // select+icmp).
2236         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2237           if (!Op1)
2238             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2239                                       RHSC, I.getName());
2240           if (!Op2)
2241             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2242                                       RHSC, I.getName());
2243           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2244         }
2245         break;
2246       }
2247       case Instruction::IntToPtr:
2248         // icmp pred inttoptr(X), null -> icmp pred X, 0
2249         if (RHSC->isNullValue() && TD &&
2250             TD->getIntPtrType(RHSC->getContext()) ==
2251                LHSI->getOperand(0)->getType())
2252           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2253                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
2254         break;
2255
2256       case Instruction::Load:
2257         // Try to optimize things like "A[i] > 4" to index computations.
2258         if (GetElementPtrInst *GEP =
2259               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2260           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2261             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2262                 !cast<LoadInst>(LHSI)->isVolatile())
2263               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2264                 return Res;
2265         }
2266         break;
2267       }
2268   }
2269
2270   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2271   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2272     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2273       return NI;
2274   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2275     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2276                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2277       return NI;
2278
2279   // Test to see if the operands of the icmp are casted versions of other
2280   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
2281   // now.
2282   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2283     if (Op0->getType()->isPointerTy() &&
2284         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2285       // We keep moving the cast from the left operand over to the right
2286       // operand, where it can often be eliminated completely.
2287       Op0 = CI->getOperand(0);
2288
2289       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2290       // so eliminate it as well.
2291       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2292         Op1 = CI2->getOperand(0);
2293
2294       // If Op1 is a constant, we can fold the cast into the constant.
2295       if (Op0->getType() != Op1->getType()) {
2296         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2297           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2298         } else {
2299           // Otherwise, cast the RHS right before the icmp
2300           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2301         }
2302       }
2303       return new ICmpInst(I.getPredicate(), Op0, Op1);
2304     }
2305   }
2306
2307   if (isa<CastInst>(Op0)) {
2308     // Handle the special case of: icmp (cast bool to X), <cst>
2309     // This comes up when you have code like
2310     //   int X = A < B;
2311     //   if (X) ...
2312     // For generality, we handle any zero-extension of any operand comparison
2313     // with a constant or another cast from the same type.
2314     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2315       if (Instruction *R = visitICmpInstWithCastAndCast(I))
2316         return R;
2317   }
2318
2319   // Special logic for binary operators.
2320   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2321   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2322   if (BO0 || BO1) {
2323     CmpInst::Predicate Pred = I.getPredicate();
2324     bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2325     if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2326       NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2327         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2328         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2329     if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2330       NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2331         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2332         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2333
2334     // Analyze the case when either Op0 or Op1 is an add instruction.
2335     // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2336     Value *A = 0, *B = 0, *C = 0, *D = 0;
2337     if (BO0 && BO0->getOpcode() == Instruction::Add)
2338       A = BO0->getOperand(0), B = BO0->getOperand(1);
2339     if (BO1 && BO1->getOpcode() == Instruction::Add)
2340       C = BO1->getOperand(0), D = BO1->getOperand(1);
2341
2342     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2343     if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2344       return new ICmpInst(Pred, A == Op1 ? B : A,
2345                           Constant::getNullValue(Op1->getType()));
2346
2347     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2348     if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2349       return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2350                           C == Op0 ? D : C);
2351
2352     // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2353     if (A && C && (A == C || A == D || B == C || B == D) &&
2354         NoOp0WrapProblem && NoOp1WrapProblem &&
2355         // Try not to increase register pressure.
2356         BO0->hasOneUse() && BO1->hasOneUse()) {
2357       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2358       Value *Y = (A == C || A == D) ? B : A;
2359       Value *Z = (C == A || C == B) ? D : C;
2360       return new ICmpInst(Pred, Y, Z);
2361     }
2362
2363     // Analyze the case when either Op0 or Op1 is a sub instruction.
2364     // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2365     A = 0; B = 0; C = 0; D = 0;
2366     if (BO0 && BO0->getOpcode() == Instruction::Sub)
2367       A = BO0->getOperand(0), B = BO0->getOperand(1);
2368     if (BO1 && BO1->getOpcode() == Instruction::Sub)
2369       C = BO1->getOperand(0), D = BO1->getOperand(1);
2370
2371     // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2372     if (A == Op1 && NoOp0WrapProblem)
2373       return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2374
2375     // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2376     if (C == Op0 && NoOp1WrapProblem)
2377       return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2378
2379     // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2380     if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2381         // Try not to increase register pressure.
2382         BO0->hasOneUse() && BO1->hasOneUse())
2383       return new ICmpInst(Pred, A, C);
2384
2385     // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2386     if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2387         // Try not to increase register pressure.
2388         BO0->hasOneUse() && BO1->hasOneUse())
2389       return new ICmpInst(Pred, D, B);
2390
2391     BinaryOperator *SRem = NULL;
2392     // icmp (srem X, Y), Y
2393     if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2394         Op1 == BO0->getOperand(1))
2395       SRem = BO0;
2396     // icmp Y, (srem X, Y)
2397     else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2398              Op0 == BO1->getOperand(1))
2399       SRem = BO1;
2400     if (SRem) {
2401       // We don't check hasOneUse to avoid increasing register pressure because
2402       // the value we use is the same value this instruction was already using.
2403       switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2404         default: break;
2405         case ICmpInst::ICMP_EQ:
2406           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2407         case ICmpInst::ICMP_NE:
2408           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2409         case ICmpInst::ICMP_SGT:
2410         case ICmpInst::ICMP_SGE:
2411           return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2412                               Constant::getAllOnesValue(SRem->getType()));
2413         case ICmpInst::ICMP_SLT:
2414         case ICmpInst::ICMP_SLE:
2415           return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2416                               Constant::getNullValue(SRem->getType()));
2417       }
2418     }
2419
2420     if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2421         BO0->hasOneUse() && BO1->hasOneUse() &&
2422         BO0->getOperand(1) == BO1->getOperand(1)) {
2423       switch (BO0->getOpcode()) {
2424       default: break;
2425       case Instruction::Add:
2426       case Instruction::Sub:
2427       case Instruction::Xor:
2428         if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
2429           return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2430                               BO1->getOperand(0));
2431         // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2432         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2433           if (CI->getValue().isSignBit()) {
2434             ICmpInst::Predicate Pred = I.isSigned()
2435                                            ? I.getUnsignedPredicate()
2436                                            : I.getSignedPredicate();
2437             return new ICmpInst(Pred, BO0->getOperand(0),
2438                                 BO1->getOperand(0));
2439           }
2440
2441           if (CI->isMaxValue(true)) {
2442             ICmpInst::Predicate Pred = I.isSigned()
2443                                            ? I.getUnsignedPredicate()
2444                                            : I.getSignedPredicate();
2445             Pred = I.getSwappedPredicate(Pred);
2446             return new ICmpInst(Pred, BO0->getOperand(0),
2447                                 BO1->getOperand(0));
2448           }
2449         }
2450         break;
2451       case Instruction::Mul:
2452         if (!I.isEquality())
2453           break;
2454
2455         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2456           // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2457           // Mask = -1 >> count-trailing-zeros(Cst).
2458           if (!CI->isZero() && !CI->isOne()) {
2459             const APInt &AP = CI->getValue();
2460             ConstantInt *Mask = ConstantInt::get(I.getContext(),
2461                                     APInt::getLowBitsSet(AP.getBitWidth(),
2462                                                          AP.getBitWidth() -
2463                                                     AP.countTrailingZeros()));
2464             Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2465             Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2466             return new ICmpInst(I.getPredicate(), And1, And2);
2467           }
2468         }
2469         break;
2470       case Instruction::UDiv:
2471       case Instruction::LShr:
2472         if (I.isSigned())
2473           break;
2474         // fall-through
2475       case Instruction::SDiv:
2476       case Instruction::AShr:
2477         if (!BO0->isExact() || !BO1->isExact())
2478           break;
2479         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2480                             BO1->getOperand(0));
2481       case Instruction::Shl: {
2482         bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2483         bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2484         if (!NUW && !NSW)
2485           break;
2486         if (!NSW && I.isSigned())
2487           break;
2488         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2489                             BO1->getOperand(0));
2490       }
2491       }
2492     }
2493   }
2494
2495   { Value *A, *B;
2496     // ~x < ~y --> y < x
2497     // ~x < cst --> ~cst < x
2498     if (match(Op0, m_Not(m_Value(A)))) {
2499       if (match(Op1, m_Not(m_Value(B))))
2500         return new ICmpInst(I.getPredicate(), B, A);
2501       if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2502         return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2503     }
2504
2505     // (a+b) <u a  --> llvm.uadd.with.overflow.
2506     // (a+b) <u b  --> llvm.uadd.with.overflow.
2507     if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2508         match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2509         (Op1 == A || Op1 == B))
2510       if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2511         return R;
2512
2513     // a >u (a+b)  --> llvm.uadd.with.overflow.
2514     // b >u (a+b)  --> llvm.uadd.with.overflow.
2515     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2516         match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2517         (Op0 == A || Op0 == B))
2518       if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2519         return R;
2520   }
2521
2522   if (I.isEquality()) {
2523     Value *A, *B, *C, *D;
2524
2525     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2526       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
2527         Value *OtherVal = A == Op1 ? B : A;
2528         return new ICmpInst(I.getPredicate(), OtherVal,
2529                             Constant::getNullValue(A->getType()));
2530       }
2531
2532       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2533         // A^c1 == C^c2 --> A == C^(c1^c2)
2534         ConstantInt *C1, *C2;
2535         if (match(B, m_ConstantInt(C1)) &&
2536             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2537           Constant *NC = ConstantInt::get(I.getContext(),
2538                                           C1->getValue() ^ C2->getValue());
2539           Value *Xor = Builder->CreateXor(C, NC);
2540           return new ICmpInst(I.getPredicate(), A, Xor);
2541         }
2542
2543         // A^B == A^D -> B == D
2544         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2545         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2546         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2547         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2548       }
2549     }
2550
2551     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2552         (A == Op0 || B == Op0)) {
2553       // A == (A^B)  ->  B == 0
2554       Value *OtherVal = A == Op0 ? B : A;
2555       return new ICmpInst(I.getPredicate(), OtherVal,
2556                           Constant::getNullValue(A->getType()));
2557     }
2558
2559     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2560     if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
2561         match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
2562       Value *X = 0, *Y = 0, *Z = 0;
2563
2564       if (A == C) {
2565         X = B; Y = D; Z = A;
2566       } else if (A == D) {
2567         X = B; Y = C; Z = A;
2568       } else if (B == C) {
2569         X = A; Y = D; Z = B;
2570       } else if (B == D) {
2571         X = A; Y = C; Z = B;
2572       }
2573
2574       if (X) {   // Build (X^Y) & Z
2575         Op1 = Builder->CreateXor(X, Y);
2576         Op1 = Builder->CreateAnd(Op1, Z);
2577         I.setOperand(0, Op1);
2578         I.setOperand(1, Constant::getNullValue(Op1->getType()));
2579         return &I;
2580       }
2581     }
2582
2583     // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
2584     // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
2585     ConstantInt *Cst1;
2586     if ((Op0->hasOneUse() &&
2587          match(Op0, m_ZExt(m_Value(A))) &&
2588          match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2589         (Op1->hasOneUse() &&
2590          match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2591          match(Op1, m_ZExt(m_Value(A))))) {
2592       APInt Pow2 = Cst1->getValue() + 1;
2593       if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2594           Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2595         return new ICmpInst(I.getPredicate(), A,
2596                             Builder->CreateTrunc(B, A->getType()));
2597     }
2598
2599     // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2600     // "icmp (and X, mask), cst"
2601     uint64_t ShAmt = 0;
2602     if (Op0->hasOneUse() &&
2603         match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2604                                            m_ConstantInt(ShAmt))))) &&
2605         match(Op1, m_ConstantInt(Cst1)) &&
2606         // Only do this when A has multiple uses.  This is most important to do
2607         // when it exposes other optimizations.
2608         !A->hasOneUse()) {
2609       unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2610
2611       if (ShAmt < ASize) {
2612         APInt MaskV =
2613           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2614         MaskV <<= ShAmt;
2615
2616         APInt CmpV = Cst1->getValue().zext(ASize);
2617         CmpV <<= ShAmt;
2618
2619         Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2620         return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2621       }
2622     }
2623   }
2624
2625   {
2626     Value *X; ConstantInt *Cst;
2627     // icmp X+Cst, X
2628     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2629       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2630
2631     // icmp X, X+Cst
2632     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2633       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2634   }
2635   return Changed ? &I : 0;
2636 }
2637
2638
2639
2640
2641
2642
2643 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2644 ///
2645 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2646                                                 Instruction *LHSI,
2647                                                 Constant *RHSC) {
2648   if (!isa<ConstantFP>(RHSC)) return 0;
2649   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
2650
2651   // Get the width of the mantissa.  We don't want to hack on conversions that
2652   // might lose information from the integer, e.g. "i64 -> float"
2653   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2654   if (MantissaWidth == -1) return 0;  // Unknown.
2655
2656   // Check to see that the input is converted from an integer type that is small
2657   // enough that preserves all bits.  TODO: check here for "known" sign bits.
2658   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2659   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
2660
2661   // If this is a uitofp instruction, we need an extra bit to hold the sign.
2662   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2663   if (LHSUnsigned)
2664     ++InputSize;
2665
2666   // If the conversion would lose info, don't hack on this.
2667   if ((int)InputSize > MantissaWidth)
2668     return 0;
2669
2670   // Otherwise, we can potentially simplify the comparison.  We know that it
2671   // will always come through as an integer value and we know the constant is
2672   // not a NAN (it would have been previously simplified).
2673   assert(!RHS.isNaN() && "NaN comparison not already folded!");
2674
2675   ICmpInst::Predicate Pred;
2676   switch (I.getPredicate()) {
2677   default: llvm_unreachable("Unexpected predicate!");
2678   case FCmpInst::FCMP_UEQ:
2679   case FCmpInst::FCMP_OEQ:
2680     Pred = ICmpInst::ICMP_EQ;
2681     break;
2682   case FCmpInst::FCMP_UGT:
2683   case FCmpInst::FCMP_OGT:
2684     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2685     break;
2686   case FCmpInst::FCMP_UGE:
2687   case FCmpInst::FCMP_OGE:
2688     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2689     break;
2690   case FCmpInst::FCMP_ULT:
2691   case FCmpInst::FCMP_OLT:
2692     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2693     break;
2694   case FCmpInst::FCMP_ULE:
2695   case FCmpInst::FCMP_OLE:
2696     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2697     break;
2698   case FCmpInst::FCMP_UNE:
2699   case FCmpInst::FCMP_ONE:
2700     Pred = ICmpInst::ICMP_NE;
2701     break;
2702   case FCmpInst::FCMP_ORD:
2703     return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2704   case FCmpInst::FCMP_UNO:
2705     return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2706   }
2707
2708   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
2709
2710   // Now we know that the APFloat is a normal number, zero or inf.
2711
2712   // See if the FP constant is too large for the integer.  For example,
2713   // comparing an i8 to 300.0.
2714   unsigned IntWidth = IntTy->getScalarSizeInBits();
2715
2716   if (!LHSUnsigned) {
2717     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
2718     // and large values.
2719     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2720     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2721                           APFloat::rmNearestTiesToEven);
2722     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
2723       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
2724           Pred == ICmpInst::ICMP_SLE)
2725         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2726       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2727     }
2728   } else {
2729     // If the RHS value is > UnsignedMax, fold the comparison. This handles
2730     // +INF and large values.
2731     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2732     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2733                           APFloat::rmNearestTiesToEven);
2734     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
2735       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
2736           Pred == ICmpInst::ICMP_ULE)
2737         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2738       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2739     }
2740   }
2741
2742   if (!LHSUnsigned) {
2743     // See if the RHS value is < SignedMin.
2744     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2745     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2746                           APFloat::rmNearestTiesToEven);
2747     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2748       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2749           Pred == ICmpInst::ICMP_SGE)
2750         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2751       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2752     }
2753   } else {
2754     // See if the RHS value is < UnsignedMin.
2755     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2756     SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
2757                           APFloat::rmNearestTiesToEven);
2758     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
2759       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
2760           Pred == ICmpInst::ICMP_UGE)
2761         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2762       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2763     }
2764   }
2765
2766   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2767   // [0, UMAX], but it may still be fractional.  See if it is fractional by
2768   // casting the FP value to the integer value and back, checking for equality.
2769   // Don't do this for zero, because -0.0 is not fractional.
2770   Constant *RHSInt = LHSUnsigned
2771     ? ConstantExpr::getFPToUI(RHSC, IntTy)
2772     : ConstantExpr::getFPToSI(RHSC, IntTy);
2773   if (!RHS.isZero()) {
2774     bool Equal = LHSUnsigned
2775       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2776       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2777     if (!Equal) {
2778       // If we had a comparison against a fractional value, we have to adjust
2779       // the compare predicate and sometimes the value.  RHSC is rounded towards
2780       // zero at this point.
2781       switch (Pred) {
2782       default: llvm_unreachable("Unexpected integer comparison!");
2783       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
2784         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2785       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
2786         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2787       case ICmpInst::ICMP_ULE:
2788         // (float)int <= 4.4   --> int <= 4
2789         // (float)int <= -4.4  --> false
2790         if (RHS.isNegative())
2791           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2792         break;
2793       case ICmpInst::ICMP_SLE:
2794         // (float)int <= 4.4   --> int <= 4
2795         // (float)int <= -4.4  --> int < -4
2796         if (RHS.isNegative())
2797           Pred = ICmpInst::ICMP_SLT;
2798         break;
2799       case ICmpInst::ICMP_ULT:
2800         // (float)int < -4.4   --> false
2801         // (float)int < 4.4    --> int <= 4
2802         if (RHS.isNegative())
2803           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2804         Pred = ICmpInst::ICMP_ULE;
2805         break;
2806       case ICmpInst::ICMP_SLT:
2807         // (float)int < -4.4   --> int < -4
2808         // (float)int < 4.4    --> int <= 4
2809         if (!RHS.isNegative())
2810           Pred = ICmpInst::ICMP_SLE;
2811         break;
2812       case ICmpInst::ICMP_UGT:
2813         // (float)int > 4.4    --> int > 4
2814         // (float)int > -4.4   --> true
2815         if (RHS.isNegative())
2816           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2817         break;
2818       case ICmpInst::ICMP_SGT:
2819         // (float)int > 4.4    --> int > 4
2820         // (float)int > -4.4   --> int >= -4
2821         if (RHS.isNegative())
2822           Pred = ICmpInst::ICMP_SGE;
2823         break;
2824       case ICmpInst::ICMP_UGE:
2825         // (float)int >= -4.4   --> true
2826         // (float)int >= 4.4    --> int > 4
2827         if (RHS.isNegative())
2828           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2829         Pred = ICmpInst::ICMP_UGT;
2830         break;
2831       case ICmpInst::ICMP_SGE:
2832         // (float)int >= -4.4   --> int >= -4
2833         // (float)int >= 4.4    --> int > 4
2834         if (!RHS.isNegative())
2835           Pred = ICmpInst::ICMP_SGT;
2836         break;
2837       }
2838     }
2839   }
2840
2841   // Lower this FP comparison into an appropriate integer version of the
2842   // comparison.
2843   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2844 }
2845
2846 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2847   bool Changed = false;
2848
2849   /// Orders the operands of the compare so that they are listed from most
2850   /// complex to least complex.  This puts constants before unary operators,
2851   /// before binary operators.
2852   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2853     I.swapOperands();
2854     Changed = true;
2855   }
2856
2857   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2858
2859   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2860     return ReplaceInstUsesWith(I, V);
2861
2862   // Simplify 'fcmp pred X, X'
2863   if (Op0 == Op1) {
2864     switch (I.getPredicate()) {
2865     default: llvm_unreachable("Unknown predicate!");
2866     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
2867     case FCmpInst::FCMP_ULT:    // True if unordered or less than
2868     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
2869     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
2870       // Canonicalize these to be 'fcmp uno %X, 0.0'.
2871       I.setPredicate(FCmpInst::FCMP_UNO);
2872       I.setOperand(1, Constant::getNullValue(Op0->getType()));
2873       return &I;
2874
2875     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
2876     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
2877     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
2878     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
2879       // Canonicalize these to be 'fcmp ord %X, 0.0'.
2880       I.setPredicate(FCmpInst::FCMP_ORD);
2881       I.setOperand(1, Constant::getNullValue(Op0->getType()));
2882       return &I;
2883     }
2884   }
2885
2886   // Handle fcmp with constant RHS
2887   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2888     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2889       switch (LHSI->getOpcode()) {
2890       case Instruction::FPExt: {
2891         // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
2892         FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
2893         ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
2894         if (!RHSF)
2895           break;
2896
2897         // We can't convert a PPC double double.
2898         if (RHSF->getType()->isPPC_FP128Ty())
2899           break;
2900
2901         const fltSemantics *Sem;
2902         // FIXME: This shouldn't be here.
2903         if (LHSExt->getSrcTy()->isHalfTy())
2904           Sem = &APFloat::IEEEhalf;
2905         else if (LHSExt->getSrcTy()->isFloatTy())
2906           Sem = &APFloat::IEEEsingle;
2907         else if (LHSExt->getSrcTy()->isDoubleTy())
2908           Sem = &APFloat::IEEEdouble;
2909         else if (LHSExt->getSrcTy()->isFP128Ty())
2910           Sem = &APFloat::IEEEquad;
2911         else if (LHSExt->getSrcTy()->isX86_FP80Ty())
2912           Sem = &APFloat::x87DoubleExtended;
2913         else
2914           break;
2915
2916         bool Lossy;
2917         APFloat F = RHSF->getValueAPF();
2918         F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
2919
2920         // Avoid lossy conversions and denormals. Zero is a special case
2921         // that's OK to convert.
2922         APFloat Fabs = F;
2923         Fabs.clearSign();
2924         if (!Lossy &&
2925             ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
2926                  APFloat::cmpLessThan) || Fabs.isZero()))
2927
2928           return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2929                               ConstantFP::get(RHSC->getContext(), F));
2930         break;
2931       }
2932       case Instruction::PHI:
2933         // Only fold fcmp into the PHI if the phi and fcmp are in the same
2934         // block.  If in the same block, we're encouraging jump threading.  If
2935         // not, we are just pessimizing the code by making an i1 phi.
2936         if (LHSI->getParent() == I.getParent())
2937           if (Instruction *NV = FoldOpIntoPhi(I))
2938             return NV;
2939         break;
2940       case Instruction::SIToFP:
2941       case Instruction::UIToFP:
2942         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2943           return NV;
2944         break;
2945       case Instruction::Select: {
2946         // If either operand of the select is a constant, we can fold the
2947         // comparison into the select arms, which will cause one to be
2948         // constant folded and the select turned into a bitwise or.
2949         Value *Op1 = 0, *Op2 = 0;
2950         if (LHSI->hasOneUse()) {
2951           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2952             // Fold the known value into the constant operand.
2953             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2954             // Insert a new FCmp of the other select operand.
2955             Op2 = Builder->CreateFCmp(I.getPredicate(),
2956                                       LHSI->getOperand(2), RHSC, I.getName());
2957           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2958             // Fold the known value into the constant operand.
2959             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2960             // Insert a new FCmp of the other select operand.
2961             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2962                                       RHSC, I.getName());
2963           }
2964         }
2965
2966         if (Op1)
2967           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2968         break;
2969       }
2970       case Instruction::FSub: {
2971         // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
2972         Value *Op;
2973         if (match(LHSI, m_FNeg(m_Value(Op))))
2974           return new FCmpInst(I.getSwappedPredicate(), Op,
2975                               ConstantExpr::getFNeg(RHSC));
2976         break;
2977       }
2978       case Instruction::Load:
2979         if (GetElementPtrInst *GEP =
2980             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2981           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2982             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2983                 !cast<LoadInst>(LHSI)->isVolatile())
2984               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2985                 return Res;
2986         }
2987         break;
2988       }
2989   }
2990
2991   // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
2992   Value *X, *Y;
2993   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
2994     return new FCmpInst(I.getSwappedPredicate(), X, Y);
2995
2996   // fcmp (fpext x), (fpext y) -> fcmp x, y
2997   if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
2998     if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
2999       if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3000         return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3001                             RHSExt->getOperand(0));
3002
3003   return Changed ? &I : 0;
3004 }