Combine ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD into ISD::LOADX. Add an
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
index d6c3fe0920f27bdde5dbb0f347653c5ac289f6c3..07b72a63729385403e25f9a376f76b62e0c2e738 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/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 <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 +48,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 +67,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 +167,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 +192,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 +208,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 +350,7 @@ void SelectionDAGLegalize::LegalizeDAG() {
   PackedNodes.clear();
 
   // Remove dead nodes now.
-  DAG.RemoveDeadNodes(OldRoot.Val);
+  DAG.RemoveDeadNodes();
 }
 
 
@@ -336,10 +408,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 +439,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 +524,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:
@@ -470,32 +542,37 @@ 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::JumpTableRelocBase:
+    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
+    case TargetLowering::Custom:
+      Tmp1 = TLI.LowerOperation(Op, DAG);
+      if (Tmp1.Val) Result = Tmp1;
+      break;
+    default:
+      Result = LegalizeOp(Node->getOperand(0));
+      break;
+    }
+    break;
   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:
@@ -556,10 +633,10 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   case ISD::INTRINSIC_W_CHAIN:
   case ISD::INTRINSIC_WO_CHAIN:
   case ISD::INTRINSIC_VOID: {
-    std::vector<SDOperand> Ops;
+    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);
+    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) == 
@@ -600,7 +677,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);
@@ -609,13 +686,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
@@ -625,7 +702,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.
@@ -637,7 +714,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;
     }
@@ -722,7 +799,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;
@@ -750,14 +827,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!");
@@ -792,18 +887,72 @@ 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.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                                 Tmp1, StackPtr, DAG.getSrcValue(NULL));
+
+      // 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.getNode(ISD::STORE, MVT::Other, Ch,
+                       Tmp2, StackPtr2, DAG.getSrcValue(NULL));
+      // Load the updated vector.
+      Result = DAG.getLoad(VT, Ch, StackPtr, DAG.getSrcValue(NULL));
       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,
@@ -818,35 +967,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;
   
@@ -867,69 +1052,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);
@@ -937,8 +1068,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.
@@ -946,14 +1080,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.
@@ -994,18 +1130,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?");
@@ -1057,25 +1193,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.
@@ -1085,7 +1238,21 @@ 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::BRCOND:
     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
     // Ensure that libcalls are emitted before a return.
@@ -1174,39 +1341,50 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
 
     MVT::ValueType VT = Node->getValueType(0);
     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
-    Tmp2 = Result.getValue(0);
-    Tmp3 = Result.getValue(1);
+    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);
+      Tmp1 = TLI.LowerOperation(Tmp3, DAG);
       if (Tmp1.Val) {
-        Tmp2 = LegalizeOp(Tmp1);
-        Tmp3 = LegalizeOp(Tmp1.getValue(1));
+        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, Node->getOperand(2));
+      Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
+      Tmp4 = LegalizeOp(Tmp1.getValue(1));
+      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;
+    AddLegalizedOperand(SDOperand(Node, 0), Tmp3);
+    AddLegalizedOperand(SDOperand(Node, 1), Tmp4);
+    return Op.ResNo ? Tmp4 : Tmp3;
   }
-  case ISD::EXTLOAD:
-  case ISD::SEXTLOAD:
-  case ISD::ZEXTLOAD: {
+  case ISD::LOADX: {
     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)) {
+    unsigned LType = cast<ConstantSDNode>(Node->getOperand(4))->getValue();
+    switch (TLI.getLoadXAction(LType, SrcVT)) {
     default: assert(0 && "This action is not supported yet!");
     case TargetLowering::Promote:
-      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
+      assert(SrcVT == MVT::i1 && "Can only promote LOADX from i1 -> i8!");
       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
-                                      DAG.getValueType(MVT::i8));
+                                      DAG.getValueType(MVT::i8),
+                                      Node->getOperand(4));
       Tmp1 = Result.getValue(0);
       Tmp2 = Result.getValue(1);
       break;
@@ -1215,12 +1393,12 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       // FALLTHROUGH
     case TargetLowering::Legal:
       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
-                                      Node->getOperand(3));
+                                      Node->getOperand(3), Node->getOperand(4));
       Tmp1 = Result.getValue(0);
       Tmp2 = Result.getValue(1);
       
       if (isCustom) {
-        Tmp3 = TLI.LowerOperation(Tmp3, DAG);
+        Tmp3 = TLI.LowerOperation(Result, DAG);
         if (Tmp3.Val) {
           Tmp1 = LegalizeOp(Tmp3);
           Tmp2 = LegalizeOp(Tmp3.getValue(1));
@@ -1236,14 +1414,13 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         Tmp2 = LegalizeOp(Load.getValue(1));
         break;
       }
-      assert(Node->getOpcode() != ISD::EXTLOAD &&
-             "EXTLOAD should always be supported!");
+      assert(LType != 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)
+      if (LType == ISD::SEXTLOAD)
         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
                              Result, DAG.getValueType(SrcVT));
       else
@@ -1321,23 +1498,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;
       }
@@ -1346,18 +1558,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:
@@ -1365,9 +1582,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;
     }
     }
@@ -1416,6 +1634,13 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         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.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
+                                        Node->getOperand(3));
+        break;
       }
       break;
     }
@@ -1448,12 +1673,16 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
           Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
                                           Node->getOperand(3));
+          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.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
                                           Node->getOperand(3));
+          // 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);
@@ -1462,10 +1691,10 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       } else {
         ExpandOp(Node->getOperand(1), Lo, Hi);
         IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
-      }
 
-      if (!TLI.isLittleEndian())
-        std::swap(Lo, Hi);
+        if (!TLI.isLittleEndian())
+          std::swap(Lo, Hi);
+      }
 
       Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
                        Node->getOperand(3));
@@ -1635,7 +1864,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 {
@@ -1812,7 +2044,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;
@@ -1851,14 +2083,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))) {
@@ -1919,12 +2151,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;
     
@@ -2059,13 +2341,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";
@@ -2322,7 +2614,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));
@@ -2571,8 +2870,8 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         // 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);
@@ -2592,6 +2891,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);
@@ -2625,7 +2927,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:
@@ -2648,7 +2952,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:
@@ -2850,8 +3154,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.
@@ -2919,12 +3241,12 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
     // 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::LOADX:
+    Result =
+      DAG.getExtLoad((ISD::LoadExtType)Node->getConstantOperandVal(4),
+                     NVT, Node->getOperand(0), Node->getOperand(1),
+                     Node->getOperand(2),
+                     cast<VTSDNode>(Node->getOperand(3))->getVT());
     // Remember that we legalized the chain.
     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
     break;
@@ -2973,6 +3295,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!");
@@ -2985,6 +3313,74 @@ 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.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                             Vector, StackPtr, DAG.getSrcValue(NULL));
+  
+  // 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, DAG.getSrcValue(NULL));
+}
+
+
 /// 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,
@@ -3122,6 +3518,17 @@ SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT,
   return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(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.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                             Node->getOperand(0), StackPtr,
+                             DAG.getSrcValue(NULL));
+  return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,DAG.getSrcValue(NULL));
+}
+
+
 /// 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) {
@@ -3140,11 +3547,7 @@ SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
   
   for (unsigned i = 1; i < NumElems; ++i) {
     SDOperand V = Node->getOperand(i);
-    std::map<SDOperand, std::vector<unsigned> >::iterator I = Values.find(V);
-    if (I != Values.end())
-      I->second.push_back(i);
-    else
-      Values[V].push_back(i);
+    Values[V].push_back(i);
     if (V.getOpcode() != ISD::UNDEF)
       isOnlyLowElement = false;
     if (SplatValue != V)
@@ -3196,10 +3599,11 @@ SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
       MVT::getIntVectorWithNumElements(NumElems);
     SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
     std::vector<SDOperand> ZeroVec(NumElems, Zero);
-    SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec);
+    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);
@@ -3226,12 +3630,13 @@ SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
         MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
       i += NumElems;
     }
-    SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
+    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.isShuffleLegal(Node->getValueType(0), ShuffleMask) &&
-        TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0))) {
-      std::vector<SDOperand> Ops;
+    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),
@@ -3241,7 +3646,8 @@ SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
       Ops.push_back(ShuffleMask);
 
       // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
-      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops);
+      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), 
+                         &Ops[0], Ops.size());
     }
   }
   
@@ -3253,7 +3659,7 @@ 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;
@@ -3274,7 +3680,8 @@ SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
   
   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();
   
@@ -3298,12 +3705,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);
 }
 
@@ -3387,6 +3791,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;
 }
 
@@ -3838,7 +4308,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
@@ -3867,7 +4336,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:
@@ -4007,10 +4478,11 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
                      Node->getOperand(1), TH, FH, Node->getOperand(4));
     break;
   }
-  case ISD::SEXTLOAD: {
+  case ISD::LOADX: {
     SDOperand Chain = Node->getOperand(0);
     SDOperand Ptr   = Node->getOperand(1);
     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
+    unsigned LType = Node->getConstantOperandVal(4);
     
     if (EVT == NVT)
       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
@@ -4020,48 +4492,20 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
     
     // 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);
+    if (LType == 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 (LType == ISD::ZEXTLOAD) {
+      // The high part is just a zero.
+      Hi = DAG.getConstant(0, NVT);
+    } else /* if (LType == ISD::EXTLOAD) */ {
+      // The high part is undefined.
+      Hi = DAG.getNode(ISD::UNDEF, NVT);
+    }
     break;
   }
   case ISD::ANY_EXTEND:
@@ -4092,8 +4536,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;
   }
@@ -4174,6 +4631,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;
@@ -4272,27 +4747,37 @@ 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);
+    bool UseLibCall = true;
+    if (HasMULHS || HasMULHU) {
       SDOperand LL, LH, RL, RH;
       ExpandOp(Node->getOperand(0), LL, LH);
       ExpandOp(Node->getOperand(1), RL, RH);
@@ -4301,7 +4786,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 &&
@@ -4310,18 +4795,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;
@@ -4365,17 +4860,23 @@ void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
   }
   
   switch (Node->getOpcode()) {
-  default: Node->dump(); 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:
@@ -4415,8 +4916,6 @@ 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: {
@@ -4474,9 +4973,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;
   
@@ -4487,7 +4983,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:
@@ -4513,13 +5011,25 @@ SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
     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:
@@ -4546,7 +5056,9 @@ SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
       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, BuildVecIdx);
+      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),
@@ -4582,6 +5094,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))
@@ -4595,6 +5113,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();