Don't assign a new stack slot if the pre-alloc splitter already assigned one.
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
index 4ed456bf11ab07c611956661a857034212e72210..8c7fa1b1ac22f5a611d4feba8a7491aa0b2bd966 100644 (file)
@@ -30,6 +30,7 @@
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetMachine.h"
+#include "llvm/Target/TargetOptions.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/ADT/Statistic.h"
@@ -53,7 +54,6 @@ static cl::opt<bool> EnableFastSpilling("fast-spill",
                                         cl::init(false), cl::Hidden);
 
 STATISTIC(numIntervals, "Number of original intervals");
-STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
 STATISTIC(numFolds    , "Number of loads/stores folded into instructions");
 STATISTIC(numSplits   , "Number of intervals split");
 
@@ -67,8 +67,12 @@ void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
   AU.addRequired<LiveVariables>();
   AU.addPreservedID(MachineLoopInfoID);
   AU.addPreservedID(MachineDominatorsID);
-  AU.addPreservedID(PHIEliminationID);
-  AU.addRequiredID(PHIEliminationID);
+  
+  if (!StrongPHIElim) {
+    AU.addPreservedID(PHIEliminationID);
+    AU.addRequiredID(PHIEliminationID);
+  }
+  
   AU.addRequiredID(TwoAddressInstructionPassID);
   MachineFunctionPass::getAnalysisUsage(AU);
 }
@@ -121,13 +125,18 @@ void LiveIntervals::computeNumbering() {
          I != E; ++I) {
       bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
       assert(inserted && "multiple MachineInstr -> index mappings");
+      inserted = true;
       i2miMap_.push_back(I);
       MIIndex += InstrSlots::NUM;
       FunctionSize++;
       
-      // Insert an empty slot after every instruction.
-      MIIndex += InstrSlots::NUM;
-      i2miMap_.push_back(0);
+      // Insert max(1, numdefs) empty slots after every instruction.
+      unsigned Slots = I->getDesc().getNumDefs();
+      if (Slots == 0)
+        Slots = 1;
+      MIIndex += InstrSlots::NUM * Slots;
+      while (Slots--)
+        i2miMap_.push_back(0);
     }
     
     // Set the MBB2IdxMap entry for this MBB.
@@ -213,7 +222,7 @@ void LiveIntervals::computeNumbering() {
           
           unsigned index = (vni->kills[i]-1) / InstrSlots::NUM;
           unsigned offset = vni->kills[i] % InstrSlots::NUM;
-          if (offset == InstrSlots::STORE) {
+          if (offset == InstrSlots::LOAD) {
             std::vector<IdxMBBPair>::const_iterator I =
              std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
             --I;
@@ -251,13 +260,6 @@ bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
 
   numIntervals += getNumIntervals();
 
-  DOUT << "********** INTERVALS **********\n";
-  for (iterator I = begin(), E = end(); I != E; ++I) {
-    I->second->print(DOUT, tri_);
-    DOUT << "\n";
-  }
-
-  numIntervalsAfter += getNumIntervals();
   DEBUG(dump());
   return true;
 }
@@ -296,13 +298,13 @@ bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
       if (index == end) break;
 
       MachineInstr *MI = getInstructionFromIndex(index);
-      unsigned SrcReg, DstReg;
-      if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
+      unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
+      if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
         if (SrcReg == li.reg || DstReg == li.reg)
           continue;
       for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
         MachineOperand& mop = MI->getOperand(i);
-        if (!mop.isRegister())
+        if (!mop.isReg())
           continue;
         unsigned PhysReg = mop.getReg();
         if (PhysReg == 0 || PhysReg == li.reg)
@@ -321,6 +323,47 @@ bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
   return false;
 }
 
+/// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
+/// it can check use as well.
+bool LiveIntervals::conflictsWithPhysRegRef(LiveInterval &li,
+                                            unsigned Reg, bool CheckUse,
+                                  SmallPtrSet<MachineInstr*,32> &JoinedCopies) {
+  for (LiveInterval::Ranges::const_iterator
+         I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
+    for (unsigned index = getBaseIndex(I->start),
+           end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
+         index += InstrSlots::NUM) {
+      // Skip deleted instructions.
+      MachineInstr *MI = 0;
+      while (index != end) {
+        MI = getInstructionFromIndex(index);
+        if (MI)
+          break;
+        index += InstrSlots::NUM;
+      }
+      if (index == end) break;
+
+      if (JoinedCopies.count(MI))
+        continue;
+      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
+        MachineOperand& MO = MI->getOperand(i);
+        if (!MO.isReg())
+          continue;
+        if (MO.isUse() && !CheckUse)
+          continue;
+        unsigned PhysReg = MO.getReg();
+        if (PhysReg == 0 || TargetRegisterInfo::isVirtualRegister(PhysReg))
+          continue;
+        if (tri_->isSubRegister(Reg, PhysReg))
+          return true;
+      }
+    }
+  }
+
+  return false;
+}
+
+
 void LiveIntervals::printRegName(unsigned reg) const {
   if (TargetRegisterInfo::isPhysicalRegister(reg))
     cerr << tri_->getName(reg);
@@ -353,11 +396,12 @@ void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
       defIndex = getUseIndex(MIIdx);
     VNInfo *ValNo;
     MachineInstr *CopyMI = NULL;
-    unsigned SrcReg, DstReg;
+    unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
     if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
         mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
-        tii_->isMoveInstr(*mi, SrcReg, DstReg))
+        tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
       CopyMI = mi;
+    // Earlyclobbers move back one.
     ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
 
     assert(ValNo->id == 0 && "First value in interval is not 0?");
@@ -398,14 +442,13 @@ void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
     // Iterate over all of the blocks that the variable is completely
     // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
     // live interval.
-    for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
-      if (vi.AliveBlocks[i]) {
-        LiveRange LR(getMBBStartIdx(i),
-                     getMBBEndIdx(i)+1,  // MBB ends at -1.
-                     ValNo);
-        interval.addRange(LR);
-        DOUT << " +" << LR;
-      }
+    for (int i = vi.AliveBlocks.find_first(); i != -1;
+         i = vi.AliveBlocks.find_next(i)) {
+      LiveRange LR(getMBBStartIdx(i),
+                   getMBBEndIdx(i)+1,  // MBB ends at -1.
+                   ValNo);
+      interval.addRange(LR);
+      DOUT << " +" << LR;
     }
 
     // Finally, this virtual register is live from the start of any killing
@@ -425,7 +468,7 @@ void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
     // must be due to phi elimination or two addr elimination.  If this is
     // the result of two address elimination, then the vreg is one of the
     // def-and-use register operand.
-    if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
+    if (mi->isRegReDefinedByTwoAddr(MOIdx)) {
       // If this is a two-address definition, then we have already processed
       // the live range.  The only problem is that we didn't realize there
       // are actually two values in the live interval.  Because of this we
@@ -434,7 +477,6 @@ void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
       assert(interval.containsOneValue());
       unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
       unsigned RedefIndex = getDefIndex(MIIdx);
-      // Earlyclobbers move back one.
       if (MO.isEarlyClobber())
         RedefIndex = getUseIndex(MIIdx);
 
@@ -457,6 +499,8 @@ void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
       // Value#0 is now defined by the 2-addr instruction.
       OldValNo->def  = RedefIndex;
       OldValNo->copy = 0;
+      if (MO.isEarlyClobber())
+        OldValNo->redefByEC = true;
       
       // Add the new live interval which replaces the range for the input copy.
       LiveRange LR(DefIndex, RedefIndex, ValNo);
@@ -504,16 +548,15 @@ void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
       // live until the end of the block.  We've already taken care of the
       // rest of the live range.
       unsigned defIndex = getDefIndex(MIIdx);
-      // Earlyclobbers move back one.
       if (MO.isEarlyClobber())
         defIndex = getUseIndex(MIIdx);
       
       VNInfo *ValNo;
       MachineInstr *CopyMI = NULL;
-      unsigned SrcReg, DstReg;
+      unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
       if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
           mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
-          tii_->isMoveInstr(*mi, SrcReg, DstReg))
+          tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
         CopyMI = mi;
       ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
       
@@ -591,8 +634,11 @@ exit:
 
   // Already exists? Extend old live interval.
   LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
-  VNInfo *ValNo = (OldLR != interval.end())
+  bool Extend = OldLR != interval.end();
+  VNInfo *ValNo = Extend
     ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
+  if (MO.isEarlyClobber() && Extend)
+    ValNo->redefByEC = true;
   LiveRange LR(start, end, ValNo);
   interval.addRange(LR);
   interval.addKill(LR.valno, end);
@@ -609,10 +655,10 @@ void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
                              getOrCreateInterval(MO.getReg()));
   else if (allocatableRegs_[MO.getReg()]) {
     MachineInstr *CopyMI = NULL;
-    unsigned SrcReg, DstReg;
+    unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
     if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
         MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
-        tii_->isMoveInstr(*MI, SrcReg, DstReg))
+        tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
       CopyMI = MI;
     handlePhysicalRegisterDef(MBB, MI, MIIdx, MO, 
                               getOrCreateInterval(MO.getReg()), CopyMI);
@@ -640,11 +686,13 @@ void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
          getInstructionFromIndex(baseIndex) == 0)
     baseIndex += InstrSlots::NUM;
   unsigned end = baseIndex;
+  bool SeenDefUse = false;
   
   while (mi != MBB->end()) {
     if (mi->killsRegister(interval.reg, tri_)) {
       DOUT << " killed";
       end = getUseIndex(baseIndex) + 1;
+      SeenDefUse = true;
       goto exit;
     } else if (mi->modifiesRegister(interval.reg, tri_)) {
       // Another instruction redefines the register before it is ever read.
@@ -653,19 +701,22 @@ void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
       // [defSlot(def), defSlot(def)+1)
       DOUT << " dead";
       end = getDefIndex(start) + 1;
+      SeenDefUse = true;
       goto exit;
     }
 
     baseIndex += InstrSlots::NUM;
-    while (baseIndex / InstrSlots::NUM < i2miMap_.size() && 
-           getInstructionFromIndex(baseIndex) == 0)
-      baseIndex += InstrSlots::NUM;
     ++mi;
+    if (mi != MBB->end()) {
+      while (baseIndex / InstrSlots::NUM < i2miMap_.size() && 
+             getInstructionFromIndex(baseIndex) == 0)
+        baseIndex += InstrSlots::NUM;
+    }
   }
 
 exit:
   // Live-in register might not be used at all.
-  if (end == MIIdx) {
+  if (!SeenDefUse) {
     if (isAlias) {
       DOUT << " dead";
       end = getDefIndex(MIIdx) + 1;
@@ -723,12 +774,16 @@ void LiveIntervals::computeIntervals() {
       for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
         MachineOperand &MO = MI->getOperand(i);
         // handle register defs - build intervals
-        if (MO.isRegister() && MO.getReg() && MO.isDef()) {
+        if (MO.isReg() && MO.getReg() && MO.isDef()) {
           handleRegisterDef(MBB, MI, MIIndex, MO, i);
         }
       }
-      
-      MIIndex += InstrSlots::NUM;
+
+      // Skip over the empty slots after each instruction.
+      unsigned Slots = MI->getDesc().getNumDefs();
+      if (Slots == 0)
+        Slots = 1;
+      MIIndex += InstrSlots::NUM * Slots;
       
       // Skip over empty indices.
       while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
@@ -738,14 +793,14 @@ void LiveIntervals::computeIntervals() {
   }
 }
 
-bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
+bool LiveIntervals::findLiveInMBBs(unsigned Start, unsigned End,
                               SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
   std::vector<IdxMBBPair>::const_iterator I =
-    std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
+    std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
 
   bool ResVal = false;
   while (I != Idx2MBBMap.end()) {
-    if (LR.end <= I->first)
+    if (I->first >= End)
       break;
     MBBs.push_back(I->second);
     ResVal = true;
@@ -754,24 +809,57 @@ bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
   return ResVal;
 }
 
+bool LiveIntervals::findReachableMBBs(unsigned Start, unsigned End,
+                              SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
+  std::vector<IdxMBBPair>::const_iterator I =
+    std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
+
+  bool ResVal = false;
+  while (I != Idx2MBBMap.end()) {
+    if (I->first > End)
+      break;
+    MachineBasicBlock *MBB = I->second;
+    if (getMBBEndIdx(MBB) > End)
+      break;
+    for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
+           SE = MBB->succ_end(); SI != SE; ++SI)
+      MBBs.push_back(*SI);
+    ResVal = true;
+    ++I;
+  }
+  return ResVal;
+}
+
 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
-  float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
-                       HUGE_VALF : 0.0F;
+  float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
   return new LiveInterval(reg, Weight);
 }
 
+/// dupInterval - Duplicate a live interval. The caller is responsible for
+/// managing the allocated memory.
+LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
+  LiveInterval *NewLI = createInterval(li->reg);
+  NewLI->Copy(*li, getVNInfoAllocator());
+  return NewLI;
+}
+
 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
 /// copy field and returns the source register that defines it.
 unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
   if (!VNI->copy)
     return 0;
 
-  if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
-    return VNI->copy->getOperand(1).getReg();
-  if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
+  if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
+    // If it's extracting out of a physical register, return the sub-register.
+    unsigned Reg = VNI->copy->getOperand(1).getReg();
+    if (TargetRegisterInfo::isPhysicalRegister(Reg))
+      Reg = tri_->getSubReg(Reg, VNI->copy->getOperand(2).getImm());
+    return Reg;
+  } else if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
     return VNI->copy->getOperand(2).getReg();
-  unsigned SrcReg, DstReg;
-  if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
+
+  unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
+  if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
     return SrcReg;
   assert(0 && "Unrecognized copy instruction!");
   return 0;
@@ -789,7 +877,7 @@ unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
   unsigned RegOp = 0;
   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
     MachineOperand &MO = MI->getOperand(i);
-    if (!MO.isRegister() || !MO.isUse())
+    if (!MO.isReg() || !MO.isUse())
       continue;
     unsigned Reg = MO.getReg();
     if (Reg == 0 || Reg == li.reg)
@@ -876,7 +964,7 @@ bool LiveIntervals::isReMaterializable(const LiveInterval &li,
     unsigned ImpUse = 0;
     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
       const MachineOperand &MO = MI->getOperand(i);
-      if (MO.isRegister()) {
+      if (MO.isReg()) {
         unsigned Reg = MO.getReg();
         if (Reg == 0)
           continue;
@@ -892,7 +980,7 @@ bool LiveIntervals::isReMaterializable(const LiveInterval &li,
         MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
                                           E = mri_->def_end();
 
-        // For the def, it should be the only def.
+        // For the def, it should be the only def of that register.
         if (MO.isDef() && (next(I) != E || IsLiveIn))
           return false;
 
@@ -905,7 +993,7 @@ bool LiveIntervals::isReMaterializable(const LiveInterval &li,
             else if (Reg != ImpUse)
               return false;
           }
-          // For uses, there should be only one associate def.
+          // For the use, there should be only one associated def.
           if (I != E && (next(I) != E || IsLiveIn))
             return false;
         }
@@ -935,6 +1023,15 @@ bool LiveIntervals::isReMaterializable(const LiveInterval &li,
   return true;
 }
 
+/// isReMaterializable - Returns true if the definition MI of the specified
+/// val# of the specified interval is re-materializable.
+bool LiveIntervals::isReMaterializable(const LiveInterval &li,
+                                       const VNInfo *ValNo, MachineInstr *MI) {
+  SmallVector<LiveInterval*, 4> Dummy1;
+  bool Dummy2;
+  return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2);
+}
+
 /// isReMaterializable - Returns true if every definition of MI of every
 /// val# of the specified interval is re-materializable.
 bool LiveIntervals::isReMaterializable(const LiveInterval &li,
@@ -967,8 +1064,6 @@ static bool FilterFoldedOps(MachineInstr *MI,
                             SmallVector<unsigned, 2> &Ops,
                             unsigned &MRInfo,
                             SmallVector<unsigned, 2> &FoldOps) {
-  const TargetInstrDesc &TID = MI->getDesc();
-
   MRInfo = 0;
   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
     unsigned OpIdx = Ops[i];
@@ -980,8 +1075,7 @@ static bool FilterFoldedOps(MachineInstr *MI,
       MRInfo |= (unsigned)VirtRegMap::isMod;
     else {
       // Filter out two-address use operand(s).
-      if (!MO.isImplicit() &&
-          TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
+      if (MI->isRegTiedToDefOperand(OpIdx)) {
         MRInfo = VirtRegMap::isModRef;
         continue;
       }
@@ -1093,7 +1187,7 @@ void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
   // use operand. Make sure we rewrite that as well.
   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
     MachineOperand &MO = MI->getOperand(i);
-    if (!MO.isRegister())
+    if (!MO.isReg())
       continue;
     unsigned Reg = MO.getReg();
     if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
@@ -1128,7 +1222,7 @@ rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
  RestartInstruction:
   for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
     MachineOperand& mop = MI->getOperand(i);
-    if (!mop.isRegister())
+    if (!mop.isReg())
       continue;
     unsigned Reg = mop.getReg();
     unsigned RegI = Reg;
@@ -1180,7 +1274,7 @@ rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
     Ops.push_back(i);
     for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
       const MachineOperand &MOj = MI->getOperand(j);
-      if (!MOj.isRegister())
+      if (!MOj.isReg())
         continue;
       unsigned RegJ = MOj.getReg();
       if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
@@ -1209,6 +1303,17 @@ rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
       if (!TrySplit)
       SSWeight += Weight;
 
+    // Create a new virtual register for the spill interval.
+    // Create the new register now so we can map the fold instruction
+    // to the new register so when it is unfolded we get the correct
+    // answer.
+    bool CreatedNewVReg = false;
+    if (NewVReg == 0) {
+      NewVReg = mri_->createVirtualRegister(rc);
+      vrm.grow();
+      CreatedNewVReg = true;
+    }
+
     if (!TryFold)
       CanFold = false;
     else {
@@ -1216,9 +1321,16 @@ rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
       // optimal point to insert a load / store later.
       if (!TrySplit) {
         if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
-                                 Ops, FoldSS, FoldSlot, Reg)) {
+                                 Ops, FoldSS, FoldSlot, NewVReg)) {
           // Folding the load/store can completely change the instruction in
           // unpredictable ways, rescan it from the beginning.
+
+          if (FoldSS) {
+            // We need to give the new vreg the same stack slot as the
+            // spilled interval.
+            vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
+          }
+
           HasUse = false;
           HasDef = false;
           CanFold = false;
@@ -1234,13 +1346,6 @@ rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
       }
     }
 
-    // Create a new virtual register for the spill interval.
-    bool CreatedNewVReg = false;
-    if (NewVReg == 0) {
-      NewVReg = mri_->createVirtualRegister(rc);
-      vrm.grow();
-      CreatedNewVReg = true;
-    }
     mop.setReg(NewVReg);
     if (mop.isImplicit())
       rewriteImplicitOps(li, MI, NewVReg, vrm);
@@ -1618,7 +1723,7 @@ LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
       NewLIs.push_back(&getOrCreateInterval(NewVReg));
       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
         MachineOperand &MO = MI->getOperand(i);
-        if (MO.isRegister() && MO.getReg() == li.reg)
+        if (MO.isReg() && MO.getReg() == li.reg)
           MO.setReg(NewVReg);
       }
     }
@@ -1662,7 +1767,7 @@ addIntervalsForSpillsFast(const LiveInterval &li,
     
     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
       MachineOperand& mop = MI->getOperand(i);
-      if (!mop.isRegister() || mop.getReg() != li.reg) continue;
+      if (!mop.isReg() || mop.getReg() != li.reg) continue;
       
       HasUse |= MI->getOperand(i).isUse();
       HasDef |= MI->getOperand(i).isDef();
@@ -1754,7 +1859,7 @@ addIntervalsForSpills(const LiveInterval &li,
   // Spill slot weight.
   SSWeight = 0.0f;
 
-  // Each bit specify whether it a spill is required in the MBB.
+  // Each bit specify whether a spill is required in the MBB.
   BitVector SpillMBBs(mf_->getNumBlockIDs());
   DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
   BitVector RestoreMBBs(mf_->getNumBlockIDs());
@@ -1795,7 +1900,7 @@ addIntervalsForSpills(const LiveInterval &li,
     int LdSlot = 0;
     bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
     bool isLoad = isLoadSS ||
-      (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
+      (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad()));
     bool IsFirstRange = true;
     for (LiveInterval::Ranges::const_iterator
            I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
@@ -1868,8 +1973,15 @@ addIntervalsForSpills(const LiveInterval &li,
   }
 
   // One stack slot per live interval.
-  if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
-    Slot = vrm.assignVirt2StackSlot(li.reg);
+  if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0) {
+    if (vrm.getStackSlot(li.reg) == VirtRegMap::NO_STACK_SLOT)
+      Slot = vrm.assignVirt2StackSlot(li.reg);
+    
+    // This case only occurs when the prealloc splitter has already assigned
+    // a stack slot to this vreg.
+    else
+      Slot = vrm.getStackSlot(li.reg);
+  }
 
   // Create new intervals and rewrite defs and uses.
   for (LiveInterval::Ranges::const_iterator
@@ -1881,7 +1993,7 @@ addIntervalsForSpills(const LiveInterval &li,
     int LdSlot = 0;
     bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
     bool isLoad = isLoadSS ||
-      (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
+      (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad());
     rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
                                Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
                                CanDelete, vrm, rc, ReMatIds, loopInfo,
@@ -1916,7 +2028,7 @@ addIntervalsForSpills(const LiveInterval &li,
           CanFold = true;
           for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
             MachineOperand &MO = MI->getOperand(j);
-            if (!MO.isRegister() || MO.getReg() != VReg)
+            if (!MO.isReg() || MO.getReg() != VReg)
               continue;
 
             Ops.push_back(j);
@@ -1939,7 +2051,7 @@ addIntervalsForSpills(const LiveInterval &li,
         if (CanFold && !Ops.empty()) {
           if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
             Folded = true;
-            if (FoundUse > 0) {
+            if (FoundUse) {
               // Also folded uses, do not issue a load.
               eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
               nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
@@ -1987,7 +2099,7 @@ addIntervalsForSpills(const LiveInterval &li,
         CanFold = true;
         for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
           MachineOperand &MO = MI->getOperand(j);
-          if (!MO.isRegister() || MO.getReg() != VReg)
+          if (!MO.isReg() || MO.getReg() != VReg)
             continue;
 
           if (MO.isDef()) {
@@ -2010,18 +2122,20 @@ addIntervalsForSpills(const LiveInterval &li,
           int LdSlot = 0;
           bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
           // If the rematerializable def is a load, also try to fold it.
-          if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
+          if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad())
             Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
                                           Ops, isLoadSS, LdSlot, VReg);
-          unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
-          if (ImpUse) {
-            // Re-matting an instruction with virtual register use. Add the
-            // register as an implicit use on the use MI and update the register
-            // interval's spill weight to HUGE_VALF to prevent it from being
-            // spilled.
-            LiveInterval &ImpLi = getInterval(ImpUse);
-            ImpLi.weight = HUGE_VALF;
-            MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
+          if (!Folded) {
+            unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
+            if (ImpUse) {
+              // Re-matting an instruction with virtual register use. Add the
+              // register as an implicit use on the use MI and update the register
+              // interval's spill weight to HUGE_VALF to prevent it from being
+              // spilled.
+              LiveInterval &ImpLi = getInterval(ImpUse);
+              ImpLi.weight = HUGE_VALF;
+              MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
+            }
           }
         }
       }
@@ -2052,8 +2166,7 @@ addIntervalsForSpills(const LiveInterval &li,
         MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
         int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
         assert(UseIdx != -1);
-        if (LastUse->getOperand(UseIdx).isImplicit() ||
-            LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
+        if (!LastUse->isRegTiedToDefOperand(UseIdx)) {
           LastUse->getOperand(UseIdx).setIsKill();
           vrm.addKillPoint(LI->reg, LastUseIdx);
         }
@@ -2108,8 +2221,9 @@ unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
 }
 
 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
-/// around all defs and uses of the specified interval.
-void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
+/// around all defs and uses of the specified interval. Return true if it
+/// was able to cut its interval.
+bool LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
                                             unsigned PhysReg, VirtRegMap &vrm) {
   unsigned SpillReg = getRepresentativeReg(PhysReg);
 
@@ -2120,6 +2234,7 @@ void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
     assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
            tri_->isSuperRegister(*AS, SpillReg));
 
+  bool Cut = false;
   LiveInterval &pli = getInterval(SpillReg);
   SmallPtrSet<MachineInstr*, 8> SeenMIs;
   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
@@ -2132,7 +2247,20 @@ void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
     unsigned Index = getInstructionIndex(MI);
     if (pli.liveAt(Index)) {
       vrm.addEmergencySpill(SpillReg, MI);
-      pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
+      unsigned StartIdx = getLoadIndex(Index);
+      unsigned EndIdx = getStoreIndex(Index)+1;
+      if (pli.isInOneLiveRange(StartIdx, EndIdx)) {
+        pli.removeRange(StartIdx, EndIdx);
+        Cut = true;
+      } else {
+        cerr << "Ran out of registers during register allocation!\n";
+        if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
+          cerr << "Please check your inline asm statement for invalid "
+               << "constraints:\n";
+          MI->print(cerr.stream(), tm_);
+        }
+        exit(1);
+      }
       for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
         if (!hasInterval(*AS))
           continue;
@@ -2142,6 +2270,7 @@ void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
       }
     }
   }
+  return Cut;
 }
 
 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,