PR4340: Run SimplifyDemandedVectorElts on insertelement instructions;
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
index 83158276e2c52c638b17e0f7c5c4afe309ff91ab..6d2ff0e3e53c5a5f5e7752fff595177d9f430374 100644 (file)
@@ -167,8 +167,11 @@ namespace {
     //   otherwise    - Change was made, replace I with returned instruction
     //
     Instruction *visitAdd(BinaryOperator &I);
+    Instruction *visitFAdd(BinaryOperator &I);
     Instruction *visitSub(BinaryOperator &I);
+    Instruction *visitFSub(BinaryOperator &I);
     Instruction *visitMul(BinaryOperator &I);
+    Instruction *visitFMul(BinaryOperator &I);
     Instruction *visitURem(BinaryOperator &I);
     Instruction *visitSRem(BinaryOperator &I);
     Instruction *visitFRem(BinaryOperator &I);
@@ -218,11 +221,12 @@ namespace {
     Instruction *visitFPToSI(FPToSIInst &FI);
     Instruction *visitUIToFP(CastInst &CI);
     Instruction *visitSIToFP(CastInst &CI);
-    Instruction *visitPtrToInt(CastInst &CI);
+    Instruction *visitPtrToInt(PtrToIntInst &CI);
     Instruction *visitIntToPtr(IntToPtrInst &CI);
     Instruction *visitBitCast(BitCastInst &CI);
     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
                                 Instruction *FI);
+    Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
     Instruction *visitSelectInst(SelectInst &SI);
     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
     Instruction *visitCallInst(CallInst &CI);
@@ -250,6 +254,8 @@ namespace {
     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
                                    bool DoXform = true);
     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
+    DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
+
 
   public:
     // InsertNewInstBefore - insert an instruction New before instruction Old
@@ -303,23 +309,6 @@ namespace {
       }
     }
 
-    // UpdateValueUsesWith - This method is to be used when an value is
-    // found to be replacable with another preexisting expression or was
-    // updated.  Here we add all uses of I to the worklist, replace all uses of
-    // I with the new value (unless the instruction was just updated), then
-    // return true, so that the inst combiner will know that I was modified.
-    //
-    bool UpdateValueUsesWith(Value *Old, Value *New) {
-      AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
-      if (Old != New)
-        Old->replaceAllUsesWith(New);
-      if (Instruction *I = dyn_cast<Instruction>(Old))
-        AddToWorkList(I);
-      if (Instruction *I = dyn_cast<Instruction>(New))
-        AddToWorkList(I);
-      return true;
-    }
-    
     // EraseInstFromFunction - When dealing with an instruction that has side
     // effects or produces a void value, we can't rely on DCE to delete the
     // instruction.  Instead, visit methods should return the value returned by
@@ -355,14 +344,22 @@ namespace {
     /// most-complex to least-complex order.
     bool SimplifyCompare(CmpInst &I);
 
-    /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
-    /// on the demanded bits.
-    bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
+    /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
+    /// based on the demanded bits.
+    Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
+                                   APInt& KnownZero, APInt& KnownOne,
+                                   unsigned Depth);
+    bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
                               APInt& KnownZero, APInt& KnownOne,
-                              unsigned Depth = 0);
-
-    Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
-                                      uint64_t &UndefElts, unsigned Depth = 0);
+                              unsigned Depth=0);
+        
+    /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
+    /// SimplifyDemandedBits knows about.  See if the instruction has any
+    /// properties that allow us to simplify its operands.
+    bool SimplifyDemandedInstructionBits(Instruction &Inst);
+        
+    Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
+                                      APInt& UndefElts, unsigned Depth = 0);
       
     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
     // PHI node as operand #0, see if we can fold the instruction into the PHI
@@ -394,8 +391,7 @@ namespace {
     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
 
     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
-                                    unsigned CastOpc,
-                                    int &NumCastsRemoved);
+                                    unsigned CastOpc, int &NumCastsRemoved);
     unsigned GetOrEnforceKnownAlignment(Value *V,
                                         unsigned PrefAlign = 0);
 
@@ -410,7 +406,8 @@ X("instcombine", "Combine redundant instructions");
 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
 static unsigned getComplexity(Value *V) {
   if (isa<Instruction>(V)) {
-    if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
+    if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
+        BinaryOperator::isNot(V))
       return 3;
     return 4;
   }
@@ -482,9 +479,16 @@ isEliminableCastPair(
   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
 
-  return Instruction::CastOps(
-      CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
-                                     DstTy, TD->getIntPtrType()));
+  unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
+                                                DstTy, TD->getIntPtrType());
+  
+  // We don't want to form an inttoptr or ptrtoint that converts to an integer
+  // type that differs from the pointer size.
+  if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
+      (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
+    Res = 0;
+  
+  return Instruction::CastOps(Res);
 }
 
 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
@@ -576,6 +580,25 @@ static inline Value *dyn_castNegVal(Value *V) {
   return 0;
 }
 
+// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
+// instruction if the LHS is a constant negative zero (which is the 'negate'
+// form).
+//
+static inline Value *dyn_castFNegVal(Value *V) {
+  if (BinaryOperator::isFNeg(V))
+    return BinaryOperator::getFNegArgument(V);
+
+  // Constants can be considered to be negated values if they can be folded.
+  if (ConstantFP *C = dyn_cast<ConstantFP>(V))
+    return ConstantExpr::getFNeg(C);
+
+  if (ConstantVector *C = dyn_cast<ConstantVector>(V))
+    if (C->getType()->getElementType()->isFloatingPoint())
+      return ConstantExpr::getFNeg(C);
+
+  return 0;
+}
+
 static inline Value *dyn_castNotVal(Value *V) {
   if (BinaryOperator::isNot(V))
     return BinaryOperator::getNotArgument(V);
@@ -708,15 +731,13 @@ static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
 // set of known zero and one bits, compute the maximum and minimum values that
 // could have the specified known zero and known one bits, returning them in
 // min/max.
-static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
-                                                   const APInt& KnownZero,
+static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
                                                    const APInt& KnownOne,
                                                    APInt& Min, APInt& Max) {
-  uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
-  assert(KnownZero.getBitWidth() == BitWidth && 
-         KnownOne.getBitWidth() == BitWidth &&
-         Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
-         "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
+  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
+         KnownZero.getBitWidth() == Min.getBitWidth() &&
+         KnownZero.getBitWidth() == Max.getBitWidth() &&
+         "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
   APInt UnknownBits = ~(KnownZero|KnownOne);
 
   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
@@ -724,9 +745,9 @@ static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
   Min = KnownOne;
   Max = KnownOne|UnknownBits;
   
-  if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
-    Min.set(BitWidth-1);
-    Max.clear(BitWidth-1);
+  if (UnknownBits.isNegative()) { // Sign bit is unknown
+    Min.set(Min.getBitWidth()-1);
+    Max.clear(Max.getBitWidth()-1);
   }
 }
 
@@ -734,14 +755,12 @@ static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
 // a set of known zero and one bits, compute the maximum and minimum values that
 // could have the specified known zero and known one bits, returning them in
 // min/max.
-static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
-                                                     const APInt &KnownZero,
+static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
                                                      const APInt &KnownOne,
                                                      APInt &Min, APInt &Max) {
-  uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
-  assert(KnownZero.getBitWidth() == BitWidth && 
-         KnownOne.getBitWidth() == BitWidth &&
-         Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
+  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
+         KnownZero.getBitWidth() == Min.getBitWidth() &&
+         KnownZero.getBitWidth() == Max.getBitWidth() &&
          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
   APInt UnknownBits = ~(KnownZero|KnownOne);
   
@@ -751,14 +770,44 @@ static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
   Max = KnownOne|UnknownBits;
 }
 
-/// SimplifyDemandedBits - This function attempts to replace V with a simpler
-/// value based on the demanded bits. When this function is called, it is known
+/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
+/// SimplifyDemandedBits knows about.  See if the instruction has any
+/// properties that allow us to simplify its operands.
+bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
+  unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
+  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
+  APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
+  
+  Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
+                                     KnownZero, KnownOne, 0);
+  if (V == 0) return false;
+  if (V == &Inst) return true;
+  ReplaceInstUsesWith(Inst, V);
+  return true;
+}
+
+/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
+/// specified instruction operand if possible, updating it in place.  It returns
+/// true if it made any change and false otherwise.
+bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
+                                        APInt &KnownZero, APInt &KnownOne,
+                                        unsigned Depth) {
+  Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
+                                          KnownZero, KnownOne, Depth);
+  if (NewVal == 0) return false;
+  U.set(NewVal);
+  return true;
+}
+
+
+/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
+/// value based on the demanded bits.  When this function is called, it is known
 /// that only the bits set in DemandedMask of the result of V are ever used
 /// downstream. Consequently, depending on the mask and V, it may be possible
 /// to replace V with a constant or one of its operands. In such cases, this
 /// function does the replacement and returns true. In all other cases, it
 /// returns false after analyzing the expression and setting KnownOne and known
-/// to be one in the expression. KnownZero contains all the bits that are known
+/// to be one in the expression.  KnownZero contains all the bits that are known
 /// to be zero in the expression. These are provided to potentially allow the
 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
 /// the expression. KnownOne and KnownZero always follow the invariant that 
@@ -766,15 +815,25 @@ static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
 /// and KnownOne must all be the same.
-bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
-                                        APInt& KnownZero, APInt& KnownOne,
-                                        unsigned Depth) {
+///
+/// This returns null if it did not change anything and it permits no
+/// simplification.  This returns V itself if it did some simplification of V's
+/// operands based on the information about what bits are demanded. This returns
+/// some other non-null value if it found out that V is equal to another value
+/// in the context where the specified bits are demanded, but not for all users.
+Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
+                                             APInt &KnownZero, APInt &KnownOne,
+                                             unsigned Depth) {
   assert(V != 0 && "Null pointer of Value???");
   assert(Depth <= 6 && "Limit Search Depth");
   uint32_t BitWidth = DemandedMask.getBitWidth();
-  const IntegerType *VTy = cast<IntegerType>(V->getType());
-  assert(VTy->getBitWidth() == BitWidth && 
-         KnownZero.getBitWidth() == BitWidth && 
+  const Type *VTy = V->getType();
+  assert((TD || !isa<PointerType>(VTy)) &&
+         "SimplifyDemandedBits needs to know bit widths!");
+  assert((!TD || TD->getTypeSizeInBits(VTy) == BitWidth) &&
+         (!isa<IntegerType>(VTy) ||
+          VTy->getPrimitiveSizeInBits() == BitWidth) &&
+         KnownZero.getBitWidth() == BitWidth &&
          KnownOne.getBitWidth() == BitWidth &&
          "Value *V, DemandedMask, KnownZero and KnownOne \
           must have same BitWidth");
@@ -782,69 +841,136 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
     // We know all of the bits for a constant!
     KnownOne = CI->getValue() & DemandedMask;
     KnownZero = ~KnownOne & DemandedMask;
-    return false;
+    return 0;
   }
-  
-  KnownZero.clear(); 
+  if (isa<ConstantPointerNull>(V)) {
+    // We know all of the bits for a constant!
+    KnownOne.clear();
+    KnownZero = DemandedMask;
+    return 0;
+  }
+
+  KnownZero.clear();
   KnownOne.clear();
-  if (!V->hasOneUse()) {    // Other users may use these bits.
-    if (Depth != 0) {       // Not at the root.
-      // Just compute the KnownZero/KnownOne bits to simplify things downstream.
-      ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
-      return false;
-    }
-    // If this is the root being simplified, allow it to have multiple uses,
-    // just set the DemandedMask to all bits.
-    DemandedMask = APInt::getAllOnesValue(BitWidth);
-  } else if (DemandedMask == 0) {   // Not demanding any bits from V.
-    if (V != UndefValue::get(VTy))
-      return UpdateValueUsesWith(V, UndefValue::get(VTy));
-    return false;
-  } else if (Depth == 6) {        // Limit search depth.
-    return false;
+  if (DemandedMask == 0) {   // Not demanding any bits from V.
+    if (isa<UndefValue>(V))
+      return 0;
+    return UndefValue::get(VTy);
   }
   
-  Instruction *I = dyn_cast<Instruction>(V);
-  if (!I) return false;        // Only analyze instructions.
-
+  if (Depth == 6)        // Limit search depth.
+    return 0;
+  
   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
+
+  Instruction *I = dyn_cast<Instruction>(V);
+  if (!I) {
+    ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
+    return 0;        // Only analyze instructions.
+  }
+
+  // If there are multiple uses of this value and we aren't at the root, then
+  // we can't do any simplifications of the operands, because DemandedMask
+  // only reflects the bits demanded by *one* of the users.
+  if (Depth != 0 && !I->hasOneUse()) {
+    // Despite the fact that we can't simplify this instruction in all User's
+    // context, we can at least compute the knownzero/knownone bits, and we can
+    // do simplifications that apply to *just* the one user if we know that
+    // this instruction has a simpler value in that context.
+    if (I->getOpcode() == Instruction::And) {
+      // If either the LHS or the RHS are Zero, the result is zero.
+      ComputeMaskedBits(I->getOperand(1), DemandedMask,
+                        RHSKnownZero, RHSKnownOne, Depth+1);
+      ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
+                        LHSKnownZero, LHSKnownOne, Depth+1);
+      
+      // If all of the demanded bits are known 1 on one side, return the other.
+      // These bits cannot contribute to the result of the 'and' in this
+      // context.
+      if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
+          (DemandedMask & ~LHSKnownZero))
+        return I->getOperand(0);
+      if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
+          (DemandedMask & ~RHSKnownZero))
+        return I->getOperand(1);
+      
+      // If all of the demanded bits in the inputs are known zeros, return zero.
+      if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
+        return Constant::getNullValue(VTy);
+      
+    } else if (I->getOpcode() == Instruction::Or) {
+      // We can simplify (X|Y) -> X or Y in the user's context if we know that
+      // only bits from X or Y are demanded.
+      
+      // If either the LHS or the RHS are One, the result is One.
+      ComputeMaskedBits(I->getOperand(1), DemandedMask, 
+                        RHSKnownZero, RHSKnownOne, Depth+1);
+      ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
+                        LHSKnownZero, LHSKnownOne, Depth+1);
+      
+      // If all of the demanded bits are known zero on one side, return the
+      // other.  These bits cannot contribute to the result of the 'or' in this
+      // context.
+      if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
+          (DemandedMask & ~LHSKnownOne))
+        return I->getOperand(0);
+      if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
+          (DemandedMask & ~RHSKnownOne))
+        return I->getOperand(1);
+      
+      // If all of the potentially set bits on one side are known to be set on
+      // the other side, just use the 'other' side.
+      if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
+          (DemandedMask & (~RHSKnownZero)))
+        return I->getOperand(0);
+      if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
+          (DemandedMask & (~LHSKnownZero)))
+        return I->getOperand(1);
+    }
+    
+    // Compute the KnownZero/KnownOne bits to simplify things downstream.
+    ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
+    return 0;
+  }
+  
+  // If this is the root being simplified, allow it to have multiple uses,
+  // just set the DemandedMask to all bits so that we can try to simplify the
+  // operands.  This allows visitTruncInst (for example) to simplify the
+  // operand of a trunc without duplicating all the logic below.
+  if (Depth == 0 && !V->hasOneUse())
+    DemandedMask = APInt::getAllOnesValue(BitWidth);
+  
   switch (I->getOpcode()) {
   default:
-    ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
+    ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
     break;
   case Instruction::And:
     // If either the LHS or the RHS are Zero, the result is zero.
-    if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
-                             RHSKnownZero, RHSKnownOne, Depth+1))
-      return true;
-    assert((RHSKnownZero & RHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
-
-    // If something is known zero on the RHS, the bits aren't demanded on the
-    // LHS.
-    if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
+    if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
+                             RHSKnownZero, RHSKnownOne, Depth+1) ||
+        SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
                              LHSKnownZero, LHSKnownOne, Depth+1))
-      return true;
-    assert((LHSKnownZero & LHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
+      return I;
+    assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
+    assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
 
     // If all of the demanded bits are known 1 on one side, return the other.
     // These bits cannot contribute to the result of the 'and'.
     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
         (DemandedMask & ~LHSKnownZero))
-      return UpdateValueUsesWith(I, I->getOperand(0));
+      return I->getOperand(0);
     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
         (DemandedMask & ~RHSKnownZero))
-      return UpdateValueUsesWith(I, I->getOperand(1));
+      return I->getOperand(1);
     
     // If all of the demanded bits in the inputs are known zeros, return zero.
     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
-      return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
+      return Constant::getNullValue(VTy);
       
     // If the RHS is a constant, see if we can simplify it.
     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
-      return UpdateValueUsesWith(I, I);
+      return I;
       
     // Output known-1 bits are only known if set in both the LHS & RHS.
     RHSKnownOne &= LHSKnownOne;
@@ -853,40 +979,35 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
     break;
   case Instruction::Or:
     // If either the LHS or the RHS are One, the result is One.
-    if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
-                             RHSKnownZero, RHSKnownOne, Depth+1))
-      return true;
-    assert((RHSKnownZero & RHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
-    // If something is known one on the RHS, the bits aren't demanded on the
-    // LHS.
-    if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
+    if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
+                             RHSKnownZero, RHSKnownOne, Depth+1) ||
+        SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
                              LHSKnownZero, LHSKnownOne, Depth+1))
-      return true;
-    assert((LHSKnownZero & LHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
+      return I;
+    assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
+    assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
     
     // If all of the demanded bits are known zero on one side, return the other.
     // These bits cannot contribute to the result of the 'or'.
     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
         (DemandedMask & ~LHSKnownOne))
-      return UpdateValueUsesWith(I, I->getOperand(0));
+      return I->getOperand(0);
     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
         (DemandedMask & ~RHSKnownOne))
-      return UpdateValueUsesWith(I, I->getOperand(1));
+      return I->getOperand(1);
 
     // If all of the potentially set bits on one side are known to be set on
     // the other side, just use the 'other' side.
     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
         (DemandedMask & (~RHSKnownZero)))
-      return UpdateValueUsesWith(I, I->getOperand(0));
+      return I->getOperand(0);
     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
         (DemandedMask & (~LHSKnownZero)))
-      return UpdateValueUsesWith(I, I->getOperand(1));
+      return I->getOperand(1);
         
     // If the RHS is a constant, see if we can simplify it.
     if (ShrinkDemandedConstant(I, 1, DemandedMask))
-      return UpdateValueUsesWith(I, I);
+      return I;
           
     // Output known-0 bits are only known if clear in both the LHS & RHS.
     RHSKnownZero &= LHSKnownZero;
@@ -894,23 +1015,20 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
     RHSKnownOne |= LHSKnownOne;
     break;
   case Instruction::Xor: {
-    if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
-                             RHSKnownZero, RHSKnownOne, Depth+1))
-      return true;
-    assert((RHSKnownZero & RHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
-    if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
+    if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
+                             RHSKnownZero, RHSKnownOne, Depth+1) ||
+        SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
                              LHSKnownZero, LHSKnownOne, Depth+1))
-      return true;
-    assert((LHSKnownZero & LHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
+      return I;
+    assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
+    assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
     
     // If all of the demanded bits are known zero on one side, return the other.
     // These bits cannot contribute to the result of the 'xor'.
     if ((DemandedMask & RHSKnownZero) == DemandedMask)
-      return UpdateValueUsesWith(I, I->getOperand(0));
+      return I->getOperand(0);
     if ((DemandedMask & LHSKnownZero) == DemandedMask)
-      return UpdateValueUsesWith(I, I->getOperand(1));
+      return I->getOperand(1);
     
     // Output known-0 bits are known if clear or set in both the LHS & RHS.
     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
@@ -926,8 +1044,7 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
       Instruction *Or =
         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
                                  I->getName());
-      InsertNewInstBefore(Or, *I);
-      return UpdateValueUsesWith(I, Or);
+      return InsertNewInstBefore(Or, *I);
     }
     
     // If all of the demanded bits on one side are known, and all of the set
@@ -940,92 +1057,80 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
         Instruction *And = 
           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
-        InsertNewInstBefore(And, *I);
-        return UpdateValueUsesWith(I, And);
+        return InsertNewInstBefore(And, *I);
       }
     }
     
     // If the RHS is a constant, see if we can simplify it.
     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
     if (ShrinkDemandedConstant(I, 1, DemandedMask))
-      return UpdateValueUsesWith(I, I);
+      return I;
     
     RHSKnownZero = KnownZeroOut;
     RHSKnownOne  = KnownOneOut;
     break;
   }
   case Instruction::Select:
-    if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
-                             RHSKnownZero, RHSKnownOne, Depth+1))
-      return true;
-    if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
+    if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
+                             RHSKnownZero, RHSKnownOne, Depth+1) ||
+        SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
                              LHSKnownZero, LHSKnownOne, Depth+1))
-      return true;
-    assert((RHSKnownZero & RHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
-    assert((LHSKnownZero & LHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
+      return I;
+    assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
+    assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
     
     // If the operands are constants, see if we can simplify them.
-    if (ShrinkDemandedConstant(I, 1, DemandedMask))
-      return UpdateValueUsesWith(I, I);
-    if (ShrinkDemandedConstant(I, 2, DemandedMask))
-      return UpdateValueUsesWith(I, I);
+    if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
+        ShrinkDemandedConstant(I, 2, DemandedMask))
+      return I;
     
     // Only known if known in both the LHS and RHS.
     RHSKnownOne &= LHSKnownOne;
     RHSKnownZero &= LHSKnownZero;
     break;
   case Instruction::Trunc: {
-    uint32_t truncBf = 
-      cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
+    unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
     DemandedMask.zext(truncBf);
     RHSKnownZero.zext(truncBf);
     RHSKnownOne.zext(truncBf);
-    if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
+    if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
                              RHSKnownZero, RHSKnownOne, Depth+1))
-      return true;
+      return I;
     DemandedMask.trunc(BitWidth);
     RHSKnownZero.trunc(BitWidth);
     RHSKnownOne.trunc(BitWidth);
-    assert((RHSKnownZero & RHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
+    assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
     break;
   }
   case Instruction::BitCast:
     if (!I->getOperand(0)->getType()->isInteger())
-      return false;
-      
-    if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
+      return false;  // vector->int or fp->int?
+    if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
                              RHSKnownZero, RHSKnownOne, Depth+1))
-      return true;
-    assert((RHSKnownZero & RHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
+      return I;
+    assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
     break;
   case Instruction::ZExt: {
     // Compute the bits in the result that are not present in the input.
-    const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
-    uint32_t SrcBitWidth = SrcTy->getBitWidth();
+    unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
     
     DemandedMask.trunc(SrcBitWidth);
     RHSKnownZero.trunc(SrcBitWidth);
     RHSKnownOne.trunc(SrcBitWidth);
-    if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
+    if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
                              RHSKnownZero, RHSKnownOne, Depth+1))
-      return true;
+      return I;
     DemandedMask.zext(BitWidth);
     RHSKnownZero.zext(BitWidth);
     RHSKnownOne.zext(BitWidth);
-    assert((RHSKnownZero & RHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
+    assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
     // The top bits are known to be zero.
     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
     break;
   }
   case Instruction::SExt: {
     // Compute the bits in the result that are not present in the input.
-    const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
-    uint32_t SrcBitWidth = SrcTy->getBitWidth();
+    unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
     
     APInt InputDemandedBits = DemandedMask & 
                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
@@ -1039,25 +1144,23 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
     InputDemandedBits.trunc(SrcBitWidth);
     RHSKnownZero.trunc(SrcBitWidth);
     RHSKnownOne.trunc(SrcBitWidth);
-    if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
+    if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
                              RHSKnownZero, RHSKnownOne, Depth+1))
-      return true;
+      return I;
     InputDemandedBits.zext(BitWidth);
     RHSKnownZero.zext(BitWidth);
     RHSKnownOne.zext(BitWidth);
-    assert((RHSKnownZero & RHSKnownOne) == 0 && 
-           "Bits known to be one AND zero?"); 
+    assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
       
     // If the sign bit of the input is known set or clear, then we know the
     // top bits of the result.
 
     // If the input sign bit is known zero, or if the NewBits are not demanded
     // convert this into a zero extension.
-    if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
-    {
+    if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
       // Convert to ZExt cast
-      CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
-      return UpdateValueUsesWith(I, NewCast);
+      CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
+      return InsertNewInstBefore(NewCast, *I);
     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
       RHSKnownOne |= NewBits;
     }
@@ -1067,7 +1170,7 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
     // Figure out what the input bits are.  If the top bits of the and result
     // are not demanded, then the add doesn't demand them from its input
     // either.
-    uint32_t NLZ = DemandedMask.countLeadingZeros();
+    unsigned NLZ = DemandedMask.countLeadingZeros();
       
     // If there is a constant on the RHS, there are a variety of xformations
     // we can do.
@@ -1082,14 +1185,14 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
 
       // Find information about known zero/one bits in the input.
-      if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
+      if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
                                LHSKnownZero, LHSKnownOne, Depth+1))
-        return true;
+        return I;
 
       // If the RHS of the add has bits set that can't affect the input, reduce
       // the constant.
       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
-        return UpdateValueUsesWith(I, I);
+        return I;
       
       // Avoid excess work.
       if (LHSKnownZero == 0 && LHSKnownOne == 0)
@@ -1100,8 +1203,7 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
         Instruction *Or =
           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
                                    I->getName());
-        InsertNewInstBefore(Or, *I);
-        return UpdateValueUsesWith(I, Or);
+        return InsertNewInstBefore(Or, *I);
       }
       
       // We can say something about the output known-zero and known-one bits,
@@ -1113,7 +1215,7 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
       // To compute this, we first compute the potential carry bits.  These are
       // the bits which may be modified.  I'm not aware of a better way to do
       // this scan.
-      const APIntRHSVal = RHS->getValue();
+      const APInt &RHSVal = RHS->getValue();
       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
       
       // Now that we know which bits have carries, compute the known-1/0 sets.
@@ -1133,12 +1235,11 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
         // Right fill the mask of bits for this ADD to demand the most
         // significant bit and all those below it.
         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
-        if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
-                                 LHSKnownZero, LHSKnownOne, Depth+1))
-          return true;
-        if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
+        if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
+                                 LHSKnownZero, LHSKnownOne, Depth+1) ||
+            SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
                                  LHSKnownZero, LHSKnownOne, Depth+1))
-          return true;
+          return I;
       }
     }
     break;
@@ -1151,12 +1252,11 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
       // significant bit and all those below it.
       uint32_t NLZ = DemandedMask.countLeadingZeros();
       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
-      if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
-                               LHSKnownZero, LHSKnownOne, Depth+1))
-        return true;
-      if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
+      if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
+                               LHSKnownZero, LHSKnownOne, Depth+1) ||
+          SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
                                LHSKnownZero, LHSKnownOne, Depth+1))
-        return true;
+        return I;
     }
     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
     // the known zeros and ones.
@@ -1166,11 +1266,10 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
-      if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
+      if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
                                RHSKnownZero, RHSKnownOne, Depth+1))
-        return true;
-      assert((RHSKnownZero & RHSKnownOne) == 0 && 
-             "Bits known to be one AND zero?"); 
+        return I;
+      assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
       RHSKnownZero <<= ShiftAmt;
       RHSKnownOne  <<= ShiftAmt;
       // low bits known zero.
@@ -1185,11 +1284,10 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
       
       // Unsigned shift right.
       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
-      if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
+      if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
                                RHSKnownZero, RHSKnownOne, Depth+1))
-        return true;
-      assert((RHSKnownZero & RHSKnownOne) == 0 && 
-             "Bits known to be one AND zero?"); 
+        return I;
+      assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
       if (ShiftAmt) {
@@ -1206,16 +1304,15 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
     // the shift amount is >= the size of the datatype, which is undefined.
     if (DemandedMask == 1) {
       // Perform the logical shift right.
-      Value *NewVal = BinaryOperator::CreateLShr(
+      Instruction *NewVal = BinaryOperator::CreateLShr(
                         I->getOperand(0), I->getOperand(1), I->getName());
-      InsertNewInstBefore(cast<Instruction>(NewVal), *I);
-      return UpdateValueUsesWith(I, NewVal);
+      return InsertNewInstBefore(NewVal, *I);
     }    
 
     // If the sign bit is the only bit demanded by this ashr, then there is no
     // need to do it, the shift doesn't change the high bit.
     if (DemandedMask.isSignBit())
-      return UpdateValueUsesWith(I, I->getOperand(0));
+      return I->getOperand(0);
     
     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
@@ -1226,12 +1323,10 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
       // demanded.
       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
         DemandedMaskIn.set(BitWidth-1);
-      if (SimplifyDemandedBits(I->getOperand(0),
-                               DemandedMaskIn,
+      if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
                                RHSKnownZero, RHSKnownOne, Depth+1))
-        return true;
-      assert((RHSKnownZero & RHSKnownOne) == 0 && 
-             "Bits known to be one AND zero?"); 
+        return I;
+      assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
       // Compute the new bits that are at the top now.
       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
@@ -1247,10 +1342,9 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
           (HighBits & ~DemandedMask) == HighBits) {
         // Perform the logical shift right.
-        Value *NewVal = BinaryOperator::CreateLShr(
+        Instruction *NewVal = BinaryOperator::CreateLShr(
                           I->getOperand(0), SA, I->getName());
-        InsertNewInstBefore(cast<Instruction>(NewVal), *I);
-        return UpdateValueUsesWith(I, NewVal);
+        return InsertNewInstBefore(NewVal, *I);
       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
         RHSKnownOne |= HighBits;
       }
@@ -1261,35 +1355,33 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
       APInt RA = Rem->getValue().abs();
       if (RA.isPowerOf2()) {
         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
-          return UpdateValueUsesWith(I, I->getOperand(0));
+          return I->getOperand(0);
 
         APInt LowBits = RA - 1;
         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
-        if (SimplifyDemandedBits(I->getOperand(0), Mask2,
+        if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
                                  LHSKnownZero, LHSKnownOne, Depth+1))
-          return true;
+          return I;
 
         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
           LHSKnownZero |= ~LowBits;
 
         KnownZero |= LHSKnownZero & DemandedMask;
 
-        assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
+        assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
       }
     }
     break;
   case Instruction::URem: {
     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
-    if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
-                             KnownZero2, KnownOne2, Depth+1))
-      return true;
-
-    uint32_t Leaders = KnownZero2.countLeadingOnes();
-    if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
+    if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
+                             KnownZero2, KnownOne2, Depth+1) ||
+        SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
                              KnownZero2, KnownOne2, Depth+1))
-      return true;
+      return I;
 
+    unsigned Leaders = KnownZero2.countLeadingOnes();
     Leaders = std::max(Leaders,
                        KnownZero2.countLeadingOnes());
     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
@@ -1325,8 +1417,7 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
                     ConstantInt::get(I->getType(), ResultBit-InputBit));
           NewVal->takeName(I);
-          InsertNewInstBefore(NewVal, *I);
-          return UpdateValueUsesWith(I, NewVal);
+          return InsertNewInstBefore(NewVal, *I);
         }
           
         // TODO: Could compute known zero/one bits based on the input.
@@ -1340,26 +1431,29 @@ bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
   
   // If the client is only demanding bits that we know, return the known
   // constant.
-  if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
-    return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
+  if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
+    Constant *C = ConstantInt::get(RHSKnownOne);
+    if (isa<PointerType>(V->getType()))
+      C = ConstantExpr::getIntToPtr(C, V->getType());
+    return C;
+  }
   return false;
 }
 
 
 /// SimplifyDemandedVectorElts - The specified value produces a vector with
-/// 64 or fewer elements.  DemandedElts contains the set of elements that are
+/// any number of elements. DemandedElts contains the set of elements that are
 /// actually used by the caller.  This method analyzes which elements of the
 /// operand are undef and returns that information in UndefElts.
 ///
 /// If the information about demanded elements can be used to simplify the
 /// operation, the operation is simplified, then the resultant value is
 /// returned.  This returns null if no change was made.
-Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
-                                                uint64_t &UndefElts,
+Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
+                                                APInt& UndefElts,
                                                 unsigned Depth) {
   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
-  assert(VWidth <= 64 && "Vector too wide to analyze!");
-  uint64_t EltMask = ~0ULL >> (64-VWidth);
+  APInt EltMask(APInt::getAllOnesValue(VWidth));
   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
 
   if (isa<UndefValue>(V)) {
@@ -1378,12 +1472,12 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
 
     std::vector<Constant*> Elts;
     for (unsigned i = 0; i != VWidth; ++i)
-      if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
+      if (!DemandedElts[i]) {   // If not demanded, set to undef.
         Elts.push_back(Undef);
-        UndefElts |= (1ULL << i);
+        UndefElts.set(i);
       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
         Elts.push_back(Undef);
-        UndefElts |= (1ULL << i);
+        UndefElts.set(i);
       } else {                               // Otherwise, defined.
         Elts.push_back(CP->getOperand(i));
       }
@@ -1404,15 +1498,17 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
     Constant *Zero = Constant::getNullValue(EltTy);
     Constant *Undef = UndefValue::get(EltTy);
     std::vector<Constant*> Elts;
-    for (unsigned i = 0; i != VWidth; ++i)
-      Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
+    for (unsigned i = 0; i != VWidth; ++i) {
+      Constant *Elt = DemandedElts[i] ? Zero : Undef;
+      Elts.push_back(Elt);
+    }
     UndefElts = DemandedElts ^ EltMask;
     return ConstantVector::get(Elts);
   }
   
   // Limit search depth.
   if (Depth == 10)
-    return false;
+    return 0;
 
   // If multiple users are using the root value, procede with
   // simplification conservatively assuming that all elements
@@ -1423,17 +1519,17 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
     // the main instcombine process.
     if (Depth != 0)
       // TODO: Just compute the UndefElts information recursively.
-      return false;
+      return 0;
 
     // Conservatively assume that all elements are needed.
     DemandedElts = EltMask;
   }
   
   Instruction *I = dyn_cast<Instruction>(V);
-  if (!I) return false;        // Only analyze instructions.
+  if (!I) return 0;        // Only analyze instructions.
   
   bool MadeChange = false;
-  uint64_t UndefElts2;
+  APInt UndefElts2(VWidth, 0);
   Value *TmpV;
   switch (I->getOpcode()) {
   default: break;
@@ -1454,44 +1550,46 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
     // If this is inserting an element that isn't demanded, remove this
     // insertelement.
     unsigned IdxNo = Idx->getZExtValue();
-    if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
+    if (IdxNo >= VWidth || !DemandedElts[IdxNo])
       return AddSoonDeadInstToWorklist(*I, 0);
     
     // Otherwise, the element inserted overwrites whatever was there, so the
     // input demanded set is simpler than the output set.
-    TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
-                                      DemandedElts & ~(1ULL << IdxNo),
+    APInt DemandedElts2 = DemandedElts;
+    DemandedElts2.clear(IdxNo);
+    TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
                                       UndefElts, Depth+1);
     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
 
     // The inserted element is defined.
-    UndefElts &= ~(1ULL << IdxNo);
+    UndefElts.clear(IdxNo);
     break;
   }
   case Instruction::ShuffleVector: {
     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
     uint64_t LHSVWidth =
       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
-    uint64_t LeftDemanded = 0, RightDemanded = 0;
+    APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
     for (unsigned i = 0; i < VWidth; i++) {
-      if (DemandedElts & (1ULL << i)) {
+      if (DemandedElts[i]) {
         unsigned MaskVal = Shuffle->getMaskValue(i);
         if (MaskVal != -1u) {
           assert(MaskVal < LHSVWidth * 2 &&
                  "shufflevector mask index out of range!");
           if (MaskVal < LHSVWidth)
-            LeftDemanded |= 1ULL << MaskVal;
+            LeftDemanded.set(MaskVal);
           else
-            RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
+            RightDemanded.set(MaskVal - LHSVWidth);
         }
       }
     }
 
+    APInt UndefElts4(LHSVWidth, 0);
     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
-                                      UndefElts2, Depth+1);
+                                      UndefElts4, Depth+1);
     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
 
-    uint64_t UndefElts3;
+    APInt UndefElts3(LHSVWidth, 0);
     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
                                       UndefElts3, Depth+1);
     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
@@ -1500,16 +1598,17 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
     for (unsigned i = 0; i < VWidth; i++) {
       unsigned MaskVal = Shuffle->getMaskValue(i);
       if (MaskVal == -1u) {
-        uint64_t NewBit = 1ULL << i;
-        UndefElts |= NewBit;
+        UndefElts.set(i);
       } else if (MaskVal < LHSVWidth) {
-        uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
-        NewUndefElts |= NewBit;
-        UndefElts |= NewBit;
+        if (UndefElts4[MaskVal]) {
+          NewUndefElts = true;
+          UndefElts.set(i);
+        }
       } else {
-        uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
-        NewUndefElts |= NewBit;
-        UndefElts |= NewBit;
+        if (UndefElts3[MaskVal - LHSVWidth]) {
+          NewUndefElts = true;
+          UndefElts.set(i);
+        }
       }
     }
 
@@ -1517,7 +1616,7 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
       // Add additional discovered undefs.
       std::vector<Constant*> Elts;
       for (unsigned i = 0; i < VWidth; ++i) {
-        if (UndefElts & (1ULL << i))
+        if (UndefElts[i])
           Elts.push_back(UndefValue::get(Type::Int32Ty));
         else
           Elts.push_back(ConstantInt::get(Type::Int32Ty,
@@ -1533,7 +1632,7 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
     if (!VTy) break;
     unsigned InVWidth = VTy->getNumElements();
-    uint64_t InputDemandedElts = 0;
+    APInt InputDemandedElts(InVWidth, 0);
     unsigned Ratio;
 
     if (VWidth == InVWidth) {
@@ -1550,8 +1649,8 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
       // elements are live.
       Ratio = VWidth/InVWidth;
       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
-        if (DemandedElts & (1ULL << OutIdx))
-          InputDemandedElts |= 1ULL << (OutIdx/Ratio);
+        if (DemandedElts[OutIdx])
+          InputDemandedElts.set(OutIdx/Ratio);
       }
     } else {
       // Untested so far.
@@ -1562,8 +1661,8 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
       // live.
       Ratio = InVWidth/VWidth;
       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
-        if (DemandedElts & (1ULL << InIdx/Ratio))
-          InputDemandedElts |= 1ULL << InIdx;
+        if (DemandedElts[InIdx/Ratio])
+          InputDemandedElts.set(InIdx);
     }
     
     // div/rem demand all inputs, because they don't want divide by zero.
@@ -1581,8 +1680,8 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
       // then an output element is undef if the corresponding input element is
       // undef.
       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
-        if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
-          UndefElts |= 1ULL << OutIdx;
+        if (UndefElts2[OutIdx/Ratio])
+          UndefElts.set(OutIdx);
     } else if (VWidth < InVWidth) {
       assert(0 && "Unimp");
       // If there are more elements in the source than there are in the result,
@@ -1590,8 +1689,8 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
       // elements are undef.
       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
-        if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
-          UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
+        if (!UndefElts2[InIdx])            // Not undef?
+          UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
     }
     break;
   }
@@ -1657,12 +1756,12 @@ Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
           default: assert(0 && "Case stmts out of sync!");
           case Intrinsic::x86_sse_sub_ss:
           case Intrinsic::x86_sse2_sub_sd:
-            TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
+            TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
                                                         II->getName()), *II);
             break;
           case Intrinsic::x86_sse_mul_ss:
           case Intrinsic::x86_sse2_mul_sd:
-            TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
+            TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
                                                          II->getName()), *II);
             break;
           }
@@ -1976,14 +2075,8 @@ Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
       return ReplaceInstUsesWith(I, RHS);
 
     // X + 0 --> X
-    if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
-      if (RHSC->isNullValue())
-        return ReplaceInstUsesWith(I, LHS);
-    } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
-      if (CFP->isExactlyValue(ConstantFP::getNegativeZero
-                              (I.getType())->getValueAPF()))
-        return ReplaceInstUsesWith(I, LHS);
-    }
+    if (RHSC->isNullValue())
+      return ReplaceInstUsesWith(I, LHS);
 
     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
       // X + (signbit) --> X ^ signbit
@@ -1994,12 +2087,8 @@ Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
       
       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
       // (X & 254)+1 -> (X&254)|1
-      if (!isa<VectorType>(I.getType())) {
-        APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-        if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
-                                 KnownZero, KnownOne))
-          return &I;
-      }
+      if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
+        return &I;
 
       // zext(i1) - 1  ->  select i1, 0, -1
       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
@@ -2245,11 +2334,6 @@ Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
         return SelectInst::Create(SI->getCondition(), A, N);
     }
   }
-  
-  // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
-  if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
-    if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
-      return ReplaceInstUsesWith(I, LHS);
 
   // Check for (add (sext x), y), see if we can merge this into an
   // integer add followed by a sext.
@@ -2287,7 +2371,42 @@ Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
       }
     }
   }
-  
+
+  return Changed ? &I : 0;
+}
+
+Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
+  bool Changed = SimplifyCommutative(I);
+  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
+
+  if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
+    // X + 0 --> X
+    if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
+      if (CFP->isExactlyValue(ConstantFP::getNegativeZero
+                              (I.getType())->getValueAPF()))
+        return ReplaceInstUsesWith(I, LHS);
+    }
+
+    if (isa<PHINode>(LHS))
+      if (Instruction *NV = FoldOpIntoPhi(I))
+        return NV;
+  }
+
+  // -A + B  -->  B - A
+  // -A + -B  -->  -(A + B)
+  if (Value *LHSV = dyn_castFNegVal(LHS))
+    return BinaryOperator::CreateFSub(RHS, LHSV);
+
+  // A + -B  -->  A - B
+  if (!isa<Constant>(RHS))
+    if (Value *V = dyn_castFNegVal(RHS))
+      return BinaryOperator::CreateFSub(LHS, V);
+
+  // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
+  if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
+    if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
+      return ReplaceInstUsesWith(I, LHS);
+
   // Check for (add double (sitofp x), y), see if we can merge this into an
   // integer add followed by a promotion.
   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
@@ -2335,8 +2454,7 @@ Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
 
-  if (Op0 == Op1 &&                        // sub X, X  -> 0
-      !I.getType()->isFPOrFPVector())
+  if (Op0 == Op1)                        // sub X, X  -> 0
     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
 
   // If this is a 'B = x-(-A)', change to B = x+A...
@@ -2397,8 +2515,7 @@ Instruction *InstCombiner::visitSub(BinaryOperator &I) {
     return BinaryOperator::CreateXor(Op0, Op1);
 
   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
-    if (Op1I->getOpcode() == Instruction::Add &&
-        !Op0->getType()->isFPOrFPVector()) {
+    if (Op1I->getOpcode() == Instruction::Add) {
       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
@@ -2415,8 +2532,7 @@ Instruction *InstCombiner::visitSub(BinaryOperator &I) {
       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
       // is not used by anyone else...
       //
-      if (Op1I->getOpcode() == Instruction::Sub &&
-          !Op1I->getType()->isFPOrFPVector()) {
+      if (Op1I->getOpcode() == Instruction::Sub) {
         // Swap the two operands of the subexpr...
         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
         Op1I->setOperand(0, IIOp1);
@@ -2454,18 +2570,17 @@ Instruction *InstCombiner::visitSub(BinaryOperator &I) {
     }
   }
 
-  if (!Op0->getType()->isFPOrFPVector())
-    if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
-      if (Op0I->getOpcode() == Instruction::Add) {
-        if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
-          return ReplaceInstUsesWith(I, Op0I->getOperand(1));
-        else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
-          return ReplaceInstUsesWith(I, Op0I->getOperand(0));
-      } else if (Op0I->getOpcode() == Instruction::Sub) {
-        if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
-          return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
-      }
+  if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
+    if (Op0I->getOpcode() == Instruction::Add) {
+      if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
+        return ReplaceInstUsesWith(I, Op0I->getOperand(1));
+      else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
+        return ReplaceInstUsesWith(I, Op0I->getOperand(0));
+    } else if (Op0I->getOpcode() == Instruction::Sub) {
+      if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
+        return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
     }
+  }
 
   ConstantInt *C1;
   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
@@ -2479,6 +2594,40 @@ Instruction *InstCombiner::visitSub(BinaryOperator &I) {
   return 0;
 }
 
+Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
+  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
+
+  // If this is a 'B = x-(-A)', change to B = x+A...
+  if (Value *V = dyn_castFNegVal(Op1))
+    return BinaryOperator::CreateFAdd(Op0, V);
+
+  if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
+    if (Op1I->getOpcode() == Instruction::FAdd) {
+      if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
+        return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
+      else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
+        return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
+    }
+
+    if (Op1I->hasOneUse()) {
+      // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
+      // is not used by anyone else...
+      //
+      if (Op1I->getOpcode() == Instruction::FSub) {
+        // Swap the two operands of the subexpr...
+        Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
+        Op1I->setOperand(0, IIOp1);
+        Op1I->setOperand(1, IIOp0);
+
+        // Create the new top level fadd instruction...
+        return BinaryOperator::CreateFAdd(Op0, Op1);
+      }
+    }
+  }
+
+  return 0;
+}
+
 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
 /// comparison only checks the sign bit.  If it only checks the sign bit, set
 /// TrueIfSigned if the result of the comparison is true when the input value is
@@ -2513,7 +2662,9 @@ Instruction *InstCombiner::visitMul(BinaryOperator &I) {
   bool Changed = SimplifyCommutative(I);
   Value *Op0 = I.getOperand(0);
 
-  if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
+  // TODO: If Op1 is undef and Op0 is finite, return zero.
+  if (!I.getType()->isFPOrFPVector() &&
+      isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
 
   // Simplify mul instructions with a constant RHS...
@@ -2539,17 +2690,8 @@ Instruction *InstCombiner::visitMul(BinaryOperator &I) {
         return BinaryOperator::CreateShl(Op0,
                  ConstantInt::get(Op0->getType(), Val.logBase2()));
       }
-    } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
-      if (Op1F->isNullValue())
-        return ReplaceInstUsesWith(I, Op1);
-
-      // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
-      // ANSI says we can drop signals, so we can do this anyway." (from GCC)
-      if (Op1F->isExactlyValue(1.0))
-        return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
     } else if (isa<VectorType>(Op1->getType())) {
-      if (isa<ConstantAggregateZero>(Op1))
-        return ReplaceInstUsesWith(I, Op1);
+      // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
 
       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
@@ -2557,9 +2699,6 @@ Instruction *InstCombiner::visitMul(BinaryOperator &I) {
 
         // As above, vector X*splat(1.0) -> X in all defined cases.
         if (Constant *Splat = Op1V->getSplatValue()) {
-          if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
-            if (F->isExactlyValue(1.0))
-              return ReplaceInstUsesWith(I, Op0);
           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
             if (CI->equalsInt(1))
               return ReplaceInstUsesWith(I, Op0);
@@ -2683,6 +2822,45 @@ Instruction *InstCombiner::visitMul(BinaryOperator &I) {
   return Changed ? &I : 0;
 }
 
+Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
+  bool Changed = SimplifyCommutative(I);
+  Value *Op0 = I.getOperand(0);
+
+  // Simplify mul instructions with a constant RHS...
+  if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
+    if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
+      // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
+      // ANSI says we can drop signals, so we can do this anyway." (from GCC)
+      if (Op1F->isExactlyValue(1.0))
+        return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
+    } else if (isa<VectorType>(Op1->getType())) {
+      if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
+        // As above, vector X*splat(1.0) -> X in all defined cases.
+        if (Constant *Splat = Op1V->getSplatValue()) {
+          if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
+            if (F->isExactlyValue(1.0))
+              return ReplaceInstUsesWith(I, Op0);
+        }
+      }
+    }
+
+    // Try to fold constant mul into select arguments.
+    if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
+      if (Instruction *R = FoldOpIntoSelect(I, SI, this))
+        return R;
+
+    if (isa<PHINode>(Op0))
+      if (Instruction *NV = FoldOpIntoPhi(I))
+        return NV;
+  }
+
+  if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
+    if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
+      return BinaryOperator::CreateFMul(Op0v, Op1v);
+
+  return Changed ? &I : 0;
+}
+
 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
 /// instruction.
 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
@@ -2955,11 +3133,6 @@ Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
 
-  // 0 % X == 0 for integer, we don't need to preserve faults!
-  if (Constant *LHS = dyn_cast<Constant>(Op0))
-    if (LHS->isNullValue())
-      return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
-
   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
     if (I.getType()->isFPOrFPVector())
       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
@@ -2985,6 +3158,11 @@ Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
   if (Instruction *common = commonRemTransforms(I))
     return common;
 
+  // 0 % X == 0 for integer, we don't need to preserve faults!
+  if (Constant *LHS = dyn_cast<Constant>(Op0))
+    if (LHS->isNullValue())
+      return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
+
   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
     // X % 0 == undef, we don't need to preserve faults!
     if (RHS->equalsInt(0))
@@ -3003,10 +3181,7 @@ Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
       }
 
       // See if we can fold away this rem instruction.
-      uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
-      APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-      if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
-                               KnownZero, KnownOne))
+      if (SimplifyDemandedInstructionBits(I))
         return &I;
     }
   }
@@ -3787,10 +3962,7 @@ Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
   // See if we can simplify any instructions used by the instruction whose sole 
   // purpose is to compute bits we don't care about.
   if (!isa<VectorType>(I.getType())) {
-    uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
-    APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-    if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
-                             KnownZero, KnownOne))
+    if (SimplifyDemandedInstructionBits(I))
       return &I;
   } else {
     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
@@ -4497,10 +4669,7 @@ Instruction *InstCombiner::visitOr(BinaryOperator &I) {
   // See if we can simplify any instructions used by the instruction whose sole 
   // purpose is to compute bits we don't care about.
   if (!isa<VectorType>(I.getType())) {
-    uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
-    APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-    if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
-                             KnownZero, KnownOne))
+    if (SimplifyDemandedInstructionBits(I))
       return &I;
   } else if (isa<ConstantAggregateZero>(Op1)) {
     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
@@ -4838,10 +5007,7 @@ Instruction *InstCombiner::visitXor(BinaryOperator &I) {
   // See if we can simplify any instructions used by the instruction whose sole 
   // purpose is to compute bits we don't care about.
   if (!isa<VectorType>(I.getType())) {
-    uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
-    APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-    if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
-                             KnownZero, KnownOne))
+    if (SimplifyDemandedInstructionBits(I))
       return &I;
   } else if (isa<ConstantAggregateZero>(Op1)) {
     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
@@ -5142,7 +5308,7 @@ static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
        ++i, ++GTI) {
     Value *Op = *i;
-    uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
+    uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
       if (OpC->isZero()) continue;
       
@@ -5176,10 +5342,11 @@ static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
     // Convert to correct type.
     if (Op->getType() != IntPtrTy) {
       if (Constant *OpC = dyn_cast<Constant>(Op))
-        Op = ConstantExpr::getSExt(OpC, IntPtrTy);
+        Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
       else
-        Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
-                                                 Op->getName()+".c"), I);
+        Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
+                                                                true,
+                                                      Op->getName()+".c"), I);
     }
     if (Size != 1) {
       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
@@ -5233,7 +5400,7 @@ static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
       } else {
-        uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
+        uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
         Offset += Size*CI->getSExtValue();
       }
     } else {
@@ -5249,7 +5416,7 @@ static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
   Value *VariableIdx = GEP->getOperand(i);
   // Determine the scale factor of the variable element.  For example, this is
   // 4 if the variable index is into an array of i32.
-  uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
+  uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
   
   // Verify that there are no other variable indices.  If so, emit the hard way.
   for (++i, ++GTI; i != e; ++i, ++GTI) {
@@ -5263,7 +5430,7 @@ static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
     } else {
-      uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
+      uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
       Offset += Size*CI->getSExtValue();
     }
   }
@@ -5537,68 +5704,74 @@ Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
   // [0, UMAX], but it may still be fractional.  See if it is fractional by
   // casting the FP value to the integer value and back, checking for equality.
   // Don't do this for zero, because -0.0 is not fractional.
-  Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
-  if (!RHS.isZero() &&
-      ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
-    // If we had a comparison against a fractional value, we have to adjust the
-    // compare predicate and sometimes the value.  RHSC is rounded towards zero
-    // at this point.
-    switch (Pred) {
-    default: assert(0 && "Unexpected integer comparison!");
-    case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
-      return ReplaceInstUsesWith(I, ConstantInt::getTrue());
-    case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
-      return ReplaceInstUsesWith(I, ConstantInt::getFalse());
-    case ICmpInst::ICMP_ULE:
-      // (float)int <= 4.4   --> int <= 4
-      // (float)int <= -4.4  --> false
-      if (RHS.isNegative())
-        return ReplaceInstUsesWith(I, ConstantInt::getFalse());
-      break;
-    case ICmpInst::ICMP_SLE:
-      // (float)int <= 4.4   --> int <= 4
-      // (float)int <= -4.4  --> int < -4
-      if (RHS.isNegative())
-        Pred = ICmpInst::ICMP_SLT;
-      break;
-    case ICmpInst::ICMP_ULT:
-      // (float)int < -4.4   --> false
-      // (float)int < 4.4    --> int <= 4
-      if (RHS.isNegative())
-        return ReplaceInstUsesWith(I, ConstantInt::getFalse());
-      Pred = ICmpInst::ICMP_ULE;
-      break;
-    case ICmpInst::ICMP_SLT:
-      // (float)int < -4.4   --> int < -4
-      // (float)int < 4.4    --> int <= 4
-      if (!RHS.isNegative())
-        Pred = ICmpInst::ICMP_SLE;
-      break;
-    case ICmpInst::ICMP_UGT:
-      // (float)int > 4.4    --> int > 4
-      // (float)int > -4.4   --> true
-      if (RHS.isNegative())
-        return ReplaceInstUsesWith(I, ConstantInt::getTrue());
-      break;
-    case ICmpInst::ICMP_SGT:
-      // (float)int > 4.4    --> int > 4
-      // (float)int > -4.4   --> int >= -4
-      if (RHS.isNegative())
-        Pred = ICmpInst::ICMP_SGE;
-      break;
-    case ICmpInst::ICMP_UGE:
-      // (float)int >= -4.4   --> true
-      // (float)int >= 4.4    --> int > 4
-      if (!RHS.isNegative())
+  Constant *RHSInt = LHSUnsigned
+    ? ConstantExpr::getFPToUI(RHSC, IntTy)
+    : ConstantExpr::getFPToSI(RHSC, IntTy);
+  if (!RHS.isZero()) {
+    bool Equal = LHSUnsigned
+      ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
+      : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
+    if (!Equal) {
+      // If we had a comparison against a fractional value, we have to adjust
+      // the compare predicate and sometimes the value.  RHSC is rounded towards
+      // zero at this point.
+      switch (Pred) {
+      default: assert(0 && "Unexpected integer comparison!");
+      case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
-      Pred = ICmpInst::ICMP_UGT;
-      break;
-    case ICmpInst::ICMP_SGE:
-      // (float)int >= -4.4   --> int >= -4
-      // (float)int >= 4.4    --> int > 4
-      if (!RHS.isNegative())
-        Pred = ICmpInst::ICMP_SGT;
-      break;
+      case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
+        return ReplaceInstUsesWith(I, ConstantInt::getFalse());
+      case ICmpInst::ICMP_ULE:
+        // (float)int <= 4.4   --> int <= 4
+        // (float)int <= -4.4  --> false
+        if (RHS.isNegative())
+          return ReplaceInstUsesWith(I, ConstantInt::getFalse());
+        break;
+      case ICmpInst::ICMP_SLE:
+        // (float)int <= 4.4   --> int <= 4
+        // (float)int <= -4.4  --> int < -4
+        if (RHS.isNegative())
+          Pred = ICmpInst::ICMP_SLT;
+        break;
+      case ICmpInst::ICMP_ULT:
+        // (float)int < -4.4   --> false
+        // (float)int < 4.4    --> int <= 4
+        if (RHS.isNegative())
+          return ReplaceInstUsesWith(I, ConstantInt::getFalse());
+        Pred = ICmpInst::ICMP_ULE;
+        break;
+      case ICmpInst::ICMP_SLT:
+        // (float)int < -4.4   --> int < -4
+        // (float)int < 4.4    --> int <= 4
+        if (!RHS.isNegative())
+          Pred = ICmpInst::ICMP_SLE;
+        break;
+      case ICmpInst::ICMP_UGT:
+        // (float)int > 4.4    --> int > 4
+        // (float)int > -4.4   --> true
+        if (RHS.isNegative())
+          return ReplaceInstUsesWith(I, ConstantInt::getTrue());
+        break;
+      case ICmpInst::ICMP_SGT:
+        // (float)int > 4.4    --> int > 4
+        // (float)int > -4.4   --> int >= -4
+        if (RHS.isNegative())
+          Pred = ICmpInst::ICMP_SGE;
+        break;
+      case ICmpInst::ICMP_UGE:
+        // (float)int >= -4.4   --> true
+        // (float)int >= 4.4    --> int > 4
+        if (!RHS.isNegative())
+          return ReplaceInstUsesWith(I, ConstantInt::getTrue());
+        Pred = ICmpInst::ICMP_UGT;
+        break;
+      case ICmpInst::ICMP_SGE:
+        // (float)int >= -4.4   --> int >= -4
+        // (float)int >= 4.4    --> int > 4
+        if (!RHS.isNegative())
+          Pred = ICmpInst::ICMP_SGT;
+        break;
+      }
     }
   }
 
@@ -5783,9 +5956,17 @@ Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
     }
   }
 
+  unsigned BitWidth = 0;
+  if (TD)
+    BitWidth = TD->getTypeSizeInBits(Ty);
+  else if (isa<IntegerType>(Ty))
+    BitWidth = Ty->getPrimitiveSizeInBits();
+
+  bool isSignBit = false;
+
   // See if we are doing a comparison with a constant.
   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
-    Value *A, *B;
+    Value *A = 0, *B = 0;
     
     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
     if (I.isEquality() && CI->isNullValue() &&
@@ -5817,105 +5998,161 @@ Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
     }
     
-    // See if we can fold the comparison based on range information we can get
-    // by checking whether bits are known to be zero or one in the input.
-    uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
-    APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-    
     // If this comparison is a normal comparison, it demands all
     // bits, if it is a sign bit comparison, it only demands the sign bit.
     bool UnusedBit;
-    bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
-    
-    if (SimplifyDemandedBits(Op0, 
+    isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
+  }
+
+  // See if we can fold the comparison based on range information we can get
+  // by checking whether bits are known to be zero or one in the input.
+  if (BitWidth != 0) {
+    APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
+    APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
+
+    if (SimplifyDemandedBits(I.getOperandUse(0),
                              isSignBit ? APInt::getSignBit(BitWidth)
                                        : APInt::getAllOnesValue(BitWidth),
-                             KnownZero, KnownOne, 0))
+                             Op0KnownZero, Op0KnownOne, 0))
       return &I;
-        
+    if (SimplifyDemandedBits(I.getOperandUse(1),
+                             APInt::getAllOnesValue(BitWidth),
+                             Op1KnownZero, Op1KnownOne, 0))
+      return &I;
+
     // Given the known and unknown bits, compute a range that the LHS could be
     // in.  Compute the Min, Max and RHS values based on the known bits. For the
     // EQ and NE we use unsigned values.
-    APInt Min(BitWidth, 0), Max(BitWidth, 0);
-    if (ICmpInst::isSignedPredicate(I.getPredicate()))
-      ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
-    else
-      ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
-    
+    APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
+    APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
+    if (ICmpInst::isSignedPredicate(I.getPredicate())) {
+      ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
+                                             Op0Min, Op0Max);
+      ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
+                                             Op1Min, Op1Max);
+    } else {
+      ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
+                                               Op0Min, Op0Max);
+      ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
+                                               Op1Min, Op1Max);
+    }
+
     // If Min and Max are known to be the same, then SimplifyDemandedBits
     // figured out that the LHS is a constant.  Just constant fold this now so
     // that code below can assume that Min != Max.
-    if (Min == Max)
-      return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
-                                                          ConstantInt::get(Min),
-                                                          CI));
-    
+    if (!isa<Constant>(Op0) && Op0Min == Op0Max)
+      return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
+    if (!isa<Constant>(Op1) && Op1Min == Op1Max)
+      return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
+
     // Based on the range information we know about the LHS, see if we can
     // simplify this comparison.  For example, (x&4) < 8  is always true.
-    const APInt &RHSVal = CI->getValue();
-    switch (I.getPredicate()) {  // LE/GE have been folded already.
+    switch (I.getPredicate()) {
     default: assert(0 && "Unknown icmp opcode!");
     case ICmpInst::ICMP_EQ:
-      if (Max.ult(RHSVal) || Min.ugt(RHSVal))
+      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
       break;
     case ICmpInst::ICMP_NE:
-      if (Max.ult(RHSVal) || Min.ugt(RHSVal))
+      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
       break;
     case ICmpInst::ICMP_ULT:
-      if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
+      if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
-      if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
+      if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
-      if (RHSVal == Max)                      // A <u MAX -> A != MAX
+      if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
-      if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
-        return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
-        
-      // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
-      if (CI->isMinValue(true))
-        return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
+      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
+        if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
+          return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
+
+        // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
+        if (CI->isMinValue(true))
+          return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
                             ConstantInt::getAllOnesValue(Op0->getType()));
+      }
       break;
     case ICmpInst::ICMP_UGT:
-      if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
+      if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
-      if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
+      if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
-        
-      if (RHSVal == Min)                      // A >u MIN -> A != MIN
+
+      if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
-      if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
-        return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
-      
-      // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
-      if (CI->isMaxValue(true))
-        return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
-                            ConstantInt::getNullValue(Op0->getType()));
+      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
+        if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
+          return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
+
+        // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
+        if (CI->isMaxValue(true))
+          return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
+                              ConstantInt::getNullValue(Op0->getType()));
+      }
       break;
     case ICmpInst::ICMP_SLT:
-      if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
+      if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
-      if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
+      if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
-      if (RHSVal == Max)                      // A <s MAX -> A != MAX
+      if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
-      if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
-        return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
+      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
+        if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
+          return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
+      }
       break;
-    case ICmpInst::ICMP_SGT: 
-      if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
+    case ICmpInst::ICMP_SGT:
+      if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
-      if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
+      if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
-        
-      if (RHSVal == Min)                      // A >s MIN -> A != MIN
+
+      if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
-      if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
-        return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
+      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
+        if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
+          return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
+      }
+      break;
+    case ICmpInst::ICMP_SGE:
+      assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
+      if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
+        return ReplaceInstUsesWith(I, ConstantInt::getTrue());
+      if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
+        return ReplaceInstUsesWith(I, ConstantInt::getFalse());
+      break;
+    case ICmpInst::ICMP_SLE:
+      assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
+      if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
+        return ReplaceInstUsesWith(I, ConstantInt::getTrue());
+      if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
+        return ReplaceInstUsesWith(I, ConstantInt::getFalse());
+      break;
+    case ICmpInst::ICMP_UGE:
+      assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
+      if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
+        return ReplaceInstUsesWith(I, ConstantInt::getTrue());
+      if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
+        return ReplaceInstUsesWith(I, ConstantInt::getFalse());
+      break;
+    case ICmpInst::ICMP_ULE:
+      assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
+      if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
+        return ReplaceInstUsesWith(I, ConstantInt::getTrue());
+      if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
+        return ReplaceInstUsesWith(I, ConstantInt::getFalse());
       break;
     }
+
+    // Turn a signed comparison into an unsigned one if both operands
+    // are known to have the same sign.
+    if (I.isSignedPredicate() &&
+        ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
+         (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
+      return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
   }
 
   // Test if the ICmpInst instruction is used exclusively by a select as
@@ -6062,18 +6299,39 @@ Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
-          Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
-          I.isEquality()) {
+          Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
         switch (Op0I->getOpcode()) {
         default: break;
         case Instruction::Add:
         case Instruction::Sub:
         case Instruction::Xor:
-          // a+x icmp eq/ne b+x --> a icmp b
-          return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
-                              Op1I->getOperand(0));
+          if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
+            return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
+                                Op1I->getOperand(0));
+          // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
+          if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
+            if (CI->getValue().isSignBit()) {
+              ICmpInst::Predicate Pred = I.isSignedPredicate()
+                                             ? I.getUnsignedPredicate()
+                                             : I.getSignedPredicate();
+              return new ICmpInst(Pred, Op0I->getOperand(0),
+                                  Op1I->getOperand(0));
+            }
+            
+            if (CI->getValue().isMaxSignedValue()) {
+              ICmpInst::Predicate Pred = I.isSignedPredicate()
+                                             ? I.getUnsignedPredicate()
+                                             : I.getSignedPredicate();
+              Pred = I.getSwappedPredicate(Pred);
+              return new ICmpInst(Pred, Op0I->getOperand(0),
+                                  Op1I->getOperand(0));
+            }
+          }
           break;
         case Instruction::Mul:
+          if (!I.isEquality())
+            break;
+
           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
             // Mask = -1 >> count-trailing-zeros(Cst).
@@ -6343,6 +6601,28 @@ Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
   const APInt &RHSV = RHS->getValue();
   
   switch (LHSI->getOpcode()) {
+  case Instruction::Trunc:
+    if (ICI.isEquality() && LHSI->hasOneUse()) {
+      // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
+      // of the high bits truncated out of x are known.
+      unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
+             SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
+      APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
+      APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
+      ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
+      
+      // If all the high bits are known, we can do this xform.
+      if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
+        // Pull in the high bits from known-ones set.
+        APInt NewRHS(RHS->getValue());
+        NewRHS.zext(SrcBits);
+        NewRHS |= KnownOne;
+        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
+                            ConstantInt::get(NewRHS));
+      }
+    }
+    break;
+      
   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
@@ -6370,6 +6650,29 @@ Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
         else
           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
       }
+
+      if (LHSI->hasOneUse()) {
+        // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
+        if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
+          const APInt &SignBit = XorCST->getValue();
+          ICmpInst::Predicate Pred = ICI.isSignedPredicate()
+                                         ? ICI.getUnsignedPredicate()
+                                         : ICI.getSignedPredicate();
+          return new ICmpInst(Pred, LHSI->getOperand(0),
+                              ConstantInt::get(RHSV ^ SignBit));
+        }
+
+        // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
+        if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
+          const APInt &NotSignBit = XorCST->getValue();
+          ICmpInst::Predicate Pred = ICI.isSignedPredicate()
+                                         ? ICI.getUnsignedPredicate()
+                                         : ICI.getSignedPredicate();
+          Pred = ICI.getSwappedPredicate(Pred);
+          return new ICmpInst(Pred, LHSI->getOperand(0),
+                              ConstantInt::get(RHSV ^ NotSignBit));
+        }
+      }
     }
     break;
   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
@@ -6471,7 +6774,7 @@ Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
       // of a loop if Y is invariant and X is not.
       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
           ICI.isEquality() && !Shift->isArithmeticShift() &&
-          isa<Instruction>(Shift->getOperand(0))) {
+          !isa<Constant>(Shift->getOperand(0))) {
         // Compute C << Y.
         Value *NS;
         if (Shift->getOpcode() == Instruction::LShr) {
@@ -6765,29 +7068,6 @@ Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
         return &ICI;
       }
     }
-  } else {  // Not a ICMP_EQ/ICMP_NE
-            // If the LHS is a cast from an integral value of the same size, 
-            // then since we know the RHS is a constant, try to simlify.
-    if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
-      Value *CastOp = Cast->getOperand(0);
-      const Type *SrcTy = CastOp->getType();
-      uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
-      if (SrcTy->isInteger() && 
-          SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
-        // If this is an unsigned comparison, try to make the comparison use
-        // smaller constant values.
-        if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
-          // X u< 128 => X s> -1
-          return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
-                           ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
-        } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
-                   RHSV == APInt::getSignedMaxValue(SrcTySize)) {
-          // X u> 127 => X s< 0
-          return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
-                              Constant::getNullValue(SrcTy));
-        }
-      }
-    }
   }
   return 0;
 }
@@ -6947,11 +7227,17 @@ Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
       return ReplaceInstUsesWith(I, CSI);
   
   // See if we can turn a signed shr into an unsigned shr.
-  if (!isa<VectorType>(I.getType()) &&
-      MaskedValueIsZero(Op0,
+  if (!isa<VectorType>(I.getType())) {
+    if (MaskedValueIsZero(Op0,
                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
-    return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
-  
+      return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
+
+    // Arithmetic shifting an all-sign-bit value is a no-op.
+    unsigned NumSignBits = ComputeNumSignBits(Op0);
+    if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
+      return ReplaceInstUsesWith(I, Op0);
+  }
+
   return 0;
 }
 
@@ -6978,6 +7264,10 @@ Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
   }
 
+  // See if we can fold away this shift.
+  if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
+    return &I;
+
   // Try to fold constant and into select arguments.
   if (isa<Constant>(Op0))
     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
@@ -6992,15 +7282,11 @@ Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
 
 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
                                                BinaryOperator &I) {
-  bool isLeftShift    = I.getOpcode() == Instruction::Shl;
+  bool isLeftShift = I.getOpcode() == Instruction::Shl;
 
   // See if we can simplify any instructions used by the instruction whose sole 
   // purpose is to compute bits we don't care about.
   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
-  APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
-  if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
-                           KnownZero, KnownOne))
-    return &I;
   
   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
   // of a signed value.
@@ -7221,22 +7507,34 @@ Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
     Value *X = ShiftOp->getOperand(0);
     
     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
-    if (AmtSum > TypeBits)
-      AmtSum = TypeBits;
     
     const IntegerType *Ty = cast<IntegerType>(I.getType());
     
     // Check for (X << c1) << c2  and  (X >> c1) >> c2
     if (I.getOpcode() == ShiftOp->getOpcode()) {
+      // If this is oversized composite shift, then unsigned shifts get 0, ashr
+      // saturates.
+      if (AmtSum >= TypeBits) {
+        if (I.getOpcode() != Instruction::AShr)
+          return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
+        AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
+      }
+      
       return BinaryOperator::Create(I.getOpcode(), X,
                                     ConstantInt::get(Ty, AmtSum));
     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
                I.getOpcode() == Instruction::AShr) {
+      if (AmtSum >= TypeBits)
+        return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
+      
       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
                I.getOpcode() == Instruction::LShr) {
       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
+      if (AmtSum >= TypeBits)
+        AmtSum = TypeBits-1;
+      
       Instruction *Shift =
         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
       InsertNewInstBefore(Shift, I);
@@ -7417,11 +7715,13 @@ Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
 
   // If the allocation has multiple uses, only promote it if we are strictly
   // increasing the alignment of the resultant allocation.  If we keep it the
-  // same, we open the door to infinite loops of various kinds.
-  if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
+  // same, we open the door to infinite loops of various kinds.  (A reference
+  // from a dbg.declare doesn't count as a use for this purpose.)
+  if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
+      CastElTyAlign == AllocElTyAlign) return 0;
 
-  uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
-  uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
+  uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
+  uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
 
   // See if we can satisfy the modulus by pulling a scale out of the array
@@ -7446,7 +7746,7 @@ Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
     if (isa<ConstantInt>(NumElements))
       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
     // otherwise multiply the amount and the number of elements
-    else if (Scale != 1) {
+    else {
       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
       Amt = InsertNewInstBefore(Tmp, AI);
     }
@@ -7466,10 +7766,15 @@ Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
   InsertNewInstBefore(New, AI);
   New->takeName(&AI);
   
-  // If the allocation has multiple uses, insert a cast and change all things
-  // that used it to use the new cast.  This will also hack on CI, but it will
-  // die soon.
-  if (!AI.hasOneUse()) {
+  // If the allocation has one real use plus a dbg.declare, just remove the
+  // declare.
+  if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
+    EraseInstFromFunction(*DI);
+  }
+  // If the allocation has multiple real uses, insert a cast and change all
+  // things that used it to use the new cast.  This will also hack on CI, but it
+  // will die soon.
+  else if (!AI.hasOneUse()) {
     AddUsesToWorkList(AI);
     // New is the allocation instruction, pointer typed. AI is the original
     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
@@ -7500,7 +7805,7 @@ Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
 /// the final result.
 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
                                               unsigned CastOpc,
-                                              int &NumCastsRemoved) {
+                                              int &NumCastsRemoved){
   // We can always evaluate constants in another type.
   if (isa<ConstantInt>(V))
     return true;
@@ -7528,7 +7833,8 @@ bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
   // require duplicating the instruction in general, which isn't profitable.
   if (!I->hasOneUse()) return false;
 
-  switch (I->getOpcode()) {
+  unsigned Opc = I->getOpcode();
+  switch (Opc) {
   case Instruction::Add:
   case Instruction::Sub:
   case Instruction::Mul:
@@ -7574,7 +7880,11 @@ bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
     // If this is the same kind of case as our original (e.g. zext+zext), we
     // can safely replace it.  Note that replacing it does not reduce the number
     // of casts in the input.
-    if (I->getOpcode() == CastOpc)
+    if (Opc == CastOpc)
+      return true;
+
+    // sext (zext ty1), ty2 -> zext ty2
+    if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
       return true;
     break;
   case Instruction::Select: {
@@ -7612,7 +7922,8 @@ Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
   // Otherwise, it must be an instruction.
   Instruction *I = cast<Instruction>(V);
   Instruction *Res = 0;
-  switch (I->getOpcode()) {
+  unsigned Opc = I->getOpcode();
+  switch (Opc) {
   case Instruction::Add:
   case Instruction::Sub:
   case Instruction::Mul:
@@ -7624,8 +7935,7 @@ Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
   case Instruction::Shl: {
     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
-    Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
-                                 LHS, RHS);
+    Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
     break;
   }    
   case Instruction::Trunc:
@@ -7695,6 +8005,66 @@ Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
   return 0;
 }
 
+/// FindElementAtOffset - Given a type and a constant offset, determine whether
+/// or not there is a sequence of GEP indices into the type that will land us at
+/// the specified offset.  If so, fill them into NewIndices and return the
+/// resultant element type, otherwise return null.
+static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
+                                       SmallVectorImpl<Value*> &NewIndices,
+                                       const TargetData *TD) {
+  if (!Ty->isSized()) return 0;
+  
+  // Start with the index over the outer type.  Note that the type size
+  // might be zero (even if the offset isn't zero) if the indexed type
+  // is something like [0 x {int, int}]
+  const Type *IntPtrTy = TD->getIntPtrType();
+  int64_t FirstIdx = 0;
+  if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
+    FirstIdx = Offset/TySize;
+    Offset -= FirstIdx*TySize;
+    
+    // Handle hosts where % returns negative instead of values [0..TySize).
+    if (Offset < 0) {
+      --FirstIdx;
+      Offset += TySize;
+      assert(Offset >= 0);
+    }
+    assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
+  }
+  
+  NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
+    
+  // Index into the types.  If we fail, set OrigBase to null.
+  while (Offset) {
+    // Indexing into tail padding between struct/array elements.
+    if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
+      return 0;
+    
+    if (const StructType *STy = dyn_cast<StructType>(Ty)) {
+      const StructLayout *SL = TD->getStructLayout(STy);
+      assert(Offset < (int64_t)SL->getSizeInBytes() &&
+             "Offset must stay within the indexed type");
+      
+      unsigned Elt = SL->getElementContainingOffset(Offset);
+      NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
+      
+      Offset -= SL->getElementOffset(Elt);
+      Ty = STy->getElementType(Elt);
+    } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
+      uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
+      assert(EltSize && "Cannot index into a zero-sized array");
+      NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
+      Offset %= EltSize;
+      Ty = AT->getElementType();
+    } else {
+      // Otherwise, we can't index into the middle of this atomic type, bail.
+      return 0;
+    }
+  }
+  
+  return Ty;
+}
+
 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
   Value *Src = CI.getOperand(0);
@@ -7725,74 +8095,21 @@ Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
         const Type *GEPIdxTy =
           cast<PointerType>(OrigBase->getType())->getElementType();
-        if (GEPIdxTy->isSized()) {
-          SmallVector<Value*, 8> NewIndices;
-          
-          // Start with the index over the outer type.  Note that the type size
-          // might be zero (even if the offset isn't zero) if the indexed type
-          // is something like [0 x {int, int}]
-          const Type *IntPtrTy = TD->getIntPtrType();
-          int64_t FirstIdx = 0;
-          if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
-            FirstIdx = Offset/TySize;
-            Offset %= TySize;
+        SmallVector<Value*, 8> NewIndices;
+        if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
+          // If we were able to index down into an element, create the GEP
+          // and bitcast the result.  This eliminates one bitcast, potentially
+          // two.
+          Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
+                                                        NewIndices.begin(),
+                                                        NewIndices.end(), "");
+          InsertNewInstBefore(NGEP, CI);
+          NGEP->takeName(GEP);
           
-            // Handle silly modulus not returning values values [0..TySize).
-            if (Offset < 0) {
-              --FirstIdx;
-              Offset += TySize;
-              assert(Offset >= 0);
-            }
-            assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
-          }
-          
-          NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
-
-          // Index into the types.  If we fail, set OrigBase to null.
-          while (Offset) {
-            if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
-              const StructLayout *SL = TD->getStructLayout(STy);
-              if (Offset < (int64_t)SL->getSizeInBytes()) {
-                unsigned Elt = SL->getElementContainingOffset(Offset);
-                NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
-              
-                Offset -= SL->getElementOffset(Elt);
-                GEPIdxTy = STy->getElementType(Elt);
-              } else {
-                // Otherwise, we can't index into this, bail out.
-                Offset = 0;
-                OrigBase = 0;
-              }
-            } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
-              const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
-              if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
-                NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
-                Offset %= EltSize;
-              } else {
-                NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
-              }
-              GEPIdxTy = STy->getElementType();
-            } else {
-              // Otherwise, we can't index into this, bail out.
-              Offset = 0;
-              OrigBase = 0;
-            }
-          }
-          if (OrigBase) {
-            // If we were able to index down into an element, create the GEP
-            // and bitcast the result.  This eliminates one bitcast, potentially
-            // two.
-            Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
-                                                          NewIndices.begin(),
-                                                          NewIndices.end(), "");
-            InsertNewInstBefore(NGEP, CI);
-            NGEP->takeName(GEP);
-            
-            if (isa<BitCastInst>(CI))
-              return new BitCastInst(NGEP, CI.getType());
-            assert(isa<PtrToIntInst>(CI));
-            return new PtrToIntInst(NGEP, CI.getType());
-          }
+          if (isa<BitCastInst>(CI))
+            return new BitCastInst(NGEP, CI.getType());
+          assert(isa<PtrToIntInst>(CI));
+          return new PtrToIntInst(NGEP, CI.getType());
         }
       }      
     }
@@ -7801,7 +8118,22 @@ Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
   return commonCastTransforms(CI);
 }
 
-
+/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
+/// type like i42.  We don't want to introduce operations on random non-legal
+/// integer types where they don't already exist in the code.  In the future,
+/// we should consider making this based off target-data, so that 32-bit targets
+/// won't get i64 operations etc.
+static bool isSafeIntegerType(const Type *Ty) {
+  switch (Ty->getPrimitiveSizeInBits()) {
+  case 8:
+  case 16:
+  case 32:
+  case 64:
+    return true;
+  default: 
+    return false;
+  }
+}
 
 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
 /// integer types. This function implements the common transforms for all those
@@ -7819,9 +8151,7 @@ Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
 
   // See if we can simplify any instructions used by the LHS whose sole 
   // purpose is to compute bits we don't care about.
-  APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
-  if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
-                           KnownZero, KnownOne))
+  if (SimplifyDemandedInstructionBits(CI))
     return &CI;
 
   // If the source isn't an instruction or has more than one use then we
@@ -7833,6 +8163,10 @@ Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
   // Attempt to propagate the cast into the instruction for int->int casts.
   int NumCastsRemoved = 0;
   if (!isa<BitCastInst>(CI) &&
+      // Only do this if the dest type is a simple type, don't convert the
+      // expression tree to something weird like i93 unless the source is also
+      // strange.
+      (isSafeIntegerType(DestTy) || !isSafeIntegerType(SrcI->getType())) &&
       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
                                  CI.getOpcode(), NumCastsRemoved)) {
     // If this cast is a truncate, evaluting in a different type always
@@ -7841,7 +8175,8 @@ Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
     // so we require that the input have eliminated at least one cast.  If this
     // is a sign extension, we insert two new casts (to do the extension) so we
     // require that two casts have been eliminated.
-    bool DoXForm;
+    bool DoXForm = false;
+    bool JustReplace = false;
     switch (CI.getOpcode()) {
     default:
       // All the others use floating point so we shouldn't actually 
@@ -7850,17 +8185,56 @@ Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
     case Instruction::Trunc:
       DoXForm = true;
       break;
-    case Instruction::ZExt:
+    case Instruction::ZExt: {
       DoXForm = NumCastsRemoved >= 1;
+      if (!DoXForm && 0) {
+        // If it's unnecessary to issue an AND to clear the high bits, it's
+        // always profitable to do this xform.
+        Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
+        APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
+        if (MaskedValueIsZero(TryRes, Mask))
+          return ReplaceInstUsesWith(CI, TryRes);
+        
+        if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
+          if (TryI->use_empty())
+            EraseInstFromFunction(*TryI);
+      }
       break;
-    case Instruction::SExt:
+    }
+    case Instruction::SExt: {
       DoXForm = NumCastsRemoved >= 2;
+      if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
+        // If we do not have to emit the truncate + sext pair, then it's always
+        // profitable to do this xform.
+        //
+        // It's not safe to eliminate the trunc + sext pair if one of the
+        // eliminated cast is a truncate. e.g.
+        // t2 = trunc i32 t1 to i16
+        // t3 = sext i16 t2 to i32
+        // !=
+        // i32 t1
+        Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
+        unsigned NumSignBits = ComputeNumSignBits(TryRes);
+        if (NumSignBits > (DestBitSize - SrcBitSize))
+          return ReplaceInstUsesWith(CI, TryRes);
+        
+        if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
+          if (TryI->use_empty())
+            EraseInstFromFunction(*TryI);
+      }
       break;
     }
+    }
     
     if (DoXForm) {
+      DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
+           << " cast: " << CI;
       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
                                            CI.getOpcode() == Instruction::SExt);
+      if (JustReplace)
+        // Just replace this cast with the result.
+        return ReplaceInstUsesWith(CI, Res);
+
       assert(Res->getType() == DestTy);
       switch (CI.getOpcode()) {
       default: assert(0 && "Unknown cast type!");
@@ -7869,18 +8243,32 @@ Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
         // Just replace this cast with the result.
         return ReplaceInstUsesWith(CI, Res);
       case Instruction::ZExt: {
-        // We need to emit an AND to clear the high bits.
         assert(SrcBitSize < DestBitSize && "Not a zext?");
+
+        // If the high bits are already zero, just replace this cast with the
+        // result.
+        APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
+        if (MaskedValueIsZero(Res, Mask))
+          return ReplaceInstUsesWith(CI, Res);
+
+        // We need to emit an AND to clear the high bits.
         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
                                                             SrcBitSize));
         return BinaryOperator::CreateAnd(Res, C);
       }
-      case Instruction::SExt:
+      case Instruction::SExt: {
+        // If the high bits are already filled with sign bit, just replace this
+        // cast with the result.
+        unsigned NumSignBits = ComputeNumSignBits(Res);
+        if (NumSignBits > (DestBitSize - SrcBitSize))
+          return ReplaceInstUsesWith(CI, Res);
+
         // We need to emit a cast to truncate, then a cast to sext.
         return CastInst::Create(Instruction::SExt,
             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
                              CI), DestTy);
       }
+      }
     }
   }
   
@@ -7979,49 +8367,33 @@ Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
   const Type *Ty = CI.getType();
   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
-  
-  if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
-    switch (SrcI->getOpcode()) {
-    default: break;
-    case Instruction::LShr:
-      // We can shrink lshr to something smaller if we know the bits shifted in
-      // are already zeros.
-      if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
-        uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
-        
-        // Get a mask for the bits shifting in.
-        APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
-        Value* SrcIOp0 = SrcI->getOperand(0);
-        if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
-          if (ShAmt >= DestBitWidth)        // All zeros.
-            return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
-
-          // Okay, we can shrink this.  Truncate the input, then return a new
-          // shift.
-          Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
-          Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
-                                       Ty, CI);
-          return BinaryOperator::CreateLShr(V1, V2);
-        }
-      } else {     // This is a variable shr.
-        
-        // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
-        // more LLVM instructions, but allows '1 << Y' to be hoisted if
-        // loop-invariant and CSE'd.
-        if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
-          Value *One = ConstantInt::get(SrcI->getType(), 1);
-
-          Value *V = InsertNewInstBefore(
-              BinaryOperator::CreateShl(One, SrcI->getOperand(1),
-                                     "tmp"), CI);
-          V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
-                                                            SrcI->getOperand(0),
-                                                            "tmp"), CI);
-          Value *Zero = Constant::getNullValue(V->getType());
-          return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
-        }
-      }
-      break;
+
+  // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
+  if (DestBitWidth == 1) {
+    Constant *One = ConstantInt::get(Src->getType(), 1);
+    Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
+    Value *Zero = Constant::getNullValue(Src->getType());
+    return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
+  }
+  
+  // Optimize trunc(lshr(), c) to pull the shift through the truncate.
+  ConstantInt *ShAmtV = 0;
+  Value *ShiftOp = 0;
+  if (Src->hasOneUse() &&
+      match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
+    uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
+    
+    // Get a mask for the bits shifting in.
+    APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
+    if (MaskedValueIsZero(ShiftOp, Mask)) {
+      if (ShAmt >= DestBitWidth)        // All zeros.
+        return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
+      
+      // Okay, we can shrink this.  Truncate the input, then return a new
+      // shift.
+      Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
+      Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
+      return BinaryOperator::CreateLShr(V1, V2);
     }
   }
   
@@ -8130,32 +8502,35 @@ Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
 
   Value *Src = CI.getOperand(0);
 
-  // If this is a cast of a cast
-  if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
-    // If this is a TRUNC followed by a ZEXT then we are dealing with integral
-    // types and if the sizes are just right we can convert this into a logical
-    // 'and' which will be much cheaper than the pair of casts.
-    if (isa<TruncInst>(CSrc)) {
-      // Get the sizes of the types involved
-      Value *A = CSrc->getOperand(0);
-      uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
-      uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
-      uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
-      // If we're actually extending zero bits and the trunc is a no-op
-      if (MidSize < DstSize && SrcSize == DstSize) {
-        // Replace both of the casts with an And of the type mask.
-        APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
-        Constant *AndConst = ConstantInt::get(AndValue);
-        Instruction *And = 
-          BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
-        // Unfortunately, if the type changed, we need to cast it back.
-        if (And->getType() != CI.getType()) {
-          And->setName(CSrc->getName()+".mask");
-          InsertNewInstBefore(And, CI);
-          And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
-        }
-        return And;
-      }
+  // If this is a TRUNC followed by a ZEXT then we are dealing with integral
+  // types and if the sizes are just right we can convert this into a logical
+  // 'and' which will be much cheaper than the pair of casts.
+  if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
+    // Get the sizes of the types involved.  We know that the intermediate type
+    // will be smaller than A or C, but don't know the relation between A and C.
+    Value *A = CSrc->getOperand(0);
+    unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
+    unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
+    unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
+    // If we're actually extending zero bits, then if
+    // SrcSize <  DstSize: zext(a & mask)
+    // SrcSize == DstSize: a & mask
+    // SrcSize  > DstSize: trunc(a) & mask
+    if (SrcSize < DstSize) {
+      APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
+      Constant *AndConst = ConstantInt::get(AndValue);
+      Instruction *And =
+        BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
+      InsertNewInstBefore(And, CI);
+      return new ZExtInst(And, CI.getType());
+    } else if (SrcSize == DstSize) {
+      APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
+      return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
+    } else if (SrcSize > DstSize) {
+      Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
+      InsertNewInstBefore(Trunc, CI);
+      APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
+      return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
     }
   }
 
@@ -8293,17 +8668,17 @@ Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
   if (Instruction *I = commonCastTransforms(CI))
     return I;
   
-  // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
+  // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
   // smaller than the destination type, we can eliminate the truncate by doing
-  // the add as the smaller type.  This applies to add/sub/mul/div as well as
+  // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
   // many builtins (sqrt, etc).
   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
   if (OpI && OpI->hasOneUse()) {
     switch (OpI->getOpcode()) {
     default: break;
-    case Instruction::Add:
-    case Instruction::Sub:
-    case Instruction::Mul:
+    case Instruction::FAdd:
+    case Instruction::FSub:
+    case Instruction::FMul:
     case Instruction::FDiv:
     case Instruction::FRem:
       const Type *SrcTy = OpI->getType();
@@ -8381,11 +8756,36 @@ Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
   return commonCastTransforms(CI);
 }
 
-Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
+Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
+  // If the destination integer type is smaller than the intptr_t type for
+  // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
+  // trunc to be exposed to other transforms.  Don't do this for extending
+  // ptrtoint's, because we don't know if the target sign or zero extends its
+  // pointers.
+  if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
+    Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
+                                                    TD->getIntPtrType(),
+                                                    "tmp"), CI);
+    return new TruncInst(P, CI.getType());
+  }
+  
   return commonPointerCastTransforms(CI);
 }
 
 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
+  // If the source integer type is larger than the intptr_t type for
+  // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
+  // allows the trunc to be exposed to other transforms.  Don't do this for
+  // extending inttoptr's, because we don't know if the target sign or zero
+  // extends to pointers.
+  if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
+      TD->getPointerSizeInBits()) {
+    Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
+                                                 TD->getIntPtrType(),
+                                                 "tmp"), CI);
+    return new IntToPtrInst(P, CI.getType());
+  }
+  
   if (Instruction *I = commonCastTransforms(CI))
     return I;
   
@@ -8401,7 +8801,7 @@ Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
     // is a single-index GEP.
     if (X->getType() == CI.getType()) {
       // Get the size of the pointee type.
-      uint64_t Size = TD->getABITypeSize(DestPointee);
+      uint64_t Size = TD->getTypeAllocSize(DestPointee);
 
       // Convert the constant to intptr type.
       APInt Offset = Cst->getValue();
@@ -8421,7 +8821,7 @@ Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
     // "inttoptr+GEP" instead of "add+intptr".
     
     // Get the size of the pointee type.
-    uint64_t Size = TD->getABITypeSize(DestPointee);
+    uint64_t Size = TD->getTypeAllocSize(DestPointee);
     
     // Convert the constant to intptr type.
     APInt Offset = Cst->getValue();
@@ -8649,6 +9049,83 @@ Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
   return 0;
 }
 
+static bool isSelect01(Constant *C1, Constant *C2) {
+  ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
+  if (!C1I)
+    return false;
+  ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
+  if (!C2I)
+    return false;
+  return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
+}
+
+/// FoldSelectIntoOp - Try fold the select into one of the operands to
+/// facilitate further optimization.
+Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
+                                            Value *FalseVal) {
+  // See the comment above GetSelectFoldableOperands for a description of the
+  // transformation we are doing here.
+  if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
+    if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
+        !isa<Constant>(FalseVal)) {
+      if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
+        unsigned OpToFold = 0;
+        if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
+          OpToFold = 1;
+        } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
+          OpToFold = 2;
+        }
+
+        if (OpToFold) {
+          Constant *C = GetSelectFoldableConstant(TVI);
+          Value *OOp = TVI->getOperand(2-OpToFold);
+          // Avoid creating select between 2 constants unless it's selecting
+          // between 0 and 1.
+          if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
+            Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
+            InsertNewInstBefore(NewSel, SI);
+            NewSel->takeName(TVI);
+            if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
+              return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
+            assert(0 && "Unknown instruction!!");
+          }
+        }
+      }
+    }
+  }
+
+  if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
+    if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
+        !isa<Constant>(TrueVal)) {
+      if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
+        unsigned OpToFold = 0;
+        if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
+          OpToFold = 1;
+        } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
+          OpToFold = 2;
+        }
+
+        if (OpToFold) {
+          Constant *C = GetSelectFoldableConstant(FVI);
+          Value *OOp = FVI->getOperand(2-OpToFold);
+          // Avoid creating select between 2 constants unless it's selecting
+          // between 0 and 1.
+          if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
+            Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
+            InsertNewInstBefore(NewSel, SI);
+            NewSel->takeName(FVI);
+            if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
+              return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
+            assert(0 && "Unknown instruction!!");
+          }
+        }
+      }
+    }
+  }
+
+  return 0;
+}
+
 /// visitSelectInstWithICmp - Visit a SelectInst that has an
 /// ICmpInst as its first operand.
 ///
@@ -8951,11 +9428,15 @@ Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
 
         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
         // even legal for FP.
-        if (TI->getOpcode() == Instruction::Sub &&
-            FI->getOpcode() == Instruction::Add) {
+        if ((TI->getOpcode() == Instruction::Sub &&
+             FI->getOpcode() == Instruction::Add) ||
+            (TI->getOpcode() == Instruction::FSub &&
+             FI->getOpcode() == Instruction::FAdd)) {
           AddOp = FI; SubOp = TI;
-        } else if (FI->getOpcode() == Instruction::Sub &&
-                   TI->getOpcode() == Instruction::Add) {
+        } else if ((FI->getOpcode() == Instruction::Sub &&
+                    TI->getOpcode() == Instruction::Add) ||
+                   (FI->getOpcode() == Instruction::FSub &&
+                    TI->getOpcode() == Instruction::FAdd)) {
           AddOp = TI; SubOp = FI;
         }
 
@@ -8994,58 +9475,9 @@ Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
 
   // See if we can fold the select into one of our operands.
   if (SI.getType()->isInteger()) {
-    // See the comment above GetSelectFoldableOperands for a description of the
-    // transformation we are doing here.
-    if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
-      if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
-          !isa<Constant>(FalseVal))
-        if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
-          unsigned OpToFold = 0;
-          if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
-            OpToFold = 1;
-          } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
-            OpToFold = 2;
-          }
-
-          if (OpToFold) {
-            Constant *C = GetSelectFoldableConstant(TVI);
-            Instruction *NewSel =
-              SelectInst::Create(SI.getCondition(),
-                                 TVI->getOperand(2-OpToFold), C);
-            InsertNewInstBefore(NewSel, SI);
-            NewSel->takeName(TVI);
-            if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
-              return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
-            else {
-              assert(0 && "Unknown instruction!!");
-            }
-          }
-        }
-
-    if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
-      if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
-          !isa<Constant>(TrueVal))
-        if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
-          unsigned OpToFold = 0;
-          if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
-            OpToFold = 1;
-          } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
-            OpToFold = 2;
-          }
-
-          if (OpToFold) {
-            Constant *C = GetSelectFoldableConstant(FVI);
-            Instruction *NewSel =
-              SelectInst::Create(SI.getCondition(), C,
-                                 FVI->getOperand(2-OpToFold));
-            InsertNewInstBefore(NewSel, SI);
-            NewSel->takeName(FVI);
-            if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
-              return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
-            else
-              assert(0 && "Unknown instruction!!");
-          }
-        }
+    Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
+    if (FoldI)
+      return FoldI;
   }
 
   if (BinaryOperator::isNot(CondVal)) {
@@ -9096,15 +9528,23 @@ static unsigned EnforceKnownAlignment(Value *V,
     // If there is a large requested alignment and we can, bump up the alignment
     // of the global.
     if (!GV->isDeclaration()) {
-      GV->setAlignment(PrefAlign);
-      Align = PrefAlign;
+      if (GV->getAlignment() >= PrefAlign)
+        Align = GV->getAlignment();
+      else {
+        GV->setAlignment(PrefAlign);
+        Align = PrefAlign;
+      }
     }
   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
     // If there is a requested alignment and if this is an alloca, round up.  We
     // don't do this for malloc, because some systems can't respect the request.
     if (isa<AllocaInst>(AI)) {
-      AI->setAlignment(PrefAlign);
-      Align = PrefAlign;
+      if (AI->getAlignment() >= PrefAlign)
+        Align = AI->getAlignment();
+      else {
+        AI->setAlignment(PrefAlign);
+        Align = PrefAlign;
+      }
     }
   }
 
@@ -9136,10 +9576,10 @@ Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
   unsigned MinAlign = std::min(DstAlign, SrcAlign);
-  unsigned CopyAlign = MI->getAlignment()->getZExtValue();
+  unsigned CopyAlign = MI->getAlignment();
 
   if (CopyAlign < MinAlign) {
-    MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
+    MI->setAlignment(MinAlign);
     return MI;
   }
   
@@ -9211,8 +9651,8 @@ Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
 
 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
-  if (MI->getAlignment()->getZExtValue() < Alignment) {
-    MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
+  if (MI->getAlignment() < Alignment) {
+    MI->setAlignment(Alignment);
     return MI;
   }
   
@@ -9222,7 +9662,7 @@ Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
     return 0;
   uint64_t Len = LenC->getZExtValue();
-  Alignment = MI->getAlignment()->getZExtValue();
+  Alignment = MI->getAlignment();
   
   // If the length is zero, this is a no-op
   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
@@ -9256,6 +9696,16 @@ Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
 /// the heavy lifting.
 ///
 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
+  // If the caller function is nounwind, mark the call as nounwind, even if the
+  // callee isn't.
+  if (CI.getParent()->getParent()->doesNotThrow() &&
+      !CI.doesNotThrow()) {
+    CI.setDoesNotThrow();
+    return &CI;
+  }
+  
+  
+  
   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
   if (!II) return visitCallSite(&CI);
   
@@ -9298,7 +9748,7 @@ Instruction *InstCombiner::visitCallInst(CallInst &CI) {
 
     // If we can determine a pointer alignment that is bigger than currently
     // set, update the alignment.
-    if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
+    if (isa<MemTransferInst>(MI)) {
       if (Instruction *I = SimplifyMemTransfer(MI))
         return I;
     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
@@ -9356,8 +9806,11 @@ Instruction *InstCombiner::visitCallInst(CallInst &CI) {
   case Intrinsic::x86_sse_cvttss2si: {
     // These intrinsics only demands the 0th element of its input vector.  If
     // we can simplify the input based on that, do so now.
-    uint64_t UndefElts;
-    if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
+    unsigned VWidth =
+      cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
+    APInt DemandedElts(VWidth, 1);
+    APInt UndefElts(VWidth, 0);
+    if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
                                               UndefElts)) {
       II->setOperand(1, V);
       return II;
@@ -9486,7 +9939,7 @@ static bool isSafeToEliminateVarargsCast(const CallSite CS,
   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
   if (!SrcTy->isSized() || !DstTy->isSized())
     return false;
-  if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
+  if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
     return false;
   return true;
 }
@@ -10025,6 +10478,9 @@ Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
   
   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
                                         FirstInst->op_end());
+  // This is true if all GEP bases are allocas and if all indices into them are
+  // constants.
+  bool AllBasePointersAreAllocas = true;
   
   // Scan to see if all operands are the same opcode, all have one use, and all
   // kill their operands (i.e. the operands have one use).
@@ -10034,6 +10490,12 @@ Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
       GEP->getNumOperands() != FirstInst->getNumOperands())
       return 0;
 
+    // Keep track of whether or not all GEPs are of alloca pointers.
+    if (AllBasePointersAreAllocas &&
+        (!isa<AllocaInst>(GEP->getOperand(0)) ||
+         !GEP->hasAllConstantIndices()))
+      AllBasePointersAreAllocas = false;
+    
     // Compare the operand lists.
     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
       if (FirstInst->getOperand(op) == GEP->getOperand(op))
@@ -10054,6 +10516,15 @@ Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
     }
   }
   
+  // If all of the base pointers of the PHI'd GEPs are from allocas, don't
+  // bother doing this transformation.  At best, this will just save a bit of
+  // offset calculation, but all the predecessors will have to materialize the
+  // stack address into a register anyway.  We'd actually rather *clone* the
+  // load up into the predecessors so that we have a load of a gep of an alloca,
+  // which can usually all be folded into the load.
+  if (AllBasePointersAreAllocas)
+    return 0;
+  
   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
   // that is variable.
   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
@@ -10092,15 +10563,15 @@ Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
 }
 
 
-/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
-/// of the block that defines it.  This means that it must be obvious the value
-/// of the load is not changed from the point of the load to the end of the
-/// block it is in.
+/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
+/// sink the load out of the block that defines it.  This means that it must be
+/// obvious the value of the load is not changed from the point of the load to
+/// the end of the block it is in.
 ///
 /// Finally, it is safe, but not profitable, to sink a load targetting a
 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
 /// to a register.
-static bool isSafeToSinkLoad(LoadInst *L) {
+static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
   BasicBlock::iterator BBI = L, E = L->getParent()->end();
   
   for (++BBI; BBI != E; ++BBI)
@@ -10122,10 +10593,20 @@ static bool isSafeToSinkLoad(LoadInst *L) {
       break;
     }
     
-    if (!isAddressTaken)
+    if (!isAddressTaken && AI->isStaticAlloca())
       return false;
   }
   
+  // If this load is a load from a GEP with a constant offset from an alloca,
+  // then we don't want to sink it.  In its present form, it will be
+  // load [constant stack offset].  Sinking it will cause us to have to
+  // materialize the stack addresses in each predecessor in a register only to
+  // do a shared load from register in the successor.
+  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
+    if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
+      if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
+        return false;
+  
   return true;
 }
 
@@ -10156,7 +10637,7 @@ Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
     // We can't sink the load if the loaded value could be modified between the
     // load and the PHI.
     if (LI->getParent() != PN.getIncomingBlock(0) ||
-        !isSafeToSinkLoad(LI))
+        !isSafeAndProfitableToSinkLoad(LI))
       return 0;
     
     // If the PHI is of volatile loads and the load block has multiple
@@ -10186,7 +10667,7 @@ Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
       // the load and the PHI.
       if (LI->isVolatile() != isVolatile ||
           LI->getParent() != PN.getIncomingBlock(i) ||
-          !isSafeToSinkLoad(LI))
+          !isSafeAndProfitableToSinkLoad(LI))
         return 0;
       
       // If the PHI is of volatile loads and the load block has multiple
@@ -10195,7 +10676,6 @@ Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
       if (isVolatile &&
           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
         return 0;
-
       
     } else if (I->getOperand(1) != ConstantOp) {
       return 0;
@@ -10464,28 +10944,6 @@ Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
   }
   if (MadeChange) return &GEP;
 
-  // If this GEP instruction doesn't move the pointer, and if the input operand
-  // is a bitcast of another pointer, just replace the GEP with a bitcast of the
-  // real input to the dest type.
-  if (GEP.hasAllZeroIndices()) {
-    if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
-      // If the bitcast is of an allocation, and the allocation will be
-      // converted to match the type of the cast, don't touch this.
-      if (isa<AllocationInst>(BCI->getOperand(0))) {
-        // See if the bitcast simplifies, if so, don't nuke this GEP yet.
-        if (Instruction *I = visitBitCast(*BCI)) {
-          if (I != BCI) {
-            I->takeName(BCI);
-            BCI->getParent()->getInstList().insert(BCI, I);
-            ReplaceInstUsesWith(*BCI, I);
-          }
-          return &GEP;
-        }
-      }
-      return new BitCastInst(BCI->getOperand(0), GEP.getType());
-    }
-  }
-  
   // Combine Indices - If the source pointer to this getelementptr instruction
   // is a getelementptr instruction, combine the indices of the two
   // getelementptr instructions into a single instruction.
@@ -10601,15 +11059,25 @@ Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
       // into     : GEP [10 x i8]* X, i32 0, ...
       //
+      // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
+      //           into     : GEP i8* X, ...
+      // 
       // This occurs when the program declares an array extern like "int X[];"
-      //
       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
       const PointerType *XTy = cast<PointerType>(X->getType());
-      if (const ArrayType *XATy =
-          dyn_cast<ArrayType>(XTy->getElementType()))
-        if (const ArrayType *CATy =
-            dyn_cast<ArrayType>(CPTy->getElementType()))
+      if (const ArrayType *CATy =
+          dyn_cast<ArrayType>(CPTy->getElementType())) {
+        // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
+        if (CATy->getElementType() == XTy->getElementType()) {
+          // -> GEP i8* X, ...
+          SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
+          return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
+                                           GEP.getName());
+        } else if (const ArrayType *XATy =
+                 dyn_cast<ArrayType>(XTy->getElementType())) {
+          // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
           if (CATy->getElementType() == XATy->getElementType()) {
+            // -> GEP [10 x i8]* X, i32 0, ...
             // At this point, we know that the cast source type is a pointer
             // to an array of the same type as the destination pointer
             // array.  Because the array type is never stepped over (there
@@ -10617,6 +11085,8 @@ Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
             GEP.setOperand(0, X);
             return &GEP;
           }
+        }
+      }
     } else if (GEP.getNumOperands() == 2) {
       // Transform things like:
       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
@@ -10624,8 +11094,8 @@ Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
       if (isa<ArrayType>(SrcElTy) &&
-          TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
-          TD->getABITypeSize(ResElTy)) {
+          TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
+          TD->getTypeAllocSize(ResElTy)) {
         Value *Idx[2];
         Idx[0] = Constant::getNullValue(Type::Int32Ty);
         Idx[1] = GEP.getOperand(1);
@@ -10642,7 +11112,7 @@ Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
       
       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
         uint64_t ArrayEltSize =
-            TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
+            TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
         
         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
         // allow either a mul, shift, or constant here.
@@ -10672,7 +11142,7 @@ Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
         // out, perform the transformation. Note, we don't know whether Scale is
         // signed or not. We'll use unsigned version of division/modulo
         // operation after making sure Scale doesn't have the sign bit set.
-        if (Scale && Scale->getSExtValue() >= 0LL &&
+        if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
             Scale->getZExtValue() % ArrayEltSize == 0) {
           Scale = ConstantInt::get(Scale->getType(),
                                    Scale->getZExtValue() / ArrayEltSize);
@@ -10696,7 +11166,56 @@ Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
       }
     }
   }
-
+  
+  /// See if we can simplify:
+  ///   X = bitcast A to B*
+  ///   Y = gep X, <...constant indices...>
+  /// into a gep of the original struct.  This is important for SROA and alias
+  /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
+  if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
+    if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
+      // Determine how much the GEP moves the pointer.  We are guaranteed to get
+      // a constant back from EmitGEPOffset.
+      ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
+      int64_t Offset = OffsetV->getSExtValue();
+      
+      // If this GEP instruction doesn't move the pointer, just replace the GEP
+      // with a bitcast of the real input to the dest type.
+      if (Offset == 0) {
+        // If the bitcast is of an allocation, and the allocation will be
+        // converted to match the type of the cast, don't touch this.
+        if (isa<AllocationInst>(BCI->getOperand(0))) {
+          // See if the bitcast simplifies, if so, don't nuke this GEP yet.
+          if (Instruction *I = visitBitCast(*BCI)) {
+            if (I != BCI) {
+              I->takeName(BCI);
+              BCI->getParent()->getInstList().insert(BCI, I);
+              ReplaceInstUsesWith(*BCI, I);
+            }
+            return &GEP;
+          }
+        }
+        return new BitCastInst(BCI->getOperand(0), GEP.getType());
+      }
+      
+      // Otherwise, if the offset is non-zero, we need to find out if there is a
+      // field at Offset in 'A's type.  If so, we can pull the cast through the
+      // GEP.
+      SmallVector<Value*, 8> NewIndices;
+      const Type *InTy =
+        cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
+      if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
+        Instruction *NGEP =
+           GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
+                                     NewIndices.end());
+        if (NGEP->getType() == GEP.getType()) return NGEP;
+        InsertNewInstBefore(NGEP, GEP);
+        NGEP->takeName(&GEP);
+        return new BitCastInst(NGEP, GEP.getType());
+      }
+    }
+  }    
+    
   return 0;
 }
 
@@ -10719,10 +11238,10 @@ Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
       InsertNewInstBefore(New, AI);
 
       // Scan to the end of the allocation instructions, to skip over a block of
-      // allocas if possible...
+      // allocas if possible...also skip interleaved debug info
       //
       BasicBlock::iterator It = New;
-      while (isa<AllocationInst>(*It)) ++It;
+      while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
 
       // Now that I is pointing to the first non-allocation-inst in the block,
       // insert our getelementptr instruction...
@@ -10742,12 +11261,17 @@ Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
     }
   }
 
-  // If alloca'ing a zero byte object, replace the alloca with a null pointer.
-  // Note that we only do this for alloca's, because malloc should allocate and
-  // return a unique pointer, even for a zero byte allocation.
-  if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
-      TD->getABITypeSize(AI.getAllocatedType()) == 0)
-    return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
+  if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
+    // If alloca'ing a zero byte object, replace the alloca with a null pointer.
+    // Note that we only do this for alloca's, because malloc should allocate
+    // and return a unique pointer, even for a zero byte allocation.
+    if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
+      return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
+
+    // If the alignment is 0 (unspecified), assign it the preferred alignment.
+    if (AI.getAlignment() == 0)
+      AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
+  }
 
   return 0;
 }
@@ -10800,40 +11324,48 @@ static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
   User *CI = cast<User>(LI.getOperand(0));
   Value *CastOp = CI->getOperand(0);
 
-  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
-    // Instead of loading constant c string, use corresponding integer value
-    // directly if string length is small enough.
-    std::string Str;
-    if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
-      unsigned len = Str.length();
-      const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
-      unsigned numBits = Ty->getPrimitiveSizeInBits();
-      // Replace LI with immediate integer store.
-      if ((numBits >> 3) == len + 1) {
-        APInt StrVal(numBits, 0);
-        APInt SingleChar(numBits, 0);
-        if (TD->isLittleEndian()) {
-          for (signed i = len-1; i >= 0; i--) {
-            SingleChar = (uint64_t) Str[i];
-            StrVal = (StrVal << 8) | SingleChar;
-          }
-        } else {
-          for (unsigned i = 0; i < len; i++) {
-            SingleChar = (uint64_t) Str[i];
+  if (TD) {
+    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
+      // Instead of loading constant c string, use corresponding integer value
+      // directly if string length is small enough.
+      std::string Str;
+      if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
+        unsigned len = Str.length();
+        const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
+        unsigned numBits = Ty->getPrimitiveSizeInBits();
+        // Replace LI with immediate integer store.
+        if ((numBits >> 3) == len + 1) {
+          APInt StrVal(numBits, 0);
+          APInt SingleChar(numBits, 0);
+          if (TD->isLittleEndian()) {
+            for (signed i = len-1; i >= 0; i--) {
+              SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
+              StrVal = (StrVal << 8) | SingleChar;
+            }
+          } else {
+            for (unsigned i = 0; i < len; i++) {
+              SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
+              StrVal = (StrVal << 8) | SingleChar;
+            }
+            // Append NULL at the end.
+            SingleChar = 0;
             StrVal = (StrVal << 8) | SingleChar;
           }
-          // Append NULL at the end.
-          SingleChar = 0;
-          StrVal = (StrVal << 8) | SingleChar;
+          Value *NL = ConstantInt::get(StrVal);
+          return IC.ReplaceInstUsesWith(LI, NL);
         }
-        Value *NL = ConstantInt::get(StrVal);
-        return IC.ReplaceInstUsesWith(LI, NL);
       }
     }
   }
 
-  const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
+  const PointerType *DestTy = cast<PointerType>(CI->getType());
+  const Type *DestPTy = DestTy->getElementType();
   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
+
+    // If the address spaces don't match, don't eliminate the cast.
+    if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
+      return 0;
+
     const Type *SrcPTy = SrcTy->getElementType();
 
     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
@@ -10898,7 +11430,8 @@ static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
 
     // If we see a free or a call (which might do a free) the pointer could be
     // marked invalid.
-    if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
+    if (isa<FreeInst>(BBI) || 
+        (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
       return false;
     
     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
@@ -10915,7 +11448,8 @@ Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
   Value *Op = LI.getOperand(0);
 
   // Attempt to improve the alignment.
-  unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
+  unsigned KnownAlign =
+    GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
   if (KnownAlign >
       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
                                 LI.getAlignment()))
@@ -10966,14 +11500,14 @@ Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
 
     // Instcombine load (constant global) into the value loaded.
     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
-      if (GV->isConstant() && !GV->isDeclaration())
+      if (GV->isConstant() && GV->hasDefinitiveInitializer())
         return ReplaceInstUsesWith(LI, GV->getInitializer());
 
     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
       if (CE->getOpcode() == Instruction::GetElementPtr) {
         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
-          if (GV->isConstant() && !GV->isDeclaration())
+          if (GV->isConstant() && GV->hasDefinitiveInitializer())
             if (Constant *V = 
                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
               return ReplaceInstUsesWith(LI, V);
@@ -10997,7 +11531,7 @@ Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
   // If this load comes from anywhere in a constant global, and if the global
   // is all undef or zero, we know what it loads.
   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
-    if (GV->isConstant() && GV->hasInitializer()) {
+    if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
       if (GV->getInitializer()->isNullValue())
         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
       else if (isa<UndefValue>(GV->getInitializer()))
@@ -11046,67 +11580,106 @@ Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
 }
 
 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
-/// when possible.
+/// when possible.  This makes it generally easy to do alias analysis and/or
+/// SROA/mem2reg of the memory object.
 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
   User *CI = cast<User>(SI.getOperand(1));
   Value *CastOp = CI->getOperand(0);
 
   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
-  if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
-    const Type *SrcPTy = SrcTy->getElementType();
-
-    if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
-      // If the source is an array, the code below will not succeed.  Check to
-      // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
-      // constants.
-      if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
-        if (Constant *CSrc = dyn_cast<Constant>(CastOp))
-          if (ASrcTy->getNumElements() != 0) {
-            Value* Idxs[2];
-            Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
-            CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
-            SrcTy = cast<PointerType>(CastOp->getType());
-            SrcPTy = SrcTy->getElementType();
-          }
-
-      if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
-          IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
-               IC.getTargetData().getTypeSizeInBits(DestPTy)) {
+  const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
+  if (SrcTy == 0) return 0;
+  
+  const Type *SrcPTy = SrcTy->getElementType();
 
-        // Okay, we are casting from one integer or pointer type to another of
-        // the same size.  Instead of casting the pointer before 
-        // the store, cast the value to be stored.
-        Value *NewCast;
-        Value *SIOp0 = SI.getOperand(0);
-        Instruction::CastOps opcode = Instruction::BitCast;
-        const Type* CastSrcTy = SIOp0->getType();
-        const Type* CastDstTy = SrcPTy;
-        if (isa<PointerType>(CastDstTy)) {
-          if (CastSrcTy->isInteger())
-            opcode = Instruction::IntToPtr;
-        } else if (isa<IntegerType>(CastDstTy)) {
-          if (isa<PointerType>(SIOp0->getType()))
-            opcode = Instruction::PtrToInt;
-        }
-        if (Constant *C = dyn_cast<Constant>(SIOp0))
-          NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
-        else
-          NewCast = IC.InsertNewInstBefore(
-            CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
-            SI);
-        return new StoreInst(NewCast, CastOp);
+  if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
+    return 0;
+  
+  /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
+  /// to its first element.  This allows us to handle things like:
+  ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
+  /// on 32-bit hosts.
+  SmallVector<Value*, 4> NewGEPIndices;
+  
+  // If the source is an array, the code below will not succeed.  Check to
+  // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
+  // constants.
+  if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
+    // Index through pointer.
+    Constant *Zero = Constant::getNullValue(Type::Int32Ty);
+    NewGEPIndices.push_back(Zero);
+    
+    while (1) {
+      if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
+        if (!STy->getNumElements()) /* Struct can be empty {} */
+          break;
+        NewGEPIndices.push_back(Zero);
+        SrcPTy = STy->getElementType(0);
+      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
+        NewGEPIndices.push_back(Zero);
+        SrcPTy = ATy->getElementType();
+      } else {
+        break;
       }
     }
+    
+    SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
   }
-  return 0;
+
+  if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
+    return 0;
+  
+  // If the pointers point into different address spaces or if they point to
+  // values with different sizes, we can't do the transformation.
+  if (SrcTy->getAddressSpace() != 
+        cast<PointerType>(CI->getType())->getAddressSpace() ||
+      IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
+      IC.getTargetData().getTypeSizeInBits(DestPTy))
+    return 0;
+
+  // Okay, we are casting from one integer or pointer type to another of
+  // the same size.  Instead of casting the pointer before 
+  // the store, cast the value to be stored.
+  Value *NewCast;
+  Value *SIOp0 = SI.getOperand(0);
+  Instruction::CastOps opcode = Instruction::BitCast;
+  const Type* CastSrcTy = SIOp0->getType();
+  const Type* CastDstTy = SrcPTy;
+  if (isa<PointerType>(CastDstTy)) {
+    if (CastSrcTy->isInteger())
+      opcode = Instruction::IntToPtr;
+  } else if (isa<IntegerType>(CastDstTy)) {
+    if (isa<PointerType>(SIOp0->getType()))
+      opcode = Instruction::PtrToInt;
+  }
+  
+  // SIOp0 is a pointer to aggregate and this is a store to the first field,
+  // emit a GEP to index into its first field.
+  if (!NewGEPIndices.empty()) {
+    if (Constant *C = dyn_cast<Constant>(CastOp))
+      CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
+                                              NewGEPIndices.size());
+    else
+      CastOp = IC.InsertNewInstBefore(
+              GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
+                                        NewGEPIndices.end()), SI);
+  }
+  
+  if (Constant *C = dyn_cast<Constant>(SIOp0))
+    NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
+  else
+    NewCast = IC.InsertNewInstBefore(
+      CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
+      SI);
+  return new StoreInst(NewCast, CastOp);
 }
 
 /// equivalentAddressValues - Test if A and B will obviously have the same
 /// value. This includes recognizing that %t0 and %t1 will have the same
 /// value in code like this:
-///   %t0 = getelementptr @a, 0, 3
+///   %t0 = getelementptr \@a, 0, 3
 ///   store i32 0, i32* %t0
-///   %t1 = getelementptr @a, 0, 3
+///   %t1 = getelementptr \@a, 0, 3
 ///   %t2 = load i32* %t1
 ///
 static bool equivalentAddressValues(Value *A, Value *B) {
@@ -11126,6 +11699,23 @@ static bool equivalentAddressValues(Value *A, Value *B) {
   return false;
 }
 
+// If this instruction has two uses, one of which is a llvm.dbg.declare,
+// return the llvm.dbg.declare.
+DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
+  if (!V->hasNUses(2))
+    return 0;
+  for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
+       UI != E; ++UI) {
+    if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
+      return DI;
+    if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
+      if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
+        return DI;
+      }
+  }
+  return 0;
+}
+
 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
   Value *Val = SI.getOperand(0);
   Value *Ptr = SI.getOperand(1);
@@ -11138,36 +11728,65 @@ Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
   
   // If the RHS is an alloca with a single use, zapify the store, making the
   // alloca dead.
-  if (Ptr->hasOneUse() && !SI.isVolatile()) {
-    if (isa<AllocaInst>(Ptr)) {
-      EraseInstFromFunction(SI);
-      ++NumCombined;
-      return 0;
-    }
-    
-    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
-      if (isa<AllocaInst>(GEP->getOperand(0)) &&
-          GEP->getOperand(0)->hasOneUse()) {
+  // If the RHS is an alloca with a two uses, the other one being a 
+  // llvm.dbg.declare, zapify the store and the declare, making the
+  // alloca dead.  We must do this to prevent declare's from affecting
+  // codegen.
+  if (!SI.isVolatile()) {
+    if (Ptr->hasOneUse()) {
+      if (isa<AllocaInst>(Ptr)) {
         EraseInstFromFunction(SI);
         ++NumCombined;
         return 0;
       }
+      if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
+        if (isa<AllocaInst>(GEP->getOperand(0))) {
+          if (GEP->getOperand(0)->hasOneUse()) {
+            EraseInstFromFunction(SI);
+            ++NumCombined;
+            return 0;
+          }
+          if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
+            EraseInstFromFunction(*DI);
+            EraseInstFromFunction(SI);
+            ++NumCombined;
+            return 0;
+          }
+        }
+      }
+    }
+    if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
+      EraseInstFromFunction(*DI);
+      EraseInstFromFunction(SI);
+      ++NumCombined;
+      return 0;
+    }
   }
 
   // Attempt to improve the alignment.
-  unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
+  unsigned KnownAlign =
+    GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
   if (KnownAlign >
       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
                                 SI.getAlignment()))
     SI.setAlignment(KnownAlign);
 
-  // Do really simple DSE, to catch cases where there are several consequtive
+  // Do really simple DSE, to catch cases where there are several consecutive
   // stores to the same location, separated by a few arithmetic operations. This
   // situation often occurs with bitfield accesses.
   BasicBlock::iterator BBI = &SI;
   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
        --ScanInsts) {
     --BBI;
+    // Don't count debug info directives, lest they affect codegen,
+    // and we skip pointer-to-pointer bitcasts, which are NOPs.
+    // It is necessary for correctness to skip those that feed into a
+    // llvm.dbg.declare, as these are not present when debugging is off.
+    if (isa<DbgInfoIntrinsic>(BBI) ||
+        (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
+      ScanInsts++;
+      continue;
+    }    
     
     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
       // Prev store isn't volatile, and stores to the same location?
@@ -11233,9 +11852,15 @@ Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
         return Res;
 
   
-  // If this store is the last instruction in the basic block, and if the block
-  // ends with an unconditional branch, try to move it to the successor block.
-  BBI = &SI; ++BBI;
+  // If this store is the last instruction in the basic block (possibly
+  // excepting debug info instructions and the pointer bitcasts that feed
+  // into them), and if the block ends with an unconditional branch, try
+  // to move it to the successor block.
+  BBI = &SI; 
+  do {
+    ++BBI;
+  } while (isa<DbgInfoIntrinsic>(BBI) ||
+           (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
     if (BI->isUnconditional())
       if (SimplifyStoreAtEndOfBlock(SI))
@@ -11293,8 +11918,15 @@ bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
   // else' case.  there is an instruction before the branch.
   StoreInst *OtherStore = 0;
   if (OtherBr->isUnconditional()) {
-    // If this isn't a store, or isn't a store to the same location, bail out.
     --BBI;
+    // Skip over debugging info.
+    while (isa<DbgInfoIntrinsic>(BBI) ||
+           (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
+      if (BBI==OtherBB->begin())
+        return false;
+      --BBI;
+    }
+    // If this isn't a store, or isn't a store to the same location, bail out.
     OtherStore = dyn_cast<StoreInst>(BBI);
     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
       return false;
@@ -11660,10 +12292,10 @@ Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
     // If the input vector has a single use, simplify it based on this use
     // property.
     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
-      uint64_t UndefElts;
+      APInt UndefElts(VectorWidth, 0);
+      APInt DemandedMask(VectorWidth, 1 << IndexVal);
       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
-                                                1 << IndexVal,
-                                                UndefElts)) {
+                                                DemandedMask, UndefElts)) {
         EI.setOperand(0, V);
         return &EI;
       }
@@ -11947,6 +12579,12 @@ Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
     }
   }
 
+  unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
+  APInt UndefElts(VWidth, 0);
+  APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
+  if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
+    return &IE;
+
   return 0;
 }
 
@@ -11962,15 +12600,14 @@ Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
   if (isa<UndefValue>(SVI.getOperand(2)))
     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
 
-  uint64_t UndefElts;
   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
 
   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
     return 0;
 
-  uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
-  if (VWidth <= 64 &&
-      SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
+  APInt UndefElts(VWidth, 0);
+  APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
+  if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
     LHS = SVI.getOperand(0);
     RHS = SVI.getOperand(1);
     MadeChange = true;
@@ -12047,9 +12684,11 @@ Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
       // If the result mask is equal to the src shuffle or this shuffle mask, do
       // the replacement.
       if (NewMask == LHSMask || NewMask == Mask) {
+        unsigned LHSInNElts =
+          cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
         std::vector<Constant*> Elts;
         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
-          if (NewMask[i] >= e*2) {
+          if (NewMask[i] >= LHSInNElts*2) {
             Elts.push_back(UndefValue::get(Type::Int32Ty));
           } else {
             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
@@ -12076,7 +12715,7 @@ static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
   assert(I->hasOneUse() && "Invariants didn't hold!");
 
   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
-  if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
+  if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
     return false;
 
   // Do not sink alloca instructions out of the entry block.
@@ -12095,6 +12734,7 @@ static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
 
   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
 
+  CopyPrecedingStopPoint(I, InsertPos);
   I->moveBefore(InsertPos);
   ++NumSunkInst;
   return true;
@@ -12157,6 +12797,8 @@ static void AddReachableCodeToWorklist(BasicBlock *BB,
           DBI_Prev->eraseFromParent();
         }
         DBI_Prev = DBI_Next;
+      } else {
+        DBI_Prev = 0;
       }
 
       IC.AddToWorkList(Inst);
@@ -12217,8 +12859,12 @@ bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
           BasicBlock::iterator I = Term; --I;
 
           DOUT << "IC: DCE: " << *I;
-          ++NumDeadInst;
-
+          // A debug intrinsic shouldn't force another iteration if we weren't
+          // going to do one without it.
+          if (!isa<DbgInfoIntrinsic>(I)) {
+            ++NumDeadInst;
+            Changed = true;
+          }
           if (!I->use_empty())
             I->replaceAllUsesWith(UndefValue::get(I->getType()));
           I->eraseFromParent();
@@ -12241,6 +12887,7 @@ bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
 
       I->eraseFromParent();
       RemoveFromWorkList(I);
+      Changed = true;
       continue;
     }
 
@@ -12255,17 +12902,21 @@ bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
       ++NumConstProp;
       I->eraseFromParent();
       RemoveFromWorkList(I);
+      Changed = true;
       continue;
     }
 
-    if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
+    if (TD &&
+        (I->getType()->getTypeID() == Type::VoidTyID ||
+         I->isTrapping())) {
       // See if we can constant fold its operands.
-      for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
-        if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
+      for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
+        if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
-            i->set(NewC);
-        }
-      }
+            if (NewC != CE) {
+              i->set(NewC);
+              Changed = true;
+            }
     }
 
     // See if we can trivially sink this instruction to a successor basic block.
@@ -12382,5 +13033,3 @@ bool InstCombiner::runOnFunction(Function &F) {
 FunctionPass *llvm::createInstructionCombiningPass() {
   return new InstCombiner();
 }
-
-