getLoad() and getStore() calls missed SVOffset operand. Thanks to Dan Gohman
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGISel.cpp
index 6a2a8e79c1b3f5222fe6dd03aa1905d96c840705..37d7eeb1a94de8f9f693128ddb7d916bd5eae3c6 100644 (file)
@@ -24,7 +24,6 @@
 #include "llvm/Instructions.h"
 #include "llvm/Intrinsics.h"
 #include "llvm/IntrinsicInst.h"
-#include "llvm/CodeGen/IntrinsicLowering.h"
 #include "llvm/CodeGen/MachineDebugInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
@@ -34,6 +33,7 @@
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/SSARegMap.h"
 #include "llvm/Target/MRegisterInfo.h"
+#include "llvm/Target/TargetAsmInfo.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetFrameInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
@@ -44,7 +44,6 @@
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Compiler.h"
-#include <iostream>
 #include <algorithm>
 using namespace llvm;
 
@@ -295,8 +294,9 @@ FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
       }
       unsigned PHIReg = ValueMap[PN];
       assert(PHIReg && "PHI node does not have an assigned virtual register!");
+      const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
       for (unsigned i = 0; i != NumElements; ++i)
-        BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
+        BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
     }
   }
 }
@@ -346,13 +346,10 @@ unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
   
   // If this value is represented with multiple target registers, make sure
   // to create enough consecutive registers of the right (smaller) type.
-  unsigned NT = VT-1;  // Find the type to use.
-  while (TLI.getNumElements((MVT::ValueType)NT) != 1)
-    --NT;
-  
-  unsigned R = MakeReg((MVT::ValueType)NT);
+  VT = TLI.getTypeToExpandTo(VT);
+  unsigned R = MakeReg(VT);
   for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
-    MakeReg((MVT::ValueType)NT);
+    MakeReg(VT);
   return R;
 }
 
@@ -458,6 +455,8 @@ public:
   void visit(Instruction &I) { visit(I.getOpcode(), I); }
 
   void visit(unsigned Opcode, User &I) {
+    // Note: this doesn't use InstVisitor, because it has to work with
+    // ConstantExpr's in addition to instructions.
     switch (Opcode) {
     default: assert(0 && "Unknown instruction type encountered!");
              abort();
@@ -528,24 +527,20 @@ public:
     else
       visitIntBinary(I, ISD::MUL, ISD::VMUL); 
   }
+  void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
+  void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
+  void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
   void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
   void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
-  void visitFDiv(User &I) { visitFPBinary(I, ISD::FDIV,  ISD::VSDIV); }
-  void visitRem(User &I) {
-    const Type *Ty = I.getType();
-    if (Ty->isFloatingPoint())
-      visitFPBinary(I, ISD::FREM, 0);
-    else 
-      visitIntBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, 0);
-  }
+  void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
   void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
   void visitOr (User &I) { visitIntBinary(I, ISD::OR,  ISD::VOR); }
   void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
   void visitShl(User &I) { visitShift(I, ISD::SHL); }
-  void visitShr(User &I) { 
-    visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
-  }
-
+  void visitLShr(User &I) { visitShift(I, ISD::SRL); }
+  void visitAShr(User &I) { visitShift(I, ISD::SRA); }
+  void visitICmp(User &I);
+  void visitFCmp(User &I);
   void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
                   ISD::CondCode FPOpc);
   void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ, 
@@ -560,13 +555,25 @@ public:
                                         ISD::SETOLT); }
   void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
                                         ISD::SETOGT); }
+  // Visit the conversion instructions
+  void visitTrunc(User &I);
+  void visitZExt(User &I);
+  void visitSExt(User &I);
+  void visitFPTrunc(User &I);
+  void visitFPExt(User &I);
+  void visitFPToUI(User &I);
+  void visitFPToSI(User &I);
+  void visitUIToFP(User &I);
+  void visitSIToFP(User &I);
+  void visitPtrToInt(User &I);
+  void visitIntToPtr(User &I);
+  void visitBitCast(User &I);
 
   void visitExtractElement(User &I);
   void visitInsertElement(User &I);
   void visitShuffleVector(User &I);
 
   void visitGetElementPtr(User &I);
-  void visitCast(User &I);
   void visitSelect(User &I);
 
   void visitMalloc(MallocInst &I);
@@ -679,19 +686,26 @@ SDOperand SelectionDAGLowering::getValue(const Value *V) {
   
   // If this type is not legal, make it so now.
   if (VT != MVT::Vector) {
-    MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
-  
-    N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
-    if (DestVT < VT) {
+    if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
       // Source must be expanded.  This input value is actually coming from the
       // register pair VMI->second and VMI->second+1.
-      N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
-                      DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
-    } else if (DestVT > VT) { // Promotion case
-      if (MVT::isFloatingPoint(VT))
-        N = DAG.getNode(ISD::FP_ROUND, VT, N);
-      else
-        N = DAG.getNode(ISD::TRUNCATE, VT, N);
+      MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
+      unsigned NumVals = TLI.getNumElements(VT);
+      N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
+      if (NumVals == 1)
+        N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
+      else {
+        assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
+        N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
+                       DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
+      }
+    } else {
+      MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
+      N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
+      if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
+        N = MVT::isFloatingPoint(VT)
+          ? DAG.getNode(ISD::FP_ROUND, VT, N)
+          : DAG.getNode(ISD::TRUNCATE, VT, N);
     }
   } else {
     // Otherwise, if this is a vector, make it available as a generic vector
@@ -845,6 +859,22 @@ void SelectionDAGLowering::FindMergedConditions(Value *Cond,
       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
     const BasicBlock *BB = CurBB->getBasicBlock();
     
+    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
+      if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
+           II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
+          // The operands of the setcc have to be in this block.  We don't know
+          // how to export them from some other block.  If this is the first
+          // block of the sequence, no exporting is needed.
+          (CurBB == CurMBB ||
+           (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
+            isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
+        SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
+                                       II->getOperand(2), TBB, FBB, CurBB);
+        SwitchCases.push_back(CB);
+        return;
+      }
+        
+    
     // If the leaf of the tree is a setcond inst, merge the condition into the
     // caseblock.
     if (BOp && isa<SetCondInst>(BOp) &&
@@ -952,6 +982,25 @@ void SelectionDAGLowering::FindMergedConditions(Value *Cond,
   }
 }
 
+/// If the set of cases should be emitted as a series of branches, return true.
+/// If we should emit this as a bunch of and/or'd together conditions, return
+/// false.
+static bool 
+ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
+  if (Cases.size() != 2) return true;
+  
+  // If this is two comparisons of the same values or'd or and'd together, they
+  // will get folded into a single comparison, so don't emit two blocks.
+  if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
+       Cases[0].CmpRHS == Cases[1].CmpRHS) ||
+      (Cases[0].CmpRHS == Cases[1].CmpLHS &&
+       Cases[0].CmpLHS == Cases[1].CmpRHS)) {
+    return false;
+  }
+  
+  return true;
+}
+
 void SelectionDAGLowering::visitBr(BranchInst &I) {
   // Update machine-CFG edges.
   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
@@ -999,21 +1048,30 @@ void SelectionDAGLowering::visitBr(BranchInst &I) {
         (BOp->getOpcode() == Instruction::And ||
          BOp->getOpcode() == Instruction::Or)) {
       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
-
       // If the compares in later blocks need to use values not currently
-      // exported from this block, export them now.  This block should always be
-      // the first entry.
+      // exported from this block, export them now.  This block should always
+      // be the first entry.
       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
       
-      for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
-        ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
-        ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
+      // Allow some cases to be rejected.
+      if (ShouldEmitAsBranches(SwitchCases)) {
+        for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
+          ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
+          ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
+        }
+        
+        // Emit the branch for this block.
+        visitSwitchCase(SwitchCases[0]);
+        SwitchCases.erase(SwitchCases.begin());
+        return;
       }
       
-      // Emit the branch for this block.
-      visitSwitchCase(SwitchCases[0]);
-      SwitchCases.erase(SwitchCases.begin());
-      return;
+      // Okay, we decided not to do this, remove any inserted MBB's and clear
+      // SwitchCases.
+      for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
+        CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
+      
+      SwitchCases.clear();
     }
   }
   
@@ -1403,6 +1461,60 @@ void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
 }
 
+void SelectionDAGLowering::visitICmp(User &I) {
+  ICmpInst *IC = cast<ICmpInst>(&I);
+  SDOperand Op1 = getValue(IC->getOperand(0));
+  SDOperand Op2 = getValue(IC->getOperand(1));
+  ISD::CondCode Opcode;
+  switch (IC->getPredicate()) {
+    case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
+    case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
+    case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
+    case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
+    case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
+    case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
+    case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
+    case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
+    case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
+    case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
+    default:
+      assert(!"Invalid ICmp predicate value");
+      Opcode = ISD::SETEQ;
+      break;
+  }
+  setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
+}
+
+void SelectionDAGLowering::visitFCmp(User &I) {
+  FCmpInst *FC = cast<FCmpInst>(&I);
+  SDOperand Op1 = getValue(FC->getOperand(0));
+  SDOperand Op2 = getValue(FC->getOperand(1));
+  ISD::CondCode Opcode;
+  switch (FC->getPredicate()) {
+    case FCmpInst::FCMP_FALSE : Opcode = ISD::SETFALSE;
+    case FCmpInst::FCMP_OEQ   : Opcode = ISD::SETOEQ;
+    case FCmpInst::FCMP_OGT   : Opcode = ISD::SETOGT;
+    case FCmpInst::FCMP_OGE   : Opcode = ISD::SETOGE;
+    case FCmpInst::FCMP_OLT   : Opcode = ISD::SETOLT;
+    case FCmpInst::FCMP_OLE   : Opcode = ISD::SETOLE;
+    case FCmpInst::FCMP_ONE   : Opcode = ISD::SETONE;
+    case FCmpInst::FCMP_ORD   : Opcode = ISD::SETO;
+    case FCmpInst::FCMP_UNO   : Opcode = ISD::SETUO;
+    case FCmpInst::FCMP_UEQ   : Opcode = ISD::SETUEQ;
+    case FCmpInst::FCMP_UGT   : Opcode = ISD::SETUGT;
+    case FCmpInst::FCMP_UGE   : Opcode = ISD::SETUGE;
+    case FCmpInst::FCMP_ULT   : Opcode = ISD::SETULT;
+    case FCmpInst::FCMP_ULE   : Opcode = ISD::SETULE;
+    case FCmpInst::FCMP_UNE   : Opcode = ISD::SETUNE;
+    case FCmpInst::FCMP_TRUE  : Opcode = ISD::SETTRUE;
+    default:
+      assert(!"Invalid FCmp predicate value");
+      Opcode = ISD::SETFALSE;
+      break;
+  }
+  setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
+}
+
 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
                                       ISD::CondCode UnsignedOpcode,
                                       ISD::CondCode FPOpcode) {
@@ -1430,63 +1542,127 @@ void SelectionDAGLowering::visitSelect(User &I) {
   }
 }
 
-void SelectionDAGLowering::visitCast(User &I) {
+
+void SelectionDAGLowering::visitTrunc(User &I) {
+  // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
+}
+
+void SelectionDAGLowering::visitZExt(User &I) {
+  // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
+  // ZExt also can't be a cast to bool for same reason. So, nothing much to do
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
+}
+
+void SelectionDAGLowering::visitSExt(User &I) {
+  // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
+  // SExt also can't be a cast to bool for same reason. So, nothing much to do
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
+}
+
+void SelectionDAGLowering::visitFPTrunc(User &I) {
+  // FPTrunc is never a no-op cast, no need to check
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
+}
+
+void SelectionDAGLowering::visitFPExt(User &I){ 
+  // FPTrunc is never a no-op cast, no need to check
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
+}
+
+void SelectionDAGLowering::visitFPToUI(User &I) { 
+  // FPToUI is never a no-op cast, no need to check
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
+}
+
+void SelectionDAGLowering::visitFPToSI(User &I) {
+  // FPToSI is never a no-op cast, no need to check
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
+}
+
+void SelectionDAGLowering::visitUIToFP(User &I) { 
+  // UIToFP is never a no-op cast, no need to check
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
+}
+
+void SelectionDAGLowering::visitSIToFP(User &I){ 
+  // UIToFP is never a no-op cast, no need to check
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
+}
+
+void SelectionDAGLowering::visitPtrToInt(User &I) {
+  // What to do depends on the size of the integer and the size of the pointer.
+  // We can either truncate, zero extend, or no-op, accordingly.
   SDOperand N = getValue(I.getOperand(0));
   MVT::ValueType SrcVT = N.getValueType();
   MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  SDOperand Result;
+  if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
+    Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
+  else 
+    // Note: ZERO_EXTEND can handle cases where the sizes are equal too
+    Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
+  setValue(&I, Result);
+}
 
+void SelectionDAGLowering::visitIntToPtr(User &I) {
+  // What to do depends on the size of the integer and the size of the pointer.
+  // We can either truncate, zero extend, or no-op, accordingly.
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType SrcVT = N.getValueType();
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
+  if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
+    setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
+  else 
+    // Note: ZERO_EXTEND can handle cases where the sizes are equal too
+    setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
+}
+
+void SelectionDAGLowering::visitBitCast(User &I) { 
+  SDOperand N = getValue(I.getOperand(0));
+  MVT::ValueType DestVT = TLI.getValueType(I.getType());
   if (DestVT == MVT::Vector) {
-    // This is a cast to a vector from something else.  This is always a bit
-    // convert.  Get information about the input vector.
+    // This is a cast to a vector from something else.  
+    // Get information about the output vector.
     const PackedType *DestTy = cast<PackedType>(I.getType());
     MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
     setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N, 
                              DAG.getConstant(DestTy->getNumElements(),MVT::i32),
                              DAG.getValueType(EltVT)));
-  } else if (SrcVT == DestVT) {
-    setValue(&I, N);  // noop cast.
-  } else if (DestVT == MVT::i1) {
-    // Cast to bool is a comparison against zero, not truncation to zero.
-    SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
-                                       DAG.getConstantFP(0.0, N.getValueType());
-    setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
-  } else if (isInteger(SrcVT)) {
-    if (isInteger(DestVT)) {        // Int -> Int cast
-      if (DestVT < SrcVT)   // Truncating cast?
-        setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
-      else if (I.getOperand(0)->getType()->isSigned())
-        setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
-      else
-        setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
-    } else if (isFloatingPoint(DestVT)) {           // Int -> FP cast
-      if (I.getOperand(0)->getType()->isSigned())
-        setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
-      else
-        setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
-    } else {
-      assert(0 && "Unknown cast!");
-    }
-  } else if (isFloatingPoint(SrcVT)) {
-    if (isFloatingPoint(DestVT)) {  // FP -> FP cast
-      if (DestVT < SrcVT)   // Rounding cast?
-        setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
-      else
-        setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
-    } else if (isInteger(DestVT)) {        // FP -> Int cast.
-      if (I.getType()->isSigned())
-        setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
-      else
-        setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
-    } else {
-      assert(0 && "Unknown cast!");
-    }
-  } else {
-    assert(SrcVT == MVT::Vector && "Unknown cast!");
-    assert(DestVT != MVT::Vector && "Casts to vector already handled!");
-    // This is a cast from a vector to something else.  This is always a bit
-    // convert.  Get information about the input vector.
+    return;
+  } 
+  MVT::ValueType SrcVT = N.getValueType();
+  if (SrcVT == MVT::Vector) {
+    // This is a cast from a vctor to something else. 
+    // Get information about the input vector.
     setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
+    return;
   }
+
+  // BitCast assures us that source and destination are the same size so this 
+  // is either a BIT_CONVERT or a no-op.
+  if (DestVT != N.getValueType())
+    setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
+  else
+    setValue(&I, N); // noop cast.
 }
 
 void SelectionDAGLowering::visitInsertElement(User &I) {
@@ -1659,7 +1835,7 @@ SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
     L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
                        DAG.getSrcValue(SV));
   } else {
-    L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
+    L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
   }
 
   if (isVolatile)
@@ -1675,7 +1851,7 @@ void SelectionDAGLowering::visitStore(StoreInst &I) {
   Value *SrcV = I.getOperand(0);
   SDOperand Src = getValue(SrcV);
   SDOperand Ptr = getValue(I.getOperand(1));
-  DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
+  DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
                            I.isVolatile()));
 }
 
@@ -1802,10 +1978,10 @@ SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
   case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
   case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
   case Intrinsic::setjmp:
-    return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
+    return "_setjmp"+!TLI.usesUnderscoreSetJmp();
     break;
   case Intrinsic::longjmp:
-    return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
+    return "_longjmp"+!TLI.usesUnderscoreLongJmp();
     break;
   case Intrinsic::memcpy_i32:
   case Intrinsic::memcpy_i64:
@@ -2187,6 +2363,8 @@ GetRegistersForValue(const std::string &ConstrCode,
   MVT::ValueType RegVT;
   MVT::ValueType ValueVT = VT;
   
+  // If this is a constraint for a specific physical register, like {r17},
+  // assign it now.
   if (PhysReg.first) {
     if (VT == MVT::Other)
       ValueVT = *PhysReg.second->vt_begin();
@@ -2216,10 +2394,36 @@ GetRegistersForValue(const std::string &ConstrCode,
     return RegsForValue(Regs, RegVT, ValueVT);
   }
   
-  // This is a reference to a register class.  Allocate NumRegs consecutive,
-  // available, registers from the class.
-  std::vector<unsigned> RegClassRegs =
-    TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
+  // Otherwise, if this was a reference to an LLVM register class, create vregs
+  // for this reference.
+  std::vector<unsigned> RegClassRegs;
+  if (PhysReg.second) {
+    // If this is an early clobber or tied register, our regalloc doesn't know
+    // how to maintain the constraint.  If it isn't, go ahead and create vreg
+    // and let the regalloc do the right thing.
+    if (!isOutReg || !isInReg) {
+      if (VT == MVT::Other)
+        ValueVT = *PhysReg.second->vt_begin();
+      RegVT = *PhysReg.second->vt_begin();
+
+      // Create the appropriate number of virtual registers.
+      SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
+      for (; NumRegs; --NumRegs)
+        Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
+      
+      return RegsForValue(Regs, RegVT, ValueVT);
+    }
+    
+    // Otherwise, we can't allocate it.  Let the code below figure out how to
+    // maintain these constraints.
+    RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
+    
+  } else {
+    // This is a reference to a register class that doesn't directly correspond
+    // to an LLVM register class.  Allocate NumRegs consecutive, available,
+    // registers from the class.
+    RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
+  }
 
   const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
   MachineFunction &MF = *CurMBB->getParent();
@@ -2275,11 +2479,6 @@ void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
   SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
                                                  MVT::Other);
 
-  // Note, we treat inline asms both with and without side-effects as the same.
-  // If an inline asm doesn't have side effects and doesn't access memory, we
-  // could not choose to not chain it.
-  bool hasSideEffects = IA->hasSideEffects();
-
   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
   std::vector<MVT::ValueType> ConstraintVTs;
   
@@ -2417,7 +2616,11 @@ void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
         GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
                              true, UsesInputRegister, 
                              OutputRegs, InputRegs);
-      assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
+      if (Regs.Regs.empty()) {
+        cerr << "Couldn't allocate output reg for contraint '"
+             << ConstraintCode << "'!\n";
+        exit(1);
+      }
 
       if (!Constraints[i].isIndirectOutput) {
         assert(RetValRegs.Regs.empty() &&
@@ -2483,8 +2686,13 @@ void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
         CTy = TLI.getConstraintType(ConstraintCode[0]);
         
       if (CTy == TargetLowering::C_Other) {
-        if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
-          assert(0 && "MATCH FAIL!");
+        InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
+                                                       ConstraintCode[0], DAG);
+        if (!InOperandVal.Val) {
+          cerr << "Invalid operand for inline asm constraint '"
+               << ConstraintCode << "'!\n";
+          exit(1);
+        }
         
         // Add information to the INLINEASM node to know about this input.
         unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
@@ -2621,9 +2829,9 @@ void SelectionDAGLowering::visitFree(FreeInst &I) {
 // basic blocks, and the scheduler passes ownership of it to this method.
 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
                                                        MachineBasicBlock *MBB) {
-  std::cerr << "If a target marks an instruction with "
-               "'usesCustomDAGSchedInserter', it must implement "
-               "TargetLowering::InsertAtEndOfBasicBlock!\n";
+  cerr << "If a target marks an instruction with "
+       << "'usesCustomDAGSchedInserter', it must implement "
+       << "TargetLowering::InsertAtEndOfBasicBlock!\n";
   abort();
   return 0;  
 }
@@ -2656,6 +2864,32 @@ void SelectionDAGLowering::visitVACopy(CallInst &I) {
                           DAG.getSrcValue(I.getOperand(2))));
 }
 
+/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
+/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
+static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
+                                        unsigned &i, SelectionDAG &DAG,
+                                        TargetLowering &TLI) {
+  if (TLI.getTypeAction(VT) != TargetLowering::Expand)
+    return SDOperand(Arg, i++);
+
+  MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
+  unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
+  if (NumVals == 1) {
+    return DAG.getNode(ISD::BIT_CONVERT, VT,
+                       ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
+  } else if (NumVals == 2) {
+    SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
+    SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
+    if (!TLI.isLittleEndian())
+      std::swap(Lo, Hi);
+    return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
+  } else {
+    // Value scalarized into many values.  Unimp for now.
+    assert(0 && "Cannot expand i64 -> i16 yet!");
+  }
+  return SDOperand();
+}
+
 /// TargetLowering::LowerArguments - This is the default LowerArguments
 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be 
@@ -2686,8 +2920,8 @@ TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
         // If this is a large integer, it needs to be broken up into small
         // integers.  Figure out what the destination type is and how many small
         // integers it turns into.
-        MVT::ValueType NVT = getTypeToTransformTo(VT);
-        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
+        MVT::ValueType NVT = getTypeToExpandTo(VT);
+        unsigned NumVals = getNumElements(VT);
         for (unsigned i = 0; i != NumVals; ++i)
           RetVals.push_back(NVT);
       } else {
@@ -2745,23 +2979,10 @@ TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
     }
     case Expand:
       if (VT != MVT::Vector) {
-        // If this is a large integer, it needs to be reassembled from small
-        // integers.  Figure out what the source elt type is and how many small
-        // integers it is.
-        MVT::ValueType NVT = getTypeToTransformTo(VT);
-        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
-        if (NumVals == 2) {
-          SDOperand Lo = SDOperand(Result, i++);
-          SDOperand Hi = SDOperand(Result, i++);
-          
-          if (!isLittleEndian())
-            std::swap(Lo, Hi);
-            
-          Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
-        } else {
-          // Value scalarized into many values.  Unimp for now.
-          assert(0 && "Cannot expand i64 -> i16 yet!");
-        }
+        // If this is a large integer or a floating point node that needs to be
+        // expanded, it needs to be reassembled from small integers.  Figure out
+        // what the source elt type is and how many small integers it is.
+        Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
       } else {
         // Otherwise, this is a vector type.  We only support legal vectors
         // right now.
@@ -2791,6 +3012,39 @@ TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
 }
 
 
+/// ExpandScalarCallArgs - Recursively expand call argument node by
+/// bit_converting it or extract a pair of elements from the larger  node.
+static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
+                                 bool isSigned, 
+                                 SmallVector<SDOperand, 32> &Ops,
+                                 SelectionDAG &DAG,
+                                 TargetLowering &TLI) {
+  if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
+    Ops.push_back(Arg);
+    Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
+    return;
+  }
+
+  MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
+  unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
+  if (NumVals == 1) {
+    Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
+    ExpandScalarCallArgs(EVT, Arg, isSigned, Ops, DAG, TLI);
+  } else if (NumVals == 2) {
+    SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
+                               DAG.getConstant(0, TLI.getPointerTy()));
+    SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
+                               DAG.getConstant(1, TLI.getPointerTy()));
+    if (!TLI.isLittleEndian())
+      std::swap(Lo, Hi);
+    ExpandScalarCallArgs(EVT, Lo, isSigned, Ops, DAG, TLI);
+    ExpandScalarCallArgs(EVT, Hi, isSigned, Ops, DAG, TLI);
+  } else {
+    // Value scalarized into many values.  Unimp for now.
+    assert(0 && "Cannot expand i64 -> i16 yet!");
+  }
+}
+
 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
 /// implementation, which just inserts an ISD::CALL node, which is later custom
 /// lowered by the target to something concrete.  FIXME: When all targets are
@@ -2834,24 +3088,7 @@ TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
         // If this is a large integer, it needs to be broken down into small
         // integers.  Figure out what the source elt type is and how many small
         // integers it is.
-        MVT::ValueType NVT = getTypeToTransformTo(VT);
-        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
-        if (NumVals == 2) {
-          SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
-                                     DAG.getConstant(0, getPointerTy()));
-          SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
-                                     DAG.getConstant(1, getPointerTy()));
-          if (!isLittleEndian())
-            std::swap(Lo, Hi);
-          
-          Ops.push_back(Lo);
-          Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
-          Ops.push_back(Hi);
-          Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
-        } else {
-          // Value scalarized into many values.  Unimp for now.
-          assert(0 && "Cannot expand i64 -> i16 yet!");
-        }
+        ExpandScalarCallArgs(VT, Op, isSigned, Ops, DAG, *this);
       } else {
         // Otherwise, this is a vector type.  We only support legal vectors
         // right now.
@@ -2894,8 +3131,8 @@ TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
         // If this is a large integer, it needs to be reassembled from small
         // integers.  Figure out what the source elt type is and how many small
         // integers it is.
-        MVT::ValueType NVT = getTypeToTransformTo(VT);
-        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
+        MVT::ValueType NVT = getTypeToExpandTo(VT);
+        unsigned NumVals = getNumElements(VT);
         for (unsigned i = 0; i != NumVals; ++i)
           RetTys.push_back(NVT);
       } else {
@@ -2962,7 +3199,10 @@ TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
           ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
         } else {
           assert(MVT::isFloatingPoint(VT));
-          ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
+          if (getTypeAction(VT) == Expand)
+            ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
+          else
+            ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
         }
       }
     } else if (RetTys.size() == 3) {
@@ -3047,13 +3287,12 @@ static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
 static SDOperand getMemsetStringVal(MVT::ValueType VT,
                                     SelectionDAG &DAG, TargetLowering &TLI,
                                     std::string &Str, unsigned Offset) {
-  MVT::ValueType CurVT = VT;
   uint64_t Val = 0;
   unsigned MSB = getSizeInBits(VT) / 8;
   if (TLI.isLittleEndian())
     Offset = Offset + MSB - 1;
   for (unsigned i = 0; i != MSB; ++i) {
-    Val = (Val << 8) | Str[Offset];
+    Val = (Val << 8) | (unsigned char)Str[Offset];
     Offset += TLI.isLittleEndian() ? -1 : 1;
   }
   return DAG.getConstant(Val, VT);
@@ -3172,7 +3411,7 @@ void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
         }
         if (G) {
           GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
-          if (GV) {
+          if (GV && GV->isConstant()) {
             Str = GV->getStringValue(false);
             if (!Str.empty()) {
               CopyFromStr = true;
@@ -3276,7 +3515,8 @@ static bool OptimizeNoopCopyExpression(CastInst *CI) {
       while (isa<PHINode>(InsertPt)) ++InsertPt;
       
       InsertedCast = 
-        new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
+        CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "", 
+                         InsertPt);
       MadeChange = true;
     }
     
@@ -3298,9 +3538,10 @@ static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
                                          Value *PtrOffset) {
   if (V) return V;   // Already computed.
   
+  // Figure out the insertion point
   BasicBlock::iterator InsertPt;
   if (BB == GEPI->getParent()) {
-    // If insert into the GEP's block, insert right after the GEP.
+    // If GEP is already inserted into BB, insert right after the GEP.
     InsertPt = GEPI;
     ++InsertPt;
   } else {
@@ -3314,11 +3555,14 @@ static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
   // operand).
   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
     if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
-      Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
+      Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
+                             "", InsertPt);
   
   // Add the offset, cast it to the right type.
   Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
-  return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
+  // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
+  return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(), 
+                              "", InsertPt);
 }
 
 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
@@ -3335,8 +3579,9 @@ static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
   while (!RepPtr->use_empty()) {
     Instruction *User = cast<Instruction>(RepPtr->use_back());
     
-    // If the user is a Pointer-Pointer cast, recurse.
-    if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
+    // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
+    // used for a Pointer-Pointer cast.
+    if (isa<BitCastInst>(User)) {
       ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
       
       // Drop the use of RepPtr. The cast is dead.  Don't delete it now, else we
@@ -3363,7 +3608,8 @@ static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
     if (GEPI->getType() != RepPtr->getType()) {
       BasicBlock::iterator IP = NewVal;
       ++IP;
-      NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
+      // NewVal must be a GEP which must be pointer type, so BitCast
+      NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
     }
     User->replaceUsesOfWith(RepPtr, NewVal);
   }
@@ -3409,7 +3655,8 @@ static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
   
   // If this is a "GEP X, 0, 0, 0", turn this into a cast.
   if (!hasConstantIndex && !hasVariableIndex) {
-    Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(), 
+    /// The GEP operand must be a pointer, so must its result -> BitCast
+    Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), 
                              GEPI->getName(), GEPI);
     GEPI->replaceAllUsesWith(NC);
     GEPI->eraseFromParent();
@@ -3424,7 +3671,7 @@ static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
   // constant offset (which we now know is non-zero) and deal with it later.
   uint64_t ConstantOffset = 0;
   const Type *UIntPtrTy = TD->getIntPtrType();
-  Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
+  Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
   const Type *Ty = GEPI->getOperand(0)->getType();
 
   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
@@ -3451,7 +3698,7 @@ static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
       // Ptr = Ptr + Idx * ElementSize;
       
       // Cast Idx to UIntPtrTy if needed.
-      Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
+      Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
       
       uint64_t ElementSize = TD->getTypeSize(Ty);
       // Mask off bits that should not be set.
@@ -3545,7 +3792,7 @@ static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
 bool SelectionDAGISel::runOnFunction(Function &Fn) {
   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
   RegMap = MF.getSSARegMap();
-  DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
+  DOUT << "\n\n\n=== " << Fn.getName() << "\n";
 
   // First, split all critical edges.
   //
@@ -3569,7 +3816,17 @@ bool SelectionDAGISel::runOnFunction(Function &Fn) {
     
     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
       Instruction *I = BBI++;
-      if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
+      
+      if (CallInst *CI = dyn_cast<CallInst>(I)) {
+        // If we found an inline asm expession, and if the target knows how to
+        // lower it to normal LLVM code, do so now.
+        if (isa<InlineAsm>(CI->getCalledValue()))
+          if (const TargetAsmInfo *TAI = 
+                TLI.getTargetMachine().getTargetAsmInfo()) {
+            if (TAI->ExpandInlineAsm(CI))
+              BBI = BB->begin();
+          }
+      } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
         MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
         // If the source of the cast is a constant, then this should have
@@ -3674,7 +3931,7 @@ SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
     }
     return DAG.getNode(ISD::TokenFactor, MVT::Other,
                        &OutChains[0], OutChains.size());
-  } else if (SrcVT < DestVT) {
+  } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
     // The src value is promoted to the register.
     if (MVT::isFloatingPoint(SrcVT))
       Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
@@ -3682,6 +3939,12 @@ SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
       Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
     return DAG.getCopyToReg(getRoot(), Reg, Op);
   } else  {
+    DestVT = TLI.getTypeToExpandTo(SrcVT);
+    unsigned NumVals = TLI.getNumElements(SrcVT);
+    if (NumVals == 1)
+      return DAG.getCopyToReg(getRoot(), Reg,
+                              DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
+    assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
     // The src value is expanded into multiple registers.
     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
                                Op, DAG.getConstant(0, TLI.getPointerTy()));
@@ -3793,6 +4056,7 @@ void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
       
       unsigned Reg;
       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
+      
       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
         unsigned &RegOut = ConstantsOut[C];
         if (RegOut == 0) {
@@ -3869,14 +4133,14 @@ void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
   // Run the DAG combiner in pre-legalize mode.
   DAG.Combine(false, AA);
   
-  DEBUG(std::cerr << "Lowered selection DAG:\n");
+  DOUT << "Lowered selection DAG:\n";
   DEBUG(DAG.dump());
   
   // Second step, hack on the DAG until it only uses operations and types that
   // the target supports.
   DAG.Legalize();
   
-  DEBUG(std::cerr << "Legalized selection DAG:\n");
+  DOUT << "Legalized selection DAG:\n";
   DEBUG(DAG.dump());
   
   // Run the DAG combiner in post-legalize mode.
@@ -3888,7 +4152,7 @@ void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
   // code to the MachineBasicBlock.
   InstructionSelectBasicBlock(DAG);
   
-  DEBUG(std::cerr << "Selected machine code:\n");
+  DOUT << "Selected machine code:\n";
   DEBUG(BB->dump());
 }  
 
@@ -4130,12 +4394,13 @@ SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
       // Otherwise, this is a memory operand.  Ask the target to select it.
       std::vector<SDOperand> SelOps;
       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
-        std::cerr << "Could not match memory address.  Inline asm failure!\n";
+        cerr << "Could not match memory address.  Inline asm failure!\n";
         exit(1);
       }
       
       // Add this to the output node.
-      Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
+      Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
+                                          MVT::i32));
       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
       i += 2;
     }