For PR786:
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
index e6a9b897a12cb512ea5e3eff2295d747773e180f..b1dfc90205ad2359c42a8d9acfc40cd0b5dad506 100644 (file)
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
-#include "llvm/Support/MathExtras.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/CallingConv.h"
 #include "llvm/Constants.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/ADT/SmallVector.h"
 #include <iostream>
-#include <set>
+#include <map>
 using namespace llvm;
 
+#ifndef NDEBUG
+static cl::opt<bool>
+ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
+                 cl::desc("Pop up a window to show dags before legalize"));
+#else
+static const bool ViewLegalizeDAGs = 0;
+#endif
+
 //===----------------------------------------------------------------------===//
 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
 /// hacks on it until the target machine can handle it.  This involves
@@ -37,7 +49,7 @@ using namespace llvm;
 /// will attempt merge setcc and brc instructions into brcc's.
 ///
 namespace {
-class SelectionDAGLegalize {
+class VISIBILITY_HIDDEN SelectionDAGLegalize {
   TargetLowering &TLI;
   SelectionDAG &DAG;
 
@@ -56,7 +68,7 @@ class SelectionDAGLegalize {
   enum LegalizeAction {
     Legal,      // The target natively supports this operation.
     Promote,    // This operation should be executed in a larger type.
-    Expand,     // Try to expand this to other ops, otherwise use a libcall.
+    Expand      // Try to expand this to other ops, otherwise use a libcall.
   };
   
   /// ValueTypeActions - This is a bitvector that contains two bits for each
@@ -156,7 +168,19 @@ private:
   /// we know that this type is legal for the target.
   SDOperand PackVectorOp(SDOperand O, MVT::ValueType PackedVT);
   
-  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest);
+  /// isShuffleLegal - Return true if a vector shuffle is legal with the
+  /// specified mask and type.  Targets can specify exactly which masks they
+  /// support and the code generator is tasked with not creating illegal masks.
+  ///
+  /// Note that this will also return true for shuffles that are promoted to a
+  /// different type.
+  ///
+  /// If this is a legal shuffle, this method returns the (possibly promoted)
+  /// build_vector Mask.  If it's not a legal shuffle, it returns null.
+  SDNode *isShuffleLegal(MVT::ValueType VT, SDOperand Mask) const;
+  
+  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
+                                    std::set<SDNode*> &NodesLeadingTo);
 
   void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
     
@@ -169,6 +193,7 @@ private:
 
   SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
   SDOperand ExpandBUILD_VECTOR(SDNode *Node);
+  SDOperand ExpandSCALAR_TO_VECTOR(SDNode *Node);
   SDOperand ExpandLegalINT_TO_FP(bool isSigned,
                                  SDOperand LegalOp,
                                  MVT::ValueType DestVT);
@@ -184,12 +209,60 @@ private:
   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
                         SDOperand &Lo, SDOperand &Hi);
 
+  SDOperand LowerVEXTRACT_VECTOR_ELT(SDOperand Op);
+  SDOperand ExpandEXTRACT_VECTOR_ELT(SDOperand Op);
+  
   SDOperand getIntPtrConstant(uint64_t Val) {
     return DAG.getConstant(Val, TLI.getPointerTy());
   }
 };
 }
 
+/// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
+/// specified mask and type.  Targets can specify exactly which masks they
+/// support and the code generator is tasked with not creating illegal masks.
+///
+/// Note that this will also return true for shuffles that are promoted to a
+/// different type.
+SDNode *SelectionDAGLegalize::isShuffleLegal(MVT::ValueType VT, 
+                                             SDOperand Mask) const {
+  switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
+  default: return 0;
+  case TargetLowering::Legal:
+  case TargetLowering::Custom:
+    break;
+  case TargetLowering::Promote: {
+    // If this is promoted to a different type, convert the shuffle mask and
+    // ask if it is legal in the promoted type!
+    MVT::ValueType NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
+
+    // If we changed # elements, change the shuffle mask.
+    unsigned NumEltsGrowth =
+      MVT::getVectorNumElements(NVT) / MVT::getVectorNumElements(VT);
+    assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
+    if (NumEltsGrowth > 1) {
+      // Renumber the elements.
+      SmallVector<SDOperand, 8> Ops;
+      for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
+        SDOperand InOp = Mask.getOperand(i);
+        for (unsigned j = 0; j != NumEltsGrowth; ++j) {
+          if (InOp.getOpcode() == ISD::UNDEF)
+            Ops.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
+          else {
+            unsigned InEltNo = cast<ConstantSDNode>(InOp)->getValue();
+            Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, MVT::i32));
+          }
+        }
+      }
+      Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, &Ops[0], Ops.size());
+    }
+    VT = NVT;
+    break;
+  }
+  }
+  return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.Val : 0;
+}
+
 /// getScalarizedOpcode - Return the scalar opcode that corresponds to the
 /// specified vector opcode.
 static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
@@ -278,7 +351,7 @@ void SelectionDAGLegalize::LegalizeDAG() {
   PackedNodes.clear();
 
   // Remove dead nodes now.
-  DAG.RemoveDeadNodes(OldRoot.Val);
+  DAG.RemoveDeadNodes();
 }
 
 
@@ -336,10 +409,18 @@ static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
 /// see if any uses can reach Dest.  If no dest operands can get to dest, 
 /// legalize them, legalize ourself, and return false, otherwise, return true.
-bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, 
-                                                        SDNode *Dest) {
+///
+/// Keep track of the nodes we fine that actually do lead to Dest in
+/// NodesLeadingTo.  This avoids retraversing them exponential number of times.
+///
+bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
+                                            std::set<SDNode*> &NodesLeadingTo) {
   if (N == Dest) return true;  // N certainly leads to Dest :)
   
+  // If we've already processed this node and it does lead to Dest, there is no
+  // need to reprocess it.
+  if (NodesLeadingTo.count(N)) return true;
+  
   // If the first result of this node has been already legalized, then it cannot
   // reach N.
   switch (getTypeAction(N->getValueType(0))) {
@@ -359,24 +440,15 @@ bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N,
   bool OperandsLeadToDest = false;
   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
-      LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest);
+      LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest, NodesLeadingTo);
 
-  if (OperandsLeadToDest) return true;
+  if (OperandsLeadToDest) {
+    NodesLeadingTo.insert(N);
+    return true;
+  }
 
   // Okay, this node looks safe, legalize it and return false.
-  switch (getTypeAction(N->getValueType(0))) {
-  case Legal:
-    LegalizeOp(SDOperand(N, 0));
-    break;
-  case Promote:
-    PromoteOp(SDOperand(N, 0));
-    break;
-  case Expand: {
-    SDOperand X, Y;
-    ExpandOp(SDOperand(N, 0), X, Y);
-    break;
-  }
-  }
+  HandleOp(SDOperand(N, 0));
   return false;
 }
 
@@ -453,6 +525,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   case ISD::Register:
   case ISD::BasicBlock:
   case ISD::TargetFrameIndex:
+  case ISD::TargetJumpTable:
   case ISD::TargetConstant:
   case ISD::TargetConstantFP:
   case ISD::TargetConstantPool:
@@ -462,6 +535,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   case ISD::SRCVALUE:
   case ISD::STRING:
   case ISD::CONDCODE:
+  case ISD::GLOBAL_OFFSET_TABLE:
     // Primitives must all be legal.
     assert(TLI.isOperationLegal(Node->getValueType(0), Node->getValueType(0)) &&
            "This must be legal!");
@@ -470,32 +544,26 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
       // If this is a target node, legalize it by legalizing the operands then
       // passing it through.
-      std::vector<SDOperand> Ops;
-      bool Changed = false;
-      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
+      SmallVector<SDOperand, 8> Ops;
+      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
         Ops.push_back(LegalizeOp(Node->getOperand(i)));
-        Changed = Changed || Node->getOperand(i) != Ops.back();
-      }
-      if (Changed)
-        if (Node->getNumValues() == 1)
-          Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
-        else {
-          std::vector<MVT::ValueType> VTs(Node->value_begin(),
-                                          Node->value_end());
-          Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
-        }
+
+      Result = DAG.UpdateNodeOperands(Result.getValue(0), &Ops[0], Ops.size());
 
       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
       return Result.getValue(Op.ResNo);
     }
     // Otherwise this is an unhandled builtin node.  splat.
+#ifndef NDEBUG
     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
+#endif
     assert(0 && "Do not know how to legalize this operator!");
     abort();
   case ISD::GlobalAddress:
   case ISD::ExternalSymbol:
-  case ISD::ConstantPool:           // Nothing to do.
+  case ISD::ConstantPool:
+  case ISD::JumpTable: // Nothing to do.
     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
     default: assert(0 && "This action is not supported yet!");
     case TargetLowering::Custom:
@@ -552,6 +620,34 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     }
     break;
   }
+    
+  case ISD::INTRINSIC_W_CHAIN:
+  case ISD::INTRINSIC_WO_CHAIN:
+  case ISD::INTRINSIC_VOID: {
+    SmallVector<SDOperand, 8> Ops;
+    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
+      Ops.push_back(LegalizeOp(Node->getOperand(i)));
+    Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
+    
+    // Allow the target to custom lower its intrinsics if it wants to.
+    if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) == 
+        TargetLowering::Custom) {
+      Tmp3 = TLI.LowerOperation(Result, DAG);
+      if (Tmp3.Val) Result = Tmp3;
+    }
+
+    if (Result.Val->getNumValues() == 1) break;
+
+    // Must have return value and chain result.
+    assert(Result.Val->getNumValues() == 2 &&
+           "Cannot return more than two values!");
+
+    // Since loads produce two values, make sure to remember that we 
+    // legalized both of them.
+    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
+    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
+    return Result.getValue(Op.ResNo);
+  }    
 
   case ISD::LOCATION:
     assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
@@ -572,7 +668,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
           cast<StringSDNode>(Node->getOperand(4))->getValue();
         unsigned SrcFile = DebugInfo->RecordSource(DirName, FName);
 
-        std::vector<SDOperand> Ops;
+        SmallVector<SDOperand, 8> Ops;
         Ops.push_back(Tmp1);  // chain
         SDOperand LineOp = Node->getOperand(1);
         SDOperand ColOp = Node->getOperand(2);
@@ -581,13 +677,13 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
           Ops.push_back(LineOp);  // line #
           Ops.push_back(ColOp);  // col #
           Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
-          Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
+          Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, &Ops[0], Ops.size());
         } else {
           unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
           unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
           unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
           Ops.push_back(DAG.getConstant(ID, MVT::i32));
-          Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
+          Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,&Ops[0],Ops.size());
         }
       } else {
         Result = Tmp1;  // chain
@@ -597,7 +693,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     case TargetLowering::Legal:
       if (Tmp1 != Node->getOperand(0) ||
           getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
-        std::vector<SDOperand> Ops;
+        SmallVector<SDOperand, 8> Ops;
         Ops.push_back(Tmp1);
         if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
           Ops.push_back(Node->getOperand(1));  // line # must be legal.
@@ -609,7 +705,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         }
         Ops.push_back(Node->getOperand(3));  // filename must be legal.
         Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
-        Result = DAG.UpdateNodeOperands(Result, Ops);
+        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
       }
       break;
     }
@@ -694,7 +790,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
           // Only do this if the target has a native EXTLOAD instruction from
           // f32.
-          TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
+          TLI.isLoadXLegal(ISD::EXTLOAD, MVT::f32)) {
         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
         VT = MVT::f32;
         Extend = true;
@@ -703,10 +799,9 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
       if (Extend) {
         Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
-                                CPIdx, DAG.getSrcValue(NULL), MVT::f32);
+                                CPIdx, NULL, 0, MVT::f32);
       } else {
-        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
-                             DAG.getSrcValue(NULL));
+        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0);
       }
     }
     break;
@@ -722,14 +817,32 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       Tmp3 = LegalizeOp(Node->getOperand(2));
       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
     } else {
-      std::vector<SDOperand> Ops;
+      SmallVector<SDOperand, 8> Ops;
       // Legalize the operands.
       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
         Ops.push_back(LegalizeOp(Node->getOperand(i)));
-      Result = DAG.UpdateNodeOperands(Result, Ops);
+      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
     }
     break;
-
+    
+  case ISD::FORMAL_ARGUMENTS:
+  case ISD::CALL:
+    // The only option for this is to custom lower it.
+    Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
+    assert(Tmp3.Val && "Target didn't custom lower this node!");
+    assert(Tmp3.Val->getNumValues() == Result.Val->getNumValues() &&
+           "Lowering call/formal_arguments produced unexpected # results!");
+    
+    // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
+    // remember that we legalized all of them, so it doesn't get relegalized.
+    for (unsigned i = 0, e = Tmp3.Val->getNumValues(); i != e; ++i) {
+      Tmp1 = LegalizeOp(Tmp3.getValue(i));
+      if (Op.ResNo == i)
+        Tmp2 = Tmp1;
+      AddLegalizedOperand(SDOperand(Node, i), Tmp1);
+    }
+    return Tmp2;
+        
   case ISD::BUILD_VECTOR:
     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
     default: assert(0 && "This action is not supported yet!");
@@ -764,18 +877,70 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       }
       // FALLTHROUGH
     case TargetLowering::Expand: {
+      // If the insert index is a constant, codegen this as a scalar_to_vector,
+      // then a shuffle that inserts it into the right position in the vector.
+      if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
+        SDOperand ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, 
+                                      Tmp1.getValueType(), Tmp2);
+        
+        unsigned NumElts = MVT::getVectorNumElements(Tmp1.getValueType());
+        MVT::ValueType ShufMaskVT = MVT::getIntVectorWithNumElements(NumElts);
+        MVT::ValueType ShufMaskEltVT = MVT::getVectorBaseType(ShufMaskVT);
+        
+        // We generate a shuffle of InVec and ScVec, so the shuffle mask should
+        // be 0,1,2,3,4,5... with the appropriate element replaced with elt 0 of
+        // the RHS.
+        SmallVector<SDOperand, 8> ShufOps;
+        for (unsigned i = 0; i != NumElts; ++i) {
+          if (i != InsertPos->getValue())
+            ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT));
+          else
+            ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT));
+        }
+        SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,
+                                         &ShufOps[0], ShufOps.size());
+        
+        Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(),
+                             Tmp1, ScVec, ShufMask);
+        Result = LegalizeOp(Result);
+        break;
+      }
+      
       // If the target doesn't support this, we have to spill the input vector
       // to a temporary stack slot, update the element, then reload it.  This is
       // badness.  We could also load the value into a vector register (either
       // with a "move to register" or "extload into register" instruction, then
       // permute it into place, if the idx is a constant and if the idx is
       // supported by the target.
-      assert(0 && "INSERT_VECTOR_ELT expand not supported yet!");
+      MVT::ValueType VT    = Tmp1.getValueType();
+      MVT::ValueType EltVT = Tmp2.getValueType();
+      MVT::ValueType IdxVT = Tmp3.getValueType();
+      MVT::ValueType PtrVT = TLI.getPointerTy();
+      SDOperand StackPtr = CreateStackTemporary(VT);
+      // Store the vector.
+      SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Tmp1, StackPtr, NULL, 0);
+
+      // Truncate or zero extend offset to target pointer type.
+      unsigned CastOpc = (IdxVT > PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
+      Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
+      // Add the offset to the index.
+      unsigned EltSize = MVT::getSizeInBits(EltVT)/8;
+      Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
+      SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
+      // Store the scalar value.
+      Ch = DAG.getStore(Ch, Tmp2, StackPtr2, NULL, 0);
+      // Load the updated vector.
+      Result = DAG.getLoad(VT, Ch, StackPtr, NULL, 0);
       break;
     }
     }
     break;
   case ISD::SCALAR_TO_VECTOR:
+    if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
+      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
+      break;
+    }
+    
     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
     Result = DAG.UpdateNodeOperands(Result, Tmp1);
     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
@@ -790,35 +955,71 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         break;
       }
       // FALLTHROUGH
-    case TargetLowering::Expand: {
-      // If the target doesn't support this, store the value to a temporary
-      // stack slot, then EXTLOAD the vector back out.
-      // TODO: If a target doesn't support this, create a stack slot for the
-      // whole vector, then store into it, then load the whole vector.
-      SDOperand StackPtr = 
-        CreateStackTemporary(Node->getOperand(0).getValueType());
-      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
-                                 Node->getOperand(0), StackPtr,
-                                 DAG.getSrcValue(NULL));
-      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0), Ch, StackPtr,
-                              DAG.getSrcValue(NULL),
-                              Node->getOperand(0).getValueType());
+    case TargetLowering::Expand:
+      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
       break;
     }
-    }
     break;
   case ISD::VECTOR_SHUFFLE:
-    assert(TLI.isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
-           "vector shuffle should not be created if not legal!");
     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
 
     // Allow targets to custom lower the SHUFFLEs they support.
-    if (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, Result.getValueType())
-        == TargetLowering::Custom) {
-      Tmp1 = TLI.LowerOperation(Result, DAG);
-      if (Tmp1.Val) Result = Tmp1;
+    switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
+    default: assert(0 && "Unknown operation action!");
+    case TargetLowering::Legal:
+      assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
+             "vector shuffle should not be created if not legal!");
+      break;
+    case TargetLowering::Custom:
+      Tmp3 = TLI.LowerOperation(Result, DAG);
+      if (Tmp3.Val) {
+        Result = Tmp3;
+        break;
+      }
+      // FALLTHROUGH
+    case TargetLowering::Expand: {
+      MVT::ValueType VT = Node->getValueType(0);
+      MVT::ValueType EltVT = MVT::getVectorBaseType(VT);
+      MVT::ValueType PtrVT = TLI.getPointerTy();
+      SDOperand Mask = Node->getOperand(2);
+      unsigned NumElems = Mask.getNumOperands();
+      SmallVector<SDOperand,8> Ops;
+      for (unsigned i = 0; i != NumElems; ++i) {
+        SDOperand Arg = Mask.getOperand(i);
+        if (Arg.getOpcode() == ISD::UNDEF) {
+          Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
+        } else {
+          assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
+          unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
+          if (Idx < NumElems)
+            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
+                                      DAG.getConstant(Idx, PtrVT)));
+          else
+            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
+                                      DAG.getConstant(Idx - NumElems, PtrVT)));
+        }
+      }
+      Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
+      break;
+    }
+    case TargetLowering::Promote: {
+      // Change base type to a different vector type.
+      MVT::ValueType OVT = Node->getValueType(0);
+      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
+
+      // Cast the two input vectors.
+      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
+      Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
+      
+      // Convert the shuffle mask to the right # elements.
+      Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
+      assert(Tmp3.Val && "Shuffle not legal?");
+      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
+      Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
+      break;
+    }
     }
     break;
   
@@ -839,69 +1040,15 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         break;
       }
       // FALLTHROUGH
-    case TargetLowering::Expand: {
-      // If the target doesn't support this, store the value to a temporary
-      // stack slot, then LOAD the scalar element back out.
-      SDOperand StackPtr = CreateStackTemporary(Tmp1.getValueType());
-      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
-                                 Tmp1, StackPtr, DAG.getSrcValue(NULL));
-      
-      // Add the offset to the index.
-      unsigned EltSize = MVT::getSizeInBits(Result.getValueType())/8;
-      Tmp2 = DAG.getNode(ISD::MUL, Tmp2.getValueType(), Tmp2,
-                         DAG.getConstant(EltSize, Tmp2.getValueType()));
-      StackPtr = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2, StackPtr);
-      
-      Result = DAG.getLoad(Result.getValueType(), Ch, StackPtr,
-                              DAG.getSrcValue(NULL));
+    case TargetLowering::Expand:
+      Result = ExpandEXTRACT_VECTOR_ELT(Result);
       break;
     }
-    }
     break;
 
-  case ISD::VEXTRACT_VECTOR_ELT: {
-    // We know that operand #0 is the Vec vector.  If the index is a constant
-    // or if the invec is a supported hardware type, we can use it.  Otherwise,
-    // lower to a store then an indexed load.
-    Tmp1 = Node->getOperand(0);
-    Tmp2 = LegalizeOp(Node->getOperand(1));
-    
-    SDNode *InVal = Tmp1.Val;
-    unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
-    MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
-    
-    // Figure out if there is a Packed type corresponding to this Vector
-    // type.  If so, convert to the packed type.
-    MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
-    if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
-      // Turn this into a packed extract_vector_elt operation.
-      Tmp1 = PackVectorOp(Tmp1, TVT);
-      Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Node->getValueType(0),
-                           Tmp1, Tmp2);
-      break;
-    } else if (NumElems == 1) {
-      // This must be an access of the only element.
-      Result = PackVectorOp(Tmp1, EVT);
-      break;
-    } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Tmp2)) {
-      SDOperand Lo, Hi;
-      SplitVectorOp(Tmp1, Lo, Hi);
-      if (CIdx->getValue() < NumElems/2) {
-        Tmp1 = Lo;
-      } else {
-        Tmp1 = Hi;
-        Tmp2 = DAG.getConstant(CIdx->getValue() - NumElems/2,
-                               Tmp2.getValueType());
-      }
-
-      // It's now an extract from the appropriate high or low part.
-      Result = LegalizeOp(DAG.UpdateNodeOperands(Result, Tmp1, Tmp2));
-    } else {
-      // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
-      assert(0 && "unimp!");
-    }
+  case ISD::VEXTRACT_VECTOR_ELT: 
+    Result = LegalizeOp(LowerVEXTRACT_VECTOR_ELT(Op));
     break;
-  }
     
   case ISD::CALLSEQ_START: {
     SDNode *CallEnd = FindCallEndFromCallStart(Node);
@@ -909,8 +1056,11 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     // Recursively Legalize all of the inputs of the call end that do not lead
     // to this call start.  This ensures that any libcalls that need be inserted
     // are inserted *before* the CALLSEQ_START.
+    {std::set<SDNode*> NodesLeadingTo;
     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
-      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node);
+      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node,
+                                   NodesLeadingTo);
+    }
 
     // Now that we legalized all of the inputs (which may have inserted
     // libcalls) create the new CALLSEQ_START node.
@@ -918,14 +1068,16 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
 
     // Merge in the last call, to ensure that this call start after the last
     // call ended.
-    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
-    Tmp1 = LegalizeOp(Tmp1);
+    if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
+      Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
+      Tmp1 = LegalizeOp(Tmp1);
+    }
       
     // Do not try to legalize the target-specific arguments (#1+).
     if (Tmp1 != Node->getOperand(0)) {
-      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
+      SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
       Ops[0] = Tmp1;
-      Result = DAG.UpdateNodeOperands(Result, Ops);
+      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
     }
     
     // Remember that the CALLSEQ_START is legalized.
@@ -966,18 +1118,18 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     // an optional flag input.
     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
       if (Tmp1 != Node->getOperand(0)) {
-        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
+        SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
         Ops[0] = Tmp1;
-        Result = DAG.UpdateNodeOperands(Result, Ops);
+        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
       }
     } else {
       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
       if (Tmp1 != Node->getOperand(0) ||
           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
-        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
+        SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
         Ops[0] = Tmp1;
         Ops.back() = Tmp2;
-        Result = DAG.UpdateNodeOperands(Result, Ops);
+        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
       }
     }
     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
@@ -1029,25 +1181,42 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
     return Op.ResNo ? Tmp2 : Tmp1;
   }
-  case ISD::INLINEASM:
-    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize Chain.
-    Tmp2 = Node->getOperand(Node->getNumOperands()-1);
-    if (Tmp2.getValueType() == MVT::Flag)     // Legalize Flag if it exists.
-      Tmp2 = Tmp3 = SDOperand(0, 0);
-    else
-      Tmp3 = LegalizeOp(Tmp2);
-    
-    if (Tmp1 != Node->getOperand(0) || Tmp2 != Tmp3) {
-      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
-      Ops[0] = Tmp1;
-      if (Tmp3.Val) Ops.back() = Tmp3;
-      Result = DAG.UpdateNodeOperands(Result, Ops);
+  case ISD::INLINEASM: {
+    SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
+    bool Changed = false;
+    // Legalize all of the operands of the inline asm, in case they are nodes
+    // that need to be expanded or something.  Note we skip the asm string and
+    // all of the TargetConstant flags.
+    SDOperand Op = LegalizeOp(Ops[0]);
+    Changed = Op != Ops[0];
+    Ops[0] = Op;
+
+    bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
+    for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
+      unsigned NumVals = cast<ConstantSDNode>(Ops[i])->getValue() >> 3;
+      for (++i; NumVals; ++i, --NumVals) {
+        SDOperand Op = LegalizeOp(Ops[i]);
+        if (Op != Ops[i]) {
+          Changed = true;
+          Ops[i] = Op;
+        }
+      }
     }
+
+    if (HasInFlag) {
+      Op = LegalizeOp(Ops.back());
+      Changed |= Op != Ops.back();
+      Ops.back() = Op;
+    }
+    
+    if (Changed)
+      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
       
     // INLINE asm returns a chain and flag, make sure to add both to the map.
     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
     return Result.getValue(Op.ResNo);
+  }
   case ISD::BR:
     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
     // Ensure that libcalls are emitted before a branch.
@@ -1057,7 +1226,68 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     
     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
     break;
+  case ISD::BRIND:
+    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
+    // Ensure that libcalls are emitted before a branch.
+    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
+    Tmp1 = LegalizeOp(Tmp1);
+    LastCALLSEQ_END = DAG.getEntryNode();
+    
+    switch (getTypeAction(Node->getOperand(1).getValueType())) {
+    default: assert(0 && "Indirect target must be legal type (pointer)!");
+    case Legal:
+      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
+      break;
+    }
+    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
+    break;
+  case ISD::BR_JT:
+    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
+    // Ensure that libcalls are emitted before a branch.
+    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
+    Tmp1 = LegalizeOp(Tmp1);
+    LastCALLSEQ_END = DAG.getEntryNode();
 
+    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
+    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
+
+    switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {  
+    default: assert(0 && "This action is not supported yet!");
+    case TargetLowering::Legal: break;
+    case TargetLowering::Custom:
+      Tmp1 = TLI.LowerOperation(Result, DAG);
+      if (Tmp1.Val) Result = Tmp1;
+      break;
+    case TargetLowering::Expand: {
+      SDOperand Chain = Result.getOperand(0);
+      SDOperand Table = Result.getOperand(1);
+      SDOperand Index = Result.getOperand(2);
+
+      MVT::ValueType PTy = TLI.getPointerTy();
+      bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
+      // PIC jump table entries are 32-bit values.
+      unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
+      Index= DAG.getNode(ISD::MUL, PTy, Index, DAG.getConstant(EntrySize, PTy));
+      SDOperand Addr = DAG.getNode(ISD::ADD, PTy, Index, Table);
+      SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Chain, Addr, NULL, 0);
+      if (isPIC) {
+        // For PIC, the sequence is:
+        // BRIND(load(Jumptable + index) + RelocBase)
+        // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
+        SDOperand Reloc;
+        if (TLI.usesGlobalOffsetTable())
+          Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
+        else
+          Reloc = Table;
+        Addr = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
+        Addr = DAG.getNode(ISD::ADD, PTy, Addr, Reloc);
+        Result = DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), Addr);
+      } else {
+        Result = DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD);
+      }
+    }
+    }
+    break;
   case ISD::BRCOND:
     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
     // Ensure that libcalls are emitted before a return.
@@ -1141,94 +1371,106 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     }
     break;
   case ISD::LOAD: {
-    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
-    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
+    LoadSDNode *LD = cast<LoadSDNode>(Node);
+    Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
+    Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
 
-    MVT::ValueType VT = Node->getValueType(0);
-    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
-    Tmp2 = Result.getValue(0);
-    Tmp3 = Result.getValue(1);
+    ISD::LoadExtType ExtType = LD->getExtensionType();
+    if (ExtType == ISD::NON_EXTLOAD) {
+      MVT::ValueType VT = Node->getValueType(0);
+      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
+      Tmp3 = Result.getValue(0);
+      Tmp4 = Result.getValue(1);
     
-    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
-    default: assert(0 && "This action is not supported yet!");
-    case TargetLowering::Legal: break;
-    case TargetLowering::Custom:
-      Tmp1 = TLI.LowerOperation(Tmp2, DAG);
-      if (Tmp1.Val) {
-        Tmp2 = LegalizeOp(Tmp1);
-        Tmp3 = LegalizeOp(Tmp1.getValue(1));
+      switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
+      default: assert(0 && "This action is not supported yet!");
+      case TargetLowering::Legal: break;
+      case TargetLowering::Custom:
+        Tmp1 = TLI.LowerOperation(Tmp3, DAG);
+        if (Tmp1.Val) {
+          Tmp3 = LegalizeOp(Tmp1);
+          Tmp4 = LegalizeOp(Tmp1.getValue(1));
+        }
+        break;
+      case TargetLowering::Promote: {
+        // Only promote a load of vector type to another.
+        assert(MVT::isVector(VT) && "Cannot promote this load!");
+        // Change base type to a different vector type.
+        MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
+
+        Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, LD->getSrcValue(),
+                           LD->getSrcValueOffset());
+        Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
+        Tmp4 = LegalizeOp(Tmp1.getValue(1));
+        break;
       }
-      break;
-    }
-    // Since loads produce two values, make sure to remember that we 
-    // legalized both of them.
-    AddLegalizedOperand(SDOperand(Node, 0), Tmp2);
-    AddLegalizedOperand(SDOperand(Node, 1), Tmp3);
-    return Op.ResNo ? Tmp3 : Tmp2;
-  }
-  case ISD::EXTLOAD:
-  case ISD::SEXTLOAD:
-  case ISD::ZEXTLOAD: {
-    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
-    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
-
-    MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
-    switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
-    default: assert(0 && "This action is not supported yet!");
-    case TargetLowering::Promote:
-      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
-      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
-                                      DAG.getValueType(MVT::i8));
+      }
+      // Since loads produce two values, make sure to remember that we 
+      // legalized both of them.
+      AddLegalizedOperand(SDOperand(Node, 0), Tmp3);
+      AddLegalizedOperand(SDOperand(Node, 1), Tmp4);
+      return Op.ResNo ? Tmp4 : Tmp3;
+    } else {
+      MVT::ValueType SrcVT = LD->getLoadedVT();
+      switch (TLI.getLoadXAction(ExtType, SrcVT)) {
+      default: assert(0 && "This action is not supported yet!");
+      case TargetLowering::Promote:
+        assert(SrcVT == MVT::i1 &&
+               "Can only promote extending LOAD from i1 -> i8!");
+        Result = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
+                                LD->getSrcValue(), LD->getSrcValueOffset(),
+                                MVT::i8);
       Tmp1 = Result.getValue(0);
       Tmp2 = Result.getValue(1);
       break;
-    case TargetLowering::Custom:
-      isCustom = true;
-      // FALLTHROUGH
-    case TargetLowering::Legal:
-      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
-                                      Node->getOperand(3));
-      Tmp1 = Result.getValue(0);
-      Tmp2 = Result.getValue(1);
+      case TargetLowering::Custom:
+        isCustom = true;
+        // FALLTHROUGH
+      case TargetLowering::Legal:
+        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
+        Tmp1 = Result.getValue(0);
+        Tmp2 = Result.getValue(1);
       
-      if (isCustom) {
-        Tmp3 = TLI.LowerOperation(Tmp3, DAG);
-        if (Tmp3.Val) {
-          Tmp1 = LegalizeOp(Tmp3);
-          Tmp2 = LegalizeOp(Tmp3.getValue(1));
+        if (isCustom) {
+          Tmp3 = TLI.LowerOperation(Result, DAG);
+          if (Tmp3.Val) {
+            Tmp1 = LegalizeOp(Tmp3);
+            Tmp2 = LegalizeOp(Tmp3.getValue(1));
+          }
         }
-      }
-      break;
-    case TargetLowering::Expand:
-      // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
-      if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
-        SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
-        Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
-        Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
-        Tmp2 = LegalizeOp(Load.getValue(1));
+        break;
+      case TargetLowering::Expand:
+        // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
+        if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
+          SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, LD->getSrcValue(),
+                                       LD->getSrcValueOffset());
+          Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
+          Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
+          Tmp2 = LegalizeOp(Load.getValue(1));
+          break;
+        }
+        assert(ExtType != ISD::EXTLOAD && "EXTLOAD should always be supported!");
+        // Turn the unsupported load into an EXTLOAD followed by an explicit
+        // zero/sign extend inreg.
+        Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
+                                Tmp1, Tmp2, LD->getSrcValue(),
+                                LD->getSrcValueOffset(), SrcVT);
+        SDOperand ValRes;
+        if (ExtType == ISD::SEXTLOAD)
+          ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
+                               Result, DAG.getValueType(SrcVT));
+        else
+          ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
+        Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
+        Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
         break;
       }
-      assert(Node->getOpcode() != ISD::EXTLOAD &&
-             "EXTLOAD should always be supported!");
-      // Turn the unsupported load into an EXTLOAD followed by an explicit
-      // zero/sign extend inreg.
-      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
-                              Tmp1, Tmp2, Node->getOperand(2), SrcVT);
-      SDOperand ValRes;
-      if (Node->getOpcode() == ISD::SEXTLOAD)
-        ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
-                             Result, DAG.getValueType(SrcVT));
-      else
-        ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
-      Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
-      Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
-      break;
+      // Since loads produce two values, make sure to remember that we legalized
+      // both of them.
+      AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
+      AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
+      return Op.ResNo ? Tmp2 : Tmp1;
     }
-    // Since loads produce two values, make sure to remember that we legalized
-    // both of them.
-    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
-    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
-    return Op.ResNo ? Tmp2 : Tmp1;
   }
   case ISD::EXTRACT_ELEMENT: {
     MVT::ValueType OpTy = Node->getOperand(0).getValueType();
@@ -1293,23 +1535,58 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
     Tmp1 = LegalizeOp(Tmp1);
     LastCALLSEQ_END = DAG.getEntryNode();
-    
+      
     switch (Node->getNumOperands()) {
-    case 2:  // ret val
-      switch (getTypeAction(Node->getOperand(1).getValueType())) {
+    case 3:  // ret val
+      Tmp2 = Node->getOperand(1);
+      Tmp3 = Node->getOperand(2);  // Signness
+      switch (getTypeAction(Tmp2.getValueType())) {
       case Legal:
-        Tmp2 = LegalizeOp(Node->getOperand(1));
-        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
+        Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
         break;
-      case Expand: {
-        SDOperand Lo, Hi;
-        ExpandOp(Node->getOperand(1), Lo, Hi);
-        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
+      case Expand:
+        if (Tmp2.getValueType() != MVT::Vector) {
+          SDOperand Lo, Hi;
+          ExpandOp(Tmp2, Lo, Hi);
+          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi, Tmp3);
+          Result = LegalizeOp(Result);
+        } else {
+          SDNode *InVal = Tmp2.Val;
+          unsigned NumElems =
+            cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+          MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+          
+          // Figure out if there is a Packed type corresponding to this Vector
+          // type.  If so, convert to the packed type.
+          MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
+          if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
+            // Turn this into a return of the packed type.
+            Tmp2 = PackVectorOp(Tmp2, TVT);
+            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
+          } else if (NumElems == 1) {
+            // Turn this into a return of the scalar type.
+            Tmp2 = PackVectorOp(Tmp2, EVT);
+            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
+            
+            // FIXME: Returns of gcc generic vectors smaller than a legal type
+            // should be returned in integer registers!
+            
+            // The scalarized value type may not be legal, e.g. it might require
+            // promotion or expansion.  Relegalize the return.
+            Result = LegalizeOp(Result);
+          } else {
+            // FIXME: Returns of gcc generic vectors larger than a legal vector
+            // type should be returned by reference!
+            SDOperand Lo, Hi;
+            SplitVectorOp(Tmp2, Lo, Hi);
+            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi, Tmp3);
+            Result = LegalizeOp(Result);
+          }
+        }
         break;
-      }
       case Promote:
         Tmp2 = PromoteOp(Node->getOperand(1));
-        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
+        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
         Result = LegalizeOp(Result);
         break;
       }
@@ -1318,18 +1595,23 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       Result = DAG.UpdateNodeOperands(Result, Tmp1);
       break;
     default: { // ret <values>
-      std::vector<SDOperand> NewValues;
+      SmallVector<SDOperand, 8> NewValues;
       NewValues.push_back(Tmp1);
-      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
+      for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2)
         switch (getTypeAction(Node->getOperand(i).getValueType())) {
         case Legal:
           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
+          NewValues.push_back(Node->getOperand(i+1));
           break;
         case Expand: {
           SDOperand Lo, Hi;
+          assert(Node->getOperand(i).getValueType() != MVT::Vector &&
+                 "FIXME: TODO: implement returning non-legal vector types!");
           ExpandOp(Node->getOperand(i), Lo, Hi);
           NewValues.push_back(Lo);
+          NewValues.push_back(Node->getOperand(i+1));
           NewValues.push_back(Hi);
+          NewValues.push_back(Node->getOperand(i+1));
           break;
         }
         case Promote:
@@ -1337,9 +1619,10 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         }
           
       if (NewValues.size() == Node->getNumOperands())
-        Result = DAG.UpdateNodeOperands(Result, NewValues);
+        Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
       else
-        Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
+        Result = DAG.getNode(ISD::RET, MVT::Other,
+                             &NewValues[0], NewValues.size());
       break;
     }
     }
@@ -1356,101 +1639,144 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     }
     break;
   case ISD::STORE: {
-    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
-    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
-
-    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
-    // FIXME: We shouldn't do this for TargetConstantFP's.
-    // FIXME: move this to the DAG Combiner!
-    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
-      if (CFP->getValueType(0) == MVT::f32) {
-        Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
-      } else {
-        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
-        Tmp3 = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
+    StoreSDNode *ST = cast<StoreSDNode>(Node);
+    Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
+    Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
+
+    if (!ST->isTruncatingStore()) {
+      // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
+      // FIXME: We shouldn't do this for TargetConstantFP's.
+      // FIXME: move this to the DAG Combiner!
+      if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(ST->getValue())) {
+        if (CFP->getValueType(0) == MVT::f32) {
+          Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
+        } else {
+          assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
+          Tmp3 = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
+        }
+        Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
+                              ST->getSrcValueOffset());
+        break;
       }
-      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Tmp3, Tmp2, 
-                           Node->getOperand(3));
-      break;
-    }
 
-    switch (getTypeAction(Node->getOperand(1).getValueType())) {
-    case Legal: {
-      Tmp3 = LegalizeOp(Node->getOperand(1));
-      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
-                                      Node->getOperand(3));
-
-      MVT::ValueType VT = Tmp3.getValueType();
-      switch (TLI.getOperationAction(ISD::STORE, VT)) {
-      default: assert(0 && "This action is not supported yet!");
-      case TargetLowering::Legal:  break;
-      case TargetLowering::Custom:
-        Tmp1 = TLI.LowerOperation(Result, DAG);
-        if (Tmp1.Val) Result = Tmp1;
+      switch (getTypeAction(ST->getStoredVT())) {
+      case Legal: {
+        Tmp3 = LegalizeOp(ST->getValue());
+        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
+                                        ST->getOffset());
+
+        MVT::ValueType VT = Tmp3.getValueType();
+        switch (TLI.getOperationAction(ISD::STORE, VT)) {
+        default: assert(0 && "This action is not supported yet!");
+        case TargetLowering::Legal:  break;
+        case TargetLowering::Custom:
+          Tmp1 = TLI.LowerOperation(Result, DAG);
+          if (Tmp1.Val) Result = Tmp1;
+          break;
+        case TargetLowering::Promote:
+          assert(MVT::isVector(VT) && "Unknown legal promote case!");
+          Tmp3 = DAG.getNode(ISD::BIT_CONVERT, 
+                             TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
+          Result = DAG.getStore(Tmp1, Tmp3, Tmp2,
+                                ST->getSrcValue(), ST->getSrcValueOffset());
+          break;
+        }
         break;
       }
-      break;
-    }
-    case Promote:
-      // Truncate the value and store the result.
-      Tmp3 = PromoteOp(Node->getOperand(1));
-      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
-                           Node->getOperand(3),
-                          DAG.getValueType(Node->getOperand(1).getValueType()));
-      break;
+      case Promote:
+        // Truncate the value and store the result.
+        Tmp3 = PromoteOp(ST->getValue());
+        Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
+                                   ST->getSrcValueOffset(), ST->getStoredVT());
+        break;
 
-    case Expand:
-      unsigned IncrementSize = 0;
-      SDOperand Lo, Hi;
+      case Expand:
+        unsigned IncrementSize = 0;
+        SDOperand Lo, Hi;
       
-      // If this is a vector type, then we have to calculate the increment as
-      // the product of the element size in bytes, and the number of elements
-      // in the high half of the vector.
-      if (Node->getOperand(1).getValueType() == MVT::Vector) {
-        SDNode *InVal = Node->getOperand(1).Val;
-        unsigned NumElems =
-          cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
-        MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
-
-        // Figure out if there is a Packed type corresponding to this Vector
-        // type.  If so, convert to the packed type.
-        MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
-        if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
-          // Turn this into a normal store of the packed type.
-          Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
-          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
-                                          Node->getOperand(3));
-          break;
-        } else if (NumElems == 1) {
-          // Turn this into a normal store of the scalar type.
-          Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
-          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
-                                          Node->getOperand(3));
-          break;
+        // If this is a vector type, then we have to calculate the increment as
+        // the product of the element size in bytes, and the number of elements
+        // in the high half of the vector.
+        if (ST->getValue().getValueType() == MVT::Vector) {
+          SDNode *InVal = ST->getValue().Val;
+          unsigned NumElems =
+            cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+          MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+
+          // Figure out if there is a Packed type corresponding to this Vector
+          // type.  If so, convert to the packed type.
+          MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
+          if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
+            // Turn this into a normal store of the packed type.
+            Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
+            Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
+                                  ST->getSrcValueOffset());
+            Result = LegalizeOp(Result);
+            break;
+          } else if (NumElems == 1) {
+            // Turn this into a normal store of the scalar type.
+            Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
+            Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
+                                  ST->getSrcValueOffset());
+            // The scalarized value type may not be legal, e.g. it might require
+            // promotion or expansion.  Relegalize the scalar store.
+            Result = LegalizeOp(Result);
+            break;
+          } else {
+            SplitVectorOp(Node->getOperand(1), Lo, Hi);
+            IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
+          }
         } else {
-          SplitVectorOp(Node->getOperand(1), Lo, Hi);
-          IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
+          ExpandOp(Node->getOperand(1), Lo, Hi);
+          IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
+
+          if (!TLI.isLittleEndian())
+            std::swap(Lo, Hi);
         }
-      } else {
-        ExpandOp(Node->getOperand(1), Lo, Hi);
-        IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
-      }
 
-      if (!TLI.isLittleEndian())
-        std::swap(Lo, Hi);
+        Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
+                          ST->getSrcValueOffset());
+        Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
+                           getIntPtrConstant(IncrementSize));
+        assert(isTypeLegal(Tmp2.getValueType()) &&
+               "Pointers must be legal!");
+        // FIXME: This sets the srcvalue of both halves to be the same, which is
+        // wrong.
+        Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
+                          ST->getSrcValueOffset());
+        Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
+        break;
+      }
+    } else {
+      // Truncating store
+      assert(isTypeLegal(ST->getValue().getValueType()) &&
+             "Cannot handle illegal TRUNCSTORE yet!");
+      Tmp3 = LegalizeOp(ST->getValue());
+    
+      // The only promote case we handle is TRUNCSTORE:i1 X into
+      //   -> TRUNCSTORE:i8 (and X, 1)
+      if (ST->getStoredVT() == MVT::i1 &&
+          TLI.getStoreXAction(MVT::i1) == TargetLowering::Promote) {
+        // Promote the bool to a mask then store.
+        Tmp3 = DAG.getNode(ISD::AND, Tmp3.getValueType(), Tmp3,
+                           DAG.getConstant(1, Tmp3.getValueType()));
+        Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
+                                   ST->getSrcValueOffset(), MVT::i8);
+      } else if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
+                 Tmp2 != ST->getBasePtr()) {
+        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
+                                        ST->getOffset());
+      }
 
-      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
-                       Node->getOperand(3));
-      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
-                         getIntPtrConstant(IncrementSize));
-      assert(isTypeLegal(Tmp2.getValueType()) &&
-             "Pointers must be legal!");
-      // FIXME: This sets the srcvalue of both halves to be the same, which is
-      // wrong.
-      Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
-                       Node->getOperand(3));
-      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
-      break;
+      MVT::ValueType StVT = cast<StoreSDNode>(Result.Val)->getStoredVT();
+      switch (TLI.getStoreXAction(StVT)) {
+      default: assert(0 && "This action is not supported yet!");
+      case TargetLowering::Legal: break;
+      case TargetLowering::Custom:
+        Tmp1 = TLI.LowerOperation(Result, DAG);
+        if (Tmp1.Val) Result = Tmp1;
+        break;
+      }
     }
     break;
   }
@@ -1528,42 +1854,6 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
     return Result;
 
-  case ISD::TRUNCSTORE: {
-    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
-    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
-
-    assert(isTypeLegal(Node->getOperand(1).getValueType()) &&
-           "Cannot handle illegal TRUNCSTORE yet!");
-    Tmp2 = LegalizeOp(Node->getOperand(1));
-    
-    // The only promote case we handle is TRUNCSTORE:i1 X into
-    //   -> TRUNCSTORE:i8 (and X, 1)
-    if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
-        TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) == 
-              TargetLowering::Promote) {
-      // Promote the bool to a mask then store.
-      Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
-                         DAG.getConstant(1, Tmp2.getValueType()));
-      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
-                           Node->getOperand(3), DAG.getValueType(MVT::i8));
-
-    } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
-               Tmp3 != Node->getOperand(2)) {
-      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
-                                      Node->getOperand(3), Node->getOperand(4));
-    }
-
-    MVT::ValueType StVT = cast<VTSDNode>(Result.Val->getOperand(4))->getVT();
-    switch (TLI.getOperationAction(Result.Val->getOpcode(), StVT)) {
-    default: assert(0 && "This action is not supported yet!");
-    case TargetLowering::Legal: break;
-    case TargetLowering::Custom:
-      Tmp1 = TLI.LowerOperation(Result, DAG);
-      if (Tmp1.Val) Result = Tmp1;
-      break;
-    }
-    break;
-  }
   case ISD::SELECT:
     switch (getTypeAction(Node->getOperand(0).getValueType())) {
     case Expand: assert(0 && "It's impossible to expand bools");
@@ -1607,7 +1897,10 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       MVT::ValueType NVT =
         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
       unsigned ExtOp, TruncOp;
-      if (MVT::isInteger(Tmp2.getValueType())) {
+      if (MVT::isVector(Tmp2.getValueType())) {
+        ExtOp   = ISD::BIT_CONVERT;
+        TruncOp = ISD::BIT_CONVERT;
+      } else if (MVT::isInteger(Tmp2.getValueType())) {
         ExtOp   = ISD::ANY_EXTEND;
         TruncOp = ISD::TRUNCATE;
       } else {
@@ -1784,7 +2077,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       // Otherwise, the target does not support this operation.  Lower the
       // operation to an explicit libcall as appropriate.
       MVT::ValueType IntPtr = TLI.getPointerTy();
-      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
+      const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
       std::vector<std::pair<SDOperand, const Type*> > Args;
 
       const char *FnName = 0;
@@ -1823,14 +2116,14 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   case ISD::SHL_PARTS:
   case ISD::SRA_PARTS:
   case ISD::SRL_PARTS: {
-    std::vector<SDOperand> Ops;
+    SmallVector<SDOperand, 8> Ops;
     bool Changed = false;
     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
       Ops.push_back(LegalizeOp(Node->getOperand(i)));
       Changed |= Ops.back() != Node->getOperand(i);
     }
     if (Changed)
-      Result = DAG.UpdateNodeOperands(Result, Ops);
+      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
 
     switch (TLI.getOperationAction(Node->getOpcode(),
                                    Node->getValueType(0))) {
@@ -1891,12 +2184,62 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
       
     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
-    default: assert(0 && "Operation not supported");
+    default: assert(0 && "BinOp legalize operation not supported");
     case TargetLowering::Legal: break;
     case TargetLowering::Custom:
       Tmp1 = TLI.LowerOperation(Result, DAG);
       if (Tmp1.Val) Result = Tmp1;
       break;
+    case TargetLowering::Expand: {
+      if (Node->getValueType(0) == MVT::i32) {
+        switch (Node->getOpcode()) {
+        default:  assert(0 && "Do not know how to expand this integer BinOp!");
+        case ISD::UDIV:
+        case ISD::SDIV:
+          const char *FnName = Node->getOpcode() == ISD::UDIV
+            ? "__udivsi3" : "__divsi3";
+          SDOperand Dummy;
+          Result = ExpandLibCall(FnName, Node, Dummy);
+        };
+        break;
+      }
+
+      assert(MVT::isVector(Node->getValueType(0)) &&
+             "Cannot expand this binary operator!");
+      // Expand the operation into a bunch of nasty scalar code.
+      SmallVector<SDOperand, 8> Ops;
+      MVT::ValueType EltVT = MVT::getVectorBaseType(Node->getValueType(0));
+      MVT::ValueType PtrVT = TLI.getPointerTy();
+      for (unsigned i = 0, e = MVT::getVectorNumElements(Node->getValueType(0));
+           i != e; ++i) {
+        SDOperand Idx = DAG.getConstant(i, PtrVT);
+        SDOperand LHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1, Idx);
+        SDOperand RHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2, Idx);
+        Ops.push_back(DAG.getNode(Node->getOpcode(), EltVT, LHS, RHS));
+      }
+      Result = DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0), 
+                           &Ops[0], Ops.size());
+      break;
+    }
+    case TargetLowering::Promote: {
+      switch (Node->getOpcode()) {
+      default:  assert(0 && "Do not know how to promote this BinOp!");
+      case ISD::AND:
+      case ISD::OR:
+      case ISD::XOR: {
+        MVT::ValueType OVT = Node->getValueType(0);
+        MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
+        assert(MVT::isVector(OVT) && "Cannot promote this BinOp!");
+        // Bit convert each of the values to the new type.
+        Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
+        Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
+        Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
+        // Bit convert the result back the original type.
+        Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
+        break;
+      }
+      }
+    }
     }
     break;
     
@@ -2031,13 +2374,23 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       }
       break;
     case TargetLowering::Expand:
+      unsigned DivOpc= (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
       if (MVT::isInteger(Node->getValueType(0))) {
-        // X % Y -> X-X/Y*Y
-        MVT::ValueType VT = Node->getValueType(0);
-        unsigned Opc = Node->getOpcode() == ISD::UREM ? ISD::UDIV : ISD::SDIV;
-        Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
-        Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
-        Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
+        if (TLI.getOperationAction(DivOpc, Node->getValueType(0)) ==
+            TargetLowering::Legal) {
+          // X % Y -> X-X/Y*Y
+          MVT::ValueType VT = Node->getValueType(0);
+          Result = DAG.getNode(DivOpc, VT, Tmp1, Tmp2);
+          Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
+          Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
+        } else {
+          assert(Node->getValueType(0) == MVT::i32 &&
+                 "Cannot expand this binary operator!");
+          const char *FnName = Node->getOpcode() == ISD::UREM
+            ? "__umodsi3" : "__modsi3";
+          SDOperand Dummy;
+          Result = ExpandLibCall(FnName, Node, Dummy);
+        }
       } else {
         // Floating point mod -> fmod libcall.
         const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
@@ -2071,17 +2424,18 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       }
       break;
     case TargetLowering::Expand: {
+      SrcValueSDNode *SV = cast<SrcValueSDNode>(Node->getOperand(2));
       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
-                                     Node->getOperand(2));
+                                     SV->getValue(), SV->getOffset());
       // Increment the pointer, VAList, to the next vaarg
       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
                                          TLI.getPointerTy()));
       // Store the incremented VAList to the legalized pointer
-      Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
-                         Node->getOperand(2));
+      Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, SV->getValue(),
+                          SV->getOffset());
       // Load the actual argument out of the pointer VAList
-      Result = DAG.getLoad(VT, Tmp3, VAList, DAG.getSrcValue(0));
+      Result = DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
       Tmp1 = LegalizeOp(Result.getValue(1));
       Result = LegalizeOp(Result);
       break;
@@ -2115,9 +2469,12 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     case TargetLowering::Expand:
       // This defaults to loading a pointer from the input and storing it to the
       // output, returning the chain.
-      Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, Node->getOperand(3));
-      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp4.getValue(1), Tmp4, Tmp2,
-                           Node->getOperand(4));
+      SrcValueSDNode *SVD = cast<SrcValueSDNode>(Node->getOperand(3));
+      SrcValueSDNode *SVS = cast<SrcValueSDNode>(Node->getOperand(4));
+      Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, SVD->getValue(),
+                         SVD->getOffset());
+      Result = DAG.getStore(Tmp4.getValue(1), Tmp4, Tmp2, SVS->getValue(),
+                            SVS->getOffset());
       break;
     }
     break;
@@ -2294,7 +2651,14 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       break;
     }
     break;
-    
+  case ISD::FPOWI: {
+    // We always lower FPOWI into a libcall.  No target support it yet.
+    const char *FnName = Node->getValueType(0) == MVT::f32
+                            ? "__powisf2" : "__powidf2";
+    SDOperand Dummy;
+    Result = ExpandLibCall(FnName, Node, Dummy);
+    break;
+  }
   case ISD::BIT_CONVERT:
     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
       Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
@@ -2312,6 +2676,36 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       }
     }
     break;
+  case ISD::VBIT_CONVERT: {
+    assert(Op.getOperand(0).getValueType() == MVT::Vector &&
+           "Can only have VBIT_CONVERT where input or output is MVT::Vector!");
+    
+    // The input has to be a vector type, we have to either scalarize it, pack
+    // it, or convert it based on whether the input vector type is legal.
+    SDNode *InVal = Node->getOperand(0).Val;
+    unsigned NumElems =
+      cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+    MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+    
+    // Figure out if there is a Packed type corresponding to this Vector
+    // type.  If so, convert to the packed type.
+    MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
+    if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
+      // Turn this into a bit convert of the packed input.
+      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
+                           PackVectorOp(Node->getOperand(0), TVT));
+      break;
+    } else if (NumElems == 1) {
+      // Turn this into a bit convert of the scalar input.
+      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
+                           PackVectorOp(Node->getOperand(0), EVT));
+      break;
+    } else {
+      // FIXME: UNIMP!  Store then reload
+      assert(0 && "Cast from unsupported vector type not implemented yet!");
+    }
+  }
+      
     // Conversion operators.  The source and destination have different types.
   case ISD::SINT_TO_FP:
   case ISD::UINT_TO_FP: {
@@ -2506,25 +2900,23 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
                              Result, ShiftCst);
       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
-        // The only way we can lower this is to turn it into a STORETRUNC,
+        // The only way we can lower this is to turn it into a TRUNCSTORE,
         // EXTLOAD pair, targetting a temporary location (a stack slot).
 
         // NOTE: there is a choice here between constantly creating new stack
         // slots and always reusing the same one.  We currently always create
         // new ones, as reuse may inhibit scheduling.
         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
-        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
-        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
+        unsigned TySize = (unsigned)TLI.getTargetData()->getTypeSize(Ty);
+        unsigned Align  = TLI.getTargetData()->getTypeAlignment(Ty);
         MachineFunction &MF = DAG.getMachineFunction();
         int SSFI =
           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
-        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
-                             Node->getOperand(0), StackSlot,
-                             DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
+        Result = DAG.getTruncStore(DAG.getEntryNode(), Node->getOperand(0),
+                                   StackSlot, NULL, 0, ExtraVT);
         Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
-                                Result, StackSlot, DAG.getSrcValue(NULL),
-                                ExtraVT);
+                                Result, StackSlot, NULL, 0, ExtraVT);
       } else {
         assert(0 && "Unknown op");
       }
@@ -2534,6 +2926,9 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   }
   }
   
+  assert(Result.getValueType() == Op.getValueType() &&
+         "Bad legalization!");
+  
   // Make sure that the generated code is itself legal.
   if (Result != Op)
     Result = LegalizeOp(Result);
@@ -2567,7 +2962,9 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
   case ISD::CopyFromReg:
     assert(0 && "CopyFromReg must be legal!");
   default:
+#ifndef NDEBUG
     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
+#endif
     assert(0 && "Do not know how to promote this operator!");
     abort();
   case ISD::UNDEF:
@@ -2590,7 +2987,7 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
                          Node->getOperand(1), Node->getOperand(2));
     break;
-
+    
   case ISD::TRUNCATE:
     switch (getTypeAction(Node->getOperand(0).getValueType())) {
     case Legal:
@@ -2792,8 +3189,26 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
   case ISD::FREM:
   case ISD::FCOPYSIGN:
     // These operators require that their input be fp extended.
-    Tmp1 = PromoteOp(Node->getOperand(0));
-    Tmp2 = PromoteOp(Node->getOperand(1));
+    switch (getTypeAction(Node->getOperand(0).getValueType())) {
+      case Legal:
+        Tmp1 = LegalizeOp(Node->getOperand(0));
+        break;
+      case Promote:
+        Tmp1 = PromoteOp(Node->getOperand(0));
+        break;
+      case Expand:
+        assert(0 && "not implemented");
+    }
+    switch (getTypeAction(Node->getOperand(1).getValueType())) {
+      case Legal:
+        Tmp2 = LegalizeOp(Node->getOperand(1));
+        break;
+      case Promote:
+        Tmp2 = PromoteOp(Node->getOperand(1));
+        break;
+      case Expand:
+        assert(0 && "not implemented");
+    }
     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
     
     // Perform FP_ROUND: this is probably overly pessimistic.
@@ -2838,38 +3253,35 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
       Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
       Result = TLI.CustomPromoteOperation(Tmp3, DAG);
     } else {
+      SrcValueSDNode *SV = cast<SrcValueSDNode>(Node->getOperand(2));
       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
-                                     Node->getOperand(2));
+                                     SV->getValue(), SV->getOffset());
       // Increment the pointer, VAList, to the next vaarg
       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
                                          TLI.getPointerTy()));
       // Store the incremented VAList to the legalized pointer
-      Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
-                         Node->getOperand(2));
+      Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, SV->getValue(),
+                          SV->getOffset());
       // Load the actual argument out of the pointer VAList
-      Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList,
-                              DAG.getSrcValue(0), VT);
+      Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList, NULL, 0, VT);
     }
     // Remember that we legalized the chain.
     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
     break;
 
-  case ISD::LOAD:
-    Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Node->getOperand(0),
-                            Node->getOperand(1), Node->getOperand(2), VT);
-    // Remember that we legalized the chain.
-    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
-    break;
-  case ISD::SEXTLOAD:
-  case ISD::ZEXTLOAD:
-  case ISD::EXTLOAD:
-    Result = DAG.getExtLoad(Node->getOpcode(), NVT, Node->getOperand(0),
-                            Node->getOperand(1), Node->getOperand(2),
-                            cast<VTSDNode>(Node->getOperand(3))->getVT());
+  case ISD::LOAD: {
+    LoadSDNode *LD = cast<LoadSDNode>(Node);
+    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(Node)
+      ? ISD::EXTLOAD : LD->getExtensionType();
+    Result = DAG.getExtLoad(ExtType, NVT,
+                            LD->getChain(), LD->getBasePtr(),
+                            LD->getSrcValue(), LD->getSrcValueOffset(),
+                            LD->getLoadedVT());
     // Remember that we legalized the chain.
     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
     break;
+  }
   case ISD::SELECT:
     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
@@ -2915,6 +3327,12 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
       break;
     }
     break;
+  case ISD::VEXTRACT_VECTOR_ELT:
+    Result = PromoteOp(LowerVEXTRACT_VECTOR_ELT(Op));
+    break;
+  case ISD::EXTRACT_VECTOR_ELT:
+    Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
+    break;
   }
 
   assert(Result.Val && "Didn't set a result!");
@@ -2927,6 +3345,73 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
   return Result;
 }
 
+/// LowerVEXTRACT_VECTOR_ELT - Lower a VEXTRACT_VECTOR_ELT operation into a
+/// EXTRACT_VECTOR_ELT operation, to memory operations, or to scalar code based
+/// on the vector type.  The return type of this matches the element type of the
+/// vector, which may not be legal for the target.
+SDOperand SelectionDAGLegalize::LowerVEXTRACT_VECTOR_ELT(SDOperand Op) {
+  // We know that operand #0 is the Vec vector.  If the index is a constant
+  // or if the invec is a supported hardware type, we can use it.  Otherwise,
+  // lower to a store then an indexed load.
+  SDOperand Vec = Op.getOperand(0);
+  SDOperand Idx = LegalizeOp(Op.getOperand(1));
+  
+  SDNode *InVal = Vec.Val;
+  unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+  MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+  
+  // Figure out if there is a Packed type corresponding to this Vector
+  // type.  If so, convert to the packed type.
+  MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
+  if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
+    // Turn this into a packed extract_vector_elt operation.
+    Vec = PackVectorOp(Vec, TVT);
+    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Op.getValueType(), Vec, Idx);
+  } else if (NumElems == 1) {
+    // This must be an access of the only element.  Return it.
+    return PackVectorOp(Vec, EVT);
+  } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
+    SDOperand Lo, Hi;
+    SplitVectorOp(Vec, Lo, Hi);
+    if (CIdx->getValue() < NumElems/2) {
+      Vec = Lo;
+    } else {
+      Vec = Hi;
+      Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
+    }
+    
+    // It's now an extract from the appropriate high or low part.  Recurse.
+    Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
+    return LowerVEXTRACT_VECTOR_ELT(Op);
+  } else {
+    // Variable index case for extract element.
+    // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
+    assert(0 && "unimp!");
+    return SDOperand();
+  }
+}
+
+/// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
+/// memory traffic.
+SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
+  SDOperand Vector = Op.getOperand(0);
+  SDOperand Idx    = Op.getOperand(1);
+  
+  // If the target doesn't support this, store the value to a temporary
+  // stack slot, then LOAD the scalar element back out.
+  SDOperand StackPtr = CreateStackTemporary(Vector.getValueType());
+  SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Vector, StackPtr, NULL, 0);
+  
+  // Add the offset to the index.
+  unsigned EltSize = MVT::getSizeInBits(Op.getValueType())/8;
+  Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
+                    DAG.getConstant(EltSize, Idx.getValueType()));
+  StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
+  
+  return DAG.getLoad(Op.getValueType(), Ch, StackPtr, NULL, 0);
+}
+
+
 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
 /// with condition CC on the current target.  This usually involves legalizing
 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
@@ -3058,26 +3543,50 @@ SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT,
   SDOperand FIPtr = CreateStackTemporary(DestVT);
   
   // Emit a store to the stack slot.
-  SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
-                                SrcOp, FIPtr, DAG.getSrcValue(NULL));
+  SDOperand Store = DAG.getStore(DAG.getEntryNode(), SrcOp, FIPtr, NULL, 0);
   // Result is a load from the stack slot.
-  return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
+  return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
+}
+
+SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
+  // Create a vector sized/aligned stack slot, store the value to element #0,
+  // then load the whole vector back out.
+  SDOperand StackPtr = CreateStackTemporary(Node->getValueType(0));
+  SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Node->getOperand(0), StackPtr,
+                              NULL, 0);
+  return DAG.getLoad(Node->getValueType(0), Ch, StackPtr, NULL, 0);
 }
 
+
 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
 /// support the operation, but do support the resultant packed vector type.
 SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
   
   // If the only non-undef value is the low element, turn this into a 
   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
+  unsigned NumElems = Node->getNumOperands();
   bool isOnlyLowElement = true;
   SDOperand SplatValue = Node->getOperand(0);
-  for (SDNode::op_iterator I = Node->op_begin()+1, E = Node->op_end();
-       I != E; ++I) {
-    if (I->getOpcode() != ISD::UNDEF)
+  std::map<SDOperand, std::vector<unsigned> > Values;
+  Values[SplatValue].push_back(0);
+  bool isConstant = true;
+  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
+      SplatValue.getOpcode() != ISD::UNDEF)
+    isConstant = false;
+  
+  for (unsigned i = 1; i < NumElems; ++i) {
+    SDOperand V = Node->getOperand(i);
+    Values[V].push_back(i);
+    if (V.getOpcode() != ISD::UNDEF)
       isOnlyLowElement = false;
-    if (SplatValue != *I)
+    if (SplatValue != V)
       SplatValue = SDOperand(0,0);
+
+    // If this isn't a constant element or an undef, we can't use a constant
+    // pool load.
+    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
+        V.getOpcode() != ISD::UNDEF)
+      isConstant = false;
   }
   
   if (isOnlyLowElement) {
@@ -3089,16 +3598,40 @@ SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
                        Node->getOperand(0));
   }
   
+  // If all elements are constants, create a load from the constant pool.
+  if (isConstant) {
+    MVT::ValueType VT = Node->getValueType(0);
+    const Type *OpNTy = 
+      MVT::getTypeForValueType(Node->getOperand(0).getValueType());
+    std::vector<Constant*> CV;
+    for (unsigned i = 0, e = NumElems; i != e; ++i) {
+      if (ConstantFPSDNode *V = 
+          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
+        CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
+      } else if (ConstantSDNode *V = 
+                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
+        CV.push_back(ConstantInt::get(OpNTy, V->getValue()));
+      } else {
+        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
+        CV.push_back(UndefValue::get(OpNTy));
+      }
+    }
+    Constant *CP = ConstantPacked::get(CV);
+    SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
+    return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0);
+  }
+  
   if (SplatValue.Val) {   // Splat of one value?
     // Build the shuffle constant vector: <0, 0, 0, 0>
     MVT::ValueType MaskVT = 
-      MVT::getIntVectorWithNumElements(Node->getNumOperands());
+      MVT::getIntVectorWithNumElements(NumElems);
     SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
-    std::vector<SDOperand> ZeroVec(Node->getNumOperands(), Zero);
-    SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec);
+    std::vector<SDOperand> ZeroVec(NumElems, Zero);
+    SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
+                                      &ZeroVec[0], ZeroVec.size());
 
     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
-    if (TLI.isShuffleLegal(Node->getValueType(0), SplatMask)) {
+    if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
       // Get the splatted value into the low element of a vector register.
       SDOperand LowValVec = 
         DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
@@ -3110,40 +3643,40 @@ SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
     }
   }
   
-  // If the elements are all constants, turn this into a load from the constant
-  // pool.
-  bool isConstant = true;
-  for (SDNode::op_iterator I = Node->op_begin(), E = Node->op_end();
-       I != E; ++I) {
-    if (!isa<ConstantFPSDNode>(I) && !isa<ConstantSDNode>(I) &&
-        I->getOpcode() != ISD::UNDEF) {
-      isConstant = false;
-      break;
+  // If there are only two unique elements, we may be able to turn this into a
+  // vector shuffle.
+  if (Values.size() == 2) {
+    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
+    MVT::ValueType MaskVT = 
+      MVT::getIntVectorWithNumElements(NumElems);
+    std::vector<SDOperand> MaskVec(NumElems);
+    unsigned i = 0;
+    for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
+           E = Values.end(); I != E; ++I) {
+      for (std::vector<unsigned>::iterator II = I->second.begin(),
+             EE = I->second.end(); II != EE; ++II)
+        MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
+      i += NumElems;
     }
-  }
-  
-  // Create a ConstantPacked, and put it in the constant pool.
-  if (isConstant) {
-    MVT::ValueType VT = Node->getValueType(0);
-    const Type *OpNTy = 
-      MVT::getTypeForValueType(Node->getOperand(0).getValueType());
-    std::vector<Constant*> CV;
-    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
-      if (ConstantFPSDNode *V = 
-          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
-        CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
-      } else if (ConstantSDNode *V = 
-                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
-        CV.push_back(ConstantUInt::get(OpNTy, V->getValue()));
-      } else {
-        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
-        CV.push_back(UndefValue::get(OpNTy));
+    SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
+                                        &MaskVec[0], MaskVec.size());
+
+    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
+    if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
+        isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
+      SmallVector<SDOperand, 8> Ops;
+      for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
+            E = Values.end(); I != E; ++I) {
+        SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
+                                   I->first);
+        Ops.push_back(Op);
       }
+      Ops.push_back(ShuffleMask);
+
+      // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
+      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), 
+                         &Ops[0], Ops.size());
     }
-    Constant *CP = ConstantPacked::get(CV);
-    SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
-    return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
-                       DAG.getSrcValue(NULL));
   }
   
   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
@@ -3154,10 +3687,9 @@ SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
   SDOperand FIPtr = CreateStackTemporary(VT);
   
   // Emit a store of each element to the stack slot.
-  std::vector<SDOperand> Stores;
+  SmallVector<SDOperand, 8> Stores;
   unsigned TypeByteSize = 
     MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
-  unsigned VectorSize = MVT::getSizeInBits(VT)/8;
   // Store (in the right endianness) the elements to memory.
   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
     // Ignore undef elements.
@@ -3168,19 +3700,19 @@ SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
     SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
     Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
     
-    Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
-                                 Node->getOperand(i), Idx, 
-                                 DAG.getSrcValue(NULL)));
+    Stores.push_back(DAG.getStore(DAG.getEntryNode(), Node->getOperand(i), Idx, 
+                                  NULL, 0));
   }
   
   SDOperand StoreChain;
   if (!Stores.empty())    // Not all undef elements?
-    StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
+    StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
+                             &Stores[0], Stores.size());
   else
     StoreChain = DAG.getEntryNode();
   
   // Result is a load from the stack slot.
-  return DAG.getLoad(VT, StoreChain, FIPtr, DAG.getSrcValue(0));
+  return DAG.getLoad(VT, StoreChain, FIPtr, NULL, 0);
 }
 
 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
@@ -3199,12 +3731,9 @@ void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
   SDOperand LHSL, LHSH;
   ExpandOp(Op, LHSL, LHSH);
 
-  std::vector<SDOperand> Ops;
-  Ops.push_back(LHSL);
-  Ops.push_back(LHSH);
-  Ops.push_back(Amt);
-  std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
-  Lo = DAG.getNode(NodeOp, VTs, Ops);
+  SDOperand Ops[] = { LHSL, LHSH, Amt };
+  MVT::ValueType VT = LHSL.getValueType();
+  Lo = DAG.getNode(NodeOp, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
   Hi = Lo.getValue(1);
 }
 
@@ -3288,6 +3817,72 @@ bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
       return true;
     }
   }
+  
+  // Okay, the shift amount isn't constant.  However, if we can tell that it is
+  // >= 32 or < 32, we can still simplify it, without knowing the actual value.
+  uint64_t Mask = NVTBits, KnownZero, KnownOne;
+  TLI.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
+  
+  // If we know that the high bit of the shift amount is one, then we can do
+  // this as a couple of simple shifts.
+  if (KnownOne & Mask) {
+    // Mask out the high bit, which we know is set.
+    Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
+                      DAG.getConstant(NVTBits-1, Amt.getValueType()));
+    
+    // Expand the incoming operand to be shifted, so that we have its parts
+    SDOperand InL, InH;
+    ExpandOp(Op, InL, InH);
+    switch(Opc) {
+    case ISD::SHL:
+      Lo = DAG.getConstant(0, NVT);              // Low part is zero.
+      Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
+      return true;
+    case ISD::SRL:
+      Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
+      Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
+      return true;
+    case ISD::SRA:
+      Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
+                       DAG.getConstant(NVTBits-1, Amt.getValueType()));
+      Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
+      return true;
+    }
+  }
+  
+  // If we know that the high bit of the shift amount is zero, then we can do
+  // this as a couple of simple shifts.
+  if (KnownZero & Mask) {
+    // Compute 32-amt.
+    SDOperand Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
+                                 DAG.getConstant(NVTBits, Amt.getValueType()),
+                                 Amt);
+    
+    // Expand the incoming operand to be shifted, so that we have its parts
+    SDOperand InL, InH;
+    ExpandOp(Op, InL, InH);
+    switch(Opc) {
+    case ISD::SHL:
+      Lo = DAG.getNode(ISD::SHL, NVT, InL, Amt);
+      Hi = DAG.getNode(ISD::OR, NVT,
+                       DAG.getNode(ISD::SHL, NVT, InH, Amt),
+                       DAG.getNode(ISD::SRL, NVT, InL, Amt2));
+      return true;
+    case ISD::SRL:
+      Hi = DAG.getNode(ISD::SRL, NVT, InH, Amt);
+      Lo = DAG.getNode(ISD::OR, NVT,
+                       DAG.getNode(ISD::SRL, NVT, InL, Amt),
+                       DAG.getNode(ISD::SHL, NVT, InH, Amt2));
+      return true;
+    case ISD::SRA:
+      Hi = DAG.getNode(ISD::SRA, NVT, InH, Amt);
+      Lo = DAG.getNode(ISD::OR, NVT,
+                       DAG.getNode(ISD::SRL, NVT, InL, Amt),
+                       DAG.getNode(ISD::SHL, NVT, InH, Amt2));
+      return true;
+    }
+  }
+  
   return false;
 }
 
@@ -3367,18 +3962,17 @@ ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
                                       SignSet, Four, Zero);
     uint64_t FF = 0x5f800000ULL;
     if (TLI.isLittleEndian()) FF <<= 32;
-    static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
+    static Constant *FudgeFactor = ConstantInt::get(Type::ULongTy, FF);
 
     SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
     SDOperand FudgeInReg;
     if (DestTy == MVT::f32)
-      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
-                               DAG.getSrcValue(NULL));
+      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, NULL, 0);
     else {
       assert(DestTy == MVT::f64 && "Unexpected conversion");
       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
-                                  CPIdx, DAG.getSrcValue(NULL), MVT::f32);
+                                  CPIdx, NULL, 0, MVT::f32);
     }
     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
   }
@@ -3435,14 +4029,11 @@ SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
     // word offset constant for Hi/Lo address computation
     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
     // set up Hi and Lo (into buffer) address based on endian
-    SDOperand Hi, Lo;
-    if (TLI.isLittleEndian()) {
-      Hi = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
-      Lo = StackSlot;
-    } else {
-      Hi = StackSlot;
-      Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
-    }
+    SDOperand Hi = StackSlot;
+    SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
+    if (TLI.isLittleEndian())
+      std::swap(Hi, Lo);
+    
     // if signed map to unsigned space
     SDOperand Op0Mapped;
     if (isSigned) {
@@ -3453,16 +4044,14 @@ SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
       Op0Mapped = Op0;
     }
     // store the lo of the constructed double - based on integer input
-    SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
-                                   Op0Mapped, Lo, DAG.getSrcValue(NULL));
+    SDOperand Store1 = DAG.getStore(DAG.getEntryNode(),
+                                    Op0Mapped, Lo, NULL, 0);
     // initial hi portion of constructed double
     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
     // store the hi of the constructed double - biased exponent
-    SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
-                                   InitialHi, Hi, DAG.getSrcValue(NULL));
+    SDOperand Store2=DAG.getStore(Store1, InitialHi, Hi, NULL, 0);
     // load the constructed double
-    SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
-                               DAG.getSrcValue(NULL));
+    SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot, NULL, 0);
     // FP constant to bias correct the final result
     SDOperand Bias = DAG.getConstantFP(isSigned ?
                                             BitsToDouble(0x4330000080000000ULL)
@@ -3504,19 +4093,18 @@ SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
   }
   if (TLI.isLittleEndian()) FF <<= 32;
-  static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
+  static Constant *FudgeFactor = ConstantInt::get(Type::ULongTy, FF);
 
   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
   SDOperand FudgeInReg;
   if (DestVT == MVT::f32)
-    FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
-                             DAG.getSrcValue(NULL));
+    FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, NULL, 0);
   else {
     assert(DestVT == MVT::f64 && "Unexpected conversion");
     FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
                                            DAG.getEntryNode(), CPIdx,
-                                           DAG.getSrcValue(NULL), MVT::f32));
+                                           NULL, 0, MVT::f32));
   }
 
   return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
@@ -3742,7 +4330,6 @@ SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
   }
 }
 
-
 /// ExpandOp - Expand the specified SDOperand into its two component pieces
 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
 /// LegalizeNodes map is filled in for any results that are not expanded, the
@@ -3771,7 +4358,9 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
   case ISD::CopyFromReg:
     assert(0 && "CopyFromReg must be legal!");
   default:
+#ifndef NDEBUG
     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
+#endif
     assert(0 && "Do not know how to expand this operator!");
     abort();
   case ISD::UNDEF:
@@ -3792,12 +4381,14 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
     
   case ISD::SIGN_EXTEND_INREG:
     ExpandOp(Node->getOperand(0), Lo, Hi);
-    // Sign extend the lo-part.
+    // sext_inreg the low part if needed.
+    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
+    
+    // The high part gets the sign extension from the lo-part.  This handles
+    // things like sextinreg V:i64 from i8.
     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
                      DAG.getConstant(MVT::getSizeInBits(NVT)-1,
                                      TLI.getShiftAmountTy()));
-    // sext_inreg the low part if needed.
-    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
     break;
 
   case ISD::BSWAP: {
@@ -3861,26 +4452,57 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
   }
     
   case ISD::LOAD: {
-    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
-    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
-    Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
-
-    // Increment the pointer to the other half.
-    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
-    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
-                      getIntPtrConstant(IncrementSize));
-    // FIXME: This creates a bogus srcvalue!
-    Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
-
-    // Build a factor node to remember that this load is independent of the
-    // other one.
-    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
-                               Hi.getValue(1));
-
-    // Remember that we legalized the chain.
-    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
-    if (!TLI.isLittleEndian())
-      std::swap(Lo, Hi);
+    LoadSDNode *LD = cast<LoadSDNode>(Node);
+    SDOperand Ch  = LD->getChain();    // Legalize the chain.
+    SDOperand Ptr = LD->getBasePtr();  // Legalize the pointer.
+    ISD::LoadExtType ExtType = LD->getExtensionType();
+
+    if (ExtType == ISD::NON_EXTLOAD) {
+      Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), LD->getSrcValueOffset());
+
+      // Increment the pointer to the other half.
+      unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
+      Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
+                        getIntPtrConstant(IncrementSize));
+      // FIXME: This creates a bogus srcvalue!
+      Hi = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), LD->getSrcValueOffset());
+
+      // Build a factor node to remember that this load is independent of the
+      // other one.
+      SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
+                                 Hi.getValue(1));
+
+      // Remember that we legalized the chain.
+      AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
+      if (!TLI.isLittleEndian())
+        std::swap(Lo, Hi);
+    } else {
+      MVT::ValueType EVT = LD->getLoadedVT();
+    
+      if (EVT == NVT)
+        Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(),
+                         LD->getSrcValueOffset());
+      else
+        Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, LD->getSrcValue(),
+                            LD->getSrcValueOffset(), EVT);
+    
+      // Remember that we legalized the chain.
+      AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
+
+      if (ExtType == ISD::SEXTLOAD) {
+        // The high part is obtained by SRA'ing all but one of the bits of the
+        // lo part.
+        unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
+        Hi = DAG.getNode(ISD::SRA, NVT, Lo,
+                         DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
+      } else if (ExtType == ISD::ZEXTLOAD) {
+        // The high part is just a zero.
+        Hi = DAG.getConstant(0, NVT);
+      } else /* if (ExtType == ISD::EXTLOAD) */ {
+        // The high part is undefined.
+        Hi = DAG.getNode(ISD::UNDEF, NVT);
+      }
+    }
     break;
   }
   case ISD::AND:
@@ -3911,63 +4533,6 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
                      Node->getOperand(1), TH, FH, Node->getOperand(4));
     break;
   }
-  case ISD::SEXTLOAD: {
-    SDOperand Chain = Node->getOperand(0);
-    SDOperand Ptr   = Node->getOperand(1);
-    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
-    
-    if (EVT == NVT)
-      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
-    else
-      Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
-                          EVT);
-    
-    // Remember that we legalized the chain.
-    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
-    
-    // The high part is obtained by SRA'ing all but one of the bits of the lo
-    // part.
-    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
-    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
-                                                       TLI.getShiftAmountTy()));
-    break;
-  }
-  case ISD::ZEXTLOAD: {
-    SDOperand Chain = Node->getOperand(0);
-    SDOperand Ptr   = Node->getOperand(1);
-    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
-    
-    if (EVT == NVT)
-      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
-    else
-      Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
-                          EVT);
-    
-    // Remember that we legalized the chain.
-    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
-
-    // The high part is just a zero.
-    Hi = DAG.getConstant(0, NVT);
-    break;
-  }
-  case ISD::EXTLOAD: {
-    SDOperand Chain = Node->getOperand(0);
-    SDOperand Ptr   = Node->getOperand(1);
-    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
-    
-    if (EVT == NVT)
-      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
-    else
-      Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
-                          EVT);
-    
-    // Remember that we legalized the chain.
-    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
-    
-    // The high part is undefined.
-    Hi = DAG.getNode(ISD::UNDEF, NVT);
-    break;
-  }
   case ISD::ANY_EXTEND:
     // The low part is any extension of the input (which degenerates to a copy).
     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
@@ -3996,8 +4561,21 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
     break;
     
   case ISD::BIT_CONVERT: {
-    SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0), 
-                                      Node->getOperand(0));
+    SDOperand Tmp;
+    if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
+      // If the target wants to, allow it to lower this itself.
+      switch (getTypeAction(Node->getOperand(0).getValueType())) {
+      case Expand: assert(0 && "cannot expand FP!");
+      case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
+      case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
+      }
+      Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp), DAG);
+    }
+
+    // Turn this into a load/store pair by default.
+    if (Tmp.Val == 0)
+      Tmp = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
+    
     ExpandOp(Tmp, Lo, Hi);
     break;
   }
@@ -4078,6 +4656,24 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
       }
     }
     
+    // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit 
+    // this X << 1 as X+X.
+    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
+      if (ShAmt->getValue() == 1 && TLI.isOperationLegal(ISD::ADDC, NVT) && 
+          TLI.isOperationLegal(ISD::ADDE, NVT)) {
+        SDOperand LoOps[2], HiOps[3];
+        ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
+        SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
+        LoOps[1] = LoOps[0];
+        Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
+
+        HiOps[1] = HiOps[0];
+        HiOps[2] = Lo.getValue(1);
+        Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
+        break;
+      }
+    }
+    
     // If we can emit an efficient shift operation, do so now.
     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
       break;
@@ -4176,27 +4772,36 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
     SDOperand LHSL, LHSH, RHSL, RHSH;
     ExpandOp(Node->getOperand(0), LHSL, LHSH);
     ExpandOp(Node->getOperand(1), RHSL, RHSH);
-    std::vector<MVT::ValueType> VTs;
-    std::vector<SDOperand> LoOps, HiOps;
-    VTs.push_back(LHSL.getValueType());
-    VTs.push_back(MVT::Flag);
-    LoOps.push_back(LHSL);
-    LoOps.push_back(RHSL);
-    HiOps.push_back(LHSH);
-    HiOps.push_back(RHSH);
+    SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
+    SDOperand LoOps[2], HiOps[3];
+    LoOps[0] = LHSL;
+    LoOps[1] = RHSL;
+    HiOps[0] = LHSH;
+    HiOps[1] = RHSH;
     if (Node->getOpcode() == ISD::ADD) {
-      Lo = DAG.getNode(ISD::ADDC, VTs, LoOps);
-      HiOps.push_back(Lo.getValue(1));
-      Hi = DAG.getNode(ISD::ADDE, VTs, HiOps);
+      Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
+      HiOps[2] = Lo.getValue(1);
+      Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
     } else {
-      Lo = DAG.getNode(ISD::SUBC, VTs, LoOps);
-      HiOps.push_back(Lo.getValue(1));
-      Hi = DAG.getNode(ISD::SUBE, VTs, HiOps);
+      Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
+      HiOps[2] = Lo.getValue(1);
+      Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
     }
     break;
   }
   case ISD::MUL: {
-    if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
+    // If the target wants to custom expand this, let them.
+    if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
+      SDOperand New = TLI.LowerOperation(Op, DAG);
+      if (New.Val) {
+        ExpandOp(New, Lo, Hi);
+        break;
+      }
+    }
+    
+    bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
+    bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
+    if (HasMULHS || HasMULHU) {
       SDOperand LL, LH, RL, RH;
       ExpandOp(Node->getOperand(0), LL, LH);
       ExpandOp(Node->getOperand(1), RL, RH);
@@ -4205,7 +4810,7 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
       // extended the sign bit of the low half through the upper half, and if so
       // emit a MULHS instead of the alternate sequence that is valid for any
       // i64 x i64 multiply.
-      if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
+      if (HasMULHS &&
           // is RH an extension of the sign bit of RL?
           RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
           RH.getOperand(1).getOpcode() == ISD::Constant &&
@@ -4214,18 +4819,28 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
           LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
           LH.getOperand(1).getOpcode() == ISD::Constant &&
           cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
+        // FIXME: Move this to the dag combiner.
+        
+        // Low part:
+        Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
+        // High part:
         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
-      } else {
+        break;
+      } else if (HasMULHU) {
+        // Low part:
+        Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
+        
+        // High part:
         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
+        break;
       }
-      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
-    } else {
-      Lo = ExpandLibCall("__muldi3" , Node, Hi);
     }
+
+    Lo = ExpandLibCall("__muldi3" , Node, Hi);
     break;
   }
   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
@@ -4269,17 +4884,23 @@ void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
   }
   
   switch (Node->getOpcode()) {
-  default: assert(0 && "Unknown vector operation!");
+  default: 
+#ifndef NDEBUG
+    Node->dump();
+#endif
+    assert(0 && "Unhandled operation in SplitVectorOp!");
   case ISD::VBUILD_VECTOR: {
-    std::vector<SDOperand> LoOps(Node->op_begin(), Node->op_begin()+NewNumElts);
+    SmallVector<SDOperand, 8> LoOps(Node->op_begin(), 
+                                    Node->op_begin()+NewNumElts);
     LoOps.push_back(NewNumEltsNode);
     LoOps.push_back(TypeNode);
-    Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, LoOps);
+    Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &LoOps[0], LoOps.size());
 
-    std::vector<SDOperand> HiOps(Node->op_begin()+NewNumElts, Node->op_end()-2);
+    SmallVector<SDOperand, 8> HiOps(Node->op_begin()+NewNumElts, 
+                                    Node->op_end()-2);
     HiOps.push_back(NewNumEltsNode);
     HiOps.push_back(TypeNode);
-    Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, HiOps);
+    Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &HiOps[0], HiOps.size());
     break;
   }
   case ISD::VADD:
@@ -4319,10 +4940,48 @@ void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
     
     // Remember that we legalized the chain.
     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
-    if (!TLI.isLittleEndian())
-      std::swap(Lo, Hi);
     break;
   }
+  case ISD::VBIT_CONVERT: {
+    // We know the result is a vector.  The input may be either a vector or a
+    // scalar value.
+    if (Op.getOperand(0).getValueType() != MVT::Vector) {
+      // Lower to a store/load.  FIXME: this could be improved probably.
+      SDOperand Ptr = CreateStackTemporary(Op.getOperand(0).getValueType());
+
+      SDOperand St = DAG.getStore(DAG.getEntryNode(),
+                                  Op.getOperand(0), Ptr, NULL, 0);
+      MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
+      St = DAG.getVecLoad(NumElements, EVT, St, Ptr, DAG.getSrcValue(0));
+      SplitVectorOp(St, Lo, Hi);
+    } else {
+      // If the input is a vector type, we have to either scalarize it, pack it
+      // or convert it based on whether the input vector type is legal.
+      SDNode *InVal = Node->getOperand(0).Val;
+      unsigned NumElems =
+        cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+      MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+
+      // If the input is from a single element vector, scalarize the vector,
+      // then treat like a scalar.
+      if (NumElems == 1) {
+        SDOperand Scalar = PackVectorOp(Op.getOperand(0), EVT);
+        Scalar = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Scalar,
+                             Op.getOperand(1), Op.getOperand(2));
+        SplitVectorOp(Scalar, Lo, Hi);
+      } else {
+        // Split the input vector.
+        SplitVectorOp(Op.getOperand(0), Lo, Hi);
+
+        // Convert each of the pieces now.
+        Lo = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Lo,
+                         NewNumEltsNode, TypeNode);
+        Hi = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Hi,
+                         NewNumEltsNode, TypeNode);
+      }
+      break;
+    }
+  }
   }
       
   // Remember in a map if the values will be reused later.
@@ -4338,9 +4997,6 @@ void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
 /// type for the result.
 SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op, 
                                              MVT::ValueType NewVT) {
-  // FIXME: THIS IS A TEMPORARY HACK
-  if (Op.getValueType() == NewVT) return Op;
-    
   assert(Op.getValueType() == MVT::Vector && "Bad PackVectorOp invocation!");
   SDNode *Node = Op.Val;
   
@@ -4351,7 +5007,9 @@ SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
   SDOperand Result;
   switch (Node->getOpcode()) {
   default: 
+#ifndef NDEBUG
     Node->dump(); std::cerr << "\n";
+#endif
     assert(0 && "Unknown vector operation in PackVectorOp!");
   case ISD::VADD:
   case ISD::VSUB:
@@ -4370,20 +5028,33 @@ SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
     
-    Result = DAG.getLoad(NewVT, Ch, Ptr, Node->getOperand(2));
+    SrcValueSDNode *SV = cast<SrcValueSDNode>(Node->getOperand(2));
+    Result = DAG.getLoad(NewVT, Ch, Ptr, SV->getValue(), SV->getOffset());
     
     // Remember that we legalized the chain.
     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
     break;
   }
   case ISD::VBUILD_VECTOR:
-    if (!MVT::isVector(NewVT)) {
+    if (Node->getOperand(0).getValueType() == NewVT) {
       // Returning a scalar?
       Result = Node->getOperand(0);
     } else {
       // Returning a BUILD_VECTOR?
-      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end()-2);
-      Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Ops);
+      
+      // If all elements of the build_vector are undefs, return an undef.
+      bool AllUndef = true;
+      for (unsigned i = 0, e = Node->getNumOperands()-2; i != e; ++i)
+        if (Node->getOperand(i).getOpcode() != ISD::UNDEF) {
+          AllUndef = false;
+          break;
+        }
+      if (AllUndef) {
+        Result = DAG.getNode(ISD::UNDEF, NewVT);
+      } else {
+        Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Node->op_begin(),
+                             Node->getNumOperands()-2);
+      }
     }
     break;
   case ISD::VINSERT_VECTOR_ELT:
@@ -4396,6 +5067,29 @@ SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
                            Node->getOperand(1), Node->getOperand(2));
     }
     break;
+  case ISD::VVECTOR_SHUFFLE:
+    if (!MVT::isVector(NewVT)) {
+      // Returning a scalar?  Figure out if it is the LHS or RHS and return it.
+      SDOperand EltNum = Node->getOperand(2).getOperand(0);
+      if (cast<ConstantSDNode>(EltNum)->getValue())
+        Result = PackVectorOp(Node->getOperand(1), NewVT);
+      else
+        Result = PackVectorOp(Node->getOperand(0), NewVT);
+    } else {
+      // Otherwise, return a VECTOR_SHUFFLE node.  First convert the index
+      // vector from a VBUILD_VECTOR to a BUILD_VECTOR.
+      std::vector<SDOperand> BuildVecIdx(Node->getOperand(2).Val->op_begin(),
+                                         Node->getOperand(2).Val->op_end()-2);
+      MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size());
+      SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT,
+                                 Node->getOperand(2).Val->op_begin(),
+                                 Node->getOperand(2).Val->getNumOperands()-2);
+      
+      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT,
+                           PackVectorOp(Node->getOperand(0), NewVT),
+                           PackVectorOp(Node->getOperand(1), NewVT), BV);
+    }
+    break;
   case ISD::VBIT_CONVERT:
     if (Op.getOperand(0).getValueType() != MVT::Vector)
       Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
@@ -4425,6 +5119,12 @@ SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
         assert(0 && "Cast from unsupported vector type not implemented yet!");
       }
     }
+    break;
+  case ISD::VSELECT:
+    Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
+                         PackVectorOp(Op.getOperand(1), NewVT),
+                         PackVectorOp(Op.getOperand(2), NewVT));
+    break;
   }
 
   if (TLI.isTypeLegal(NewVT))
@@ -4438,6 +5138,8 @@ SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
 // SelectionDAG::Legalize - This is the entry point for the file.
 //
 void SelectionDAG::Legalize() {
+  if (ViewLegalizeDAGs) viewGraph();
+
   /// run - This is the main entry point to this class.
   ///
   SelectionDAGLegalize(*this).LegalizeDAG();