Do not use typeinfo to identify pass in pass manager.
[oota-llvm.git] / lib / Analysis / ScalarEvolution.cpp
index 1df54c56ca459a7c8b1137615d5f30a5b934be48..5dae7f0bf1c78f1362957ecaa2192b1297d37091 100644 (file)
@@ -102,6 +102,7 @@ MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
                         cl::init(100));
 
 namespace {
+  const int ScalarEvolution::ID = 0;
   RegisterPass<ScalarEvolution>
   R("scalar-evolution", "Scalar Evolution Analysis");
 }
@@ -124,7 +125,13 @@ ConstantRange SCEV::getValueRange() const {
   const Type *Ty = getType();
   assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
   // Default to a full range if no better information is available.
-  return ConstantRange(getType());
+  return ConstantRange(getBitWidth());
+}
+
+uint32_t SCEV::getBitWidth() const {
+  if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
+    return ITy->getBitWidth();
+  return 0;
 }
 
 
@@ -177,7 +184,7 @@ SCEVHandle SCEVConstant::get(ConstantInt *V) {
 }
 
 ConstantRange SCEVConstant::getValueRange() const {
-  return ConstantRange(V);
+  return ConstantRange(V->getValue());
 }
 
 const Type *SCEVConstant::getType() const { return V->getType(); }
@@ -205,7 +212,7 @@ SCEVTruncateExpr::~SCEVTruncateExpr() {
 }
 
 ConstantRange SCEVTruncateExpr::getValueRange() const {
-  return getOperand()->getValueRange().truncate(getType());
+  return getOperand()->getValueRange().truncate(getBitWidth());
 }
 
 void SCEVTruncateExpr::print(std::ostream &OS) const {
@@ -231,7 +238,7 @@ SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
 }
 
 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
-  return getOperand()->getValueRange().zeroExtend(getType());
+  return getOperand()->getValueRange().zeroExtend(getBitWidth());
 }
 
 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
@@ -454,6 +461,10 @@ SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
   return SCEVUnknown::get(C);
 }
 
+SCEVHandle SCEVUnknown::getIntegerSCEV(const APInt& Val) {
+  return SCEVUnknown::get(ConstantInt::get(Val));
+}
+
 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
 /// input value to the specified type.  If the type must be extended, it is zero
 /// extended.
@@ -490,12 +501,11 @@ static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
   // Handle this case efficiently, it is common to have constant iteration
   // counts while computing loop exit values.
   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
-    uint64_t Val = SC->getValue()->getZExtValue();
-    uint64_t Result = 1;
+    const APInt& Val = SC->getValue()->getValue();
+    APInt Result(Val.getBitWidth(), 1);
     for (; NumSteps; --NumSteps)
       Result *= Val-(NumSteps-1);
-    Constant *Res = ConstantInt::get(Type::Int64Ty, Result);
-    return SCEVUnknown::get(ConstantExpr::getTruncOrBitCast(Res, V->getType()));
+    return SCEVUnknown::get(ConstantInt::get(Result));
   }
 
   const Type *Ty = V->getType();
@@ -593,7 +603,8 @@ SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
     assert(Idx < Ops.size());
     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
       // We found two constants, fold them together!
-      Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
+      Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() + 
+                                        RHSC->getValue()->getValue());
       if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
         Ops[0] = SCEVConstant::get(CI);
         Ops.erase(Ops.begin()+1);  // Erase the folded element
@@ -608,7 +619,7 @@ SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
     }
 
     // If we are left with a constant zero being added, strip it off.
-    if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
+    if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
       Ops.erase(Ops.begin());
       --Idx;
     }
@@ -830,7 +841,8 @@ SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
     ++Idx;
     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
       // We found two constants, fold them together!
-      Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
+      Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() * 
+                                        RHSC->getValue()->getValue());
       if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
         Ops[0] = SCEVConstant::get(CI);
         Ops.erase(Ops.begin()+1);  // Erase the folded element
@@ -848,7 +860,7 @@ SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
       Ops.erase(Ops.begin());
       --Idx;
-    } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
+    } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
       // If we have a multiply of zero, it will always be zero.
       return Ops[0];
     }
@@ -1017,7 +1029,7 @@ SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
   if (Operands.size() == 1) return Operands[0];
 
   if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
-    if (StepC->getValue()->isNullValue()) {
+    if (StepC->getValue()->isZero()) {
       Operands.pop_back();
       return get(Operands, L);             // { X,+,0 }  -->  X
     }
@@ -1138,7 +1150,7 @@ namespace {
     SCEVHandle ComputeIterationCount(const Loop *L);
 
     /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
-    /// 'setcc load X, cst', try to se if we can compute the trip count.
+    /// 'setcc load X, cst', try to see if we can compute the trip count.
     SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
                                                         Constant *RHS,
                                                         const Loop *L,
@@ -1171,7 +1183,7 @@ namespace {
     /// in the header of its containing loop, we know the loop executes a
     /// constant number of times, and the PHI node is just a recurrence
     /// involving constants, fold it.
-    Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
+    Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
                                                 const Loop *L);
   };
 }
@@ -1323,33 +1335,41 @@ SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
 
 /// GetConstantFactor - Determine the largest constant factor that S has.  For
 /// example, turn {4,+,8} -> 4.    (S umod result) should always equal zero.
-static uint64_t GetConstantFactor(SCEVHandle S) {
+static APInt GetConstantFactor(SCEVHandle S) {
   if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
-    if (uint64_t V = C->getValue()->getZExtValue())
+    const APInt& V = C->getValue()->getValue();
+    if (!V.isMinValue())
       return V;
     else   // Zero is a multiple of everything.
-      return 1ULL << (S->getType()->getPrimitiveSizeInBits()-1);
+      return APInt(C->getBitWidth(), 1).shl(C->getBitWidth()-1);
   }
 
-  if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
-    return GetConstantFactor(T->getOperand()) &
-           T->getType()->getIntegerTypeMask();
+  if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) {
+    return GetConstantFactor(T->getOperand()).trunc(
+                               cast<IntegerType>(T->getType())->getBitWidth());
+  }
   if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
-    return GetConstantFactor(E->getOperand());
+    return GetConstantFactor(E->getOperand()).zext(
+                               cast<IntegerType>(E->getType())->getBitWidth());
   
   if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
     // The result is the min of all operands.
-    uint64_t Res = GetConstantFactor(A->getOperand(0));
-    for (unsigned i = 1, e = A->getNumOperands(); i != e && Res > 1; ++i)
-      Res = std::min(Res, GetConstantFactor(A->getOperand(i)));
+    APInt Res(GetConstantFactor(A->getOperand(0)));
+    for (unsigned i = 1, e = A->getNumOperands(); 
+         i != e && Res.ugt(APInt(Res.getBitWidth(),1)); ++i) {
+      APInt Tmp(GetConstantFactor(A->getOperand(i)));
+      Res = APIntOps::umin(Res, Tmp);
+    }
     return Res;
   }
 
   if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
     // The result is the product of all the operands.
-    uint64_t Res = GetConstantFactor(M->getOperand(0));
-    for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i)
-      Res *= GetConstantFactor(M->getOperand(i));
+    APInt Res(GetConstantFactor(M->getOperand(0)));
+    for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i) {
+      APInt Tmp(GetConstantFactor(M->getOperand(i)));
+      Res *= Tmp;
+    }
     return Res;
   }
     
@@ -1357,15 +1377,16 @@ static uint64_t GetConstantFactor(SCEVHandle S) {
     // For now, we just handle linear expressions.
     if (A->getNumOperands() == 2) {
       // We want the GCD between the start and the stride value.
-      uint64_t Start = GetConstantFactor(A->getOperand(0));
-      if (Start == 1) return 1;
-      uint64_t Stride = GetConstantFactor(A->getOperand(1));
-      return GreatestCommonDivisor64(Start, Stride);
+      APInt Start(GetConstantFactor(A->getOperand(0)));
+      if (Start == 1) 
+        return Start;
+      APInt Stride(GetConstantFactor(A->getOperand(1)));
+      return APIntOps::GreatestCommonDivisor(Start, Stride);
     }
   }
   
   // SCEVSDivExpr, SCEVUnknown.
-  return 1;
+  return APInt(S->getBitWidth(), 1);
 }
 
 /// createSCEV - We know that there is no SCEV for the specified value.
@@ -1394,21 +1415,32 @@ SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
       // optimizations will transparently handle this case.
       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
         SCEVHandle LHS = getSCEV(I->getOperand(0));
-        uint64_t CommonFact = GetConstantFactor(LHS);
-        assert(CommonFact && "Common factor should at least be 1!");
-        if (CommonFact > CI->getZExtValue()) {
+        APInt CommonFact(GetConstantFactor(LHS));
+        assert(!CommonFact.isMinValue() &&
+               "Common factor should at least be 1!");
+        if (CommonFact.ugt(CI->getValue())) {
           // If the LHS is a multiple that is larger than the RHS, use +.
           return SCEVAddExpr::get(LHS,
                                   getSCEV(I->getOperand(1)));
         }
       }
       break;
-      
+    case Instruction::Xor:
+      // If the RHS of the xor is a signbit, then this is just an add.
+      // Instcombine turns add of signbit into xor as a strength reduction step.
+      if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
+        if (CI->getValue().isSignBit())
+          return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
+                                  getSCEV(I->getOperand(1)));
+      }
+      break;
+
     case Instruction::Shl:
       // Turn shift left of a constant amount into a multiply.
       if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
-        Constant *X = ConstantInt::get(V->getType(), 1);
-        X = ConstantExpr::getShl(X, SA);
+        uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
+        Constant *X = ConstantInt::get(
+          APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
         return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
       }
       break;
@@ -1567,7 +1599,8 @@ SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
           ConstantExpr::getBitCast(CompVal, RealTy));
         if (CompVal) {
           // Form the constant range.
-          ConstantRange CompRange(Cond, CompVal);
+          ConstantRange CompRange(
+              ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
 
           SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, 
               false /*Always treat as unsigned range*/);
@@ -1719,7 +1752,7 @@ ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
     // Evaluate the condition for this iteration.
     Result = ConstantExpr::getICmp(predicate, Result, RHS);
     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
-    if (cast<ConstantInt>(Result)->getZExtValue() == false) {
+    if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
 #if 0
       cerr << "\n***\n*** Computed loop count " << *ItCst
            << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
@@ -1736,7 +1769,7 @@ ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
 /// CanConstantFold - Return true if we can constant fold an instruction of the
 /// specified type, assuming that all operands were constants.
 static bool CanConstantFold(const Instruction *I) {
-  if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CmpInst>(I) ||
+  if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
     return true;
 
@@ -1746,41 +1779,6 @@ static bool CanConstantFold(const Instruction *I) {
   return false;
 }
 
-/// ConstantFold - Constant fold an instruction of the specified type with the
-/// specified constant operands.  This function may modify the operands vector.
-static Constant *ConstantFold(const Instruction *I,
-                              std::vector<Constant*> &Operands) {
-  if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
-    return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
-
-  if (isa<CastInst>(I))
-    return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
-
-  switch (I->getOpcode()) {
-  case Instruction::Select:
-    return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
-  case Instruction::Call:
-    if (Function *GV = dyn_cast<Function>(Operands[0])) {
-      Operands.erase(Operands.begin());
-      return ConstantFoldCall(cast<Function>(GV), Operands);
-    }
-    return 0;
-  case Instruction::GetElementPtr: {
-    Constant *Base = Operands[0];
-    Operands.erase(Operands.begin());
-    return ConstantExpr::getGetElementPtr(Base, Operands);
-  }
-  case Instruction::ICmp:
-    return ConstantExpr::getICmp(
-        cast<ICmpInst>(I)->getPredicate(), Operands[0], Operands[1]);
-  case Instruction::FCmp:
-    return ConstantExpr::getFCmp(
-        cast<FCmpInst>(I)->getPredicate(), Operands[0], Operands[1]);
-  }
-  return 0;
-}
-
-
 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
 /// in the loop that V is derived from.  We allow arbitrary operations along the
 /// way, but the operands of an operation must either be constants or a value
@@ -1841,7 +1839,7 @@ static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
     if (Operands[i] == 0) return 0;
   }
 
-  return ConstantFold(I, Operands);
+  return ConstantFoldInstOperands(I, &Operands[0], Operands.size());
 }
 
 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
@@ -1849,13 +1847,13 @@ static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
 /// constant number of times, and the PHI node is just a recurrence
 /// involving constants, fold it.
 Constant *ScalarEvolutionsImpl::
-getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
+getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
   std::map<PHINode*, Constant*>::iterator I =
     ConstantEvolutionLoopExitValue.find(PN);
   if (I != ConstantEvolutionLoopExitValue.end())
     return I->second;
 
-  if (Its > MaxBruteForceIterations)
+  if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
     return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
 
   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
@@ -1875,11 +1873,11 @@ getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
     return RetVal = 0;  // Not derived from same PHI.
 
   // Execute the loop symbolically to determine the exit value.
-  unsigned IterationNum = 0;
-  unsigned NumIterations = Its;
-  if (NumIterations != Its)
-    return RetVal = 0;  // More than 2^32 iterations??
+  if (Its.getActiveBits() >= 32)
+    return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
 
+  unsigned NumIterations = Its.getZExtValue(); // must be in range
+  unsigned IterationNum = 0;
   for (Constant *PHIVal = StartCST; ; ++IterationNum) {
     if (IterationNum == NumIterations)
       return RetVal = PHIVal;  // Got exit value!
@@ -1929,7 +1927,7 @@ ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
     // Couldn't symbolically evaluate.
     if (!CondVal) return UnknownValue;
 
-    if (CondVal->getZExtValue() == uint64_t(ExitWhen)) {
+    if (CondVal->getValue() == uint64_t(ExitWhen)) {
       ConstantEvolutionLoopExitValue[PN] = PHIVal;
       ++NumBruteForceTripCountsComputed;
       return SCEVConstant::get(ConstantInt::get(Type::Int32Ty, IterationNum));
@@ -1971,7 +1969,7 @@ SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
               // this is a constant evolving PHI node, get the final value at
               // the specified iteration number.
               Constant *RV = getConstantEvolutionLoopExitValue(PN,
-                                               ICC->getValue()->getZExtValue(),
+                                                    ICC->getValue()->getValue(),
                                                                LI);
               if (RV) return SCEVUnknown::get(RV);
             }
@@ -2006,7 +2004,8 @@ SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
             }
           }
         }
-        return SCEVUnknown::get(ConstantFold(I, Operands));
+        Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size());
+        return SCEVUnknown::get(C);
       }
     }
 
@@ -2087,57 +2086,53 @@ SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
 static std::pair<SCEVHandle,SCEVHandle>
 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
-  SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
-  SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
-  SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
+  SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
+  SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
+  SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
 
   // We currently can only solve this if the coefficients are constants.
-  if (!L || !M || !N) {
-    SCEV *CNC = new SCEVCouldNotCompute();
-    return std::make_pair(CNC, CNC);
-  }
-
-  Constant *C = L->getValue();
-  Constant *Two = ConstantInt::get(C->getType(), 2);
-
-  // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
-  // The B coefficient is M-N/2
-  Constant *B = ConstantExpr::getSub(M->getValue(),
-                                     ConstantExpr::getSDiv(N->getValue(),
-                                                          Two));
-  // The A coefficient is N/2
-  Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
-
-  // Compute the B^2-4ac term.
-  Constant *SqrtTerm =
-    ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
-                         ConstantExpr::getMul(A, C));
-  SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
-
-  // Compute floor(sqrt(B^2-4ac))
-  uint64_t SqrtValV = cast<ConstantInt>(SqrtTerm)->getZExtValue();
-  uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
-  // The square root might not be precise for arbitrary 64-bit integer
-  // values.  Do some sanity checks to ensure it's correct.
-  if (SqrtValV2*SqrtValV2 > SqrtValV ||
-      (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
+  if (!LC || !MC || !NC) {
     SCEV *CNC = new SCEVCouldNotCompute();
     return std::make_pair(CNC, CNC);
   }
 
-  ConstantInt *SqrtVal = ConstantInt::get(Type::Int64Ty, SqrtValV2);
-  SqrtTerm = ConstantExpr::getTruncOrBitCast(SqrtVal, SqrtTerm->getType());
-
-  Constant *NegB = ConstantExpr::getNeg(B);
-  Constant *TwoA = ConstantExpr::getMul(A, Two);
-
-  // The divisions must be performed as signed divisions.
-  Constant *Solution1 =
-    ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
-  Constant *Solution2 =
-    ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
-  return std::make_pair(SCEVUnknown::get(Solution1),
-                        SCEVUnknown::get(Solution2));
+  uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
+  const APInt &L = LC->getValue()->getValue();
+  const APInt &M = MC->getValue()->getValue();
+  const APInt &N = NC->getValue()->getValue();
+  APInt Two(BitWidth, 2);
+  APInt Four(BitWidth, 4);
+
+  { 
+    using namespace APIntOps;
+    const APInt& C = L;
+    // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
+    // The B coefficient is M-N/2
+    APInt B(M);
+    B -= sdiv(N,Two);
+
+    // The A coefficient is N/2
+    APInt A(N.sdiv(Two));
+
+    // Compute the B^2-4ac term.
+    APInt SqrtTerm(B);
+    SqrtTerm *= B;
+    SqrtTerm -= Four * (A * C);
+
+    // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
+    // integer value or else APInt::sqrt() will assert.
+    APInt SqrtVal(SqrtTerm.sqrt());
+
+    // Compute the two solutions for the quadratic formula. 
+    // The divisions must be performed as signed divisions.
+    APInt NegB(-B);
+    APInt TwoA( A << 1 );
+    ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
+    ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
+
+    return std::make_pair(SCEVUnknown::get(Solution1), 
+                          SCEVUnknown::get(Solution2));
+    } // end APIntOps namespace
 }
 
 /// HowFarToZero - Return the number of times a backedge comparing the specified
@@ -2146,7 +2141,7 @@ SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
   // If the value is a constant
   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
     // If the value is already zero, the branch will execute zero times.
-    if (C->getValue()->isNullValue()) return C;
+    if (C->getValue()->isZero()) return C;
     return UnknownValue;  // Otherwise it will loop infinitely.
   }
 
@@ -2209,7 +2204,7 @@ SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
         // should not accept a root of 2.
         SCEVHandle Val = AddRec->evaluateAtIteration(R1);
         if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
-          if (EvalVal->getValue()->isNullValue())
+          if (EvalVal->getValue()->isZero())
             return R1;  // We found a quadratic root!
       }
     }
@@ -2349,13 +2344,13 @@ SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
 
   // If the start is a non-zero constant, shift the range to simplify things.
   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
-    if (!SC->getValue()->isNullValue()) {
+    if (!SC->getValue()->isZero()) {
       std::vector<SCEVHandle> Operands(op_begin(), op_end());
       Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
       SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
       if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
         return ShiftedAddRec->getNumIterationsInRange(
-                                      Range.subtract(SC->getValue()),isSigned);
+                           Range.subtract(SC->getValue()->getValue()),isSigned);
       // This is strange and shouldn't happen.
       return new SCEVCouldNotCompute();
     }
@@ -2372,8 +2367,8 @@ SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
 
   // First check to see if the range contains zero.  If not, the first
   // iteration exits.
-  ConstantInt *Zero = ConstantInt::get(getType(), 0);
-  if (!Range.contains(Zero, isSigned)) return SCEVConstant::get(Zero);
+  if (!Range.contains(APInt(getBitWidth(),0))) 
+    return SCEVConstant::get(ConstantInt::get(getType(),0));
 
   if (isAffine()) {
     // If this is an affine expression then we have this situation:
@@ -2382,29 +2377,27 @@ SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
     // Since we know that zero is in the range, we know that the upper value of
     // the range must be the first possible exit value.  Also note that we
     // already checked for a full range.
-    ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
-    ConstantInt *A     = cast<SCEVConstant>(getOperand(1))->getValue();
-    ConstantInt *One   = ConstantInt::get(getType(), 1);
+    const APInt &Upper = Range.getUpper();
+    APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
+    APInt One(getBitWidth(),1);
 
     // The exit value should be (Upper+A-1)/A.
-    Constant *ExitValue = Upper;
-    if (A != One) {
-      ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
-      ExitValue = ConstantExpr::getSDiv(ExitValue, A);
-    }
-    assert(isa<ConstantInt>(ExitValue) &&
-           "Constant folding of integers not implemented?");
+    APInt ExitVal(Upper);
+    if (A != One)
+      ExitVal = (Upper + A - One).sdiv(A);
+    ConstantInt *ExitValue = ConstantInt::get(ExitVal);
 
     // Evaluate at the exit value.  If we really did fall out of the valid
     // range, then we computed our trip count, otherwise wrap around or other
     // things must have happened.
     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
-    if (Range.contains(Val, isSigned))
+    if (Range.contains(Val->getValue()))
       return new SCEVCouldNotCompute();  // Something strange happened
 
     // Ensure that the previous value is in the range.  This is a sanity check.
-    assert(Range.contains(EvaluateConstantChrecAtConstant(this,
-                          ConstantExpr::getSub(ExitValue, One)), isSigned) &&
+    assert(Range.contains(
+           EvaluateConstantChrecAtConstant(this, 
+           ConstantInt::get(ExitVal - One))->getValue()) &&
            "Linear scev computation is off in a bad way!");
     return SCEVConstant::get(cast<ConstantInt>(ExitValue));
   } else if (isQuadratic()) {
@@ -2413,7 +2406,8 @@ SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
     // terms of figuring out when zero is crossed, instead of when
     // Range.getUpper() is crossed.
     std::vector<SCEVHandle> NewOps(op_begin(), op_end());
-    NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
+    NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(
+                                           ConstantInt::get(Range.getUpper())));
     SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
 
     // Next, solve the constructed addrec
@@ -2434,25 +2428,21 @@ SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
         // for "X*X < 5", for example, we should not return a root of 2.
         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
                                                              R1->getValue());
-        if (Range.contains(R1Val, isSigned)) {
+        if (Range.contains(R1Val->getValue())) {
           // The next iteration must be out of the range...
-          Constant *NextVal =
-            ConstantExpr::getAdd(R1->getValue(),
-                                 ConstantInt::get(R1->getType(), 1));
+          Constant *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
 
           R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
-          if (!Range.contains(R1Val, isSigned))
+          if (!Range.contains(R1Val->getValue()))
             return SCEVUnknown::get(NextVal);
           return new SCEVCouldNotCompute();  // Something strange happened
         }
 
         // If R1 was not in the range, then it is a good return value.  Make
         // sure that R1-1 WAS in the range though, just in case.
-        Constant *NextVal =
-          ConstantExpr::getSub(R1->getValue(),
-                               ConstantInt::get(R1->getType(), 1));
+        Constant *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
         R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
-        if (Range.contains(R1Val, isSigned))
+        if (Range.contains(R1Val->getValue()))
           return R1;
         return new SCEVCouldNotCompute();  // Something strange happened
       }
@@ -2465,7 +2455,6 @@ SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
   // incredibly important, we will be able to simplify the exit test a lot, and
   // we are almost guaranteed to get a trip count in this case.
   ConstantInt *TestVal = ConstantInt::get(getType(), 0);
-  ConstantInt *One     = ConstantInt::get(getType(), 1);
   ConstantInt *EndVal  = TestVal;  // Stop when we wrap around.
   do {
     ++NumBruteForceEvaluations;
@@ -2474,11 +2463,11 @@ SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
       return new SCEVCouldNotCompute();
 
     // Check to see if we found the value!
-    if (!Range.contains(cast<SCEVConstant>(Val)->getValue(), isSigned))
+    if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
       return SCEVConstant::get(TestVal);
 
     // Increment to test the next index.
-    TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
+    TestVal = ConstantInt::get(TestVal->getValue()+1);
   } while (TestVal != EndVal);
 
   return new SCEVCouldNotCompute();