Removed UINT_TO_FP and SINT_TO_FP from ISel outright.
[oota-llvm.git] / lib / Target / PowerPC / PPCISelPattern.cpp
index c544e4d7fd01e71973c6f3776c4eb4d9370062a7..e0255dfee0853ba32aacc346a61dc6fc9580c7cf 100644 (file)
@@ -17,6 +17,7 @@
 #include "PowerPCInstrBuilder.h"
 #include "PowerPCInstrInfo.h"
 #include "PPC32TargetMachine.h"
+#include "PPC32ISelLowering.h"
 #include "llvm/Constants.h"
 #include "llvm/Function.h"
 #include "llvm/CodeGen/MachineConstantPool.h"
@@ -26,7 +27,6 @@
 #include "llvm/CodeGen/SelectionDAGISel.h"
 #include "llvm/CodeGen/SSARegMap.h"
 #include "llvm/Target/TargetData.h"
-#include "llvm/Target/TargetLowering.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MathExtras.h"
 #include <algorithm>
 using namespace llvm;
 
-//===----------------------------------------------------------------------===//
-//  PPC32TargetLowering - PPC32 Implementation of the TargetLowering interface
-namespace {
-  class PPC32TargetLowering : public TargetLowering {
-    int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
-    int ReturnAddrIndex;              // FrameIndex for return slot.
-  public:
-    PPC32TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
-      // Fold away setcc operations if possible.
-      setSetCCIsExpensive();
-
-      // Set up the register classes.
-      addRegisterClass(MVT::i32, PPC32::GPRCRegisterClass);
-      addRegisterClass(MVT::f32, PPC32::FPRCRegisterClass);
-      addRegisterClass(MVT::f64, PPC32::FPRCRegisterClass);
-
-      // PowerPC has no intrinsics for these particular operations
-      setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
-      setOperationAction(ISD::MEMSET, MVT::Other, Expand);
-      setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
-
-      // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
-      setOperationAction(ISD::SEXTLOAD, MVT::i1, Expand);
-      setOperationAction(ISD::SEXTLOAD, MVT::i8, Expand);
-
-      // PowerPC has no SREM/UREM instructions
-      setOperationAction(ISD::SREM, MVT::i32, Expand);
-      setOperationAction(ISD::UREM, MVT::i32, Expand);
-
-      // We don't support sin/cos/sqrt/fmod
-      setOperationAction(ISD::FSIN , MVT::f64, Expand);
-      setOperationAction(ISD::FCOS , MVT::f64, Expand);
-      setOperationAction(ISD::SREM , MVT::f64, Expand);
-      setOperationAction(ISD::FSIN , MVT::f32, Expand);
-      setOperationAction(ISD::FCOS , MVT::f32, Expand);
-      setOperationAction(ISD::SREM , MVT::f32, Expand);
-
-      // If we're enabling GP optimizations, use hardware square root
-      if (!GPOPT) {
-        setOperationAction(ISD::FSQRT, MVT::f64, Expand);
-        setOperationAction(ISD::FSQRT, MVT::f32, Expand);
-      }
-
-      //PowerPC does not have CTPOP or CTTZ
-      setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
-      setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
-
-      setSetCCResultContents(ZeroOrOneSetCCResult);
-      addLegalFPImmediate(+0.0); // Necessary for FSEL
-      addLegalFPImmediate(-0.0); //
-
-      computeRegisterProperties();
-    }
-
-    /// LowerArguments - This hook must be implemented to indicate how we should
-    /// lower the arguments for the specified function, into the specified DAG.
-    virtual std::vector<SDOperand>
-    LowerArguments(Function &F, SelectionDAG &DAG);
-
-    /// LowerCallTo - This hook lowers an abstract call to a function into an
-    /// actual call.
-    virtual std::pair<SDOperand, SDOperand>
-    LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg, unsigned CC,
-                bool isTailCall, SDOperand Callee, ArgListTy &Args,
-                SelectionDAG &DAG);
-
-    virtual SDOperand LowerVAStart(SDOperand Chain, SDOperand VAListP,
-                                   Value *VAListV, SelectionDAG &DAG);
-
-    virtual std::pair<SDOperand,SDOperand>
-      LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
-                 const Type *ArgTy, SelectionDAG &DAG);
-
-    virtual std::pair<SDOperand, SDOperand>
-    LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
-                            SelectionDAG &DAG);
-  };
-}
-
-
-std::vector<SDOperand>
-PPC32TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
-  //
-  // add beautiful description of PPC stack frame format, or at least some docs
-  //
-  MachineFunction &MF = DAG.getMachineFunction();
-  MachineFrameInfo *MFI = MF.getFrameInfo();
-  MachineBasicBlock& BB = MF.front();
-  std::vector<SDOperand> ArgValues;
-
-  // Due to the rather complicated nature of the PowerPC ABI, rather than a
-  // fixed size array of physical args, for the sake of simplicity let the STL
-  // handle tracking them for us.
-  std::vector<unsigned> argVR, argPR, argOp;
-  unsigned ArgOffset = 24;
-  unsigned GPR_remaining = 8;
-  unsigned FPR_remaining = 13;
-  unsigned GPR_idx = 0, FPR_idx = 0;
-  static const unsigned GPR[] = {
-    PPC::R3, PPC::R4, PPC::R5, PPC::R6,
-    PPC::R7, PPC::R8, PPC::R9, PPC::R10,
-  };
-  static const unsigned FPR[] = {
-    PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
-    PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
-  };
-
-  // Add DAG nodes to load the arguments...  On entry to a function on PPC,
-  // the arguments start at offset 24, although they are likely to be passed
-  // in registers.
-  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
-    SDOperand newroot, argt;
-    unsigned ObjSize;
-    bool needsLoad = false;
-    bool ArgLive = !I->use_empty();
-    MVT::ValueType ObjectVT = getValueType(I->getType());
-
-    switch (ObjectVT) {
-    default: assert(0 && "Unhandled argument type!");
-    case MVT::i1:
-    case MVT::i8:
-    case MVT::i16:
-    case MVT::i32:
-      ObjSize = 4;
-      if (!ArgLive) break;
-      if (GPR_remaining > 0) {
-        MF.addLiveIn(GPR[GPR_idx]);
-        argt = newroot = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32,
-                                            DAG.getRoot());
-        if (ObjectVT != MVT::i32)
-          argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, newroot);
-      } else {
-        needsLoad = true;
-      }
-      break;
-      case MVT::i64: ObjSize = 8;
-      if (!ArgLive) break;
-      if (GPR_remaining > 0) {
-        SDOperand argHi, argLo;
-        MF.addLiveIn(GPR[GPR_idx]);
-        argHi = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32, DAG.getRoot());
-        // If we have two or more remaining argument registers, then both halves
-        // of the i64 can be sourced from there.  Otherwise, the lower half will
-        // have to come off the stack.  This can happen when an i64 is preceded
-        // by 28 bytes of arguments.
-        if (GPR_remaining > 1) {
-          MF.addLiveIn(GPR[GPR_idx+1]);
-          argLo = DAG.getCopyFromReg(GPR[GPR_idx+1], MVT::i32, argHi);
-        } else {
-          int FI = MFI->CreateFixedObject(4, ArgOffset+4);
-          SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
-          argLo = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
-                              DAG.getSrcValue(NULL));
-        }
-        // Build the outgoing arg thingy
-        argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
-        newroot = argLo;
-      } else {
-        needsLoad = true;
-      }
-      break;
-      case MVT::f32:
-      case MVT::f64:
-      ObjSize = (ObjectVT == MVT::f64) ? 8 : 4;
-      if (!ArgLive) break;
-      if (FPR_remaining > 0) {
-        MF.addLiveIn(FPR[FPR_idx]);
-        argt = newroot = DAG.getCopyFromReg(FPR[FPR_idx], ObjectVT,
-                                            DAG.getRoot());
-        --FPR_remaining;
-        ++FPR_idx;
-      } else {
-        needsLoad = true;
-      }
-      break;
-    }
-
-    // We need to load the argument to a virtual register if we determined above
-    // that we ran out of physical registers of the appropriate type
-    if (needsLoad) {
-      unsigned SubregOffset = 0;
-      if (ObjectVT == MVT::i8 || ObjectVT == MVT::i1) SubregOffset = 3;
-      if (ObjectVT == MVT::i16) SubregOffset = 2;
-      int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
-      SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
-      FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN,
-                        DAG.getConstant(SubregOffset, MVT::i32));
-      argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
-                                   DAG.getSrcValue(NULL));
-    }
-
-    // Every 4 bytes of argument space consumes one of the GPRs available for
-    // argument passing.
-    if (GPR_remaining > 0) {
-      unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
-      GPR_remaining -= delta;
-      GPR_idx += delta;
-    }
-    ArgOffset += ObjSize;
-    if (newroot.Val)
-      DAG.setRoot(newroot.getValue(1));
-
-    ArgValues.push_back(argt);
-  }
-
-  // If the function takes variable number of arguments, make a frame index for
-  // the start of the first vararg value... for expansion of llvm.va_start.
-  if (F.isVarArg()) {
-    VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
-    SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
-    // If this function is vararg, store any remaining integer argument regs
-    // to their spots on the stack so that they may be loaded by deferencing the
-    // result of va_next.
-    std::vector<SDOperand> MemOps;
-    for (; GPR_remaining > 0; --GPR_remaining, ++GPR_idx) {
-      MF.addLiveIn(GPR[GPR_idx]);
-      SDOperand Val = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32, DAG.getRoot());
-      SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
-                                    Val, FIN, DAG.getSrcValue(NULL));
-      MemOps.push_back(Store);
-      // Increment the address by four for the next argument to store
-      SDOperand PtrOff = DAG.getConstant(4, getPointerTy());
-      FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, PtrOff);
-    }
-    DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps));
-  }
-
-  // Finally, inform the code generator which regs we return values in.
-  switch (getValueType(F.getReturnType())) {
-  default: assert(0 && "Unknown type!");
-  case MVT::isVoid: break;
-  case MVT::i1:
-  case MVT::i8:
-  case MVT::i16:
-  case MVT::i32:
-    MF.addLiveOut(PPC::R3);
-    break;
-  case MVT::i64:
-    MF.addLiveOut(PPC::R3);
-    MF.addLiveOut(PPC::R4);
-    break;
-  case MVT::f32:
-  case MVT::f64:
-    MF.addLiveOut(PPC::F1);
-    break;
-  }
-
-  return ArgValues;
-}
-
-std::pair<SDOperand, SDOperand>
-PPC32TargetLowering::LowerCallTo(SDOperand Chain,
-                                 const Type *RetTy, bool isVarArg,
-                                 unsigned CallingConv, bool isTailCall,
-                                 SDOperand Callee, ArgListTy &Args,
-                                 SelectionDAG &DAG) {
-  // args_to_use will accumulate outgoing args for the ISD::CALL case in
-  // SelectExpr to use to put the arguments in the appropriate registers.
-  std::vector<SDOperand> args_to_use;
-
-  // Count how many bytes are to be pushed on the stack, including the linkage
-  // area, and parameter passing area.
-  unsigned NumBytes = 24;
-
-  if (Args.empty()) {
-    Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
-                        DAG.getConstant(NumBytes, getPointerTy()));
-  } else {
-    for (unsigned i = 0, e = Args.size(); i != e; ++i)
-      switch (getValueType(Args[i].second)) {
-      default: assert(0 && "Unknown value type!");
-      case MVT::i1:
-      case MVT::i8:
-      case MVT::i16:
-      case MVT::i32:
-      case MVT::f32:
-        NumBytes += 4;
-        break;
-      case MVT::i64:
-      case MVT::f64:
-        NumBytes += 8;
-        break;
-      }
-
-    // Just to be safe, we'll always reserve the full 24 bytes of linkage area
-    // plus 32 bytes of argument space in case any called code gets funky on us.
-    if (NumBytes < 56) NumBytes = 56;
-
-    // Adjust the stack pointer for the new arguments...
-    // These operations are automatically eliminated by the prolog/epilog pass
-    Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
-                        DAG.getConstant(NumBytes, getPointerTy()));
-
-    // Set up a copy of the stack pointer for use loading and storing any
-    // arguments that may not fit in the registers available for argument
-    // passing.
-    SDOperand StackPtr = DAG.getCopyFromReg(PPC::R1, MVT::i32,
-                                            DAG.getEntryNode());
-
-    // Figure out which arguments are going to go in registers, and which in
-    // memory.  Also, if this is a vararg function, floating point operations
-    // must be stored to our stack, and loaded into integer regs as well, if
-    // any integer regs are available for argument passing.
-    unsigned ArgOffset = 24;
-    unsigned GPR_remaining = 8;
-    unsigned FPR_remaining = 13;
-
-    std::vector<SDOperand> MemOps;
-    for (unsigned i = 0, e = Args.size(); i != e; ++i) {
-      // PtrOff will be used to store the current argument to the stack if a
-      // register cannot be found for it.
-      SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
-      PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
-      MVT::ValueType ArgVT = getValueType(Args[i].second);
-
-      switch (ArgVT) {
-      default: assert(0 && "Unexpected ValueType for argument!");
-      case MVT::i1:
-      case MVT::i8:
-      case MVT::i16:
-        // Promote the integer to 32 bits.  If the input type is signed use a
-        // sign extend, otherwise use a zero extend.
-        if (Args[i].second->isSigned())
-          Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
-        else
-          Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
-        // FALL THROUGH
-      case MVT::i32:
-        if (GPR_remaining > 0) {
-          args_to_use.push_back(Args[i].first);
-          --GPR_remaining;
-        } else {
-          MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
-                                       Args[i].first, PtrOff,
-                                       DAG.getSrcValue(NULL)));
-        }
-        ArgOffset += 4;
-        break;
-      case MVT::i64:
-        // If we have one free GPR left, we can place the upper half of the i64
-        // in it, and store the other half to the stack.  If we have two or more
-        // free GPRs, then we can pass both halves of the i64 in registers.
-        if (GPR_remaining > 0) {
-          SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
-            Args[i].first, DAG.getConstant(1, MVT::i32));
-          SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
-            Args[i].first, DAG.getConstant(0, MVT::i32));
-          args_to_use.push_back(Hi);
-          --GPR_remaining;
-          if (GPR_remaining > 0) {
-            args_to_use.push_back(Lo);
-            --GPR_remaining;
-          } else {
-            SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
-            PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
-            MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
-                                         Lo, PtrOff, DAG.getSrcValue(NULL)));
-          }
-        } else {
-          MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
-                                       Args[i].first, PtrOff,
-                                       DAG.getSrcValue(NULL)));
-        }
-        ArgOffset += 8;
-        break;
-      case MVT::f32:
-      case MVT::f64:
-        if (FPR_remaining > 0) {
-          args_to_use.push_back(Args[i].first);
-          --FPR_remaining;
-          if (isVarArg) {
-            SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Chain,
-                                          Args[i].first, PtrOff,
-                                          DAG.getSrcValue(NULL));
-            MemOps.push_back(Store);
-            // Float varargs are always shadowed in available integer registers
-            if (GPR_remaining > 0) {
-              SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
-                                           DAG.getSrcValue(NULL));
-              MemOps.push_back(Load);
-              args_to_use.push_back(Load);
-              --GPR_remaining;
-            }
-            if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
-              SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
-              PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
-              SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
-                                           DAG.getSrcValue(NULL));
-              MemOps.push_back(Load);
-              args_to_use.push_back(Load);
-              --GPR_remaining;
-            }
-          } else {
-            // If we have any FPRs remaining, we may also have GPRs remaining.
-            // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
-            // GPRs.
-            if (GPR_remaining > 0) {
-              args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
-              --GPR_remaining;
-            }
-            if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
-              args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
-              --GPR_remaining;
-            }
-          }
-        } else {
-          MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
-                                       Args[i].first, PtrOff,
-                                       DAG.getSrcValue(NULL)));
-        }
-        ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
-        break;
-      }
-    }
-    if (!MemOps.empty())
-      Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps);
-  }
-
-  std::vector<MVT::ValueType> RetVals;
-  MVT::ValueType RetTyVT = getValueType(RetTy);
-  if (RetTyVT != MVT::isVoid)
-    RetVals.push_back(RetTyVT);
-  RetVals.push_back(MVT::Other);
-
-  SDOperand TheCall = SDOperand(DAG.getCall(RetVals,
-                                            Chain, Callee, args_to_use), 0);
-  Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
-  Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
-                      DAG.getConstant(NumBytes, getPointerTy()));
-  return std::make_pair(TheCall, Chain);
-}
-
-SDOperand PPC32TargetLowering::LowerVAStart(SDOperand Chain, SDOperand VAListP,
-                                            Value *VAListV, SelectionDAG &DAG) {
-  // vastart just stores the address of the VarArgsFrameIndex slot into the
-  // memory location argument.
-  SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
-  return DAG.getNode(ISD::STORE, MVT::Other, Chain, FR, VAListP,
-                     DAG.getSrcValue(VAListV));
-}
-
-std::pair<SDOperand,SDOperand>
-PPC32TargetLowering::LowerVAArg(SDOperand Chain,
-                                SDOperand VAListP, Value *VAListV,
-                                const Type *ArgTy, SelectionDAG &DAG) {
-  MVT::ValueType ArgVT = getValueType(ArgTy);
-
-  SDOperand VAList =
-    DAG.getLoad(MVT::i32, Chain, VAListP, DAG.getSrcValue(VAListV));
-  SDOperand Result = DAG.getLoad(ArgVT, Chain, VAList, DAG.getSrcValue(NULL));
-  unsigned Amt;
-  if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
-    Amt = 4;
-  else {
-    assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
-           "Other types should have been promoted for varargs!");
-    Amt = 8;
-  }
-  VAList = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
-                      DAG.getConstant(Amt, VAList.getValueType()));
-  Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain,
-                      VAList, VAListP, DAG.getSrcValue(VAListV));
-  return std::make_pair(Result, Chain);
-}
-
-
-std::pair<SDOperand, SDOperand> PPC32TargetLowering::
-LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
-                        SelectionDAG &DAG) {
-  assert(0 && "LowerFrameReturnAddress unimplemented");
-  abort();
-}
-
 namespace {
 Statistic<>Recorded("ppc-codegen", "Number of recording ops emitted");
 Statistic<>FusedFP("ppc-codegen", "Number of fused fp operations");
 Statistic<>FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
+
 //===--------------------------------------------------------------------===//
 /// ISel - PPC32 specific code to select PPC32 machine instructions for
 /// SelectionDAG operations.
@@ -555,150 +83,137 @@ public:
     ISelDAG = 0;
   }
 
+  // convenience functions for virtual register creation
+  inline unsigned MakeIntReg() {
+    return RegMap->createVirtualRegister(PPC32::GPRCRegisterClass);
+  }
+  inline unsigned MakeFPReg() {
+    return RegMap->createVirtualRegister(PPC32::FPRCRegisterClass);
+  }
+  
   // dag -> dag expanders for integer divide by constant
   SDOperand BuildSDIVSequence(SDOperand N);
   SDOperand BuildUDIVSequence(SDOperand N);
 
   unsigned getGlobalBaseReg();
   unsigned getConstDouble(double floatVal, unsigned Result);
-  void MoveCRtoGPR(unsigned CCReg, bool Inv, unsigned Idx, unsigned Result);
+  void MoveCRtoGPR(unsigned CCReg, ISD::CondCode CC, unsigned Result);
   bool SelectBitfieldInsert(SDOperand OR, unsigned Result);
   unsigned FoldIfWideZeroExtend(SDOperand N);
-  unsigned SelectCC(SDOperand CC, unsigned &Opc, bool &Inv, unsigned &Idx);
-  unsigned SelectCCExpr(SDOperand N, unsigned& Opc, bool &Inv, unsigned &Idx);
+  unsigned SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
+  bool SelectIntImmediateExpr(SDOperand N, unsigned Result,
+                              unsigned OCHi, unsigned OCLo,
+                              bool IsArithmetic = false, bool Negate = false);
   unsigned SelectExpr(SDOperand N, bool Recording=false);
   void Select(SDOperand N);
 
   unsigned SelectAddr(SDOperand N, unsigned& Reg, int& offset);
   void SelectBranchCC(SDOperand N);
+  
+  virtual const char *getPassName() const {
+    return "PowerPC Pattern Instruction Selection";
+  } 
 };
 
-/// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
-/// returns zero when the input is not exactly a power of two.
-static unsigned ExactLog2(unsigned Val) {
-  if (Val == 0 || (Val & (Val-1))) return 0;
-  unsigned Count = 0;
-  while (Val != 1) {
-    Val >>= 1;
-    ++Count;
+// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
+// any number of 0s on either side.  The 1s are allowed to wrap from LSB to
+// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
+// not, since all 1s are not contiguous.
+static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
+  if (isShiftedMask_32(Val)) {
+    // look for the first non-zero bit
+    MB = CountLeadingZeros_32(Val);
+    // look for the first zero bit after the run of ones
+    ME = CountLeadingZeros_32((Val - 1) ^ Val);
+    return true;
+  } else if (isShiftedMask_32(Val = ~Val)) { // invert mask
+    // effectively look for the first zero bit
+    ME = CountLeadingZeros_32(Val) - 1;
+    // effectively look for the first one bit after the run of zeros
+    MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
+    return true;
   }
-  return Count;
+  // no run present
+  return false;
 }
 
-// IsRunOfOnes - returns true if Val consists of one contiguous run of 1's with
-// any number of 0's on either side.  the 1's are allowed to wrap from LSB to
-// MSB.  so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
-// not, since all 1's are not contiguous.
-static bool IsRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
-  bool isRun = true;
-  MB = 0;
-  ME = 0;
-
-  // look for first set bit
-  int i = 0;
-  for (; i < 32; i++) {
-    if ((Val & (1 << (31 - i))) != 0) {
-      MB = i;
-      ME = i;
-      break;
-    }
+// isRotateAndMask - Returns true if Mask and Shift can be folded in to a rotate
+// and mask opcode and mask operation.
+static bool isRotateAndMask(unsigned Opcode, unsigned Shift, unsigned Mask,
+                            bool IsShiftMask,
+                            unsigned &SH, unsigned &MB, unsigned &ME) {
+  if (Shift > 31) return false;
+  unsigned Indeterminant = ~0;       // bit mask marking indeterminant results
+  
+  if (Opcode == ISD::SHL) { // shift left
+    // apply shift to mask if it comes first
+    if (IsShiftMask) Mask = Mask << Shift;
+    // determine which bits are made indeterminant by shift
+    Indeterminant = ~(0xFFFFFFFFu << Shift);
+  } else if (Opcode == ISD::SRA || Opcode == ISD::SRL) { // shift rights
+    // apply shift to mask if it comes first
+    if (IsShiftMask) Mask = Mask >> Shift;
+    // determine which bits are made indeterminant by shift
+    Indeterminant = ~(0xFFFFFFFFu >> Shift);
+    // adjust for the left rotate
+    Shift = 32 - Shift;
   }
-
-  // look for last set bit
-  for (; i < 32; i++) {
-    if ((Val & (1 << (31 - i))) == 0)
-      break;
-    ME = i;
-  }
-
-  // look for next set bit
-  for (; i < 32; i++) {
-    if ((Val & (1 << (31 - i))) != 0)
-      break;
+  
+  // if the mask doesn't intersect any Indeterminant bits
+  if (Mask && !(Mask & Indeterminant)) {
+    SH = Shift;
+    // make sure the mask is still a mask (wrap arounds may not be)
+    return isRunOfOnes(Mask, MB, ME);
   }
+  
+  // can't do it
+  return false;
+}
 
-  // if we exhausted all the bits, we found a match at this point for 0*1*0*
-  if (i == 32)
+// isIntImmediate - This method tests to see if a constant operand.
+// If so Imm will receive the 32 bit value.
+static bool isIntImmediate(SDOperand N, unsigned& Imm) {
+  // test for constant
+  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
+    // retrieve value
+    Imm = (unsigned)CN->getSignExtended();
+    // passes muster
     return true;
-
-  // since we just encountered more 1's, if it doesn't wrap around to the
-  // most significant bit of the word, then we did not find a match to 1*0*1* so
-  // exit.
-  if (MB != 0)
-    return false;
-
-  // look for last set bit
-  for (MB = i; i < 32; i++) {
-    if ((Val & (1 << (31 - i))) == 0)
-      break;
   }
-
-  // if we exhausted all the bits, then we found a match for 1*0*1*, otherwise,
-  // the value is not a run of ones.
-  if (i == 32)
-    return true;
+  // not a constant
   return false;
 }
 
-/// getImmediateForOpcode - This method returns a value indicating whether
-/// the ConstantSDNode N can be used as an immediate to Opcode.  The return
-/// values are either 0, 1 or 2.  0 indicates that either N is not a
-/// ConstantSDNode, or is not suitable for use by that opcode.
-/// Return value codes for turning into an enum someday:
-/// 1: constant may be used in normal immediate form.
-/// 2: constant may be used in shifted immediate form.
-/// 3: log base 2 of the constant may be used.
-/// 4: constant is suitable for integer division conversion
-/// 5: constant is a bitfield mask
-///
-static unsigned getImmediateForOpcode(SDOperand N, unsigned Opcode,
-                                      unsigned& Imm, bool U = false) {
-  if (N.getOpcode() != ISD::Constant) return 0;
+// isOpcWithIntImmediate - This method tests to see if the node is a specific
+// opcode and that it has a immediate integer right operand.
+// If so Imm will receive the 32 bit value.
+static bool isOpcWithIntImmediate(SDOperand N, unsigned Opc, unsigned& Imm) {
+  return N.getOpcode() == Opc && isIntImmediate(N.getOperand(1), Imm);
+}
 
-  int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
+// isOprShiftImm - Returns true if the specified operand is a shift opcode with
+// a immediate shift count less than 32.
+static bool isOprShiftImm(SDOperand N, unsigned& Opc, unsigned& SH) {
+  Opc = N.getOpcode();
+  return (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
+         isIntImmediate(N.getOperand(1), SH) && SH < 32;
+}
 
-  switch(Opcode) {
-  default: return 0;
-  case ISD::ADD:
-    if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
-    if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
-    break;
-  case ISD::AND: {
-    unsigned MB, ME;
-    if (IsRunOfOnes(v, MB, ME)) { Imm = MB << 16 | ME & 0xFFFF; return 5; }
-    if (v >= 0 && v <= 65535) { Imm = v & 0xFFFF; return 1; }
-    if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
-    break;
-  }
-  case ISD::XOR:
-  case ISD::OR:
-    if (v >= 0 && v <= 65535) { Imm = v & 0xFFFF; return 1; }
-    if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
-    break;
-  case ISD::MUL:
-    if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
-    break;
-  case ISD::SUB:
-    // handle subtract-from separately from subtract, since subi is really addi
-    if (U && v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
-    if (!U && v <= 32768 && v >= -32767) { Imm = (-v) & 0xFFFF; return 1; }
-    break;
-  case ISD::SETCC:
-    if (U && (v >= 0 && v <= 65535)) { Imm = v & 0xFFFF; return 1; }
-    if (!U && (v <= 32767 && v >= -32768)) { Imm = v & 0xFFFF; return 1; }
-    break;
-  case ISD::SDIV:
-    if ((Imm = ExactLog2(v))) { return 3; }
-    if ((Imm = ExactLog2(-v))) { Imm = -Imm; return 3; }
-    if (v <= -2 || v >= 2) { return 4; }
-    break;
-  case ISD::UDIV:
-    if (v > 1) { return 4; }
-    break;
-  }
-  return 0;
+// isOprNot - Returns true if the specified operand is an xor with immediate -1.
+static bool isOprNot(SDOperand N) {
+  unsigned Imm;
+  return isOpcWithIntImmediate(N, ISD::XOR, Imm) && (signed)Imm == -1;
 }
 
+// Immediate constant composers.
+// Lo16 - grabs the lo 16 bits from a 32 bit constant.
+// Hi16 - grabs the hi 16 bits from a 32 bit constant.
+// HA16 - computes the hi bits required if the lo bits are add/subtracted in
+// arithmethically.
+static unsigned Lo16(unsigned x)  { return x & 0x0000FFFF; }
+static unsigned Hi16(unsigned x)  { return Lo16(x >> 16); }
+static unsigned HA16(unsigned x)  { return Hi16((signed)x - (signed short)x); }
+
 /// NodeHasRecordingVariant - If SelectExpr can always produce code for
 /// NodeOpcode that also sets CR0 as a side effect, return true.  Otherwise,
 /// return false.
@@ -712,21 +227,19 @@ static bool NodeHasRecordingVariant(unsigned NodeOpcode) {
 }
 
 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
-/// to Condition.  If the Condition is unordered or unsigned, the bool argument
-/// U is set to true, otherwise it is set to false.
-static unsigned getBCCForSetCC(unsigned Condition, bool& U) {
-  U = false;
-  switch (Condition) {
+/// to Condition.
+static unsigned getBCCForSetCC(ISD::CondCode CC) {
+  switch (CC) {
   default: assert(0 && "Unknown condition!"); abort();
   case ISD::SETEQ:  return PPC::BEQ;
   case ISD::SETNE:  return PPC::BNE;
-  case ISD::SETULT: U = true;
+  case ISD::SETULT:
   case ISD::SETLT:  return PPC::BLT;
-  case ISD::SETULE: U = true;
+  case ISD::SETULE:
   case ISD::SETLE:  return PPC::BLE;
-  case ISD::SETUGT: U = true;
+  case ISD::SETUGT:
   case ISD::SETGT:  return PPC::BGT;
-  case ISD::SETUGE: U = true;
+  case ISD::SETUGE:
   case ISD::SETGE:  return PPC::BGE;
   }
   return 0;
@@ -752,8 +265,8 @@ static unsigned getCROpForSetCC(unsigned Opcode, bool Inv1, bool Inv2) {
 /// getCRIdxForSetCC - Return the index of the condition register field
 /// associated with the SetCC condition, and whether or not the field is
 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
-static unsigned getCRIdxForSetCC(unsigned Condition, bool& Inv) {
-  switch (Condition) {
+static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
+  switch (CC) {
   default: assert(0 && "Unknown condition!"); abort();
   case ISD::SETULT:
   case ISD::SETLT:  Inv = false;  return 0;
@@ -803,7 +316,7 @@ struct mu {
 static struct ms magic(int d) {
   int p;
   unsigned int ad, anc, delta, q1, r1, q2, r2, t;
-  const unsigned int two31 = 2147483648U; // 2^31
+  const unsigned int two31 = 0x80000000U;
   struct ms mag;
 
   ad = abs(d);
@@ -938,7 +451,7 @@ unsigned ISel::getGlobalBaseReg() {
     // Insert the set of GlobalBaseReg into the first MBB of the function
     MachineBasicBlock &FirstMBB = BB->getParent()->front();
     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
-    GlobalBaseReg = MakeReg(MVT::i32);
+    GlobalBaseReg = MakeIntReg();
     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg).addReg(PPC::LR);
     GlobalBaseInitialized = true;
@@ -949,8 +462,8 @@ unsigned ISel::getGlobalBaseReg() {
 /// getConstDouble - Loads a floating point value into a register, via the
 /// Constant Pool.  Optionally takes a register in which to load the value.
 unsigned ISel::getConstDouble(double doubleVal, unsigned Result=0) {
-  unsigned Tmp1 = MakeReg(MVT::i32);
-  if (0 == Result) Result = MakeReg(MVT::f64);
+  unsigned Tmp1 = MakeIntReg();
+  if (0 == Result) Result = MakeFPReg();
   MachineConstantPool *CP = BB->getParent()->getConstantPool();
   ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, doubleVal);
   unsigned CPI = CP->getConstantPoolIndex(CFP);
@@ -965,12 +478,16 @@ unsigned ISel::getConstDouble(double doubleVal, unsigned Result=0) {
 
 /// MoveCRtoGPR - Move CCReg[Idx] to the least significant bit of Result.  If
 /// Inv is true, then invert the result.
-void ISel::MoveCRtoGPR(unsigned CCReg, bool Inv, unsigned Idx, unsigned Result){
-  unsigned IntCR = MakeReg(MVT::i32);
+void ISel::MoveCRtoGPR(unsigned CCReg, ISD::CondCode CC, unsigned Result){
+  bool Inv;
+  unsigned IntCR = MakeIntReg();
+  unsigned Idx = getCRIdxForSetCC(CC, Inv);
   BuildMI(BB, PPC::MCRF, 1, PPC::CR7).addReg(CCReg);
-  BuildMI(BB, GPOPT ? PPC::MFOCRF : PPC::MFCR, 1, IntCR).addReg(PPC::CR7);
+  bool GPOpt =
+    TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor();
+  BuildMI(BB, GPOpt ? PPC::MFOCRF : PPC::MFCR, 1, IntCR).addReg(PPC::CR7);
   if (Inv) {
-    unsigned Tmp1 = MakeReg(MVT::i32);
+    unsigned Tmp1 = MakeIntReg();
     BuildMI(BB, PPC::RLWINM, 4, Tmp1).addReg(IntCR).addImm(32-(3-Idx))
       .addImm(31).addImm(31);
     BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp1).addImm(1);
@@ -992,6 +509,7 @@ void ISel::MoveCRtoGPR(unsigned CCReg, bool Inv, unsigned Idx, unsigned Result){
 bool ISel::SelectBitfieldInsert(SDOperand OR, unsigned Result) {
   bool IsRotate = false;
   unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, Amount = 0;
+  unsigned Value;
 
   SDOperand Op0 = OR.getOperand(0);
   SDOperand Op1 = OR.getOperand(1);
@@ -1006,34 +524,32 @@ bool ISel::SelectBitfieldInsert(SDOperand OR, unsigned Result) {
     return false;
 
   // Generate Mask value for Target
-  if (ConstantSDNode *CN =
-      dyn_cast<ConstantSDNode>(Op0.getOperand(1).Val)) {
+  if (isIntImmediate(Op0.getOperand(1), Value)) {
     switch(Op0Opc) {
-    case ISD::SHL: TgtMask <<= (unsigned)CN->getValue(); break;
-    case ISD::SRL: TgtMask >>= (unsigned)CN->getValue(); break;
-    case ISD::AND: TgtMask &= (unsigned)CN->getValue(); break;
+    case ISD::SHL: TgtMask <<= Value; break;
+    case ISD::SRL: TgtMask >>= Value; break;
+    case ISD::AND: TgtMask &= Value; break;
     }
   } else {
     return false;
   }
 
   // Generate Mask value for Insert
-  if (ConstantSDNode *CN =
-      dyn_cast<ConstantSDNode>(Op1.getOperand(1).Val)) {
+  if (isIntImmediate(Op1.getOperand(1), Value)) {
     switch(Op1Opc) {
     case ISD::SHL:
-      Amount = CN->getValue();
+      Amount = Value;
       InsMask <<= Amount;
       if (Op0Opc == ISD::SRL) IsRotate = true;
       break;
     case ISD::SRL:
-      Amount = CN->getValue();
+      Amount = Value;
       InsMask >>= Amount;
       Amount = 32-Amount;
       if (Op0Opc == ISD::SHL) IsRotate = true;
       break;
     case ISD::AND:
-      InsMask &= (unsigned)CN->getValue();
+      InsMask &= Value;
       break;
     }
   } else {
@@ -1048,20 +564,18 @@ bool ISel::SelectBitfieldInsert(SDOperand OR, unsigned Result) {
   if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
     if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
         Op1.getOperand(0).getOpcode() == ISD::SRL) {
-      if (ConstantSDNode *CN =
-          dyn_cast<ConstantSDNode>(Op1.getOperand(0).getOperand(1).Val)) {
+      if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
         Amount = Op1.getOperand(0).getOpcode() == ISD::SHL ?
-          CN->getValue() : 32 - CN->getValue();
+          Value : 32 - Value;
         Tmp3 = SelectExpr(Op1.getOperand(0).getOperand(0));
       }
     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
                Op0.getOperand(0).getOpcode() == ISD::SRL) {
-      if (ConstantSDNode *CN =
-          dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(1).Val)) {
+      if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
         std::swap(Op0, Op1);
         std::swap(TgtMask, InsMask);
         Amount = Op1.getOperand(0).getOpcode() == ISD::SHL ?
-          CN->getValue() : 32 - CN->getValue();
+          Value : 32 - Value;
         Tmp3 = SelectExpr(Op1.getOperand(0).getOperand(0));
       }
     }
@@ -1072,7 +586,7 @@ bool ISel::SelectBitfieldInsert(SDOperand OR, unsigned Result) {
   // of set bits).  Given that, Select the arguments and generate the rlwimi
   // instruction.
   unsigned MB, ME;
-  if (((TgtMask & InsMask) == 0) && IsRunOfOnes(InsMask, MB, ME)) {
+  if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
     unsigned Tmp1, Tmp2;
     bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
     // Check for rotlwi / rotrwi here, a special case of bitfield insert
@@ -1102,16 +616,13 @@ bool ISel::SelectBitfieldInsert(SDOperand OR, unsigned Result) {
 /// shift do the mask.
 unsigned ISel::FoldIfWideZeroExtend(SDOperand N) {
   unsigned C;
-  if (N.getOpcode() == ISD::AND &&
-      5 == getImmediateForOpcode(N.getOperand(1), ISD::AND, C) && // isMask
-      31 == (C & 0xFFFF) && // ME
-      26 >= (C >> 16))      // MB
+  if (isOpcWithIntImmediate(N, ISD::AND, C) && isMask_32(C) && C > 63)
     return SelectExpr(N.getOperand(0));
   else
     return SelectExpr(N);
 }
 
-unsigned ISel::SelectCC(SDOperand CC, unsigned& Opc, bool &Inv, unsigned& Idx) {
+unsigned ISel::SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC) {
   unsigned Result, Tmp1, Tmp2;
   bool AlreadySelected = false;
   static const unsigned CompareOpcodes[] =
@@ -1120,105 +631,50 @@ unsigned ISel::SelectCC(SDOperand CC, unsigned& Opc, bool &Inv, unsigned& Idx) {
   // Allocate a condition register for this expression
   Result = RegMap->createVirtualRegister(PPC32::CRRCRegisterClass);
 
-  // If the first operand to the select is a SETCC node, then we can fold it
-  // into the branch that selects which value to return.
-  if (SetCCSDNode* SetCC = dyn_cast<SetCCSDNode>(CC.Val)) {
-    bool U;
-    Opc = getBCCForSetCC(SetCC->getCondition(), U);
-    Idx = getCRIdxForSetCC(SetCC->getCondition(), Inv);
-
-    // Pass the optional argument U to getImmediateForOpcode for SETCC,
-    // so that it knows whether the SETCC immediate range is signed or not.
-    if (1 == getImmediateForOpcode(SetCC->getOperand(1), ISD::SETCC,
-                                   Tmp2, U)) {
-      // For comparisons against zero, we can implicity set CR0 if a recording
-      // variant (e.g. 'or.' instead of 'or') of the instruction that defines
-      // operand zero of the SetCC node is available.
-      if (0 == Tmp2 &&
-          NodeHasRecordingVariant(SetCC->getOperand(0).getOpcode()) &&
-          SetCC->getOperand(0).Val->hasOneUse()) {
-        RecordSuccess = false;
-        Tmp1 = SelectExpr(SetCC->getOperand(0), true);
-        if (RecordSuccess) {
-          ++Recorded;
-          BuildMI(BB, PPC::MCRF, 1, Result).addReg(PPC::CR0);
-          return Result;
-        }
-        AlreadySelected = true;
+  // Use U to determine whether the SETCC immediate range is signed or not.
+  bool U = ISD::isUnsignedIntSetCC(CC);
+  if (isIntImmediate(RHS, Tmp2) && 
+      ((U && isUInt16(Tmp2)) || (!U && isInt16(Tmp2)))) {
+    Tmp2 = Lo16(Tmp2);
+    // For comparisons against zero, we can implicity set CR0 if a recording
+    // variant (e.g. 'or.' instead of 'or') of the instruction that defines
+    // operand zero of the SetCC node is available.
+    if (Tmp2 == 0 &&
+        NodeHasRecordingVariant(LHS.getOpcode()) && LHS.Val->hasOneUse()) {
+      RecordSuccess = false;
+      Tmp1 = SelectExpr(LHS, true);
+      if (RecordSuccess) {
+        ++Recorded;
+        BuildMI(BB, PPC::MCRF, 1, Result).addReg(PPC::CR0);
+        return Result;
       }
-      // If we could not implicitly set CR0, then emit a compare immediate
-      // instead.
-      if (!AlreadySelected) Tmp1 = SelectExpr(SetCC->getOperand(0));
-      if (U)
-        BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
-      else
-        BuildMI(BB, PPC::CMPWI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
-    } else {
-      bool IsInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
-      unsigned CompareOpc = CompareOpcodes[2 * IsInteger + U];
-      Tmp1 = SelectExpr(SetCC->getOperand(0));
-      Tmp2 = SelectExpr(SetCC->getOperand(1));
-      BuildMI(BB, CompareOpc, 2, Result).addReg(Tmp1).addReg(Tmp2);
+      AlreadySelected = true;
     }
+    // If we could not implicitly set CR0, then emit a compare immediate
+    // instead.
+    if (!AlreadySelected) Tmp1 = SelectExpr(LHS);
+    if (U)
+      BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
+    else
+      BuildMI(BB, PPC::CMPWI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
   } else {
-    // If this isn't a SetCC, then select the value and compare it against zero,
-    // treating it as if it were a boolean.
-    Opc = PPC::BNE;
-    Idx = getCRIdxForSetCC(ISD::SETNE, Inv);
-    Tmp1 = SelectExpr(CC);
-    BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(0);
+    bool IsInteger = MVT::isInteger(LHS.getValueType());
+    unsigned CompareOpc = CompareOpcodes[2 * IsInteger + U];
+    Tmp1 = SelectExpr(LHS);
+    Tmp2 = SelectExpr(RHS);
+    BuildMI(BB, CompareOpc, 2, Result).addReg(Tmp1).addReg(Tmp2);
   }
   return Result;
 }
 
-unsigned ISel::SelectCCExpr(SDOperand N, unsigned& Opc, bool &Inv,
-                            unsigned &Idx) {
-  bool Inv0, Inv1;
-  unsigned Idx0, Idx1, CROpc, Opc1, Tmp1, Tmp2;
-
-  // Allocate a condition register for this expression
-  unsigned Result = RegMap->createVirtualRegister(PPC32::CRRCRegisterClass);
-
-  // Check for the operations we support:
-  switch(N.getOpcode()) {
-  default:
-    Opc = PPC::BNE;
-    Idx = getCRIdxForSetCC(ISD::SETNE, Inv);
-    Tmp1 = SelectExpr(N);
-    BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(0);
-    break;
-  case ISD::OR:
-  case ISD::AND:
-    Tmp1 = SelectCCExpr(N.getOperand(0), Opc, Inv0, Idx0);
-    Tmp2 = SelectCCExpr(N.getOperand(1), Opc1, Inv1, Idx1);
-    CROpc = getCROpForSetCC(N.getOpcode(), Inv0, Inv1);
-    if (Inv0 && !Inv1) {
-      std::swap(Tmp1, Tmp2);
-      std::swap(Idx0, Idx1);
-      Opc = Opc1;
-    }
-    if (Inv0 && Inv1) Opc = PPC32InstrInfo::invertPPCBranchOpcode(Opc);
-    BuildMI(BB, CROpc, 5, Result).addImm(Idx0).addReg(Tmp1).addImm(Idx0)
-      .addReg(Tmp2).addImm(Idx1);
-    Inv = false;
-    Idx = Idx0;
-    break;
-  case ISD::SETCC:
-    Tmp1 = SelectCC(N, Opc, Inv, Idx);
-    Result = Tmp1;
-    break;
-  }
-  return Result;
-}
-
-/// Check to see if the load is a constant offset from a base register
+/// Check to see if the load is a constant offset from a base register.
 unsigned ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
 {
   unsigned imm = 0, opcode = N.getOpcode();
   if (N.getOpcode() == ISD::ADD) {
     bool isFrame = N.getOperand(0).getOpcode() == ISD::FrameIndex;
-    if (1 == getImmediateForOpcode(N.getOperand(1), opcode, imm)) {
-      offset = imm;
+    if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
+      offset = Lo16(imm);
       if (isFrame) {
         ++FrameOff;
         Reg = cast<FrameIndexSDNode>(N.getOperand(0))->getIndex();
@@ -1233,6 +689,22 @@ unsigned ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
       return 2;
     }
   }
+  // Now check if we're dealing with a global, and whether or not we should emit
+  // an optimized load or store for statics.
+  if(GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(N)) {
+    GlobalValue *GV = GN->getGlobal();
+    if (!GV->hasWeakLinkage() && !GV->isExternal()) {
+      unsigned GlobalHi = MakeIntReg();
+      if (PICEnabled)
+        BuildMI(BB, PPC::ADDIS, 2, GlobalHi).addReg(getGlobalBaseReg())
+          .addGlobalAddress(GV);
+      else
+        BuildMI(BB, PPC::LIS, 1, GlobalHi).addGlobalAddress(GV);
+      Reg = GlobalHi;
+      offset = 0;
+      return 3;
+    }
+  }
   Reg = SelectExpr(N);
   offset = 0;
   return 0;
@@ -1241,12 +713,12 @@ unsigned ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
 void ISel::SelectBranchCC(SDOperand N)
 {
   MachineBasicBlock *Dest =
-    cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
+    cast<BasicBlockSDNode>(N.getOperand(4))->getBasicBlock();
 
-  bool Inv;
-  unsigned Opc, CCReg, Idx;
   Select(N.getOperand(0));  //chain
-  CCReg = SelectCC(N.getOperand(1), Opc, Inv, Idx);
+  ISD::CondCode CC = cast<CondCodeSDNode>(N.getOperand(1))->get();
+  unsigned CCReg = SelectCC(N.getOperand(2), N.getOperand(3), CC);
+  unsigned Opc = getBCCForSetCC(CC);
 
   // Iterate to the next basic block
   ilist<MachineBasicBlock>::iterator It = BB;
@@ -1256,9 +728,9 @@ void ISel::SelectBranchCC(SDOperand N)
   // and build a PowerPC branch pseudo-op, suitable for long branch conversion
   // if necessary by the branch selection pass.  Otherwise, emit a standard
   // conditional branch.
-  if (N.getOpcode() == ISD::BRCONDTWOWAY) {
+  if (N.getOpcode() == ISD::BRTWOWAY_CC) {
     MachineBasicBlock *Fallthrough =
-      cast<BasicBlockSDNode>(N.getOperand(3))->getBasicBlock();
+      cast<BasicBlockSDNode>(N.getOperand(5))->getBasicBlock();
     if (Dest != It) {
       BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
         .addMBB(Dest).addMBB(Fallthrough);
@@ -1283,6 +755,50 @@ void ISel::SelectBranchCC(SDOperand N)
   return;
 }
 
+// SelectIntImmediateExpr - Choose code for opcodes with immediate value.
+bool ISel::SelectIntImmediateExpr(SDOperand N, unsigned Result,
+                                  unsigned OCHi, unsigned OCLo,
+                                  bool IsArithmetic, bool Negate) {
+  // check constant
+  ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1));
+  // exit if not a constant
+  if (!CN) return false;
+  // extract immediate
+  unsigned C = (unsigned)CN->getSignExtended();
+  // negate if required (ISD::SUB)
+  if (Negate) C = -C;
+  // get the hi and lo portions of constant
+  unsigned Hi = IsArithmetic ? HA16(C) : Hi16(C);
+  unsigned Lo = Lo16(C);
+  // assume no intermediate result from lo instruction (same as final result)
+  unsigned Tmp = Result;
+  // check if two instructions are needed
+  if (Hi && Lo) {
+    // exit if usage indicates it would be better to load immediate into a 
+    // register
+    if (CN->use_size() > 2) return false;
+    // need intermediate result for two instructions
+    Tmp = MakeIntReg();
+  }
+  // get first operand
+  unsigned Opr0 = SelectExpr(N.getOperand(0));
+  // is a lo instruction needed
+  if (Lo) {
+    // generate instruction for hi portion
+    const MachineInstrBuilder &MIBLo = BuildMI(BB, OCLo, 2, Tmp).addReg(Opr0);
+    if (IsArithmetic) MIBLo.addSImm(Lo); else MIBLo.addImm(Lo);
+    // need to switch out first operand for hi instruction
+    Opr0 = Tmp;
+  }
+  // is a ho instruction needed
+  if (Hi) {
+    // generate instruction for hi portion
+    const MachineInstrBuilder &MIBHi = BuildMI(BB, OCHi, 2, Result).addReg(Opr0);
+    if (IsArithmetic) MIBHi.addSImm(Hi); else MIBHi.addImm(Hi);
+  }
+  return true;
+}
+
 unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
   unsigned Result;
   unsigned Tmp1, Tmp2, Tmp3;
@@ -1292,11 +808,12 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
   SDNode *Node = N.Val;
   MVT::ValueType DestType = N.getValueType();
 
-  if (Node->getOpcode() == ISD::CopyFromReg &&
-      (MRegisterInfo::isVirtualRegister(cast<RegSDNode>(Node)->getReg()) ||
-       cast<RegSDNode>(Node)->getReg() == PPC::R1))
+  if (Node->getOpcode() == ISD::CopyFromReg) {
+    unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
     // Just use the specified register as our input.
-    return cast<RegSDNode>(Node)->getReg();
+    if (MRegisterInfo::isVirtualRegister(Reg) || Reg == PPC::R1)
+      return Reg;
+  }
 
   unsigned &Reg = ExprMap[N];
   if (Reg) return Reg;
@@ -1334,7 +851,7 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
 
   switch (opcode) {
   default:
-    Node->dump();
+    Node->dump(); std::cerr << '\n';
     assert(0 && "Node not handled!\n");
   case ISD::UNDEF:
     BuildMI(BB, PPC::IMPLICIT_DEF, 0, Result);
@@ -1365,7 +882,7 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
 
   case ISD::ConstantPool:
     Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
-    Tmp2 = MakeReg(MVT::i32);
+    Tmp2 = MakeIntReg();
     if (PICEnabled)
       BuildMI(BB, PPC::ADDIS, 2, Tmp2).addReg(getGlobalBaseReg())
         .addConstantPoolIndex(Tmp1);
@@ -1381,7 +898,7 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
 
   case ISD::GlobalAddress: {
     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
-    Tmp1 = MakeReg(MVT::i32);
+    Tmp1 = MakeIntReg();
     if (PICEnabled)
       BuildMI(BB, PPC::ADDIS, 2, Tmp1).addReg(getGlobalBaseReg())
         .addGlobalAddress(GV);
@@ -1424,7 +941,7 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
     }
 
     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Address)) {
-      Tmp1 = MakeReg(MVT::i32);
+      Tmp1 = MakeIntReg();
       int CPI = CP->getIndex();
       if (PICEnabled)
         BuildMI(BB, PPC::ADDIS, 2, Tmp1).addReg(getGlobalBaseReg())
@@ -1435,21 +952,6 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
     } else if (Address.getOpcode() == ISD::FrameIndex) {
       Tmp1 = cast<FrameIndexSDNode>(Address)->getIndex();
       addFrameReference(BuildMI(BB, Opc, 2, Result), (int)Tmp1);
-    } else if(GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(Address)){
-      GlobalValue *GV = GN->getGlobal();
-      Tmp1 = MakeReg(MVT::i32);
-      if (PICEnabled)
-        BuildMI(BB, PPC::ADDIS, 2, Tmp1).addReg(getGlobalBaseReg())
-          .addGlobalAddress(GV);
-      else
-        BuildMI(BB, PPC::LIS, 1, Tmp1).addGlobalAddress(GV);
-      if (GV->hasWeakLinkage() || GV->isExternal()) {
-        Tmp2 = MakeReg(MVT::i32);
-        BuildMI(BB, PPC::LWZ, 2, Tmp2).addGlobalAddress(GV).addReg(Tmp1);
-        BuildMI(BB, Opc, 2, Result).addSImm(0).addReg(Tmp2);
-      } else {
-        BuildMI(BB, Opc, 2, Result).addGlobalAddress(GV).addReg(Tmp1);
-      }
     } else {
       int offset;
       switch(SelectAddr(Address, Tmp1, offset)) {
@@ -1464,6 +966,11 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
         Opc = IndexedOpForOp(Opc);
         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(offset);
         break;
+      case 3: {
+        GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Address);
+        GlobalValue *GV = GN->getGlobal();
+        BuildMI(BB, Opc, 2, Result).addGlobalAddress(GV).addReg(Tmp1);
+      }
       }
     }
     return Result;
@@ -1579,7 +1086,7 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
     DestType = N.getValue(0).getValueType();
     if (Result == 1)
       Result = ExprMap[N.getValue(0)] = MakeReg(DestType);
-    Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
+    Tmp1 = dyn_cast<RegisterSDNode>(Node->getOperand(1))->getReg();
     if (MVT::isInteger(DestType))
       BuildMI(BB, PPC::OR, 2, Result).addReg(Tmp1).addReg(Tmp1);
     else
@@ -1587,35 +1094,62 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
     return Result;
 
   case ISD::SHL:
-    Tmp1 = SelectExpr(N.getOperand(0));
-    if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
-      Tmp2 = CN->getValue() & 0x1F;
+    if (isIntImmediate(N.getOperand(1), Tmp2)) {
+      unsigned SH, MB, ME;
+      if (isOpcWithIntImmediate(N.getOperand(0), ISD::AND, Tmp3) &&
+          isRotateAndMask(ISD::SHL, Tmp2, Tmp3, true, SH, MB, ME)) {
+        Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
+        BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(SH)
+          .addImm(MB).addImm(ME);
+        return Result;
+      }
+      Tmp1 = SelectExpr(N.getOperand(0));
+      Tmp2 &= 0x1F;
       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(Tmp2).addImm(0)
         .addImm(31-Tmp2);
     } else {
+      Tmp1 = SelectExpr(N.getOperand(0));
       Tmp2 = FoldIfWideZeroExtend(N.getOperand(1));
       BuildMI(BB, PPC::SLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
     }
     return Result;
 
   case ISD::SRL:
-    Tmp1 = SelectExpr(N.getOperand(0));
-    if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
-      Tmp2 = CN->getValue() & 0x1F;
+    if (isIntImmediate(N.getOperand(1), Tmp2)) {
+      unsigned SH, MB, ME;
+      if (isOpcWithIntImmediate(N.getOperand(0), ISD::AND, Tmp3) &&
+          isRotateAndMask(ISD::SRL, Tmp2, Tmp3, true, SH, MB, ME)) {
+        Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
+        BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(SH)
+          .addImm(MB).addImm(ME);
+        return Result;
+      }
+      Tmp1 = SelectExpr(N.getOperand(0));
+      Tmp2 &= 0x1F;
       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(32-Tmp2)
         .addImm(Tmp2).addImm(31);
     } else {
+      Tmp1 = SelectExpr(N.getOperand(0));
       Tmp2 = FoldIfWideZeroExtend(N.getOperand(1));
       BuildMI(BB, PPC::SRW, 2, Result).addReg(Tmp1).addReg(Tmp2);
     }
     return Result;
 
   case ISD::SRA:
-    Tmp1 = SelectExpr(N.getOperand(0));
-    if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
-      Tmp2 = CN->getValue() & 0x1F;
+    if (isIntImmediate(N.getOperand(1), Tmp2)) {
+      unsigned SH, MB, ME;
+      if (isOpcWithIntImmediate(N.getOperand(0), ISD::AND, Tmp3) &&
+          isRotateAndMask(ISD::SRA, Tmp2, Tmp3, true, SH, MB, ME)) {
+        Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
+        BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(SH)
+          .addImm(MB).addImm(ME);
+        return Result;
+      }
+      Tmp1 = SelectExpr(N.getOperand(0));
+      Tmp2 &= 0x1F;
       BuildMI(BB, PPC::SRAWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
     } else {
+      Tmp1 = SelectExpr(N.getOperand(0));
       Tmp2 = FoldIfWideZeroExtend(N.getOperand(1));
       BuildMI(BB, PPC::SRAW, 2, Result).addReg(Tmp1).addReg(Tmp2);
     }
@@ -1654,112 +1188,104 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
       return Result;
     }
+    if (SelectIntImmediateExpr(N, Result, PPC::ADDIS, PPC::ADDI, true))
+      return Result;
     Tmp1 = SelectExpr(N.getOperand(0));
-    switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
-      default: assert(0 && "unhandled result code");
-      case 0: // No immediate
-        Tmp2 = SelectExpr(N.getOperand(1));
-        BuildMI(BB, PPC::ADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
-        break;
-      case 1: // Low immediate
-        BuildMI(BB, PPC::ADDI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
-        break;
-      case 2: // Shifted immediate
-        BuildMI(BB, PPC::ADDIS, 2, Result).addReg(Tmp1).addSImm(Tmp2);
-        break;
-    }
+    Tmp2 = SelectExpr(N.getOperand(1));
+    BuildMI(BB, PPC::ADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
     return Result;
 
   case ISD::AND:
-    switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
-      default: assert(0 && "unhandled result code");
-      case 0: // No immediate
-        // Check for andc: and, (xor a, -1), b
-        if (N.getOperand(0).getOpcode() == ISD::XOR &&
-          N.getOperand(0).getOperand(1).getOpcode() == ISD::Constant &&
-        cast<ConstantSDNode>(N.getOperand(0).getOperand(1))->isAllOnesValue()) {
+    if (isIntImmediate(N.getOperand(1), Tmp2)) {
+      if (isShiftedMask_32(Tmp2) || isShiftedMask_32(~Tmp2)) {
+        unsigned SH, MB, ME;
+        Opc = Recording ? PPC::RLWINMo : PPC::RLWINM;
+        unsigned OprOpc;
+        if (isOprShiftImm(N.getOperand(0), OprOpc, Tmp3) &&
+            isRotateAndMask(OprOpc, Tmp3, Tmp2, false, SH, MB, ME)) {
           Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
-          Tmp2 = SelectExpr(N.getOperand(1));
-          BuildMI(BB, PPC::ANDC, 2, Result).addReg(Tmp2).addReg(Tmp1);
-          return Result;
+        } else {
+          Tmp1 = SelectExpr(N.getOperand(0));
+          isRunOfOnes(Tmp2, MB, ME);
+          SH = 0;
         }
-        // It wasn't and-with-complement, emit a regular and
-        Tmp1 = SelectExpr(N.getOperand(0));
-        Tmp2 = SelectExpr(N.getOperand(1));
-        Opc = Recording ? PPC::ANDo : PPC::AND;
-        BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
-        break;
-      case 1: // Low immediate
+        BuildMI(BB, Opc, 4, Result).addReg(Tmp1).addImm(SH)
+          .addImm(MB).addImm(ME);
+        RecordSuccess = true;
+        return Result;
+      } else if (isUInt16(Tmp2)) {
+        Tmp2 = Lo16(Tmp2);
         Tmp1 = SelectExpr(N.getOperand(0));
         BuildMI(BB, PPC::ANDIo, 2, Result).addReg(Tmp1).addImm(Tmp2);
-        break;
-      case 2: // Shifted immediate
+        RecordSuccess = true;
+        return Result;
+      } else if (isUInt16(Tmp2)) {
+        Tmp2 = Hi16(Tmp2);
         Tmp1 = SelectExpr(N.getOperand(0));
         BuildMI(BB, PPC::ANDISo, 2, Result).addReg(Tmp1).addImm(Tmp2);
-        break;
-      case 5: // Bitfield mask
-        Opc = Recording ? PPC::RLWINMo : PPC::RLWINM;
-        Tmp3 = Tmp2 >> 16;  // MB
-        Tmp2 &= 0xFFFF;     // ME
-
-        // FIXME: Catch SHL-AND in addition to SRL-AND in this block.
-        if (N.getOperand(0).getOpcode() == ISD::SRL)
-          if (ConstantSDNode *SA =
-              dyn_cast<ConstantSDNode>(N.getOperand(0).getOperand(1))) {
-
-            // We can fold the RLWINM and the SRL together if the mask is
-            // clearing the top bits which are rotated around.
-            unsigned RotAmt = 32-(SA->getValue() & 31);
-            if (Tmp2 <= RotAmt) {
-              Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
-              BuildMI(BB, Opc, 4, Result).addReg(Tmp1).addImm(RotAmt)
-                .addImm(Tmp3).addImm(Tmp2);
-              break;
-            }
-          }
-
-        Tmp1 = SelectExpr(N.getOperand(0));
-        BuildMI(BB, Opc, 4, Result).addReg(Tmp1).addImm(0)
-          .addImm(Tmp3).addImm(Tmp2);
-        break;
+        RecordSuccess = true;
+       return Result;
+      }
+    }
+    if (isOprNot(N.getOperand(1))) {
+      Tmp1 = SelectExpr(N.getOperand(0));
+      Tmp2 = SelectExpr(N.getOperand(1).getOperand(0));
+      BuildMI(BB, PPC::ANDC, 2, Result).addReg(Tmp1).addReg(Tmp2);
+      RecordSuccess = false;
+      return Result;
     }
+    if (isOprNot(N.getOperand(0))) {
+      Tmp1 = SelectExpr(N.getOperand(1));
+      Tmp2 = SelectExpr(N.getOperand(0).getOperand(0));
+      BuildMI(BB, PPC::ANDC, 2, Result).addReg(Tmp1).addReg(Tmp2);
+      RecordSuccess = false;
+      return Result;
+    }
+    // emit a regular and
+    Tmp1 = SelectExpr(N.getOperand(0));
+    Tmp2 = SelectExpr(N.getOperand(1));
+    Opc = Recording ? PPC::ANDo : PPC::AND;
+    BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
     RecordSuccess = true;
     return Result;
 
   case ISD::OR:
     if (SelectBitfieldInsert(N, Result))
       return Result;
-    Tmp1 = SelectExpr(N.getOperand(0));
-    switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
-      default: assert(0 && "unhandled result code");
-      case 0: // No immediate
-        Tmp2 = SelectExpr(N.getOperand(1));
-        Opc = Recording ? PPC::ORo : PPC::OR;
-        RecordSuccess = true;
-        BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
-        break;
-      case 1: // Low immediate
-        BuildMI(BB, PPC::ORI, 2, Result).addReg(Tmp1).addImm(Tmp2);
-        break;
-      case 2: // Shifted immediate
-        BuildMI(BB, PPC::ORIS, 2, Result).addReg(Tmp1).addImm(Tmp2);
-        break;
+    if (SelectIntImmediateExpr(N, Result, PPC::ORIS, PPC::ORI))
+      return Result;
+    if (isOprNot(N.getOperand(1))) {
+      Tmp1 = SelectExpr(N.getOperand(0));
+      Tmp2 = SelectExpr(N.getOperand(1).getOperand(0));
+      BuildMI(BB, PPC::ORC, 2, Result).addReg(Tmp1).addReg(Tmp2);
+      RecordSuccess = false;
+      return Result;
     }
+    if (isOprNot(N.getOperand(0))) {
+      Tmp1 = SelectExpr(N.getOperand(1));
+      Tmp2 = SelectExpr(N.getOperand(0).getOperand(0));
+      BuildMI(BB, PPC::ORC, 2, Result).addReg(Tmp1).addReg(Tmp2);
+      RecordSuccess = false;
+      return Result;
+    }
+    // emit regular or
+    Tmp1 = SelectExpr(N.getOperand(0));
+    Tmp2 = SelectExpr(N.getOperand(1));
+    Opc = Recording ? PPC::ORo : PPC::OR;
+    RecordSuccess = true;
+    BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
     return Result;
 
   case ISD::XOR: {
     // Check for EQV: xor, (xor a, -1), b
-    if (N.getOperand(0).getOpcode() == ISD::XOR &&
-        N.getOperand(0).getOperand(1).getOpcode() == ISD::Constant &&
-        cast<ConstantSDNode>(N.getOperand(0).getOperand(1))->isAllOnesValue()) {
+    if (isOprNot(N.getOperand(0))) {
       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
       Tmp2 = SelectExpr(N.getOperand(1));
       BuildMI(BB, PPC::EQV, 2, Result).addReg(Tmp1).addReg(Tmp2);
       return Result;
     }
     // Check for NOT, NOR, EQV, and NAND: xor (copy, or, xor, and), -1
-    if (N.getOperand(1).getOpcode() == ISD::Constant &&
-        cast<ConstantSDNode>(N.getOperand(1))->isAllOnesValue()) {
+    if (isOprNot(N)) {
       switch(N.getOperand(0).getOpcode()) {
       case ISD::OR:
         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
@@ -1783,24 +1309,16 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
       }
       return Result;
     }
+    if (SelectIntImmediateExpr(N, Result, PPC::XORIS, PPC::XORI))
+      return Result;
+    // emit regular xor
     Tmp1 = SelectExpr(N.getOperand(0));
-    switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
-      default: assert(0 && "unhandled result code");
-      case 0: // No immediate
-        Tmp2 = SelectExpr(N.getOperand(1));
-        BuildMI(BB, PPC::XOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
-        break;
-      case 1: // Low immediate
-        BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp1).addImm(Tmp2);
-        break;
-      case 2: // Shifted immediate
-        BuildMI(BB, PPC::XORIS, 2, Result).addReg(Tmp1).addImm(Tmp2);
-        break;
-    }
+    Tmp2 = SelectExpr(N.getOperand(1));
+    BuildMI(BB, PPC::XOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
     return Result;
   }
 
-  case ISD::SUB:
+   case ISD::SUB:
     if (!MVT::isInteger(DestType)) {
       if (!NoExcessFPPrecision && N.getOperand(0).getOpcode() == ISD::MUL &&
           N.getOperand(0).Val->hasOneUse()) {
@@ -1828,24 +1346,25 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
       return Result;
     }
-    if (1 == getImmediateForOpcode(N.getOperand(0), opcode, Tmp1, true)) {
+    if (isIntImmediate(N.getOperand(0), Tmp1) && isInt16(Tmp1)) {
+      Tmp1 = Lo16(Tmp1);
       Tmp2 = SelectExpr(N.getOperand(1));
       BuildMI(BB, PPC::SUBFIC, 2, Result).addReg(Tmp2).addSImm(Tmp1);
-    } else if (1 == getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
-      Tmp1 = SelectExpr(N.getOperand(0));
-      BuildMI(BB, PPC::ADDI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
-    } else {
-      Tmp1 = SelectExpr(N.getOperand(0));
-      Tmp2 = SelectExpr(N.getOperand(1));
-      BuildMI(BB, PPC::SUBF, 2, Result).addReg(Tmp2).addReg(Tmp1);
+      return Result;
     }
+    if (SelectIntImmediateExpr(N, Result, PPC::ADDIS, PPC::ADDI, true, true))
+        return Result;
+    Tmp1 = SelectExpr(N.getOperand(0));
+    Tmp2 = SelectExpr(N.getOperand(1));
+    BuildMI(BB, PPC::SUBF, 2, Result).addReg(Tmp2).addReg(Tmp1);
     return Result;
 
   case ISD::MUL:
     Tmp1 = SelectExpr(N.getOperand(0));
-    if (1 == getImmediateForOpcode(N.getOperand(1), opcode, Tmp2))
+    if (isIntImmediate(N.getOperand(1), Tmp2) && isInt16(Tmp2)) {
+      Tmp2 = Lo16(Tmp2);
       BuildMI(BB, PPC::MULLI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
-    else {
+    else {
       Tmp2 = SelectExpr(N.getOperand(1));
       switch (DestType) {
       default: assert(0 && "Unknown type to ISD::MUL"); break;
@@ -1866,31 +1385,41 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
     return Result;
 
   case ISD::SDIV:
-  case ISD::UDIV:
-    switch (getImmediateForOpcode(N.getOperand(1), opcode, Tmp3)) {
-    default: break;
-    // If this is an sdiv by a power of two, we can use an srawi/addze pair.
-    case 3:
-      Tmp1 = MakeReg(MVT::i32);
-      Tmp2 = SelectExpr(N.getOperand(0));
-      if ((int)Tmp3 < 0) {
-        unsigned Tmp4 = MakeReg(MVT::i32);
-        BuildMI(BB, PPC::SRAWI, 2, Tmp1).addReg(Tmp2).addImm(-Tmp3);
-        BuildMI(BB, PPC::ADDZE, 1, Tmp4).addReg(Tmp1);
-        BuildMI(BB, PPC::NEG, 1, Result).addReg(Tmp4);
-      } else {
+    if (isIntImmediate(N.getOperand(1), Tmp3)) {
+      if ((signed)Tmp3 > 0 && isPowerOf2_32(Tmp3)) {
+        Tmp3 = Log2_32(Tmp3);
+        Tmp1 = MakeIntReg();
+        Tmp2 = SelectExpr(N.getOperand(0));
         BuildMI(BB, PPC::SRAWI, 2, Tmp1).addReg(Tmp2).addImm(Tmp3);
         BuildMI(BB, PPC::ADDZE, 1, Result).addReg(Tmp1);
+        return Result;
+      } else if ((signed)Tmp3 < 0 && isPowerOf2_32(-Tmp3)) {
+        Tmp3 = Log2_32(-Tmp3);
+        Tmp2 = SelectExpr(N.getOperand(0));
+        Tmp1 = MakeIntReg();
+        unsigned Tmp4 = MakeIntReg();
+        BuildMI(BB, PPC::SRAWI, 2, Tmp1).addReg(Tmp2).addImm(Tmp3);
+        BuildMI(BB, PPC::ADDZE, 1, Tmp4).addReg(Tmp1);
+        BuildMI(BB, PPC::NEG, 1, Result).addReg(Tmp4);
+        return Result;
       }
-      return Result;
+    }
+    // fall thru
+  case ISD::UDIV:
     // If this is a divide by constant, we can emit code using some magic
     // constants to implement it as a multiply instead.
-    case 4:
-      ExprMap.erase(N);
-      if (opcode == ISD::SDIV)
-        return SelectExpr(BuildSDIVSequence(N));
-      else
-        return SelectExpr(BuildUDIVSequence(N));
+    if (isIntImmediate(N.getOperand(1), Tmp3)) {
+      if (opcode == ISD::SDIV) {
+        if ((signed)Tmp3 < -1 || (signed)Tmp3 > 1) {
+          ExprMap.erase(N);
+          return SelectExpr(BuildSDIVSequence(N));
+        }
+      } else {
+        if ((signed)Tmp3 > 1) {
+          ExprMap.erase(N);
+          return SelectExpr(BuildUDIVSequence(N));
+        }
+      }
     }
     Tmp1 = SelectExpr(N.getOperand(0));
     Tmp2 = SelectExpr(N.getOperand(1));
@@ -1907,16 +1436,36 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
   case ISD::SUB_PARTS: {
     assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
            "Not an i64 add/sub!");
-    // Emit all of the operands.
-    std::vector<unsigned> InVals;
-    for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
-      InVals.push_back(SelectExpr(N.getOperand(i)));
+    unsigned Tmp4 = 0;
+    bool ME = isIntImmediate(N.getOperand(3),Tmp3) && ((signed)Tmp3 == -1);
+    bool ZE = isIntImmediate(N.getOperand(3),Tmp3) && (Tmp3 == 0);
+    bool IM = isIntImmediate(N.getOperand(2),Tmp3) && ((signed)Tmp3 >= -32768 ||
+                                                       (signed)Tmp3 <   32768);
+    Tmp1 = SelectExpr(N.getOperand(0));
+    Tmp2 = SelectExpr(N.getOperand(1));
+    if (!IM || N.getOpcode() == ISD::SUB_PARTS)
+      Tmp3 = SelectExpr(N.getOperand(2));
+    if ((!ME && !ZE) || N.getOpcode() == ISD::SUB_PARTS)
+      Tmp4 = SelectExpr(N.getOperand(3));
+    
     if (N.getOpcode() == ISD::ADD_PARTS) {
-      BuildMI(BB, PPC::ADDC, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
-      BuildMI(BB, PPC::ADDE, 2, Result+1).addReg(InVals[1]).addReg(InVals[3]);
+      // Codegen the low 32 bits of the add.  Interestingly, there is no shifted
+      // form of add immediate carrying.
+      if (IM)
+        BuildMI(BB, PPC::ADDIC, 2, Result).addReg(Tmp1).addSImm(Tmp3);
+      else
+        BuildMI(BB, PPC::ADDC, 2, Result).addReg(Tmp1).addReg(Tmp3);
+      // Codegen the high 32 bits, adding zero, minus one, or the full value
+      // along with the carry flag produced by addc/addic to tmp2.
+      if (ZE)
+        BuildMI(BB, PPC::ADDZE, 1, Result+1).addReg(Tmp2);
+      else if (ME)
+        BuildMI(BB, PPC::ADDME, 1, Result+1).addReg(Tmp2);
+      else
+        BuildMI(BB, PPC::ADDE, 2, Result+1).addReg(Tmp2).addReg(Tmp4);
     } else {
-      BuildMI(BB, PPC::SUBFC, 2, Result).addReg(InVals[2]).addReg(InVals[0]);
-      BuildMI(BB, PPC::SUBFE, 2, Result+1).addReg(InVals[3]).addReg(InVals[1]);
+      BuildMI(BB, PPC::SUBFC, 2, Result).addReg(Tmp3).addReg(Tmp1);
+      BuildMI(BB, PPC::SUBFE, 2, Result+1).addReg(Tmp4).addReg(Tmp2);
     }
     return Result+N.ResNo;
   }
@@ -1929,12 +1478,12 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
     unsigned ShiftOpLo = SelectExpr(N.getOperand(0));
     unsigned ShiftOpHi = SelectExpr(N.getOperand(1));
     unsigned SHReg = FoldIfWideZeroExtend(N.getOperand(2));
-    Tmp1 = MakeReg(MVT::i32);
-    Tmp2 = MakeReg(MVT::i32);
-    Tmp3 = MakeReg(MVT::i32);
-    unsigned Tmp4 = MakeReg(MVT::i32);
-    unsigned Tmp5 = MakeReg(MVT::i32);
-    unsigned Tmp6 = MakeReg(MVT::i32);
+    Tmp1 = MakeIntReg();
+    Tmp2 = MakeIntReg();
+    Tmp3 = MakeIntReg();
+    unsigned Tmp4 = MakeIntReg();
+    unsigned Tmp5 = MakeIntReg();
+    unsigned Tmp6 = MakeIntReg();
     BuildMI(BB, PPC::SUBFIC, 2, Tmp1).addReg(SHReg).addSImm(32);
     if (ISD::SHL_PARTS == opcode) {
       BuildMI(BB, PPC::SLW, 2, Tmp2).addReg(ShiftOpHi).addReg(SHReg);
@@ -1971,7 +1520,7 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
       BuildMI(BB, PPC::BLE, 2).addReg(PPC::CR0).addMBB(PhiMBB);
       // Select correct least significant half if the shift amount > 32
       BB = TmpMBB;
-      unsigned Tmp7 = MakeReg(MVT::i32);
+      unsigned Tmp7 = MakeIntReg();
       BuildMI(BB, PPC::OR, 2, Tmp7).addReg(Tmp6).addReg(Tmp6);
       TmpMBB->addSuccessor(PhiMBB);
       BB = PhiMBB;
@@ -1981,182 +1530,112 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
     return Result+N.ResNo;
   }
 
-  case ISD::FP_TO_UINT:
   case ISD::FP_TO_SINT: {
-    bool U = (ISD::FP_TO_UINT == opcode);
     Tmp1 = SelectExpr(N.getOperand(0));
-    if (!U) {
-      Tmp2 = MakeReg(MVT::f64);
-      BuildMI(BB, PPC::FCTIWZ, 1, Tmp2).addReg(Tmp1);
-      int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
-      addFrameReference(BuildMI(BB, PPC::STFD, 3).addReg(Tmp2), FrameIdx);
-      addFrameReference(BuildMI(BB, PPC::LWZ, 2, Result), FrameIdx, 4);
-      return Result;
-    } else {
-      unsigned Zero = getConstDouble(0.0);
-      unsigned MaxInt = getConstDouble((1LL << 32) - 1);
-      unsigned Border = getConstDouble(1LL << 31);
-      unsigned UseZero = MakeReg(MVT::f64);
-      unsigned UseMaxInt = MakeReg(MVT::f64);
-      unsigned UseChoice = MakeReg(MVT::f64);
-      unsigned TmpReg = MakeReg(MVT::f64);
-      unsigned TmpReg2 = MakeReg(MVT::f64);
-      unsigned ConvReg = MakeReg(MVT::f64);
-      unsigned IntTmp = MakeReg(MVT::i32);
-      unsigned XorReg = MakeReg(MVT::i32);
-      MachineFunction *F = BB->getParent();
-      int FrameIdx = F->getFrameInfo()->CreateStackObject(8, 8);
-      // Update machine-CFG edges
-      MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
-      MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
-      MachineBasicBlock *OldMBB = BB;
-      ilist<MachineBasicBlock>::iterator It = BB; ++It;
-      F->getBasicBlockList().insert(It, XorMBB);
-      F->getBasicBlockList().insert(It, PhiMBB);
-      BB->addSuccessor(XorMBB);
-      BB->addSuccessor(PhiMBB);
-      // Convert from floating point to unsigned 32-bit value
-      // Use 0 if incoming value is < 0.0
-      BuildMI(BB, PPC::FSEL, 3, UseZero).addReg(Tmp1).addReg(Tmp1).addReg(Zero);
-      // Use 2**32 - 1 if incoming value is >= 2**32
-      BuildMI(BB, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(Tmp1);
-      BuildMI(BB, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt).addReg(UseZero)
-        .addReg(MaxInt);
-      // Subtract 2**31
-      BuildMI(BB, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
-      // Use difference if >= 2**31
-      BuildMI(BB, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice).addReg(Border);
-      BuildMI(BB, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
-        .addReg(UseChoice);
-      // Convert to integer
-      BuildMI(BB, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
-      addFrameReference(BuildMI(BB, PPC::STFD, 3).addReg(ConvReg), FrameIdx);
-      addFrameReference(BuildMI(BB, PPC::LWZ, 2, IntTmp), FrameIdx, 4);
-      BuildMI(BB, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
-      BuildMI(BB, PPC::B, 1).addMBB(XorMBB);
-
-      // XorMBB:
-      //   add 2**31 if input was >= 2**31
-      BB = XorMBB;
-      BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
-      XorMBB->addSuccessor(PhiMBB);
-
-      // PhiMBB:
-      //   DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
-      BB = PhiMBB;
-      BuildMI(BB, PPC::PHI, 4, Result).addReg(IntTmp).addMBB(OldMBB)
-        .addReg(XorReg).addMBB(XorMBB);
-      return Result;
-    }
-    assert(0 && "Should never get here");
-    return 0;
+    Tmp2 = MakeFPReg();
+    BuildMI(BB, PPC::FCTIWZ, 1, Tmp2).addReg(Tmp1);
+    int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
+    addFrameReference(BuildMI(BB, PPC::STFD, 3).addReg(Tmp2), FrameIdx);
+    addFrameReference(BuildMI(BB, PPC::LWZ, 2, Result), FrameIdx, 4);
+    return Result;
   }
 
-  case ISD::SETCC:
-    if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(Node)) {
-      if (ConstantSDNode *CN =
-          dyn_cast<ConstantSDNode>(SetCC->getOperand(1).Val)) {
-        // We can codegen setcc op, imm very efficiently compared to a brcond.
-        // Check for those cases here.
-        // setcc op, 0
-        if (CN->getValue() == 0) {
-          Tmp1 = SelectExpr(SetCC->getOperand(0));
-          switch (SetCC->getCondition()) {
-          default: SetCC->dump(); assert(0 && "Unhandled SetCC condition"); abort();
-          case ISD::SETEQ:
-            Tmp2 = MakeReg(MVT::i32);
-            BuildMI(BB, PPC::CNTLZW, 1, Tmp2).addReg(Tmp1);
-            BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp2).addImm(27)
-              .addImm(5).addImm(31);
-            break;
-          case ISD::SETNE:
-            Tmp2 = MakeReg(MVT::i32);
-            BuildMI(BB, PPC::ADDIC, 2, Tmp2).addReg(Tmp1).addSImm(-1);
-            BuildMI(BB, PPC::SUBFE, 2, Result).addReg(Tmp2).addReg(Tmp1);
-            break;
-          case ISD::SETLT:
-            BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(1)
-              .addImm(31).addImm(31);
-            break;
-          case ISD::SETGT:
-            Tmp2 = MakeReg(MVT::i32);
-            Tmp3 = MakeReg(MVT::i32);
-            BuildMI(BB, PPC::NEG, 2, Tmp2).addReg(Tmp1);
-            BuildMI(BB, PPC::ANDC, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
-            BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp3).addImm(1)
-              .addImm(31).addImm(31);
-            break;
-          }
-          return Result;
+  case ISD::SETCC: {
+    ISD::CondCode CC = cast<CondCodeSDNode>(Node->getOperand(2))->get();
+    if (isIntImmediate(Node->getOperand(1), Tmp3)) {
+      // We can codegen setcc op, imm very efficiently compared to a brcond.
+      // Check for those cases here.
+      // setcc op, 0
+      if (Tmp3 == 0) {
+        Tmp1 = SelectExpr(Node->getOperand(0));
+        switch (CC) {
+        default: Node->dump(); assert(0 && "Unhandled SetCC condition"); abort();
+        case ISD::SETEQ:
+          Tmp2 = MakeIntReg();
+          BuildMI(BB, PPC::CNTLZW, 1, Tmp2).addReg(Tmp1);
+          BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp2).addImm(27)
+            .addImm(5).addImm(31);
+          break;
+        case ISD::SETNE:
+          Tmp2 = MakeIntReg();
+          BuildMI(BB, PPC::ADDIC, 2, Tmp2).addReg(Tmp1).addSImm(-1);
+          BuildMI(BB, PPC::SUBFE, 2, Result).addReg(Tmp2).addReg(Tmp1);
+          break;
+        case ISD::SETLT:
+          BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(1)
+            .addImm(31).addImm(31);
+          break;
+        case ISD::SETGT:
+          Tmp2 = MakeIntReg();
+          Tmp3 = MakeIntReg();
+          BuildMI(BB, PPC::NEG, 2, Tmp2).addReg(Tmp1);
+          BuildMI(BB, PPC::ANDC, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
+          BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp3).addImm(1)
+            .addImm(31).addImm(31);
+          break;
         }
-        // setcc op, -1
-        if (CN->isAllOnesValue()) {
-          Tmp1 = SelectExpr(SetCC->getOperand(0));
-          switch (SetCC->getCondition()) {
-          default: assert(0 && "Unhandled SetCC condition"); abort();
-          case ISD::SETEQ:
-            Tmp2 = MakeReg(MVT::i32);
-            Tmp3 = MakeReg(MVT::i32);
-            BuildMI(BB, PPC::ADDIC, 2, Tmp2).addReg(Tmp1).addSImm(1);
-            BuildMI(BB, PPC::LI, 1, Tmp3).addSImm(0);
-            BuildMI(BB, PPC::ADDZE, 1, Result).addReg(Tmp3);
-            break;
-          case ISD::SETNE:
-            Tmp2 = MakeReg(MVT::i32);
-            Tmp3 = MakeReg(MVT::i32);
-            BuildMI(BB, PPC::NOR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
-            BuildMI(BB, PPC::ADDIC, 2, Tmp3).addReg(Tmp2).addSImm(-1);
-            BuildMI(BB, PPC::SUBFE, 2, Result).addReg(Tmp3).addReg(Tmp2);
-            break;
-          case ISD::SETLT:
-            Tmp2 = MakeReg(MVT::i32);
-            Tmp3 = MakeReg(MVT::i32);
-            BuildMI(BB, PPC::ADDI, 2, Tmp2).addReg(Tmp1).addSImm(1);
-            BuildMI(BB, PPC::AND, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
-            BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp3).addImm(1)
-              .addImm(31).addImm(31);
-            break;
-          case ISD::SETGT:
-            Tmp2 = MakeReg(MVT::i32);
-            BuildMI(BB, PPC::RLWINM, 4, Tmp2).addReg(Tmp1).addImm(1)
-              .addImm(31).addImm(31);
-            BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp2).addImm(1);
-            break;
-          }
-          return Result;
+        return Result;
+      } else if (Tmp3 == ~0U) {        // setcc op, -1
+        Tmp1 = SelectExpr(Node->getOperand(0));
+        switch (CC) {
+        default: assert(0 && "Unhandled SetCC condition"); abort();
+        case ISD::SETEQ:
+          Tmp2 = MakeIntReg();
+          Tmp3 = MakeIntReg();
+          BuildMI(BB, PPC::ADDIC, 2, Tmp2).addReg(Tmp1).addSImm(1);
+          BuildMI(BB, PPC::LI, 1, Tmp3).addSImm(0);
+          BuildMI(BB, PPC::ADDZE, 1, Result).addReg(Tmp3);
+          break;
+        case ISD::SETNE:
+          Tmp2 = MakeIntReg();
+          Tmp3 = MakeIntReg();
+          BuildMI(BB, PPC::NOR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
+          BuildMI(BB, PPC::ADDIC, 2, Tmp3).addReg(Tmp2).addSImm(-1);
+          BuildMI(BB, PPC::SUBFE, 2, Result).addReg(Tmp3).addReg(Tmp2);
+          break;
+        case ISD::SETLT:
+          Tmp2 = MakeIntReg();
+          Tmp3 = MakeIntReg();
+          BuildMI(BB, PPC::ADDI, 2, Tmp2).addReg(Tmp1).addSImm(1);
+          BuildMI(BB, PPC::AND, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
+          BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp3).addImm(1)
+            .addImm(31).addImm(31);
+          break;
+        case ISD::SETGT:
+          Tmp2 = MakeIntReg();
+          BuildMI(BB, PPC::RLWINM, 4, Tmp2).addReg(Tmp1).addImm(1)
+            .addImm(31).addImm(31);
+          BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp2).addImm(1);
+          break;
         }
+        return Result;
       }
-
-      bool Inv;
-      unsigned CCReg = SelectCC(N, Opc, Inv, Tmp2);
-      MoveCRtoGPR(CCReg, Inv, Tmp2, Result);
-      return Result;
     }
-    assert(0 && "Is this legal?");
-    return 0;
-
-  case ISD::SELECT: {
-    SetCCSDNode* SetCC = dyn_cast<SetCCSDNode>(N.getOperand(0).Val);
-    if (SetCC && N.getOperand(0).getOpcode() == ISD::SETCC &&
-        !MVT::isInteger(SetCC->getOperand(0).getValueType()) &&
-        !MVT::isInteger(N.getOperand(1).getValueType()) &&
+
+    unsigned CCReg = SelectCC(N.getOperand(0), N.getOperand(1), CC);
+    MoveCRtoGPR(CCReg, CC, Result);
+    return Result;
+  }
+    
+  case ISD::SELECT_CC: {
+    ISD::CondCode CC = cast<CondCodeSDNode>(N.getOperand(4))->get();
+    if (!MVT::isInteger(N.getOperand(0).getValueType()) &&
         !MVT::isInteger(N.getOperand(2).getValueType()) &&
-        SetCC->getCondition() != ISD::SETEQ &&
-        SetCC->getCondition() != ISD::SETNE) {
-      MVT::ValueType VT = SetCC->getOperand(0).getValueType();
-      unsigned TV = SelectExpr(N.getOperand(1)); // Use if TRUE
-      unsigned FV = SelectExpr(N.getOperand(2)); // Use if FALSE
+        CC != ISD::SETEQ && CC != ISD::SETNE) {
+      MVT::ValueType VT = N.getOperand(0).getValueType();
+      unsigned TV = SelectExpr(N.getOperand(2)); // Use if TRUE
+      unsigned FV = SelectExpr(N.getOperand(3)); // Use if FALSE
 
-      ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(SetCC->getOperand(1));
+      ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(1));
       if (CN && (CN->isExactlyValue(-0.0) || CN->isExactlyValue(0.0))) {
-        switch(SetCC->getCondition()) {
+        switch(CC) {
         default: assert(0 && "Invalid FSEL condition"); abort();
         case ISD::SETULT:
         case ISD::SETLT:
           std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
         case ISD::SETUGE:
         case ISD::SETGE:
-          Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
+          Tmp1 = SelectExpr(N.getOperand(0));   // Val to compare against
           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp1).addReg(TV).addReg(FV);
           return Result;
         case ISD::SETUGT:
@@ -2164,11 +1643,11 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
           std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
         case ISD::SETULE:
         case ISD::SETLE: {
-          if (SetCC->getOperand(0).getOpcode() == ISD::FNEG) {
-            Tmp2 = SelectExpr(SetCC->getOperand(0).getOperand(0));
+          if (N.getOperand(0).getOpcode() == ISD::FNEG) {
+            Tmp2 = SelectExpr(N.getOperand(0).getOperand(0));
           } else {
             Tmp2 = MakeReg(VT);
-            Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
+            Tmp1 = SelectExpr(N.getOperand(0));   // Val to compare against
             BuildMI(BB, PPC::FNEG, 1, Tmp2).addReg(Tmp1);
           }
           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp2).addReg(TV).addReg(FV);
@@ -2177,10 +1656,10 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
         }
       } else {
         Opc = (MVT::f64 == VT) ? PPC::FSUB : PPC::FSUBS;
-        Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
-        Tmp2 = SelectExpr(SetCC->getOperand(1));
+        Tmp1 = SelectExpr(N.getOperand(0));   // Val to compare against
+        Tmp2 = SelectExpr(N.getOperand(1));
         Tmp3 =  MakeReg(VT);
-        switch(SetCC->getCondition()) {
+        switch(CC) {
         default: assert(0 && "Invalid FSEL condition"); abort();
         case ISD::SETULT:
         case ISD::SETLT:
@@ -2205,14 +1684,16 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
         }
       }
       assert(0 && "Should never get here");
-      return 0;
     }
 
-    bool Inv;
-    unsigned TrueValue = SelectExpr(N.getOperand(1)); //Use if TRUE
-    unsigned FalseValue = SelectExpr(N.getOperand(2)); //Use if FALSE
-    unsigned CCReg = SelectCC(N.getOperand(0), Opc, Inv, Tmp3);
-
+    // If the False value only has one use, we can generate better code by
+    // selecting it in the fallthrough basic block rather than here, which
+    // increases register pressure.
+    unsigned TrueValue = SelectExpr(N.getOperand(2));
+    unsigned FalseValue = SelectExpr(N.getOperand(3));
+    unsigned CCReg = SelectCC(N.getOperand(0), N.getOperand(1), CC);
+    Opc = getBCCForSetCC(CC);
+    
     // Create an iterator with which to insert the MBB for copying the false
     // value and the MBB to hold the PHI instruction for this SetCC.
     MachineBasicBlock *thisMBB = BB;
@@ -2255,17 +1736,13 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
   case ISD::Constant:
     switch (N.getValueType()) {
     default: assert(0 && "Cannot use constants of this type!");
-    case MVT::i1:
-      BuildMI(BB, PPC::LI, 1, Result)
-        .addSImm(!cast<ConstantSDNode>(N)->isNullValue());
-      break;
     case MVT::i32:
       {
         int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
         if (v < 32768 && v >= -32768) {
           BuildMI(BB, PPC::LI, 1, Result).addSImm(v);
         } else {
-          Tmp1 = MakeReg(MVT::i32);
+          Tmp1 = MakeIntReg();
           BuildMI(BB, PPC::LIS, 1, Tmp1).addSImm(v >> 16);
           BuildMI(BB, PPC::ORI, 2, Result).addReg(Tmp1).addImm(v & 0xFFFF);
         }
@@ -2337,42 +1814,6 @@ unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
     Tmp1 = SelectExpr(N.getOperand(0));
     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
     return Result;
-
-  case ISD::UINT_TO_FP:
-  case ISD::SINT_TO_FP: {
-    assert (N.getOperand(0).getValueType() == MVT::i32
-            && "int to float must operate on i32");
-    bool IsUnsigned = (ISD::UINT_TO_FP == opcode);
-    Tmp1 = SelectExpr(N.getOperand(0));  // Get the operand register
-    Tmp2 = MakeReg(MVT::f64); // temp reg to load the integer value into
-    Tmp3 = MakeReg(MVT::i32); // temp reg to hold the conversion constant
-
-    int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
-    MachineConstantPool *CP = BB->getParent()->getConstantPool();
-
-    if (IsUnsigned) {
-      unsigned ConstF = getConstDouble(0x1.000000p52);
-      // Store the hi & low halves of the fp value, currently in int regs
-      BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
-      addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
-      addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp1), FrameIdx, 4);
-      addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
-      // Generate the return value with a subtract
-      BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
-    } else {
-      unsigned ConstF = getConstDouble(0x1.000008p52);
-      unsigned TmpL = MakeReg(MVT::i32);
-      // Store the hi & low halves of the fp value, currently in int regs
-      BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
-      addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
-      BuildMI(BB, PPC::XORIS, 2, TmpL).addReg(Tmp1).addImm(0x8000);
-      addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(TmpL), FrameIdx, 4);
-      addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
-      // Generate the return value with a subtract
-      BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
-    }
-    return Result;
-  }
   }
   return 0;
 }
@@ -2410,18 +1851,18 @@ void ISel::Select(SDOperand N) {
     BuildMI(BB, PPC::B, 1).addMBB(Dest);
     return;
   }
-  case ISD::BRCOND:
-  case ISD::BRCONDTWOWAY:
+  case ISD::BR_CC:
+  case ISD::BRTWOWAY_CC:
     SelectBranchCC(N);
     return;
   case ISD::CopyToReg:
     Select(N.getOperand(0));
-    Tmp1 = SelectExpr(N.getOperand(1));
-    Tmp2 = cast<RegSDNode>(N)->getReg();
+    Tmp1 = SelectExpr(N.getOperand(2));
+    Tmp2 = cast<RegisterSDNode>(N.getOperand(1))->getReg();
 
     if (Tmp1 != Tmp2) {
-      if (N.getOperand(1).getValueType() == MVT::f64 ||
-          N.getOperand(1).getValueType() == MVT::f32)
+      if (N.getOperand(2).getValueType() == MVT::f64 ||
+          N.getOperand(2).getValueType() == MVT::f32)
         BuildMI(BB, PPC::FMR, 1, Tmp2).addReg(Tmp1);
       else
         BuildMI(BB, PPC::OR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
@@ -2429,7 +1870,8 @@ void ISel::Select(SDOperand N) {
     return;
   case ISD::ImplicitDef:
     Select(N.getOperand(0));
-    BuildMI(BB, PPC::IMPLICIT_DEF, 0, cast<RegSDNode>(N)->getReg());
+    BuildMI(BB, PPC::IMPLICIT_DEF, 0,
+            cast<RegisterSDNode>(N.getOperand(1))->getReg());
     return;
   case ISD::RET:
     switch (N.getNumOperands()) {
@@ -2493,21 +1935,6 @@ void ISel::Select(SDOperand N) {
     if(Address.getOpcode() == ISD::FrameIndex) {
       Tmp2 = cast<FrameIndexSDNode>(Address)->getIndex();
       addFrameReference(BuildMI(BB, Opc, 3).addReg(Tmp1), (int)Tmp2);
-    } else if(GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(Address)){
-      GlobalValue *GV = GN->getGlobal();
-      Tmp2 = MakeReg(MVT::i32);
-      if (PICEnabled)
-        BuildMI(BB, PPC::ADDIS, 2, Tmp2).addReg(getGlobalBaseReg())
-          .addGlobalAddress(GV);
-      else
-        BuildMI(BB, PPC::LIS, 1, Tmp2).addGlobalAddress(GV);
-      if (GV->hasWeakLinkage() || GV->isExternal()) {
-        Tmp3 = MakeReg(MVT::i32);
-        BuildMI(BB, PPC::LWZ, 2, Tmp3).addGlobalAddress(GV).addReg(Tmp2);
-        BuildMI(BB, Opc, 3).addReg(Tmp1).addSImm(0).addReg(Tmp3);
-      } else {
-        BuildMI(BB, Opc, 3).addReg(Tmp1).addGlobalAddress(GV).addReg(Tmp2);
-      }
     } else {
       int offset;
       switch(SelectAddr(Address, Tmp2, offset)) {
@@ -2522,6 +1949,11 @@ void ISel::Select(SDOperand N) {
         Opc = IndexedOpForOp(Opc);
         BuildMI(BB, Opc, 3).addReg(Tmp1).addReg(Tmp2).addReg(offset);
         break;
+      case 3: {
+        GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Address);
+        GlobalValue *GV = GN->getGlobal();
+        BuildMI(BB, Opc, 3).addReg(Tmp1).addGlobalAddress(GV).addReg(Tmp2);
+      }
       }
     }
     return;