Delete a store whose input is a load from the same pointer:
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
index 5b5a70edb6e62a067d288b07758f172c2099dd63..242fffd180284b8978a5ae1fa477ace21b6e3ca8 100644 (file)
@@ -9,22 +9,6 @@
 //
 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
 // both before and after the DAG is legalized.
-//
-// FIXME: Missing folds
-// sdiv, udiv, srem, urem (X, const) where X is an integer can be expanded into
-//  a sequence of multiplies, shifts, and adds.  This should be controlled by
-//  some kind of hint from the target that int div is expensive.
-// various folds of mulh[s,u] by constants such as -1, powers of 2, etc.
-//
-// FIXME: select C, pow2, pow2 -> something smart
-// FIXME: trunc(select X, Y, Z) -> select X, trunc(Y), trunc(Z)
-// FIXME: Dead stores -> nuke
-// FIXME: shr X, (and Y,31) -> shr X, Y   (TRICKY!)
-// FIXME: mul (x, const) -> shifts + adds
-// FIXME: undef values
-// FIXME: divide by zero is currently left unfolded.  do we want to turn this
-//        into an undef?
-// FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
 // 
 //===----------------------------------------------------------------------===//
 
@@ -157,7 +141,7 @@ namespace {
     /// it can be simplified or if things it uses can be simplified by bit
     /// propagation.  If so, return true.
     bool SimplifyDemandedBits(SDOperand Op, uint64_t Demanded = ~0ULL) {
-      TargetLowering::TargetLoweringOpt TLO(DAG);
+      TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
       uint64_t KnownZero, KnownOne;
       Demanded &= MVT::getIntVTBitMask(Op.getValueType());
       if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
@@ -280,6 +264,8 @@ namespace {
     SDOperand XformToShuffleWithZero(SDNode *N);
     SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
     
+    SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
+
     bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
     SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
     SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
@@ -1306,15 +1292,17 @@ SDOperand DAGCombiner::visitSREM(SDNode *N) {
       DAG.MaskedValueIsZero(N0, SignBit))
     return DAG.getNode(ISD::UREM, VT, N0, N1);
   
-  // Unconditionally lower X%C -> X-X/C*C.  This allows the X/C logic to hack on
-  // the remainder operation.
+  // If X/C can be simplified by the division-by-constant logic, lower
+  // X%C to the equivalent of X-X/C*C.
   if (N1C && !N1C->isNullValue()) {
     SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
-    SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
-    SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
-    AddToWorkList(Div.Val);
-    AddToWorkList(Mul.Val);
-    return Sub;
+    SDOperand OptimizedDiv = combine(Div.Val);
+    if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
+      SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
+      SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
+      AddToWorkList(Mul.Val);
+      return Sub;
+    }
   }
   
   // undef % X -> 0
@@ -1351,15 +1339,17 @@ SDOperand DAGCombiner::visitUREM(SDNode *N) {
     }
   }
   
-  // Unconditionally lower X%C -> X-X/C*C.  This allows the X/C logic to hack on
-  // the remainder operation.
+  // If X/C can be simplified by the division-by-constant logic, lower
+  // X%C to the equivalent of X-X/C*C.
   if (N1C && !N1C->isNullValue()) {
     SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
-    SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
-    SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
-    AddToWorkList(Div.Val);
-    AddToWorkList(Mul.Val);
-    return Sub;
+    SDOperand OptimizedDiv = combine(Div.Val);
+    if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
+      SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
+      SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
+      AddToWorkList(Mul.Val);
+      return Sub;
+    }
   }
   
   // undef % X -> 0
@@ -1419,7 +1409,8 @@ SDOperand DAGCombiner::visitMULHU(SDNode *N) {
 bool DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N,
                                              unsigned LoOp, unsigned HiOp) {
   // If the high half is not needed, just compute the low half.
-  if (!N->hasAnyUseOfValue(1) &&
+  bool HiExists = N->hasAnyUseOfValue(1);
+  if (!HiExists &&
       (!AfterLegalize ||
        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0),
@@ -1430,7 +1421,8 @@ bool DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N,
   }
 
   // If the low half is not needed, just compute the high half.
-  if (!N->hasAnyUseOfValue(0) &&
+  bool LoExists = N->hasAnyUseOfValue(0);
+  if (!LoExists &&
       (!AfterLegalize ||
        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
@@ -1440,36 +1432,37 @@ bool DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N,
     return true;
   }
 
-  // If the two computed results can be siplified separately, separate them.
-  SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
-                             N->op_begin(), N->getNumOperands());
-  SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
-                             N->op_begin(), N->getNumOperands());
-  unsigned LoExists = !Lo.use_empty();
-  unsigned HiExists = !Hi.use_empty();
-  SDOperand LoOpt = Lo;
-  SDOperand HiOpt = Hi;
-  if (!LoExists || !HiExists) {
-    SDOperand Pair = DAG.getNode(ISD::BUILD_PAIR, MVT::Other, Lo, Hi);
-    assert(Pair.use_empty() && "Pair with type MVT::Other already exists!");
-    LoOpt = combine(Lo.Val);
-    HiOpt = combine(Hi.Val);
-    if (!LoOpt.Val)
-      LoOpt = Pair.getOperand(0);
-    if (!HiOpt.Val)
-      HiOpt = Pair.getOperand(1);
-    DAG.DeleteNode(Pair.Val);
-  }
-  if ((LoExists || LoOpt != Lo) &&
-      (HiExists || HiOpt != Hi) &&
-      TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()) &&
-      TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())) {
-    DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), LoOpt);
-    DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), HiOpt);
-    return true;
+  // If both halves are used, return as it is.
+  if (LoExists && HiExists)
+    return false;
+
+  // If the two computed results can be simplified separately, separate them.
+  bool RetVal = false;
+  if (LoExists) {
+    SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
+                               N->op_begin(), N->getNumOperands());
+    SDOperand LoOpt = combine(Lo.Val);
+    if (LoOpt.Val && LoOpt != Lo &&
+        TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())) {
+      RetVal = true;
+      DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), LoOpt);
+    } else
+      DAG.DeleteNode(Lo.Val);
   }
 
-  return false;
+  if (HiExists) {
+    SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
+                               N->op_begin(), N->getNumOperands());
+    SDOperand HiOpt = combine(Hi.Val);
+    if (HiOpt.Val && HiOpt != Hi &&
+        TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())) {
+      RetVal = true;
+      DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), HiOpt);
+    } else
+      DAG.DeleteNode(Hi.Val);
+  }
+
+  return RetVal;
 }
 
 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
@@ -1711,17 +1704,21 @@ SDOperand DAGCombiner::visitAND(SDNode *N) {
         // For big endian targets, we need to add an offset to the pointer to
         // load the correct bytes.  For little endian systems, we merely need to
         // read fewer bytes from the same pointer.
-        unsigned PtrOff =
-          (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
+        unsigned LVTStoreBytes = MVT::getStoreSizeInBits(LoadedVT)/8;
+        unsigned EVTStoreBytes = MVT::getStoreSizeInBits(EVT)/8;
+        unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
+        unsigned Alignment = LN0->getAlignment();
         SDOperand NewPtr = LN0->getBasePtr();
-        if (!TLI.isLittleEndian())
+        if (!TLI.isLittleEndian()) {
           NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
                                DAG.getConstant(PtrOff, PtrType));
+          Alignment = MinAlign(Alignment, PtrOff);
+        }
         AddToWorkList(NewPtr.Val);
         SDOperand Load =
           DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
                          LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
-                         LN0->isVolatile(), LN0->getAlignment());
+                         LN0->isVolatile(), Alignment);
         AddToWorkList(N);
         CombineTo(N0.Val, Load, Load.getValue(1));
         return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
@@ -2136,6 +2133,77 @@ SDOperand DAGCombiner::visitXOR(SDNode *N) {
   return SDOperand();
 }
 
+/// visitShiftByConstant - Handle transforms common to the three shifts, when
+/// the shift amount is a constant.
+SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
+  SDNode *LHS = N->getOperand(0).Val;
+  if (!LHS->hasOneUse()) return SDOperand();
+  
+  // We want to pull some binops through shifts, so that we have (and (shift))
+  // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
+  // thing happens with address calculations, so it's important to canonicalize
+  // it.
+  bool HighBitSet = false;  // Can we transform this if the high bit is set?
+  
+  switch (LHS->getOpcode()) {
+  default: return SDOperand();
+  case ISD::OR:
+  case ISD::XOR:
+    HighBitSet = false; // We can only transform sra if the high bit is clear.
+    break;
+  case ISD::AND:
+    HighBitSet = true;  // We can only transform sra if the high bit is set.
+    break;
+  case ISD::ADD:
+    if (N->getOpcode() != ISD::SHL) 
+      return SDOperand(); // only shl(add) not sr[al](add).
+    HighBitSet = false; // We can only transform sra if the high bit is clear.
+    break;
+  }
+  
+  // We require the RHS of the binop to be a constant as well.
+  ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
+  if (!BinOpCst) return SDOperand();
+  
+  
+  // FIXME: disable this for unless the input to the binop is a shift by a
+  // constant.  If it is not a shift, it pessimizes some common cases like:
+  //
+  //void foo(int *X, int i) { X[i & 1235] = 1; }
+  //int bar(int *X, int i) { return X[i & 255]; }
+  SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
+  if ((BinOpLHSVal->getOpcode() != ISD::SHL && 
+       BinOpLHSVal->getOpcode() != ISD::SRA &&
+       BinOpLHSVal->getOpcode() != ISD::SRL) ||
+      !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
+    return SDOperand();
+  
+  MVT::ValueType VT = N->getValueType(0);
+  
+  // If this is a signed shift right, and the high bit is modified
+  // by the logical operation, do not perform the transformation.
+  // The highBitSet boolean indicates the value of the high bit of
+  // the constant which would cause it to be modified for this
+  // operation.
+  if (N->getOpcode() == ISD::SRA) {
+    uint64_t BinOpRHSSign = BinOpCst->getValue() >> MVT::getSizeInBits(VT)-1;
+    if ((bool)BinOpRHSSign != HighBitSet)
+      return SDOperand();
+  }
+  
+  // Fold the constants, shifting the binop RHS by the shift amount.
+  SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
+                                 LHS->getOperand(1), N->getOperand(1));
+
+  // Create the new shift.
+  SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
+                                   N->getOperand(1));
+
+  // Create the new binop.
+  return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
+}
+
+
 SDOperand DAGCombiner::visitSHL(SDNode *N) {
   SDOperand N0 = N->getOperand(0);
   SDOperand N1 = N->getOperand(1);
@@ -2190,7 +2258,8 @@ SDOperand DAGCombiner::visitSHL(SDNode *N) {
   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
     return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
                        DAG.getConstant(~0ULL << N1C->getValue(), VT));
-  return SDOperand();
+  
+  return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
 }
 
 SDOperand DAGCombiner::visitSRA(SDNode *N) {
@@ -2250,7 +2319,8 @@ SDOperand DAGCombiner::visitSRA(SDNode *N) {
   // If the sign bit is known to be zero, switch this to a SRL.
   if (DAG.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
     return DAG.getNode(ISD::SRL, VT, N0, N1);
-  return SDOperand();
+
+  return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
 }
 
 SDOperand DAGCombiner::visitSRL(SDNode *N) {
@@ -2344,7 +2414,7 @@ SDOperand DAGCombiner::visitSRL(SDNode *N) {
   if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
     return SDOperand(N, 0);
   
-  return SDOperand();
+  return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
 }
 
 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
@@ -2411,13 +2481,13 @@ SDOperand DAGCombiner::visitSELECT(SDNode *N) {
     return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
   }
   // fold select C, 0, X -> ~C & X
-  if (VT == VT0 && N1C && N1C->isNullValue()) {
+  if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
     AddToWorkList(XORNode.Val);
     return DAG.getNode(ISD::AND, VT, XORNode, N2);
   }
   // fold select C, X, 1 -> ~C | X
-  if (VT == VT0 && N2C && N2C->getValue() == 1) {
+  if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getValue() == 1) {
     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
     AddToWorkList(XORNode.Val);
     return DAG.getNode(ISD::OR, VT, XORNode, N1);
@@ -2493,6 +2563,74 @@ SDOperand DAGCombiner::visitSETCC(SDNode *N) {
                        cast<CondCodeSDNode>(N->getOperand(2))->get());
 }
 
+// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
+// "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
+// transformation. Returns true if extension are possible and the above
+// mentioned transformation is profitable. 
+static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
+                                    unsigned ExtOpc,
+                                    SmallVector<SDNode*, 4> &ExtendNodes,
+                                    TargetLowering &TLI) {
+  bool HasCopyToRegUses = false;
+  bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
+  for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
+       UI != UE; ++UI) {
+    SDNode *User = *UI;
+    if (User == N)
+      continue;
+    // FIXME: Only extend SETCC N, N and SETCC N, c for now.
+    if (User->getOpcode() == ISD::SETCC) {
+      ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
+      if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
+        // Sign bits will be lost after a zext.
+        return false;
+      bool Add = false;
+      for (unsigned i = 0; i != 2; ++i) {
+        SDOperand UseOp = User->getOperand(i);
+        if (UseOp == N0)
+          continue;
+        if (!isa<ConstantSDNode>(UseOp))
+          return false;
+        Add = true;
+      }
+      if (Add)
+        ExtendNodes.push_back(User);
+    } else {
+      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
+        SDOperand UseOp = User->getOperand(i);
+        if (UseOp == N0) {
+          // If truncate from extended type to original load type is free
+          // on this target, then it's ok to extend a CopyToReg.
+          if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
+            HasCopyToRegUses = true;
+          else
+            return false;
+        }
+      }
+    }
+  }
+
+  if (HasCopyToRegUses) {
+    bool BothLiveOut = false;
+    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
+         UI != UE; ++UI) {
+      SDNode *User = *UI;
+      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
+        SDOperand UseOp = User->getOperand(i);
+        if (UseOp.Val == N && UseOp.ResNo == 0) {
+          BothLiveOut = true;
+          break;
+        }
+      }
+    }
+    if (BothLiveOut)
+      // Both unextended and extended values are live out. There had better be
+      // good a reason for the transformation.
+      return ExtendNodes.size();
+  }
+  return true;
+}
+
 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
   SDOperand N0 = N->getOperand(0);
   MVT::ValueType VT = N->getValueType(0);
@@ -2556,19 +2694,40 @@ SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
   }
   
   // fold (sext (load x)) -> (sext (truncate (sextload x)))
-  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
+  if (ISD::isNON_EXTLoad(N0.Val) &&
       (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
-    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
-    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
-                                       LN0->getBasePtr(), LN0->getSrcValue(),
-                                       LN0->getSrcValueOffset(),
-                                       N0.getValueType(), 
-                                       LN0->isVolatile(),
-                                       LN0->getAlignment());
-    CombineTo(N, ExtLoad);
-    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
-              ExtLoad.getValue(1));
-    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+    bool DoXform = true;
+    SmallVector<SDNode*, 4> SetCCs;
+    if (!N0.hasOneUse())
+      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
+    if (DoXform) {
+      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
+      SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
+                                         LN0->getBasePtr(), LN0->getSrcValue(),
+                                         LN0->getSrcValueOffset(),
+                                         N0.getValueType(), 
+                                         LN0->isVolatile(),
+                                         LN0->getAlignment());
+      CombineTo(N, ExtLoad);
+      SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
+      CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
+      // Extend SetCC uses if necessary.
+      for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
+        SDNode *SetCC = SetCCs[i];
+        SmallVector<SDOperand, 4> Ops;
+        for (unsigned j = 0; j != 2; ++j) {
+          SDOperand SOp = SetCC->getOperand(j);
+          if (SOp == Trunc)
+            Ops.push_back(ExtLoad);
+          else
+            Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
+          }
+        Ops.push_back(SetCC->getOperand(2));
+        CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
+                                     &Ops[0], Ops.size()));
+      }
+      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+    }
   }
 
   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
@@ -2652,19 +2811,40 @@ SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
   }
   
   // fold (zext (load x)) -> (zext (truncate (zextload x)))
-  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
+  if (ISD::isNON_EXTLoad(N0.Val) &&
       (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
-    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
-    SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
-                                       LN0->getBasePtr(), LN0->getSrcValue(),
-                                       LN0->getSrcValueOffset(),
-                                       N0.getValueType(),
-                                       LN0->isVolatile(), 
-                                       LN0->getAlignment());
-    CombineTo(N, ExtLoad);
-    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
-              ExtLoad.getValue(1));
-    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+    bool DoXform = true;
+    SmallVector<SDNode*, 4> SetCCs;
+    if (!N0.hasOneUse())
+      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
+    if (DoXform) {
+      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
+      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
+                                         LN0->getBasePtr(), LN0->getSrcValue(),
+                                         LN0->getSrcValueOffset(),
+                                         N0.getValueType(),
+                                         LN0->isVolatile(), 
+                                         LN0->getAlignment());
+      CombineTo(N, ExtLoad);
+      SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
+      CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
+      // Extend SetCC uses if necessary.
+      for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
+        SDNode *SetCC = SetCCs[i];
+        SmallVector<SDOperand, 4> Ops;
+        for (unsigned j = 0; j != 2; ++j) {
+          SDOperand SOp = SetCC->getOperand(j);
+          if (SOp == Trunc)
+            Ops.push_back(ExtLoad);
+          else
+            Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
+          }
+        Ops.push_back(SetCC->getOperand(2));
+        CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
+                                     &Ops[0], Ops.size()));
+      }
+      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+    }
   }
 
   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
@@ -2876,19 +3056,23 @@ SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
     MVT::ValueType PtrType = N0.getOperand(1).getValueType();
     // For big endian targets, we need to adjust the offset to the pointer to
     // load the correct bytes.
-    if (!TLI.isLittleEndian())
-      ShAmt = MVT::getSizeInBits(N0.getValueType()) - ShAmt - EVTBits;
+    if (!TLI.isLittleEndian()) {
+      unsigned LVTStoreBits = MVT::getStoreSizeInBits(N0.getValueType());
+      unsigned EVTStoreBits = MVT::getStoreSizeInBits(EVT);
+      ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
+    }
     uint64_t PtrOff =  ShAmt / 8;
+    unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
     SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
                                    DAG.getConstant(PtrOff, PtrType));
     AddToWorkList(NewPtr.Val);
     SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
       ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
                     LN0->getSrcValue(), LN0->getSrcValueOffset(),
-                    LN0->isVolatile(), LN0->getAlignment())
+                    LN0->isVolatile(), NewAlign)
       : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
                        LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
-                       LN0->isVolatile(), LN0->getAlignment());
+                       LN0->isVolatile(), NewAlign);
     AddToWorkList(N);
     if (CombineSRL) {
       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
@@ -3905,8 +4089,8 @@ SDOperand DAGCombiner::visitLOAD(SDNode *N) {
       // Replace the chain to void dependency.
       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
         ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
-                              LD->getSrcValue(), LD->getSrcValueOffset(),
-                              LD->isVolatile(), LD->getAlignment());
+                               LD->getSrcValue(), LD->getSrcValueOffset(),
+                               LD->isVolatile(), LD->getAlignment());
       } else {
         ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
                                   LD->getValueType(0),
@@ -3980,7 +4164,7 @@ SDOperand DAGCombiner::visitSTORE(SDNode *N) {
                               ST->getSrcValueOffset(), ST->isVolatile(),
                               ST->getAlignment());
         } else if (TLI.isTypeLegal(MVT::i32)) {
-          // Many FP stores are not make apparent until after legalize, e.g. for
+          // Many FP stores are not made apparent until after legalize, e.g. for
           // argument passing.  Since this is so common, custom legalize the
           // 64-bit integer store into two 32-bit stores.
           uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
@@ -3998,8 +4182,7 @@ SDOperand DAGCombiner::visitSTORE(SDNode *N) {
           Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
                             DAG.getConstant(4, Ptr.getValueType()));
           SVOffset += 4;
-          if (Alignment > 4)
-            Alignment = 4;
+          Alignment = MinAlign(Alignment, 4U);
           SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
                                        SVOffset, isVolatile, Alignment);
           return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
@@ -4040,7 +4223,7 @@ SDOperand DAGCombiner::visitSTORE(SDNode *N) {
   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
     return SDOperand(N, 0);
 
-  // FIXME: is there such a think as a truncating indexed store?
+  // FIXME: is there such a thing as a truncating indexed store?
   if (ST->isTruncatingStore() && ST->getAddressingMode() == ISD::UNINDEXED &&
       MVT::isInteger(Value.getValueType())) {
     // See if we can simplify the input to this truncstore with knowledge that
@@ -4060,6 +4243,17 @@ SDOperand DAGCombiner::visitSTORE(SDNode *N) {
       return SDOperand(N, 0);
   }
   
+  // If this is a load followed by a store to the same location, then the store
+  // is dead/noop.
+  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
+    if (Chain.Val == Ld && Ld->getBasePtr() == Ptr &&
+        ST->getAddressingMode() == ISD::UNINDEXED &&
+        ST->getStoredVT() == Ld->getLoadedVT()) {
+      // The store is dead, remove it.
+      return Chain;
+    }
+  }
+  
   return SDOperand();
 }
 
@@ -4098,7 +4292,8 @@ SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
       unsigned NumElts = MVT::getVectorNumElements(VT);
       if (InVec.getOpcode() == ISD::BIT_CONVERT) {
         MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
-        if (NumElts != MVT::getVectorNumElements(BCVT))
+        if (!MVT::isVector(BCVT) ||
+            NumElts != MVT::getVectorNumElements(BCVT))
           return SDOperand();
         InVec = InVec.getOperand(0);
         EVT = MVT::getVectorElementType(BCVT);