Hide debugging options
[oota-llvm.git] / lib / CodeGen / RegAlloc / PhyRegAlloc.cpp
index e2d455bad9d02fa623ff6425f1cbd8072de1c01a..ab9b1a7b1765ea5728da80dc0124c9db6c6727e4 100644 (file)
 //     9/10/01  -  Ruchira Sasanka - created.
 //**************************************************************************/
 
+#include "llvm/CodeGen/RegisterAllocation.h"
 #include "llvm/CodeGen/PhyRegAlloc.h"
 #include "llvm/CodeGen/MachineInstr.h"
+#include "llvm/CodeGen/MachineInstrAnnot.h"
+#include "llvm/CodeGen/MachineCodeForMethod.h"
+#include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h"
+#include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/MachineFrameInfo.h"
+#include "llvm/BasicBlock.h"
+#include "llvm/Function.h"
+#include "llvm/Type.h"
+#include "llvm/iOther.h"
+#include "llvm/CodeGen/RegAllocCommon.h"
 #include <iostream>
 #include <math.h>
 using std::cerr;
@@ -22,33 +32,65 @@ using std::cerr;
 // ***TODO: There are several places we add instructions. Validate the order
 //          of adding these instructions.
 
-
-
-cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
+cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::Hidden,
   "enable register allocation debugging information",
   clEnumValN(RA_DEBUG_None   , "n", "disable debug output"),
   clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
   clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
 
 
+//----------------------------------------------------------------------------
+// RegisterAllocation pass front end...
+//----------------------------------------------------------------------------
+namespace {
+  class RegisterAllocator : public FunctionPass {
+    TargetMachine &Target;
+  public:
+    inline RegisterAllocator(TargetMachine &T) : Target(T) {}
+
+    const char *getPassName() const { return "Register Allocation"; }
+    
+    bool runOnFunction(Function *F) {
+      if (DEBUG_RA)
+        cerr << "\n******************** Function "<< F->getName()
+             << " ********************\n";
+      
+      PhyRegAlloc PRA(F, Target, &getAnalysis<FunctionLiveVarInfo>(),
+                      &getAnalysis<LoopInfo>());
+      PRA.allocateRegisters();
+      
+      if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
+      return false;
+    }
+
+    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+      AU.addRequired(LoopInfo::ID);
+      AU.addRequired(FunctionLiveVarInfo::ID);
+    }
+  };
+}
+
+Pass *getRegisterAllocator(TargetMachine &T) {
+  return new RegisterAllocator(T);
+}
+
 //----------------------------------------------------------------------------
 // Constructor: Init local composite objects and create register classes.
 //----------------------------------------------------------------------------
-PhyRegAlloc::PhyRegAlloc(Method *M, 
-                        const TargetMachine& tm, 
-                        MethodLiveVarInfo *const Lvi) 
-                       :  TM(tm), Meth(M),
-                          mcInfo(MachineCodeForMethod::get(M)),
-                          LVI(Lvi), LRI(M, tm, RegClassList), 
-                         MRI( tm.getRegInfo() ),
+PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm, 
+                        FunctionLiveVarInfo *Lvi, LoopInfo *LDC) 
+                       :  TM(tm), Meth(F),
+                          mcInfo(MachineCodeForMethod::get(F)),
+                          LVI(Lvi), LRI(F, tm, RegClassList), 
+                         MRI(tm.getRegInfo()),
                           NumOfRegClasses(MRI.getNumOfRegClasses()),
-                         LoopDepthCalc(M) {
+                         LoopDepthCalc(LDC) {
 
   // create each RegisterClass and put in RegClassList
   //
   for(unsigned int rc=0; rc < NumOfRegClasses; rc++)  
-    RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc), 
-                                        &ResColList) );
+    RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
+                                        &ResColList));
 }
 
 
@@ -56,56 +98,49 @@ PhyRegAlloc::PhyRegAlloc(Method *M,
 // Destructor: Deletes register classes
 //----------------------------------------------------------------------------
 PhyRegAlloc::~PhyRegAlloc() { 
+  for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
+    delete RegClassList[rc];
 
-  for( unsigned int rc=0; rc < NumOfRegClasses; rc++) { 
-    RegClass *RC = RegClassList[rc];
-    delete RC;
-  }
+  AddedInstrMap.clear();
 } 
 
 //----------------------------------------------------------------------------
 // This method initally creates interference graphs (one in each reg class)
 // and IGNodeList (one in each IG). The actual nodes will be pushed later. 
 //----------------------------------------------------------------------------
-void PhyRegAlloc::createIGNodeListsAndIGs()
-{
-  if(DEBUG_RA ) cerr << "Creating LR lists ...\n";
+void PhyRegAlloc::createIGNodeListsAndIGs() {
+  if (DEBUG_RA) cerr << "Creating LR lists ...\n";
 
   // hash map iterator
-  LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
+  LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();   
 
   // hash map end
-  LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
-
-    for(  ; HMI != HMIEnd ; ++HMI ) {
-      
-      if( (*HMI).first ) { 
-
-       LiveRange *L = (*HMI).second;   // get the LiveRange
-
-       if( !L) { 
-         if( DEBUG_RA) {
-           cerr << "\n*?!?Warning: Null liver range found for: ";
-           printValue(HMI->first); cerr << "\n";
-         }
-         continue;
-       }
+  LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();   
+
+  for (; HMI != HMIEnd ; ++HMI ) {
+    if (HMI->first) { 
+      LiveRange *L = HMI->second;   // get the LiveRange
+      if (!L) { 
+        if( DEBUG_RA) {
+          cerr << "\n*?!?Warning: Null liver range found for: "
+               << RAV(HMI->first) << "\n";
+        }
+        continue;
+      }
                                         // if the Value * is not null, and LR  
                                         // is not yet written to the IGNodeList
-       if( !(L->getUserIGNode())  ) {  
-                                  
-        RegClass *const RC =           // RegClass of first value in the LR
-          //RegClassList [MRI.getRegClassIDOfValue(*(L->begin()))];
-          RegClassList[ L->getRegClass()->getID() ];
-
-        RC-> addLRToIG( L );           // add this LR to an IG
-       }
+      if( !(L->getUserIGNode())  ) {  
+        RegClass *const RC =           // RegClass of first value in the LR
+          RegClassList[ L->getRegClass()->getID() ];
+        
+        RC->addLRToIG(L);              // add this LR to an IG
+      }
     }
   }
-
-                                        // init RegClassList
+    
+  // init RegClassList
   for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
-    RegClassList[ rc ]->createInterferenceGraph();
+    RegClassList[rc]->createInterferenceGraph();
 
   if( DEBUG_RA)
     cerr << "LRLists Created!\n";
@@ -120,11 +155,11 @@ void PhyRegAlloc::createIGNodeListsAndIGs()
 // class as that of live var. The live var passed to this function is the 
 // LVset AFTER the instruction
 //----------------------------------------------------------------------------
-void PhyRegAlloc::addInterference(const Value *const Def, 
-                                 const LiveVarSet *const LVSet,
-                                 const bool isCallInst) {
+void PhyRegAlloc::addInterference(const Value *Def, 
+                                 const ValueSet *LVSet,
+                                 bool isCallInst) {
 
-  LiveVarSet::const_iterator LIt = LVSet->begin();
+  ValueSet::const_iterator LIt = LVSet->begin();
 
   // get the live range of instruction
   //
@@ -139,45 +174,35 @@ void PhyRegAlloc::addInterference(const Value *const Def,
   //
   for( ; LIt != LVSet->end(); ++LIt) {
 
-    if( DEBUG_RA > 1) {
-      cerr << "< Def="; printValue(Def);     
-      cerr << ", Lvar=";  printValue( *LIt); cerr  << "> ";
-    }
+    if (DEBUG_RA > 1)
+      cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
 
     //  get the live range corresponding to live var
     //
-    LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );    
+    LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
 
     // LROfVar can be null if it is a const since a const 
     // doesn't have a dominating def - see Assumptions above
     //
-    if( LROfVar)   {  
-
+    if (LROfVar) {  
       if(LROfDef == LROfVar)            // do not set interf for same LR
        continue;
 
       // if 2 reg classes are the same set interference
       //
-      if( RCOfDef == LROfVar->getRegClass() ){ 
+      if (RCOfDef == LROfVar->getRegClass()) {
        RCOfDef->setInterference( LROfDef, LROfVar);  
-
+      } else if (DEBUG_RA > 1)  { 
+        // we will not have LRs for values not explicitly allocated in the
+        // instruction stream (e.g., constants)
+        cerr << " warning: no live range for " << RAV(*LIt) << "\n";
       }
-
-    else if(DEBUG_RA > 1)  { 
-      // we will not have LRs for values not explicitly allocated in the
-      // instruction stream (e.g., constants)
-      cerr << " warning: no live range for " ; 
-      printValue(*LIt); cerr << "\n"; }
-    
     }
   }
-
 }
 
 
 
-
 //----------------------------------------------------------------------------
 // For a call instruction, this method sets the CallInterference flag in 
 // the LR of each variable live int the Live Variable Set live after the
@@ -186,26 +211,12 @@ void PhyRegAlloc::addInterference(const Value *const Def,
 //----------------------------------------------------------------------------
 
 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst, 
-                                      const LiveVarSet *const LVSetAft ) {
-
-  // Now find the LR of the return value of the call
-  // We do this because, we look at the LV set *after* the instruction
-  // to determine, which LRs must be saved across calls. The return value
-  // of the call is live in this set - but it does not interfere with call
-  // (i.e., we can allocate a volatile register to the return value)
-  //
-  LiveRange *RetValLR = NULL;
-  const Value *RetVal = MRI.getCallInstRetVal( MInst );
-
-  if( RetVal ) {
-    RetValLR = LRI.getLiveRangeForValue( RetVal );
-    assert( RetValLR && "No LR for RetValue of call");
-  }
+                                      const ValueSet *LVSetAft) {
 
   if( DEBUG_RA)
     cerr << "\n For call inst: " << *MInst;
 
-  LiveVarSet::const_iterator LIt = LVSetAft->begin();
+  ValueSet::const_iterator LIt = LVSetAft->begin();
 
   // for each live var in live variable set after machine inst
   //
@@ -217,23 +228,44 @@ void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
 
     if( LR && DEBUG_RA) {
       cerr << "\n\tLR Aft Call: ";
-      LR->printSet();
+      printSet(*LR);
     }
    
-
     // LR can be null if it is a const since a const 
     // doesn't have a dominating def - see Assumptions above
     //
-    if( LR && (LR != RetValLR) )   {  
+    if( LR )   {  
       LR->setCallInterference();
       if( DEBUG_RA) {
        cerr << "\n  ++Added call interf for LR: " ;
-       LR->printSet();
+       printSet(*LR);
       }
     }
 
   }
 
+  // Now find the LR of the return value of the call
+  // We do this because, we look at the LV set *after* the instruction
+  // to determine, which LRs must be saved across calls. The return value
+  // of the call is live in this set - but it does not interfere with call
+  // (i.e., we can allocate a volatile register to the return value)
+  //
+  CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
+  
+  if (const Value *RetVal = argDesc->getReturnValue()) {
+    LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
+    assert( RetValLR && "No LR for RetValue of call");
+    RetValLR->clearCallInterference();
+  }
+
+  // If the CALL is an indirect call, find the LR of the function pointer.
+  // That has a call interference because it conflicts with outgoing args.
+  if( const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
+    LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
+    assert( AddrValLR && "No LR for indirect addr val of call");
+    AddrValLR->setCallInterference();
+  }
+
 }
 
 
@@ -250,30 +282,27 @@ void PhyRegAlloc::buildInterferenceGraphs()
   if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
 
   unsigned BBLoopDepthCost;
-  Method::const_iterator BBI = Meth->begin();  // random iterator for BBs   
-
-  for( ; BBI != Meth->end(); ++BBI) {          // traverse BBs in random order
+  for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
+       BBI != BBE; ++BBI) {
 
     // find the 10^(loop_depth) of this BB 
     //
-    BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc.getLoopDepth(*BBI));
+    BBLoopDepthCost = (unsigned) pow(10.0, LoopDepthCalc->getLoopDepth(*BBI));
 
     // get the iterator for machine instructions
     //
     const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
-    MachineCodeForBasicBlock::const_iterator 
-      MInstIterator = MIVec.begin();
+    MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
 
     // iterate over all the machine instructions in BB
     //
-    for( ; MInstIterator != MIVec.end(); ++MInstIterator) {  
+    for( ; MII != MIVec.end(); ++MII) {  
 
-      const MachineInstr * MInst = *MInstIterator
+      const MachineInstr *MInst = *MII
 
       // get the LV set after the instruction
       //
-      const LiveVarSet *const LVSetAI = 
-       LVI->getLiveVarSetAfterMInst(MInst, *BBI);
+      const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
     
       const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
 
@@ -283,31 +312,27 @@ void PhyRegAlloc::buildInterferenceGraphs()
        // coloring algo to avoid allocating volatile colors to live ranges
        // that span across calls (since they have to be saved/restored)
        //
-       setCallInterferences( MInst,  LVSetAI);
+       setCallInterferences(MInst, &LVSetAI);
       }
 
 
       // iterate over all MI operands to find defs
       //
-      for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
-
-               if( OpI.isDef() ) {     
-         // create a new LR iff this operand is a def
-         //
-         addInterference(*OpI, LVSetAI, isCallInst );
-       } 
+      for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
+             OpE = MInst->end(); OpI != OpE; ++OpI) {
+               if (OpI.isDef())    // create a new LR iff this operand is a def
+         addInterference(*OpI, &LVSetAI, isCallInst);
 
        // Calculate the spill cost of each live range
        //
-       LiveRange *LR = LRI.getLiveRangeForValue( *OpI );
-       if( LR )
-         LR->addSpillCost(BBLoopDepthCost);
+       LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
+       if (LR) LR->addSpillCost(BBLoopDepthCost);
       } 
 
 
       // if there are multiple defs in this instruction e.g. in SETX
       //   
-      if( (TM.getInstrInfo()).isPseudoInstr( MInst->getOpCode()) )
+      if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
        addInterf4PseudoInstr(MInst);
 
 
@@ -318,17 +343,16 @@ void PhyRegAlloc::buildInterferenceGraphs()
       if(  NumOfImpRefs > 0 ) {
        for(unsigned z=0; z < NumOfImpRefs; z++) 
          if( MInst->implicitRefIsDefined(z) )
-           addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
+           addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
       }
 
 
     } // for all machine instructions in BB
-    
-  } // for all BBs in method
+  } // for all BBs in function
 
 
-  // add interferences for method arguments. Since there are no explict 
-  // defs in method for args, we have to add them manually
+  // add interferences for function arguments. Since there are no explict 
+  // defs in the function for args, we have to add them manually
   //  
   addInterferencesForArgs();          
 
@@ -351,75 +375,60 @@ void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
 
   // iterate over  MI operands to find defs
   //
-  for( MachineInstr::val_const_op_iterator It1(MInst);!It1.done(); ++It1) {
-    
-    const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 ); 
-
-    if( !LROfOp1 && It1.isDef() )
-      assert( 0 && "No LR for Def in PSEUDO insruction");
-
-    MachineInstr::val_const_op_iterator It2 = It1;
-    ++It2;
-       
-    for(  ; !It2.done(); ++It2) {
-
-      const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 ); 
-
-      if( LROfOp2) {
-           
-       RegClass *const RCOfOp1 = LROfOp1->getRegClass(); 
-       RegClass *const RCOfOp2 = LROfOp2->getRegClass(); 
+  for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
+         ItE = MInst->end(); It1 != ItE; ++It1) {
+    const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1); 
+    assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
+
+    MachineInstr::const_val_op_iterator It2 = It1;
+    for(++It2; It2 != ItE; ++It2) {
+      const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2); 
+
+      if (LROfOp2) {
+       RegClass *RCOfOp1 = LROfOp1->getRegClass(); 
+       RegClass *RCOfOp2 = LROfOp2->getRegClass(); 
  
        if( RCOfOp1 == RCOfOp2 ){ 
          RCOfOp1->setInterference( LROfOp1, LROfOp2 );  
          setInterf = true;
        }
-
       } // if Op2 has a LR
-
     } // for all other defs in machine instr
-
   } // for all operands in an instruction
 
-  if( !setInterf && (MInst->getNumOperands() > 2) ) {
+  if (!setInterf && MInst->getNumOperands() > 2) {
     cerr << "\nInterf not set for any operand in pseudo instr:\n";
     cerr << *MInst;
     assert(0 && "Interf not set for pseudo instr with > 2 operands" );
-    
   }
-
 } 
 
 
 
 //----------------------------------------------------------------------------
-// This method will add interferences for incoming arguments to a method.
+// This method will add interferences for incoming arguments to a function.
 //----------------------------------------------------------------------------
-void PhyRegAlloc::addInterferencesForArgs()
-{
-                                              // get the InSet of root BB
-  const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );  
+void PhyRegAlloc::addInterferencesForArgs() {
+  // get the InSet of root BB
+  const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());  
 
-                                              // get the argument list
-  const Method::ArgumentListType& ArgList = Meth->getArgumentList();  
+  // get the argument list
+  const Function::ArgumentListType &ArgList = Meth->getArgumentList();  
 
-                                              // get an iterator to arg list
-  Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();          
+  // get an iterator to arg list
+  Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();          
 
 
   for( ; ArgIt != ArgList.end() ; ++ArgIt) {  // for each argument
-    addInterference( *ArgIt, InSet, false );  // add interferences between 
+    addInterference((Value*)*ArgIt, &InSet, false);// add interferences between 
                                               // args and LVars at start
-    if( DEBUG_RA > 1) {
-       cerr << " - %% adding interference for  argument ";    
-      printValue((const Value *)*ArgIt); cerr << "\n";
-    }
+    if( DEBUG_RA > 1)
+      cerr << " - %% adding interference for  argument "
+           << RAV((const Value *)*ArgIt) << "\n";
   }
 }
 
 
-
-
 //----------------------------------------------------------------------------
 // This method is called after register allocation is complete to set the
 // allocated reisters in the machine code. This code will add register numbers
@@ -428,53 +437,103 @@ void PhyRegAlloc::addInterferencesForArgs()
 // additional instructions produced by the register allocator to the 
 // instruction stream. 
 //----------------------------------------------------------------------------
-void PhyRegAlloc::updateMachineCode()
-{
 
-  Method::const_iterator BBI = Meth->begin();  // random iterator for BBs   
+//-----------------------------
+// Utility functions used below
+//-----------------------------
+inline void
+PrependInstructions(vector<MachineInstr *> &IBef,
+                    MachineCodeForBasicBlock& MIVec,
+                    MachineCodeForBasicBlock::iterator& MII,
+                    const std::string& msg)
+{
+  if (!IBef.empty())
+    {
+      MachineInstr* OrigMI = *MII;
+      std::vector<MachineInstr *>::iterator AdIt; 
+      for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
+        {
+          if (DEBUG_RA) {
+            if (OrigMI) cerr << "For MInst: " << *OrigMI;
+            cerr << msg << " PREPENDed instr: " << **AdIt << "\n";
+          }
+          MII = MIVec.insert(MII, *AdIt);
+          ++MII;
+        }
+    }
+}
 
-  for( ; BBI != Meth->end(); ++BBI) {          // traverse BBs in random order
+inline void
+AppendInstructions(std::vector<MachineInstr *> &IAft,
+                   MachineCodeForBasicBlock& MIVec,
+                   MachineCodeForBasicBlock::iterator& MII,
+                   const std::string& msg)
+{
+  if (!IAft.empty())
+    {
+      MachineInstr* OrigMI = *MII;
+      std::vector<MachineInstr *>::iterator AdIt; 
+      for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
+        {
+          if(DEBUG_RA) {
+            if (OrigMI) cerr << "For MInst: " << *OrigMI;
+            cerr << msg << " APPENDed instr: "  << **AdIt << "\n";
+          }
+          ++MII;    // insert before the next instruction
+          MII = MIVec.insert(MII, *AdIt);
+        }
+    }
+}
 
-    // get the iterator for machine instructions
-    //
-    MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
-    MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
 
+void PhyRegAlloc::updateMachineCode()
+{
+  const BasicBlock* entryBB = Meth->getEntryNode();
+  if (entryBB) {
+    MachineCodeForBasicBlock& MIVec = entryBB->getMachineInstrVec();
+    MachineCodeForBasicBlock::iterator MII = MIVec.begin();
+    
+    // Insert any instructions needed at method entry
+    PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
+                        "At function entry: \n");
+    assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
+           "InstrsAfter should be unnecessary since we are just inserting at "
+           "the function entry point here.");
+  }
+  
+  for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
+       BBI != BBE; ++BBI) {
+    
     // iterate over all the machine instructions in BB
-    //
-    for( ; MInstIterator != MIVec.end(); ++MInstIterator) {  
+    MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
+    for(MachineCodeForBasicBlock::iterator MII = MIVec.begin();
+        MII != MIVec.end(); ++MII) {  
       
-      MachineInstr *MInst = *MInstIterator
+      MachineInstr *MInst = *MII
       
       unsigned Opcode =  MInst->getOpCode();
     
       // do not process Phis
-      if( (TM.getInstrInfo()).isPhi( Opcode ) )
+      if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
        continue;
 
       // Now insert speical instructions (if necessary) for call/return
       // instructions. 
       //
-      if( (TM.getInstrInfo()).isCall( Opcode) ||  
-         (TM.getInstrInfo()).isReturn( Opcode)  ) {
+      if (TM.getInstrInfo().isCall(Opcode) ||
+         TM.getInstrInfo().isReturn(Opcode)) {
 
-       AddedInstrns *AI = AddedInstrMap[ MInst];
-       if ( !AI ) { 
-         AI = new AddedInstrns();
-         AddedInstrMap[ MInst ] = AI;
-       }
+       AddedInstrns &AI = AddedInstrMap[MInst];
        
        // Tmp stack poistions are needed by some calls that have spilled args
        // So reset it before we call each such method
        //
        mcInfo.popAllTempValues(TM);  
        
-       if( (TM.getInstrInfo()).isCall( Opcode ) )
-         MRI.colorCallArgs( MInst, LRI, AI, *this, *BBI );
-       
-       else if (  (TM.getInstrInfo()).isReturn(Opcode) ) 
-         MRI.colorRetValue( MInst, LRI, AI );
-       
+       if (TM.getInstrInfo().isCall(Opcode))
+         MRI.colorCallArgs(MInst, LRI, &AI, *this, *BBI);
+       else if (TM.getInstrInfo().isReturn(Opcode))
+         MRI.colorRetValue(MInst, LRI, &AI);
       }
       
 
@@ -562,32 +621,14 @@ void PhyRegAlloc::updateMachineCode()
       // If there are instructions to be added, *before* this machine
       // instruction, add them now.
       //      
-      if( AddedInstrMap[ MInst ] ) {
-       std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
-
-       if( ! IBef.empty() ) {
-         std::deque<MachineInstr *>::iterator AdIt; 
-
-         for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
-
-           if( DEBUG_RA) {
-             cerr << "For inst " << *MInst;
-             cerr << " PREPENDed instr: " << **AdIt << "\n";
-           }
-                   
-           MInstIterator = MIVec.insert( MInstIterator, *AdIt );
-           ++MInstIterator;
-         }
-
-       }
-
+      if(AddedInstrMap.count(MInst)) {
+        PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
       }
-
+      
       // If there are instructions to be added *after* this machine
       // instruction, add them now
       //
-      if( AddedInstrMap[ MInst ] && 
-         ! (AddedInstrMap[ MInst ]->InstrnsAfter).empty() ) {
+      if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
 
        // if there are delay slots for this instruction, the instructions
        // added after it must really go after the delayed instruction(s)
@@ -595,44 +636,16 @@ void PhyRegAlloc::updateMachineCode()
        // corresponding delayed instruction
        
        unsigned delay;
-       if((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){ 
-         move2DelayedInstr(MInst,  *(MInstIterator+delay) );
+       if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){ 
+         move2DelayedInstr(MInst,  *(MII+delay) );
 
          if(DEBUG_RA)  cerr<< "\nMoved an added instr after the delay slot";
        }
        
        else {
-       
-
          // Here we can add the "instructions after" to the current
          // instruction since there are no delay slots for this instruction
-
-         std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
-         
-         if( ! IAft.empty() ) {     
-           
-           std::deque<MachineInstr *>::iterator AdIt; 
-           
-           ++MInstIterator;   // advance to the next instruction
-           
-           for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
-             
-             if(DEBUG_RA) {
-               cerr << "For inst " << *MInst;
-               cerr << " APPENDed instr: "  << **AdIt << "\n";
-             }       
-
-             MInstIterator = MIVec.insert( MInstIterator, *AdIt );
-             ++MInstIterator;
-           }
-
-           // MInsterator already points to the next instr. Since the
-           // for loop also increments it, decrement it to point to the
-           // instruction added last
-           --MInstIterator;  
-           
-         }
-         
+         AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
        }  // if not delay
        
       }
@@ -665,75 +678,65 @@ void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
   unsigned RegType = MRI.getRegType( LR );
   int SpillOff = LR->getSpillOffFromFP();
   RegClass *RC = LR->getRegClass();
-  const LiveVarSet *LVSetBef =  LVI->getLiveVarSetBeforeMInst(MInst, BB);
+  const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
 
   mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
   
-  MachineInstr *MIBef=NULL,  *AdIMid=NULL, *MIAft=NULL;
+  MachineInstr *MIBef=NULL, *MIAft=NULL;
+  vector<MachineInstr*> AdIMid;
   
-  int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
+  int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
   
   // get the added instructions for this instruciton
-  AddedInstrns *AI = AddedInstrMap[ MInst ];
-  if ( !AI ) { 
-    AI = new AddedInstrns();
-    AddedInstrMap[ MInst ] = AI;
-  }
-
+  AddedInstrns &AI = AddedInstrMap[MInst];
     
-  if( !isDef ) {
-
+  if (!isDef) {
     // for a USE, we have to load the value of LR from stack to a TmpReg
     // and use the TmpReg as one operand of instruction
 
     // actual loading instruction
-    AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
-
-    if( MIBef )
-      (AI->InstrnsBefore).push_back(MIBef);
-
-    (AI->InstrnsBefore).push_back(AdIMid);
-
-    if( MIAft)
-      (AI->InstrnsAfter).push_front(MIAft);
-    
+    MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType, AdIMid);
+    AI.InstrnsBefore.insert(AI.InstrnsBefore.end(),
+                            AdIMid.begin(), AdIMid.end());
     
-  } 
-  else {   // if this is a Def
+    if(MIBef)
+      AI.InstrnsBefore.push_back(MIBef);
 
+    if(MIAft)
+      AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft);
+    
+  } else {   // if this is a Def
     // for a DEF, we have to store the value produced by this instruction
     // on the stack position allocated for this LR
 
     // actual storing instruction
-    AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
-
-    if( MIBef )
-      (AI->InstrnsBefore).push_back(MIBef);
-
-    (AI->InstrnsAfter).push_front(AdIMid);
-
-    if( MIAft)
-      (AI->InstrnsAfter).push_front(MIAft);
+    MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType, AdIMid);
+    
+    if (MIBef)
+      AI.InstrnsBefore.push_back(MIBef);
+    
+    AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(),
+                           AdIMid.begin(), AdIMid.end());
+    
+    if (MIAft)
+      AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft);
 
   }  // if !DEF
-
+  
   cerr << "\nFor Inst " << *MInst;
-  cerr << " - SPILLED LR: "; LR->printSet();
+  cerr << " - SPILLED LR: "; printSet(*LR);
   cerr << "\n - Added Instructions:";
-  if( MIBef ) cerr <<  *MIBef;
-  cerr <<  *AdIMid;
-  if( MIAft ) cerr <<  *MIAft;
-
-  Op.setRegForValue( TmpRegU );    // set the opearnd
-
+  if (MIBef) cerr <<  *MIBef;
+  for (vector<MachineInstr*>::const_iterator II=AdIMid.begin();
+       II != AdIMid.end(); ++II)
+    cerr <<  **II;
+  if (MIAft) cerr <<  *MIAft;
 
+  Op.setRegForValue(TmpRegU);    // set the opearnd
 }
 
 
 
-
-
-
 //----------------------------------------------------------------------------
 // We can use the following method to get a temporary register to be used
 // BEFORE any given machine instruction. If there is a register available,
@@ -746,9 +749,9 @@ void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC, 
                                  const int RegType,
                                  const MachineInstr *MInst, 
-                                 const LiveVarSet *LVSetBef,
-                                 MachineInstr *MIBef,
-                                 MachineInstr *MIAft) {
+                                 const ValueSet *LVSetBef,
+                                 MachineInstr *&MIBef,
+                                 MachineInstr *&MIAft) {
 
   int RegU =  getUnusedUniRegAtMI(RC, MInst, LVSetBef);
 
@@ -764,8 +767,16 @@ int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
     int TmpOff = mcInfo.pushTempValue(TM,  MRI.getSpilledRegSize(RegType) );
     
     RegU = getUniRegNotUsedByThisInst(RC, MInst);
-    MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
-    MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
+
+    vector<MachineInstr*> mvec;
+    
+    MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType, mvec);
+    assert(mvec.size() == 1 && "Need to return a vector here too");
+    MIBef = * mvec.begin();
+    
+    MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType, mvec);
+    assert(mvec.size() == 1 && "Need to return a vector here too");
+    MIAft = * mvec.begin();
   }
 
   return RegU;
@@ -783,7 +794,7 @@ int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
 //----------------------------------------------------------------------------
 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, 
                                  const MachineInstr *MInst, 
-                                 const LiveVarSet *LVSetBef) {
+                                 const ValueSet *LVSetBef) {
 
   unsigned NumAvailRegs =  RC->getNumOfAvailRegs();
   
@@ -792,7 +803,7 @@ int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
   for(unsigned i=0; i <  NumAvailRegs; i++)     // Reset array
       IsColorUsedArr[i] = false;
       
-  LiveVarSet::const_iterator LIt = LVSetBef->begin();
+  ValueSet::const_iterator LIt = LVSetBef->begin();
 
   // for each live var in live variable set after machine inst
   for( ; LIt != LVSetBef->end(); ++LIt) {
@@ -802,9 +813,8 @@ int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
 
     // LR can be null if it is a const since a const 
     // doesn't have a dominating def - see Assumptions above
-    if( LRofLV )     
-      if( LRofLV->hasColor() ) 
-       IsColorUsedArr[ LRofLV->getColor() ] = true;
+    if( LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() ) 
+      IsColorUsedArr[ LRofLV->getColor() ] = true;
   }
 
   // It is possible that one operand of this MInst was already spilled
@@ -922,22 +932,17 @@ void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
 // corresponding delayed instruction using the following method.
 
 //----------------------------------------------------------------------------
-void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
-                                    const MachineInstr *DelayedMI) {
+void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
+                                    const MachineInstr *DelayedMI) {
 
   // "added after" instructions of the original instr
-  std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
+  std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
 
   // "added instructions" of the delayed instr
-  AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
-
-  if(! DelayAdI )  {                // create a new "added after" if necessary
-    DelayAdI = new AddedInstrns();
-    AddedInstrMap[DelayedMI] =  DelayAdI;
-  }
+  AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
 
   // "added after" instructions of the delayed instr
-  std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
+  std::vector<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
 
   // go thru all the "added after instructions" of the original instruction
   // and append them to the "addded after instructions" of the delayed
@@ -955,33 +960,25 @@ void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
 void PhyRegAlloc::printMachineCode()
 {
 
-  cerr << "\n;************** Method " << Meth->getName()
+  cerr << "\n;************** Function " << Meth->getName()
        << " *****************\n";
 
-  Method::const_iterator BBI = Meth->begin();  // random iterator for BBs   
-
-  for( ; BBI != Meth->end(); ++BBI) {          // traverse BBs in random order
-
-    cerr << "\n"; printLabel( *BBI); cerr << ": ";
+  for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
+       BBI != BBE; ++BBI) {
+    cerr << "\n"; printLabel(*BBI); cerr << ": ";
 
     // get the iterator for machine instructions
     MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
-    MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
+    MachineCodeForBasicBlock::iterator MII = MIVec.begin();
 
     // iterate over all the machine instructions in BB
-    for( ; MInstIterator != MIVec.end(); ++MInstIterator) {  
-      
-      MachineInstr *const MInst = *MInstIterator; 
-
+    for( ; MII != MIVec.end(); ++MII) {  
+      MachineInstr *const MInst = *MII; 
 
       cerr << "\n\t";
       cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
-      
-
-      //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
 
       for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
-
        MachineOperand& Op = MInst->getOperand(OpNum);
 
        if( Op.getOperandType() ==  MachineOperand::MO_VirtualRegister || 
@@ -996,7 +993,7 @@ void PhyRegAlloc::printMachineCode()
          }
 
          // if a label or a constant
-         if(isa<BasicBlock>(Val) {
+         if(isa<BasicBlock>(Val)) {
            cerr << "\t"; printLabel(   Op.getVRegValue () );
          } else {
            // else it must be a register value
@@ -1029,15 +1026,11 @@ void PhyRegAlloc::printMachineCode()
     
 
       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
-      if(  NumOfImpRefs > 0 ) {
-       
+      if( NumOfImpRefs > 0) {
        cerr << "\tImplicit:";
 
-       for(unsigned z=0; z < NumOfImpRefs; z++) {
-         printValue(  MInst->getImplicitRef(z) );
-         cerr << "\t";
-       }
-       
+       for(unsigned z=0; z < NumOfImpRefs; z++)
+         cerr << RAV(MInst->getImplicitRef(z)) << "\t";
       }
 
     } // for all machine instructions
@@ -1068,28 +1061,20 @@ void PhyRegAlloc::colorCallRetArgs()
     unsigned OpCode =  CRMI->getOpCode();
  
     // get the added instructions for this Call/Ret instruciton
-    AddedInstrns *AI = AddedInstrMap[ CRMI ];
-    if ( !AI ) { 
-      AI = new AddedInstrns();
-      AddedInstrMap[ CRMI ] = AI;
-    }
+    AddedInstrns &AI = AddedInstrMap[CRMI];
 
-    // Tmp stack poistions are needed by some calls that have spilled args
+    // Tmp stack positions are needed by some calls that have spilled args
     // So reset it before we call each such method
     //mcInfo.popAllTempValues(TM);  
 
-
-    
-    if( (TM.getInstrInfo()).isCall( OpCode ) )
-      MRI.colorCallArgs( CRMI, LRI, AI, *this );
     
-    else if (  (TM.getInstrInfo()).isReturn(OpCode) ) 
-      MRI.colorRetValue( CRMI, LRI, AI );
-    
-    else assert( 0 && "Non Call/Ret instrn in CallRetInstrList\n" );
-
+    if (TM.getInstrInfo().isCall(OpCode))
+      MRI.colorCallArgs(CRMI, LRI, &AI, *this);
+    else if (TM.getInstrInfo().isReturn(OpCode)) 
+      MRI.colorRetValue(CRMI, LRI, &AI);
+    else
+      assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
   }
-
 }
 
 #endif 
@@ -1100,16 +1085,10 @@ void PhyRegAlloc::colorCallRetArgs()
 void PhyRegAlloc::colorIncomingArgs()
 {
   const BasicBlock *const FirstBB = Meth->front();
-  const MachineInstr *FirstMI = *((FirstBB->getMachineInstrVec()).begin());
-  assert( FirstMI && "No machine instruction in entry BB");
+  const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
+  assert(FirstMI && "No machine instruction in entry BB");
 
-  AddedInstrns *AI = AddedInstrMap[ FirstMI ];
-  if (!AI) { 
-    AI = new AddedInstrns();
-    AddedInstrMap[FirstMI] = AI;
-  }
-
-  MRI.colorMethodArgs(Meth, LRI, AI );
+  MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
 }
 
 
@@ -1139,16 +1118,12 @@ void PhyRegAlloc::markUnusableSugColors()
   LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
   LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
 
-    for(  ; HMI != HMIEnd ; ++HMI ) {
-      
-      if( (*HMI).first ) { 
-
-       LiveRange *L = (*HMI).second;      // get the LiveRange
-
-       if(L) { 
-         if( L->hasSuggestedColor() ) {
-
-           int RCID = (L->getRegClass())->getID();
+    for(; HMI != HMIEnd ; ++HMI ) {
+      if (HMI->first) { 
+       LiveRange *L = HMI->second;      // get the LiveRange
+       if (L) { 
+         if(L->hasSuggestedColor()) {
+           int RCID = L->getRegClass()->getID();
            if( MRI.isRegVolatile( RCID,  L->getSuggestedColor()) &&
                L->isCallInterference() )
              L->setSuggestedColorUsable( false );
@@ -1169,22 +1144,19 @@ void PhyRegAlloc::markUnusableSugColors()
 // this method allocate a new spill position on the stack.
 //----------------------------------------------------------------------------
 
-void PhyRegAlloc::allocateStackSpace4SpilledLRs()
-{
-  if(DEBUG_RA ) cerr << "\nsetting LR stack offsets ...\n";
+void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
+  if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
 
-  // hash map iterator
-  LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
-  LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
+  LiveRangeMapType::const_iterator HMI    = LRI.getLiveRangeMap()->begin();   
+  LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();   
 
-    for(  ; HMI != HMIEnd ; ++HMI ) {
-      if(HMI->first && HMI->second) {
-       LiveRange *L = HMI->second;      // get the LiveRange
-        if( ! L->hasColor() ) 
-          //  NOTE: ** allocating the size of long Type **
-          L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
-      }
-    } // for all LR's in hash map
+  for( ; HMI != HMIEnd ; ++HMI) {
+    if (HMI->first && HMI->second) {
+      LiveRange *L = HMI->second;      // get the LiveRange
+      if (!L->hasColor())   //  NOTE: ** allocating the size of long Type **
+        L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
+    }
+  } // for all LR's in hash map
 }
 
 
@@ -1202,7 +1174,7 @@ void PhyRegAlloc::allocateRegisters()
   //
   LRI.constructLiveRanges();            // create LR info
 
-  if( DEBUG_RA )
+  if (DEBUG_RA)
     LRI.printLiveRanges();
   
   createIGNodeListsAndIGs();            // create IGNode list and IGs
@@ -1210,7 +1182,7 @@ void PhyRegAlloc::allocateRegisters()
   buildInterferenceGraphs();            // build IGs in all reg classes
   
   
-  if( DEBUG_RA ) {
+  if (DEBUG_RA) {
     // print all LRs in all reg classes
     for( unsigned int rc=0; rc < NumOfRegClasses  ; rc++)  
       RegClassList[ rc ]->printIGNodeList(); 
@@ -1257,19 +1229,16 @@ void PhyRegAlloc::allocateRegisters()
   //
   colorIncomingArgs();
 
-
   // Now update the machine code with register names and add any 
   // additional code inserted by the register allocator to the instruction
   // stream
   //
   updateMachineCode(); 
 
-
   if (DEBUG_RA) {
     MachineCodeForMethod::get(Meth).dump();
     printMachineCode();                   // only for DEBUGGING
   }
-
 }