For instructions in a delay slot of another instruction,
[oota-llvm.git] / lib / Target / SparcV9 / RegAlloc / PhyRegAlloc.cpp
1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
2 // 
3 //  Register allocation for LLVM.
4 // 
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/CodeGen/RegisterAllocation.h"
8 #include "RegAllocCommon.h"
9 #include "RegClass.h"
10 #include "llvm/CodeGen/IGNode.h"
11 #include "llvm/CodeGen/PhyRegAlloc.h"
12 #include "llvm/CodeGen/MachineInstrBuilder.h"
13 #include "llvm/CodeGen/MachineInstrAnnot.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineFunctionInfo.h"
16 #include "llvm/CodeGen/FunctionLiveVarInfo.h"
17 #include "llvm/CodeGen/InstrSelection.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetFrameInfo.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetRegInfo.h"
23 #include "llvm/Function.h"
24 #include "llvm/Type.h"
25 #include "llvm/iOther.h"
26 #include "Support/STLExtras.h"
27 #include "Support/SetOperations.h"
28 #include "Support/CommandLine.h"
29 #include <math.h>
30 using std::cerr;
31 using std::vector;
32
33 RegAllocDebugLevel_t DEBUG_RA;
34
35 static cl::opt<RegAllocDebugLevel_t, true>
36 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
37         cl::desc("enable register allocation debugging information"),
38         cl::values(
39   clEnumValN(RA_DEBUG_None   ,     "n", "disable debug output"),
40   clEnumValN(RA_DEBUG_Results,     "y", "debug output for allocation results"),
41   clEnumValN(RA_DEBUG_Coloring,    "c", "debug output for graph coloring step"),
42   clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
43   clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
44   clEnumValN(RA_DEBUG_Verbose,     "v", "extra debug output"),
45                    0));
46
47 //----------------------------------------------------------------------------
48 // RegisterAllocation pass front end...
49 //----------------------------------------------------------------------------
50 namespace {
51   class RegisterAllocator : public FunctionPass {
52     TargetMachine &Target;
53   public:
54     inline RegisterAllocator(TargetMachine &T) : Target(T) {}
55
56     const char *getPassName() const { return "Register Allocation"; }
57     
58     bool runOnFunction(Function &F) {
59       if (DEBUG_RA)
60         cerr << "\n********* Function "<< F.getName() << " ***********\n";
61       
62       PhyRegAlloc PRA(&F, Target, &getAnalysis<FunctionLiveVarInfo>(),
63                       &getAnalysis<LoopInfo>());
64       PRA.allocateRegisters();
65       
66       if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
67       return false;
68     }
69
70     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71       AU.addRequired<LoopInfo>();
72       AU.addRequired<FunctionLiveVarInfo>();
73     }
74   };
75 }
76
77 Pass *getRegisterAllocator(TargetMachine &T) {
78   return new RegisterAllocator(T);
79 }
80
81 //----------------------------------------------------------------------------
82 // Constructor: Init local composite objects and create register classes.
83 //----------------------------------------------------------------------------
84 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm, 
85                          FunctionLiveVarInfo *Lvi, LoopInfo *LDC) 
86   :  TM(tm), Fn(F), MF(MachineFunction::get(F)), LVI(Lvi),
87      LRI(F, tm, RegClassList), MRI(tm.getRegInfo()),
88      NumOfRegClasses(MRI.getNumOfRegClasses()), LoopDepthCalc(LDC) {
89
90   // create each RegisterClass and put in RegClassList
91   //
92   for (unsigned rc=0; rc != NumOfRegClasses; rc++)  
93     RegClassList.push_back(new RegClass(F, &tm.getRegInfo(),
94                                         MRI.getMachineRegClass(rc)));
95 }
96
97
98 //----------------------------------------------------------------------------
99 // Destructor: Deletes register classes
100 //----------------------------------------------------------------------------
101 PhyRegAlloc::~PhyRegAlloc() { 
102   for ( unsigned rc=0; rc < NumOfRegClasses; rc++)
103     delete RegClassList[rc];
104
105   AddedInstrMap.clear();
106
107
108 //----------------------------------------------------------------------------
109 // This method initally creates interference graphs (one in each reg class)
110 // and IGNodeList (one in each IG). The actual nodes will be pushed later. 
111 //----------------------------------------------------------------------------
112 void PhyRegAlloc::createIGNodeListsAndIGs() {
113   if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "Creating LR lists ...\n";
114
115   // hash map iterator
116   LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();   
117
118   // hash map end
119   LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();   
120
121   for (; HMI != HMIEnd ; ++HMI ) {
122     if (HMI->first) { 
123       LiveRange *L = HMI->second;   // get the LiveRange
124       if (!L) { 
125         if (DEBUG_RA)
126           cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
127                << RAV(HMI->first) << "****\n";
128         continue;
129       }
130
131       // if the Value * is not null, and LR is not yet written to the IGNodeList
132       if (!(L->getUserIGNode())  ) {  
133         RegClass *const RC =           // RegClass of first value in the LR
134           RegClassList[ L->getRegClass()->getID() ];
135         RC->addLRToIG(L);              // add this LR to an IG
136       }
137     }
138   }
139     
140   // init RegClassList
141   for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)  
142     RegClassList[rc]->createInterferenceGraph();
143
144   if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "LRLists Created!\n";
145 }
146
147
148 //----------------------------------------------------------------------------
149 // This method will add all interferences at for a given instruction.
150 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg 
151 // class as that of live var. The live var passed to this function is the 
152 // LVset AFTER the instruction
153 //----------------------------------------------------------------------------
154
155 void PhyRegAlloc::addInterference(const Value *Def, 
156                                   const ValueSet *LVSet,
157                                   bool isCallInst) {
158
159   ValueSet::const_iterator LIt = LVSet->begin();
160
161   // get the live range of instruction
162   //
163   const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );   
164
165   IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
166   assert( IGNodeOfDef );
167
168   RegClass *const RCOfDef = LROfDef->getRegClass(); 
169
170   // for each live var in live variable set
171   //
172   for ( ; LIt != LVSet->end(); ++LIt) {
173
174     if (DEBUG_RA >= RA_DEBUG_Verbose)
175       cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
176
177     //  get the live range corresponding to live var
178     // 
179     LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
180
181     // LROfVar can be null if it is a const since a const 
182     // doesn't have a dominating def - see Assumptions above
183     //
184     if (LROfVar)
185       if (LROfDef != LROfVar)                  // do not set interf for same LR
186         if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
187           RCOfDef->setInterference( LROfDef, LROfVar);  
188   }
189 }
190
191
192
193 //----------------------------------------------------------------------------
194 // For a call instruction, this method sets the CallInterference flag in 
195 // the LR of each variable live int the Live Variable Set live after the
196 // call instruction (except the return value of the call instruction - since
197 // the return value does not interfere with that call itself).
198 //----------------------------------------------------------------------------
199
200 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst, 
201                                        const ValueSet *LVSetAft) {
202
203   if (DEBUG_RA >= RA_DEBUG_Interference)
204     cerr << "\n For call inst: " << *MInst;
205
206   // for each live var in live variable set after machine inst
207   //
208   for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
209        LIt != LEnd; ++LIt) {
210
211     //  get the live range corresponding to live var
212     //
213     LiveRange *const LR = LRI.getLiveRangeForValue(*LIt ); 
214
215     // LR can be null if it is a const since a const 
216     // doesn't have a dominating def - see Assumptions above
217     //
218     if (LR ) {  
219       if (DEBUG_RA >= RA_DEBUG_Interference) {
220         cerr << "\n\tLR after Call: ";
221         printSet(*LR);
222       }
223       LR->setCallInterference();
224       if (DEBUG_RA >= RA_DEBUG_Interference) {
225         cerr << "\n  ++After adding call interference for LR: " ;
226         printSet(*LR);
227       }
228     }
229
230   }
231
232   // Now find the LR of the return value of the call
233   // We do this because, we look at the LV set *after* the instruction
234   // to determine, which LRs must be saved across calls. The return value
235   // of the call is live in this set - but it does not interfere with call
236   // (i.e., we can allocate a volatile register to the return value)
237   //
238   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
239   
240   if (const Value *RetVal = argDesc->getReturnValue()) {
241     LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
242     assert( RetValLR && "No LR for RetValue of call");
243     RetValLR->clearCallInterference();
244   }
245
246   // If the CALL is an indirect call, find the LR of the function pointer.
247   // That has a call interference because it conflicts with outgoing args.
248   if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
249     LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
250     assert( AddrValLR && "No LR for indirect addr val of call");
251     AddrValLR->setCallInterference();
252   }
253
254 }
255
256
257
258
259 //----------------------------------------------------------------------------
260 // This method will walk thru code and create interferences in the IG of
261 // each RegClass. Also, this method calculates the spill cost of each
262 // Live Range (it is done in this method to save another pass over the code).
263 //----------------------------------------------------------------------------
264 void PhyRegAlloc::buildInterferenceGraphs()
265 {
266
267   if (DEBUG_RA >= RA_DEBUG_Interference)
268     cerr << "Creating interference graphs ...\n";
269
270   unsigned BBLoopDepthCost;
271   for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
272        BBI != BBE; ++BBI) {
273     const MachineBasicBlock &MBB = *BBI;
274     const BasicBlock *BB = MBB.getBasicBlock();
275
276     // find the 10^(loop_depth) of this BB 
277     //
278     BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
279
280     // get the iterator for machine instructions
281     //
282     MachineBasicBlock::const_iterator MII = MBB.begin();
283
284     // iterate over all the machine instructions in BB
285     //
286     for ( ; MII != MBB.end(); ++MII) {
287       const MachineInstr *MInst = *MII;
288
289       // get the LV set after the instruction
290       //
291       const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
292       bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
293
294       if (isCallInst ) {
295         // set the isCallInterference flag of each live range wich extends
296         // accross this call instruction. This information is used by graph
297         // coloring algo to avoid allocating volatile colors to live ranges
298         // that span across calls (since they have to be saved/restored)
299         //
300         setCallInterferences(MInst, &LVSetAI);
301       }
302
303       // iterate over all MI operands to find defs
304       //
305       for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
306              OpE = MInst->end(); OpI != OpE; ++OpI) {
307         if (OpI.isDefOnly() || OpI.isDefAndUse()) // create a new LR since def
308           addInterference(*OpI, &LVSetAI, isCallInst);
309
310         // Calculate the spill cost of each live range
311         //
312         LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
313         if (LR) LR->addSpillCost(BBLoopDepthCost);
314       } 
315
316
317       // if there are multiple defs in this instruction e.g. in SETX
318       //   
319       if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
320         addInterf4PseudoInstr(MInst);
321
322
323       // Also add interference for any implicit definitions in a machine
324       // instr (currently, only calls have this).
325       //
326       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
327       for (unsigned z=0; z < NumOfImpRefs; z++) 
328         if (MInst->getImplicitOp(z).opIsDefOnly() ||
329             MInst->getImplicitOp(z).opIsDefAndUse())
330           addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
331
332     } // for all machine instructions in BB
333   } // for all BBs in function
334
335
336   // add interferences for function arguments. Since there are no explict 
337   // defs in the function for args, we have to add them manually
338   //  
339   addInterferencesForArgs();          
340
341   if (DEBUG_RA >= RA_DEBUG_Interference)
342     cerr << "Interference graphs calculated!\n";
343 }
344
345
346
347 //--------------------------------------------------------------------------
348 // Pseudo instructions will be exapnded to multiple instructions by the
349 // assembler. Consequently, all the opernds must get distinct registers.
350 // Therefore, we mark all operands of a pseudo instruction as they interfere
351 // with one another.
352 //--------------------------------------------------------------------------
353 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
354
355   bool setInterf = false;
356
357   // iterate over  MI operands to find defs
358   //
359   for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
360          ItE = MInst->end(); It1 != ItE; ++It1) {
361     const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1); 
362     assert((LROfOp1 || !It1.isUseOnly())&& "No LR for Def in PSEUDO insruction");
363
364     MachineInstr::const_val_op_iterator It2 = It1;
365     for (++It2; It2 != ItE; ++It2) {
366       const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2); 
367
368       if (LROfOp2) {
369         RegClass *RCOfOp1 = LROfOp1->getRegClass(); 
370         RegClass *RCOfOp2 = LROfOp2->getRegClass(); 
371  
372         if (RCOfOp1 == RCOfOp2 ){ 
373           RCOfOp1->setInterference( LROfOp1, LROfOp2 );  
374           setInterf = true;
375         }
376       } // if Op2 has a LR
377     } // for all other defs in machine instr
378   } // for all operands in an instruction
379
380   if (!setInterf && MInst->getNumOperands() > 2) {
381     cerr << "\nInterf not set for any operand in pseudo instr:\n";
382     cerr << *MInst;
383     assert(0 && "Interf not set for pseudo instr with > 2 operands" );
384   }
385
386
387
388
389 //----------------------------------------------------------------------------
390 // This method will add interferences for incoming arguments to a function.
391 //----------------------------------------------------------------------------
392
393 void PhyRegAlloc::addInterferencesForArgs() {
394   // get the InSet of root BB
395   const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());  
396
397   for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
398     // add interferences between args and LVars at start 
399     addInterference(AI, &InSet, false);
400     
401     if (DEBUG_RA >= RA_DEBUG_Interference)
402       cerr << " - %% adding interference for  argument " << RAV(AI) << "\n";
403   }
404 }
405
406
407 //----------------------------------------------------------------------------
408 // This method is called after register allocation is complete to set the
409 // allocated reisters in the machine code. This code will add register numbers
410 // to MachineOperands that contain a Value. Also it calls target specific
411 // methods to produce caller saving instructions. At the end, it adds all
412 // additional instructions produced by the register allocator to the 
413 // instruction stream. 
414 //----------------------------------------------------------------------------
415
416 //-----------------------------
417 // Utility functions used below
418 //-----------------------------
419 inline void
420 InsertBefore(MachineInstr* newMI,
421              MachineBasicBlock& MBB,
422              MachineBasicBlock::iterator& MII)
423 {
424   MII = MBB.insert(MII, newMI);
425   ++MII;
426 }
427
428 inline void
429 InsertAfter(MachineInstr* newMI,
430             MachineBasicBlock& MBB,
431             MachineBasicBlock::iterator& MII)
432 {
433   ++MII;    // insert before the next instruction
434   MII = MBB.insert(MII, newMI);
435 }
436
437 inline void
438 DeleteInstruction(MachineBasicBlock& MBB,
439                   MachineBasicBlock::iterator& MII)
440 {
441   MII = MBB.erase(MII);
442 }
443
444 inline void
445 SubstituteInPlace(MachineInstr* newMI,
446                   MachineBasicBlock& MBB,
447                   MachineBasicBlock::iterator MII)
448 {
449   *MII = newMI;
450 }
451
452 inline void
453 PrependInstructions(vector<MachineInstr *> &IBef,
454                     MachineBasicBlock& MBB,
455                     MachineBasicBlock::iterator& MII,
456                     const std::string& msg)
457 {
458   if (!IBef.empty())
459     {
460       MachineInstr* OrigMI = *MII;
461       std::vector<MachineInstr *>::iterator AdIt; 
462       for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
463         {
464           if (DEBUG_RA) {
465             if (OrigMI) cerr << "For MInst:\n  " << *OrigMI;
466             cerr << msg << "PREPENDed instr:\n  " << **AdIt << "\n";
467           }
468           InsertBefore(*AdIt, MBB, MII);
469         }
470     }
471 }
472
473 inline void
474 AppendInstructions(std::vector<MachineInstr *> &IAft,
475                    MachineBasicBlock& MBB,
476                    MachineBasicBlock::iterator& MII,
477                    const std::string& msg)
478 {
479   if (!IAft.empty())
480     {
481       MachineInstr* OrigMI = *MII;
482       std::vector<MachineInstr *>::iterator AdIt; 
483       for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
484         {
485           if (DEBUG_RA) {
486             if (OrigMI) cerr << "For MInst:\n  " << *OrigMI;
487             cerr << msg << "APPENDed instr:\n  "  << **AdIt << "\n";
488           }
489           InsertAfter(*AdIt, MBB, MII);
490         }
491     }
492 }
493
494 static bool MarkAllocatedRegs(MachineInstr* MInst,
495                               LiveRangeInfo& LRI,
496                               const TargetRegInfo& MRI)
497 {
498   bool instrNeedsSpills = false;
499
500   // First, set the registers for operands in the machine instruction
501   // if a register was successfully allocated.  Do this first because we
502   // will need to know which registers are already used by this instr'n.
503   // 
504   for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
505     {
506       MachineOperand& Op = MInst->getOperand(OpNum);
507       if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
508           Op.getType() ==  MachineOperand::MO_CCRegister)
509         {
510           const Value *const Val =  Op.getVRegValue();
511           if (const LiveRange* LR = LRI.getLiveRangeForValue(Val)) {
512             // Remember if any operand needs spilling
513             instrNeedsSpills |= LR->isMarkedForSpill();
514
515             // An operand may have a color whether or not it needs spilling
516             if (LR->hasColor())
517               MInst->SetRegForOperand(OpNum,
518                           MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
519                                                LR->getColor()));
520           }
521         }
522     } // for each operand
523
524   return instrNeedsSpills;
525 }
526
527 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
528                                     MachineBasicBlock &MBB)
529 {
530   MachineInstr* MInst = *MII;
531   unsigned Opcode = MInst->getOpCode();
532
533   // Reset tmp stack positions so they can be reused for each machine instr.
534   MF.getInfo()->popAllTempValues();  
535
536   // Mark the operands for which regs have been allocated.
537   bool instrNeedsSpills = MarkAllocatedRegs(*MII, LRI, MRI);
538
539 #ifndef NDEBUG
540   // Mark that the operands have been updated.  Later,
541   // setRelRegsUsedByThisInst() is called to find registers used by each
542   // MachineInst, and it should not be used for an instruction until
543   // this is done.  This flag just serves as a sanity check.
544   OperandsColoredMap[MInst] = true;
545 #endif
546
547   // Now insert caller-saving code before/after the call.
548   // Do this before inserting spill code since some registers must be
549   // used by save/restore and spill code should not use those registers.
550   //
551   if (TM.getInstrInfo().isCall(Opcode)) {
552     AddedInstrns &AI = AddedInstrMap[MInst];
553     insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
554                            MBB.getBasicBlock());
555   }
556
557   // Now insert spill code for remaining operands not allocated to
558   // registers.  This must be done even for call return instructions
559   // since those are not handled by the special code above.
560   if (instrNeedsSpills)
561     for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
562       {
563         MachineOperand& Op = MInst->getOperand(OpNum);
564         if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
565             Op.getType() ==  MachineOperand::MO_CCRegister)
566           {
567             const Value* Val = Op.getVRegValue();
568             if (const LiveRange *LR = LRI.getLiveRangeForValue(Val))
569               if (LR->isMarkedForSpill())
570                 insertCode4SpilledLR(LR, MII, MBB, OpNum);
571           }
572       } // for each operand
573 }
574
575 void PhyRegAlloc::updateMachineCode()
576 {
577   // Insert any instructions needed at method entry
578   MachineBasicBlock::iterator MII = MF.front().begin();
579   PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF.front(), MII,
580                       "At function entry: \n");
581   assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
582          "InstrsAfter should be unnecessary since we are just inserting at "
583          "the function entry point here.");
584   
585   for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
586        BBI != BBE; ++BBI) {
587
588     MachineBasicBlock &MBB = *BBI;
589
590     // Iterate over all machine instructions in BB and mark operands with
591     // their assigned registers or insert spill code, as appropriate. 
592     // Also, fix operands of call/return instructions.
593     for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
594       if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
595         updateInstruction(MII, MBB);
596
597     // Now, move code out of delay slots of branches and returns if needed.
598     // (Also, move "after" code from calls to the last delay slot instruction.)
599     // Moving code out of delay slots is needed in 2 situations:
600     // (1) If this is a branch and it needs instructions inserted after it,
601     //     move any existing instructions out of the delay slot so that the
602     //     instructions can go into the delay slot.  This only supports the
603     //     case that #instrsAfter <= #delay slots.
604     // 
605     // (2) If any instruction in the delay slot needs
606     //     instructions inserted, move it out of the delay slot and before the
607     //     branch because putting code before or after it would be VERY BAD!
608     // 
609     // If the annul bit of the branch is set, neither of these is legal!
610     // If so, we need to handle spill differently but annulling is not yet used.
611     //
612     for (MachineBasicBlock::iterator MII = MBB.begin();
613          MII != MBB.end(); ++MII)
614       if (unsigned delaySlots =
615           TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
616         { 
617           MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
618           
619           // Check the 2 conditions above:
620           // (1) Does a branch need instructions added after it?
621           // (2) O/w does delay slot instr. need instrns before or after?
622           bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
623                            TM.getInstrInfo().isReturn(MInst->getOpCode()));
624           bool cond1 = (isBranch &&
625                         AddedInstrMap.count(MInst) &&
626                         AddedInstrMap[MInst].InstrnsAfter.size() > 0);
627           bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
628                         (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
629                          AddedInstrMap[DelaySlotMI].InstrnsAfter.size()  > 0));
630
631           if (cond1 || cond2)
632             {
633               assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
634                      "FIXME: Moving an annulled delay slot instruction!"); 
635               assert(delaySlots==1 &&
636                      "InsertBefore does not yet handle >1 delay slots!");
637               InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
638
639               // In case (1), delete it and don't replace with anything!
640               // Otherwise (i.e., case (2) only) replace it with a NOP.
641               if (cond1) {
642                 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
643                 --MII;                         // reset MII for ++MII of loop
644               }
645               else
646                 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
647                                   MBB, MII+1);        // replace with NOP
648
649               if (DEBUG_RA) {
650                 cerr << "\nRegAlloc: Moved instr. with added code: "
651                      << *DelaySlotMI
652                      << "           out of delay slots of instr: " << *MInst;
653               }
654             }
655           else
656             // For non-branch instr with delay slots (probably a call), move
657             // InstrAfter to the instr. in the last delay slot.
658             move2DelayedInstr(*MII, *(MII+delaySlots));
659         }
660
661     // Finally iterate over all instructions in BB and insert before/after
662     // 
663     for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
664       MachineInstr *MInst = *MII; 
665
666       // do not process Phis
667       if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
668         continue;
669
670       // if there are any added instructions...
671       if (AddedInstrMap.count(MInst)) {
672         AddedInstrns &CallAI = AddedInstrMap[MInst];
673
674 #ifndef NDEBUG
675         bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
676                          TM.getInstrInfo().isReturn(MInst->getOpCode()));
677         assert((!isBranch ||
678                 AddedInstrMap[MInst].InstrnsAfter.size() <=
679                 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
680                "Cannot put more than #delaySlots instrns after "
681                "branch or return! Need to handle temps differently.");
682 #endif
683
684 #ifndef NDEBUG
685         // Temporary sanity checking code to detect whether the same machine
686         // instruction is ever inserted twice before/after a call.
687         // I suspect this is happening but am not sure. --Vikram, 7/1/03.
688         // 
689         std::set<const MachineInstr*> instrsSeen;
690         for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
691           assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
692                  "Duplicate machine instruction in InstrnsBefore!");
693           instrsSeen.insert(CallAI.InstrnsBefore[i]);
694         } 
695         for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
696           assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
697                  "Duplicate machine instruction in InstrnsBefore/After!");
698           instrsSeen.insert(CallAI.InstrnsAfter[i]);
699         } 
700 #endif
701
702         // Now add the instructions before/after this MI.
703         // We do this here to ensure that spill for an instruction is inserted
704         // as close as possible to an instruction (see above insertCode4Spill)
705         //      
706         if (! CallAI.InstrnsBefore.empty())
707           PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
708         
709         if (! CallAI.InstrnsAfter.empty())
710           AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
711
712       } // if there are any added instructions
713
714     } // for each machine instruction
715
716   }
717 }
718
719
720
721 //----------------------------------------------------------------------------
722 // This method inserts spill code for AN operand whose LR was spilled.
723 // This method may be called several times for a single machine instruction
724 // if it contains many spilled operands. Each time it is called, it finds
725 // a register which is not live at that instruction and also which is not
726 // used by other spilled operands of the same instruction. Then it uses
727 // this register temporarily to accomodate the spilled value.
728 //----------------------------------------------------------------------------
729
730 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR, 
731                                        MachineBasicBlock::iterator& MII,
732                                        MachineBasicBlock &MBB,
733                                        const unsigned OpNum) {
734
735   MachineInstr *MInst = *MII;
736   const BasicBlock *BB = MBB.getBasicBlock();
737
738   assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
739          "Outgoing arg of a call must be handled elsewhere (func arg ok)");
740   assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
741          "Return value of a ret must be handled elsewhere");
742
743   MachineOperand& Op = MInst->getOperand(OpNum);
744   bool isDef =  Op.opIsDefOnly();
745   bool isDefAndUse = Op.opIsDefAndUse();
746   unsigned RegType = MRI.getRegTypeForLR(LR);
747   int SpillOff = LR->getSpillOffFromFP();
748   RegClass *RC = LR->getRegClass();
749
750   // Get the live-variable set to find registers free before this instr.
751   const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
752
753 #ifndef NDEBUG
754   // If this instr. is in the delay slot of a branch or return, we need to
755   // include all live variables before that branch or return -- we don't want to
756   // trample those!  Verify that the set is included in the LV set before MInst.
757   // 
758   if (MII != MBB.begin()) {
759     MachineInstr *PredMI = *(MII-1);
760     if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
761       assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
762              .empty() && "Live-var set before branch should be included in "
763              "live-var set of each delay slot instruction!");
764   }
765 #endif
766
767   MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
768   
769   vector<MachineInstr*> MIBef, MIAft;
770   vector<MachineInstr*> AdIMid;
771   
772   // Choose a register to hold the spilled value, if one was not preallocated.
773   // This may insert code before and after MInst to free up the value.  If so,
774   // this code should be first/last in the spill sequence before/after MInst.
775   int TmpRegU=(LR->hasColor()
776                ? MRI.getUnifiedRegNum(LR->getRegClass()->getID(),LR->getColor())
777                : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
778   
779   // Set the operand first so that it this register does not get used
780   // as a scratch register for later calls to getUsableUniRegAtMI below
781   MInst->SetRegForOperand(OpNum, TmpRegU);
782   
783   // get the added instructions for this instruction
784   AddedInstrns &AI = AddedInstrMap[MInst];
785
786   // We may need a scratch register to copy the spilled value to/from memory.
787   // This may itself have to insert code to free up a scratch register.  
788   // Any such code should go before (after) the spill code for a load (store).
789   // The scratch reg is not marked as used because it is only used
790   // for the copy and not used across MInst.
791   int scratchRegType = -1;
792   int scratchReg = -1;
793   if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
794     {
795       scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
796                                        MInst, MIBef, MIAft);
797       assert(scratchReg != MRI.getInvalidRegNum());
798     }
799   
800   if (!isDef || isDefAndUse) {
801     // for a USE, we have to load the value of LR from stack to a TmpReg
802     // and use the TmpReg as one operand of instruction
803     
804     // actual loading instruction(s)
805     MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
806                     RegType, scratchReg);
807     
808     // the actual load should be after the instructions to free up TmpRegU
809     MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
810     AdIMid.clear();
811   }
812   
813   if (isDef || isDefAndUse) {   // if this is a Def
814     // for a DEF, we have to store the value produced by this instruction
815     // on the stack position allocated for this LR
816     
817     // actual storing instruction(s)
818     MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
819                     RegType, scratchReg);
820     
821     MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
822   }  // if !DEF
823   
824   // Finally, insert the entire spill code sequences before/after MInst
825   AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
826   AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
827   
828   if (DEBUG_RA) {
829     cerr << "\nFor Inst:\n  " << *MInst;
830     cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
831     cerr << "; added Instructions:";
832     for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
833     for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
834   }
835 }
836
837
838
839 //----------------------------------------------------------------------------
840 // This method inserts caller saving/restoring instructons before/after
841 // a call machine instruction. The caller saving/restoring instructions are
842 // inserted like:
843 //    ** caller saving instructions
844 //    other instructions inserted for the call by ColorCallArg
845 //    CALL instruction
846 //    other instructions inserted for the call ColorCallArg
847 //    ** caller restoring instructions
848 //----------------------------------------------------------------------------
849
850 void
851 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
852                                     std::vector<MachineInstr*> &instrnsAfter,
853                                     MachineInstr *CallMI, 
854                                     const BasicBlock *BB)
855 {
856   assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
857   
858   // has set to record which registers were saved/restored
859   //
860   hash_set<unsigned> PushedRegSet;
861
862   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
863   
864   // if the call is to a instrumentation function, do not insert save and
865   // restore instructions the instrumentation function takes care of save
866   // restore for volatile regs.
867   //
868   // FIXME: this should be made general, not specific to the reoptimizer!
869   //
870   const Function *Callee = argDesc->getCallInst()->getCalledFunction();
871   bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
872
873   // Now check if the call has a return value (using argDesc) and if so,
874   // find the LR of the TmpInstruction representing the return value register.
875   // (using the last or second-last *implicit operand* of the call MI).
876   // Insert it to to the PushedRegSet since we must not save that register
877   // and restore it after the call.
878   // We do this because, we look at the LV set *after* the instruction
879   // to determine, which LRs must be saved across calls. The return value
880   // of the call is live in this set - but we must not save/restore it.
881   // 
882   if (const Value *origRetVal = argDesc->getReturnValue()) {
883     unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
884                              (argDesc->getIndirectFuncPtr()? 1 : 2));
885     const TmpInstruction* tmpRetVal =
886       cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
887     assert(tmpRetVal->getOperand(0) == origRetVal &&
888            tmpRetVal->getType() == origRetVal->getType() &&
889            "Wrong implicit ref?");
890     LiveRange *RetValLR = LRI.getLiveRangeForValue(tmpRetVal);
891     assert(RetValLR && "No LR for RetValue of call");
892
893     if (! RetValLR->isMarkedForSpill())
894       PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
895                                                RetValLR->getColor()));
896   }
897
898   const ValueSet &LVSetAft =  LVI->getLiveVarSetAfterMInst(CallMI, BB);
899   ValueSet::const_iterator LIt = LVSetAft.begin();
900
901   // for each live var in live variable set after machine inst
902   for( ; LIt != LVSetAft.end(); ++LIt) {
903
904    //  get the live range corresponding to live var
905     LiveRange *const LR = LRI.getLiveRangeForValue(*LIt);    
906
907     // LR can be null if it is a const since a const 
908     // doesn't have a dominating def - see Assumptions above
909     if( LR )   {  
910       
911       if(! LR->isMarkedForSpill()) {
912
913         assert(LR->hasColor() && "LR is neither spilled nor colored?");
914         unsigned RCID = LR->getRegClassID();
915         unsigned Color = LR->getColor();
916
917         if (MRI.isRegVolatile(RCID, Color) ) {
918
919           //if the function is special LLVM function,
920           //And the register is not modified by call, don't save and restore
921           if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
922             continue;
923
924           // if the value is in both LV sets (i.e., live before and after 
925           // the call machine instruction)
926           
927           unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
928           
929           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
930             
931             // if we haven't already pushed that register
932
933             unsigned RegType = MRI.getRegTypeForLR(LR);
934
935             // Now get two instructions - to push on stack and pop from stack
936             // and add them to InstrnsBefore and InstrnsAfter of the
937             // call instruction
938             // 
939             int StackOff =
940               MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
941             
942             //---- Insert code for pushing the reg on stack ----------
943             
944             std::vector<MachineInstr*> AdIBef, AdIAft;
945             
946             // We may need a scratch register to copy the saved value
947             // to/from memory.  This may itself have to insert code to
948             // free up a scratch register.  Any such code should go before
949             // the save code.  The scratch register, if any, is by default
950             // temporary and not "used" by the instruction unless the
951             // copy code itself decides to keep the value in the scratch reg.
952             int scratchRegType = -1;
953             int scratchReg = -1;
954             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
955               { // Find a register not live in the LVSet before CallMI
956                 const ValueSet &LVSetBef =
957                   LVI->getLiveVarSetBeforeMInst(CallMI, BB);
958                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
959                                                  CallMI, AdIBef, AdIAft);
960                 assert(scratchReg != MRI.getInvalidRegNum());
961               }
962             
963             if (AdIBef.size() > 0)
964               instrnsBefore.insert(instrnsBefore.end(),
965                                    AdIBef.begin(), AdIBef.end());
966             
967             MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
968                             StackOff, RegType, scratchReg);
969             
970             if (AdIAft.size() > 0)
971               instrnsBefore.insert(instrnsBefore.end(),
972                                    AdIAft.begin(), AdIAft.end());
973             
974             //---- Insert code for popping the reg from the stack ----------
975
976             AdIBef.clear();
977             AdIAft.clear();
978             
979             // We may need a scratch register to copy the saved value
980             // from memory.  This may itself have to insert code to
981             // free up a scratch register.  Any such code should go
982             // after the save code.  As above, scratch is not marked "used".
983             // 
984             scratchRegType = -1;
985             scratchReg = -1;
986             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
987               { // Find a register not live in the LVSet after CallMI
988                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
989                                                  CallMI, AdIBef, AdIAft);
990                 assert(scratchReg != MRI.getInvalidRegNum());
991               }
992             
993             if (AdIBef.size() > 0)
994               instrnsAfter.insert(instrnsAfter.end(),
995                                   AdIBef.begin(), AdIBef.end());
996             
997             MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
998                             Reg, RegType, scratchReg);
999             
1000             if (AdIAft.size() > 0)
1001               instrnsAfter.insert(instrnsAfter.end(),
1002                                   AdIAft.begin(), AdIAft.end());
1003             
1004             PushedRegSet.insert(Reg);
1005             
1006             if(DEBUG_RA) {
1007               std::cerr << "\nFor call inst:" << *CallMI;
1008               std::cerr << " -inserted caller saving instrs: Before:\n\t ";
1009               for_each(instrnsBefore.begin(), instrnsBefore.end(),
1010                        std::mem_fun(&MachineInstr::dump));
1011               std::cerr << " -and After:\n\t ";
1012               for_each(instrnsAfter.begin(), instrnsAfter.end(),
1013                        std::mem_fun(&MachineInstr::dump));
1014             }       
1015           } // if not already pushed
1016
1017         } // if LR has a volatile color
1018         
1019       } // if LR has color
1020
1021     } // if there is a LR for Var
1022     
1023   } // for each value in the LV set after instruction
1024 }
1025
1026
1027 //----------------------------------------------------------------------------
1028 // We can use the following method to get a temporary register to be used
1029 // BEFORE any given machine instruction. If there is a register available,
1030 // this method will simply return that register and set MIBef = MIAft = NULL.
1031 // Otherwise, it will return a register and MIAft and MIBef will contain
1032 // two instructions used to free up this returned register.
1033 // Returned register number is the UNIFIED register number
1034 //----------------------------------------------------------------------------
1035
1036 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
1037                                      const ValueSet *LVSetBef,
1038                                      MachineInstr *MInst, 
1039                                      std::vector<MachineInstr*>& MIBef,
1040                                      std::vector<MachineInstr*>& MIAft) {
1041   
1042   RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
1043   
1044   int RegU =  getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
1045   
1046   if (RegU == -1) {
1047     // we couldn't find an unused register. Generate code to free up a reg by
1048     // saving it on stack and restoring after the instruction
1049     
1050     int TmpOff = MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
1051     
1052     RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
1053     
1054     // Check if we need a scratch register to copy this register to memory.
1055     int scratchRegType = -1;
1056     if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
1057       {
1058         int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
1059                                              MInst, MIBef, MIAft);
1060         assert(scratchReg != MRI.getInvalidRegNum());
1061         
1062         // We may as well hold the value in the scratch register instead
1063         // of copying it to memory and back.  But we have to mark the
1064         // register as used by this instruction, so it does not get used
1065         // as a scratch reg. by another operand or anyone else.
1066         ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
1067         MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
1068         MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
1069       }
1070     else
1071       { // the register can be copied directly to/from memory so do it.
1072         MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
1073         MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
1074       }
1075   }
1076   
1077   return RegU;
1078 }
1079
1080
1081 //----------------------------------------------------------------------------
1082 // This method is called to get a new unused register that can be used
1083 // to accomodate a temporary value.  This method may be called several times
1084 // for a single machine instruction.  Each time it is called, it finds a
1085 // register which is not live at that instruction and also which is not used
1086 // by other spilled operands of the same instruction.  Return register number
1087 // is relative to the register class, NOT the unified number.
1088 //----------------------------------------------------------------------------
1089
1090 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, 
1091                                      const int RegType,
1092                                      const MachineInstr *MInst,
1093                                      const ValueSet* LVSetBef) {
1094   
1095   RC->clearColorsUsed();     // Reset array
1096
1097   if (LVSetBef == NULL) {
1098       LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
1099       assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
1100   }
1101
1102   ValueSet::const_iterator LIt = LVSetBef->begin();
1103
1104   // for each live var in live variable set after machine inst
1105   for ( ; LIt != LVSetBef->end(); ++LIt) {
1106
1107    //  get the live range corresponding to live var, and its RegClass
1108     LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );    
1109
1110     // LR can be null if it is a const since a const 
1111     // doesn't have a dominating def - see Assumptions above
1112     if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
1113       RC->markColorsUsed(LRofLV->getColor(),
1114                          MRI.getRegTypeForLR(LRofLV), RegType);
1115   }
1116
1117   // It is possible that one operand of this MInst was already spilled
1118   // and it received some register temporarily. If that's the case,
1119   // it is recorded in machine operand. We must skip such registers.
1120   // 
1121   setRelRegsUsedByThisInst(RC, RegType, MInst);
1122
1123   int unusedReg = RC->getUnusedColor(RegType);   // find first unused color
1124   if (unusedReg >= 0)
1125     return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1126
1127   return -1;
1128 }
1129
1130
1131 //----------------------------------------------------------------------------
1132 // Get any other register in a register class, other than what is used
1133 // by operands of a machine instruction. Returns the unified reg number.
1134 //----------------------------------------------------------------------------
1135 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC, 
1136                                             const int RegType,
1137                                             const MachineInstr *MInst) {
1138   RC->clearColorsUsed();
1139
1140   setRelRegsUsedByThisInst(RC, RegType, MInst);
1141
1142   // find the first unused color
1143   int unusedReg = RC->getUnusedColor(RegType);
1144   assert(unusedReg >= 0 &&
1145          "FATAL: No free register could be found in reg class!!");
1146
1147   return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1148 }
1149
1150
1151 //----------------------------------------------------------------------------
1152 // This method modifies the IsColorUsedArr of the register class passed to it.
1153 // It sets the bits corresponding to the registers used by this machine
1154 // instructions. Both explicit and implicit operands are set.
1155 //----------------------------------------------------------------------------
1156
1157 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1158                              const TargetRegInfo &TRI) {
1159   unsigned classId = 0;
1160   int classRegNum = TRI.getClassRegNum(RegNo, classId);
1161   if (RC->getID() == classId)
1162     RC->markColorsUsed(classRegNum, RegType, RegType);
1163 }
1164
1165 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1166                                            const MachineInstr *MI)
1167 {
1168   assert(OperandsColoredMap[MI] == true &&
1169          "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1170          "are marked for an instruction.");
1171
1172   // Add the registers already marked as used by the instruction.
1173   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1174     if (MI->getOperand(i).hasAllocatedReg())
1175       markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1176
1177   for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1178     if (MI->getImplicitOp(i).hasAllocatedReg())
1179       markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1180                        RegType,MRI);
1181
1182   // Add all of the scratch registers that are used to save values across the
1183   // instruction (e.g., for saving state register values).
1184   std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1185     IR = ScratchRegsUsed.equal_range(MI);
1186   for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1187     markRegisterUsed(I->second, RC, RegType, MRI);
1188
1189   // If there are implicit references, mark their allocated regs as well
1190   // 
1191   for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1192     if (const LiveRange*
1193         LRofImpRef = LRI.getLiveRangeForValue(MI->getImplicitRef(z)))    
1194       if (LRofImpRef->hasColor())
1195         // this implicit reference is in a LR that received a color
1196         RC->markColorsUsed(LRofImpRef->getColor(),
1197                            MRI.getRegTypeForLR(LRofImpRef), RegType);
1198 }
1199
1200
1201 //----------------------------------------------------------------------------
1202 // If there are delay slots for an instruction, the instructions
1203 // added after it must really go after the delayed instruction(s).
1204 // So, we move the InstrAfter of that instruction to the 
1205 // corresponding delayed instruction using the following method.
1206 //----------------------------------------------------------------------------
1207
1208 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1209                                     const MachineInstr *DelayedMI)
1210 {
1211   // "added after" instructions of the original instr
1212   std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1213
1214   if (DEBUG_RA && OrigAft.size() > 0) {
1215     cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1216     cerr << "         to last delay slot instrn: " << *DelayedMI;
1217   }
1218
1219   // "added after" instructions of the delayed instr
1220   std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1221
1222   // go thru all the "added after instructions" of the original instruction
1223   // and append them to the "added after instructions" of the delayed
1224   // instructions
1225   DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1226
1227   // empty the "added after instructions" of the original instruction
1228   OrigAft.clear();
1229 }
1230
1231 //----------------------------------------------------------------------------
1232 // This method prints the code with registers after register allocation is
1233 // complete.
1234 //----------------------------------------------------------------------------
1235 void PhyRegAlloc::printMachineCode()
1236 {
1237
1238   cerr << "\n;************** Function " << Fn->getName()
1239        << " *****************\n";
1240
1241   for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
1242        BBI != BBE; ++BBI) {
1243     cerr << "\n"; printLabel(BBI->getBasicBlock()); cerr << ": ";
1244
1245     // get the iterator for machine instructions
1246     MachineBasicBlock& MBB = *BBI;
1247     MachineBasicBlock::iterator MII = MBB.begin();
1248
1249     // iterate over all the machine instructions in BB
1250     for ( ; MII != MBB.end(); ++MII) {  
1251       MachineInstr *MInst = *MII; 
1252
1253       cerr << "\n\t";
1254       cerr << TM.getInstrInfo().getName(MInst->getOpCode());
1255
1256       for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
1257         MachineOperand& Op = MInst->getOperand(OpNum);
1258
1259         if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
1260             Op.getType() ==  MachineOperand::MO_CCRegister /*|| 
1261             Op.getType() ==  MachineOperand::MO_PCRelativeDisp*/ ) {
1262
1263           const Value *const Val = Op.getVRegValue () ;
1264           // ****this code is temporary till NULL Values are fixed
1265           if (! Val ) {
1266             cerr << "\t<*NULL*>";
1267             continue;
1268           }
1269
1270           // if a label or a constant
1271           if (isa<BasicBlock>(Val)) {
1272             cerr << "\t"; printLabel(   Op.getVRegValue () );
1273           } else {
1274             // else it must be a register value
1275             const int RegNum = Op.getAllocatedRegNum();
1276
1277             cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1278             if (Val->hasName() )
1279               cerr << "(" << Val->getName() << ")";
1280             else 
1281               cerr << "(" << Val << ")";
1282
1283             if (Op.opIsDefOnly() || Op.opIsDefAndUse())
1284               cerr << "*";
1285
1286             const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1287             if (LROfVal )
1288               if (LROfVal->hasSpillOffset() )
1289                 cerr << "$";
1290           }
1291
1292         } 
1293         else if (Op.getType() ==  MachineOperand::MO_MachineRegister) {
1294           cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1295         }
1296
1297         else 
1298           cerr << "\t" << Op;      // use dump field
1299       }
1300
1301     
1302
1303       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
1304       if (NumOfImpRefs > 0) {
1305         cerr << "\tImplicit:";
1306
1307         for (unsigned z=0; z < NumOfImpRefs; z++)
1308           cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1309       }
1310
1311     } // for all machine instructions
1312
1313     cerr << "\n";
1314
1315   } // for all BBs
1316
1317   cerr << "\n";
1318 }
1319
1320
1321 //----------------------------------------------------------------------------
1322
1323 //----------------------------------------------------------------------------
1324 void PhyRegAlloc::colorIncomingArgs()
1325 {
1326   MRI.colorMethodArgs(Fn, LRI, AddedInstrAtEntry.InstrnsBefore,
1327                       AddedInstrAtEntry.InstrnsAfter);
1328 }
1329
1330
1331 //----------------------------------------------------------------------------
1332 // Used to generate a label for a basic block
1333 //----------------------------------------------------------------------------
1334 void PhyRegAlloc::printLabel(const Value *Val) {
1335   if (Val->hasName())
1336     cerr  << Val->getName();
1337   else
1338     cerr << "Label" << Val;
1339 }
1340
1341
1342 //----------------------------------------------------------------------------
1343 // This method calls setSugColorUsable method of each live range. This
1344 // will determine whether the suggested color of LR is  really usable.
1345 // A suggested color is not usable when the suggested color is volatile
1346 // AND when there are call interferences
1347 //----------------------------------------------------------------------------
1348
1349 void PhyRegAlloc::markUnusableSugColors()
1350 {
1351   // hash map iterator
1352   LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
1353   LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
1354
1355     for (; HMI != HMIEnd ; ++HMI ) {
1356       if (HMI->first) { 
1357         LiveRange *L = HMI->second;      // get the LiveRange
1358         if (L) { 
1359           if (L->hasSuggestedColor()) {
1360             int RCID = L->getRegClass()->getID();
1361             if (MRI.isRegVolatile( RCID,  L->getSuggestedColor()) &&
1362                 L->isCallInterference() )
1363               L->setSuggestedColorUsable( false );
1364             else
1365               L->setSuggestedColorUsable( true );
1366           }
1367         } // if L->hasSuggestedColor()
1368       }
1369     } // for all LR's in hash map
1370 }
1371
1372
1373
1374 //----------------------------------------------------------------------------
1375 // The following method will set the stack offsets of the live ranges that
1376 // are decided to be spillled. This must be called just after coloring the
1377 // LRs using the graph coloring algo. For each live range that is spilled,
1378 // this method allocate a new spill position on the stack.
1379 //----------------------------------------------------------------------------
1380
1381 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1382   if (DEBUG_RA) cerr << "\nSetting LR stack offsets for spills...\n";
1383
1384   LiveRangeMapType::const_iterator HMI    = LRI.getLiveRangeMap()->begin();   
1385   LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();   
1386
1387   for ( ; HMI != HMIEnd ; ++HMI) {
1388     if (HMI->first && HMI->second) {
1389       LiveRange *L = HMI->second;       // get the LiveRange
1390       if (L->isMarkedForSpill()) {      // NOTE: allocating size of long Type **
1391         int stackOffset = MF.getInfo()->allocateSpilledValue(Type::LongTy);
1392         L->setSpillOffFromFP(stackOffset);
1393         if (DEBUG_RA)
1394           cerr << "  LR# " << L->getUserIGNode()->getIndex()
1395                << ": stack-offset = " << stackOffset << "\n";
1396       }
1397     }
1398   } // for all LR's in hash map
1399 }
1400
1401
1402 //----------------------------------------------------------------------------
1403 // The entry pont to Register Allocation
1404 //----------------------------------------------------------------------------
1405
1406 void PhyRegAlloc::allocateRegisters()
1407 {
1408
1409   // make sure that we put all register classes into the RegClassList 
1410   // before we call constructLiveRanges (now done in the constructor of 
1411   // PhyRegAlloc class).
1412   //
1413   LRI.constructLiveRanges();            // create LR info
1414
1415   if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1416     LRI.printLiveRanges();
1417   
1418   createIGNodeListsAndIGs();            // create IGNode list and IGs
1419
1420   buildInterferenceGraphs();            // build IGs in all reg classes
1421   
1422   
1423   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1424     // print all LRs in all reg classes
1425     for ( unsigned rc=0; rc < NumOfRegClasses  ; rc++)  
1426       RegClassList[rc]->printIGNodeList(); 
1427     
1428     // print IGs in all register classes
1429     for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1430       RegClassList[rc]->printIG();       
1431   }
1432
1433   LRI.coalesceLRs();                    // coalesce all live ranges
1434
1435   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1436     // print all LRs in all reg classes
1437     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1438       RegClassList[rc]->printIGNodeList();
1439     
1440     // print IGs in all register classes
1441     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1442       RegClassList[rc]->printIG();
1443   }
1444
1445
1446   // mark un-usable suggested color before graph coloring algorithm.
1447   // When this is done, the graph coloring algo will not reserve
1448   // suggested color unnecessarily - they can be used by another LR
1449   //
1450   markUnusableSugColors(); 
1451
1452   // color all register classes using the graph coloring algo
1453   for (unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1454     RegClassList[rc]->colorAllRegs();    
1455
1456   // Atter graph coloring, if some LRs did not receive a color (i.e, spilled)
1457   // a poistion for such spilled LRs
1458   //
1459   allocateStackSpace4SpilledLRs();
1460
1461   // Reset the temp. area on the stack before use by the first instruction.
1462   // This will also happen after updating each instruction.
1463   MF.getInfo()->popAllTempValues();
1464
1465   // color incoming args - if the correct color was not received
1466   // insert code to copy to the correct register
1467   //
1468   colorIncomingArgs();
1469
1470   // Now update the machine code with register names and add any 
1471   // additional code inserted by the register allocator to the instruction
1472   // stream
1473   //
1474   updateMachineCode(); 
1475
1476   if (DEBUG_RA) {
1477     cerr << "\n**** Machine Code After Register Allocation:\n\n";
1478     MF.dump();
1479   }
1480 }
1481
1482
1483