Include appropriate file
[oota-llvm.git] / lib / Target / SparcV9 / RegAlloc / PhyRegAlloc.cpp
1 // $Id$
2 //***************************************************************************
3 // File:
4 //      PhyRegAlloc.cpp
5 // 
6 // Purpose:
7 //      Register allocation for LLVM.
8 //      
9 // History:
10 //      9/10/01  -  Ruchira Sasanka - created.
11 //**************************************************************************/
12
13 #include "llvm/CodeGen/RegisterAllocation.h"
14 #include "llvm/CodeGen/PhyRegAlloc.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineCodeForMethod.h"
17 #include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/MachineFrameInfo.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Function.h"
23 #include "llvm/Type.h"
24 #include <iostream>
25 #include <math.h>
26 using std::cerr;
27
28
29 // ***TODO: There are several places we add instructions. Validate the order
30 //          of adding these instructions.
31
32 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
33   "enable register allocation debugging information",
34   clEnumValN(RA_DEBUG_None   , "n", "disable debug output"),
35   clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
36   clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
37
38
39 //----------------------------------------------------------------------------
40 // RegisterAllocation pass front end...
41 //----------------------------------------------------------------------------
42 namespace {
43   class RegisterAllocator : public FunctionPass {
44     TargetMachine &Target;
45   public:
46     inline RegisterAllocator(TargetMachine &T) : Target(T) {}
47     
48     bool runOnFunction(Function *F) {
49       if (DEBUG_RA)
50         cerr << "\n******************** Function "<< F->getName()
51              << " ********************\n";
52       
53       PhyRegAlloc PRA(F, Target, &getAnalysis<FunctionLiveVarInfo>(),
54                       &getAnalysis<LoopInfo>());
55       PRA.allocateRegisters();
56       
57       if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
58       return false;
59     }
60
61     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62       AU.addRequired(LoopInfo::ID);
63       AU.addRequired(FunctionLiveVarInfo::ID);
64     }
65   };
66 }
67
68 Pass *getRegisterAllocator(TargetMachine &T) {
69   return new RegisterAllocator(T);
70 }
71
72 //----------------------------------------------------------------------------
73 // Constructor: Init local composite objects and create register classes.
74 //----------------------------------------------------------------------------
75 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm, 
76                          FunctionLiveVarInfo *Lvi, LoopInfo *LDC) 
77                        :  TM(tm), Meth(F),
78                           mcInfo(MachineCodeForMethod::get(F)),
79                           LVI(Lvi), LRI(F, tm, RegClassList), 
80                           MRI(tm.getRegInfo()),
81                           NumOfRegClasses(MRI.getNumOfRegClasses()),
82                           LoopDepthCalc(LDC) {
83
84   // create each RegisterClass and put in RegClassList
85   //
86   for(unsigned int rc=0; rc < NumOfRegClasses; rc++)  
87     RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
88                                         &ResColList));
89 }
90
91
92 //----------------------------------------------------------------------------
93 // Destructor: Deletes register classes
94 //----------------------------------------------------------------------------
95 PhyRegAlloc::~PhyRegAlloc() { 
96   for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
97     delete RegClassList[rc];
98
99   AddedInstrMap.clear();
100
101
102 //----------------------------------------------------------------------------
103 // This method initally creates interference graphs (one in each reg class)
104 // and IGNodeList (one in each IG). The actual nodes will be pushed later. 
105 //----------------------------------------------------------------------------
106 void PhyRegAlloc::createIGNodeListsAndIGs() {
107   if (DEBUG_RA) cerr << "Creating LR lists ...\n";
108
109   // hash map iterator
110   LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();   
111
112   // hash map end
113   LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();   
114
115   for (; HMI != HMIEnd ; ++HMI ) {
116     if (HMI->first) { 
117       LiveRange *L = HMI->second;   // get the LiveRange
118       if (!L) { 
119         if( DEBUG_RA) {
120           cerr << "\n*?!?Warning: Null liver range found for: "
121                << RAV(HMI->first) << "\n";
122         }
123         continue;
124       }
125                                         // if the Value * is not null, and LR  
126                                         // is not yet written to the IGNodeList
127       if( !(L->getUserIGNode())  ) {  
128         RegClass *const RC =           // RegClass of first value in the LR
129           RegClassList[ L->getRegClass()->getID() ];
130         
131         RC->addLRToIG(L);              // add this LR to an IG
132       }
133     }
134   }
135     
136   // init RegClassList
137   for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
138     RegClassList[rc]->createInterferenceGraph();
139
140   if( DEBUG_RA)
141     cerr << "LRLists Created!\n";
142 }
143
144
145
146
147 //----------------------------------------------------------------------------
148 // This method will add all interferences at for a given instruction.
149 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg 
150 // class as that of live var. The live var passed to this function is the 
151 // LVset AFTER the instruction
152 //----------------------------------------------------------------------------
153 void PhyRegAlloc::addInterference(const Value *Def, 
154                                   const ValueSet *LVSet,
155                                   bool isCallInst) {
156
157   ValueSet::const_iterator LIt = LVSet->begin();
158
159   // get the live range of instruction
160   //
161   const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );   
162
163   IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
164   assert( IGNodeOfDef );
165
166   RegClass *const RCOfDef = LROfDef->getRegClass(); 
167
168   // for each live var in live variable set
169   //
170   for( ; LIt != LVSet->end(); ++LIt) {
171
172     if (DEBUG_RA > 1)
173       cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
174
175     //  get the live range corresponding to live var
176     //
177     LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
178
179     // LROfVar can be null if it is a const since a const 
180     // doesn't have a dominating def - see Assumptions above
181     //
182     if (LROfVar) {  
183       if(LROfDef == LROfVar)            // do not set interf for same LR
184         continue;
185
186       // if 2 reg classes are the same set interference
187       //
188       if (RCOfDef == LROfVar->getRegClass()) {
189         RCOfDef->setInterference( LROfDef, LROfVar);  
190       } else if (DEBUG_RA > 1)  { 
191         // we will not have LRs for values not explicitly allocated in the
192         // instruction stream (e.g., constants)
193         cerr << " warning: no live range for " << RAV(*LIt) << "\n";
194       }
195     }
196   }
197 }
198
199
200
201 //----------------------------------------------------------------------------
202 // For a call instruction, this method sets the CallInterference flag in 
203 // the LR of each variable live int the Live Variable Set live after the
204 // call instruction (except the return value of the call instruction - since
205 // the return value does not interfere with that call itself).
206 //----------------------------------------------------------------------------
207
208 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst, 
209                                        const ValueSet *LVSetAft) {
210
211   if( DEBUG_RA)
212     cerr << "\n For call inst: " << *MInst;
213
214   ValueSet::const_iterator LIt = LVSetAft->begin();
215
216   // for each live var in live variable set after machine inst
217   //
218   for( ; LIt != LVSetAft->end(); ++LIt) {
219
220     //  get the live range corresponding to live var
221     //
222     LiveRange *const LR = LRI.getLiveRangeForValue(*LIt ); 
223
224     if( LR && DEBUG_RA) {
225       cerr << "\n\tLR Aft Call: ";
226       printSet(*LR);
227     }
228    
229     // LR can be null if it is a const since a const 
230     // doesn't have a dominating def - see Assumptions above
231     //
232     if( LR )   {  
233       LR->setCallInterference();
234       if( DEBUG_RA) {
235         cerr << "\n  ++Added call interf for LR: " ;
236         printSet(*LR);
237       }
238     }
239
240   }
241
242   // Now find the LR of the return value of the call
243   // We do this because, we look at the LV set *after* the instruction
244   // to determine, which LRs must be saved across calls. The return value
245   // of the call is live in this set - but it does not interfere with call
246   // (i.e., we can allocate a volatile register to the return value)
247   //
248   if( const Value *RetVal = MRI.getCallInstRetVal( MInst )) {
249     LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
250     assert( RetValLR && "No LR for RetValue of call");
251     RetValLR->clearCallInterference();
252   }
253
254   // If the CALL is an indirect call, find the LR of the function pointer.
255   // That has a call interference because it conflicts with outgoing args.
256   if( const Value *AddrVal = MRI.getCallInstIndirectAddrVal( MInst )) {
257     LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
258     assert( AddrValLR && "No LR for indirect addr val of call");
259     AddrValLR->setCallInterference();
260   }
261
262 }
263
264
265
266
267 //----------------------------------------------------------------------------
268 // This method will walk thru code and create interferences in the IG of
269 // each RegClass. Also, this method calculates the spill cost of each
270 // Live Range (it is done in this method to save another pass over the code).
271 //----------------------------------------------------------------------------
272 void PhyRegAlloc::buildInterferenceGraphs()
273 {
274
275   if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
276
277   unsigned BBLoopDepthCost;
278   for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
279        BBI != BBE; ++BBI) {
280
281     // find the 10^(loop_depth) of this BB 
282     //
283     BBLoopDepthCost = (unsigned) pow(10.0, LoopDepthCalc->getLoopDepth(*BBI));
284
285     // get the iterator for machine instructions
286     //
287     const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
288     MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
289
290     // iterate over all the machine instructions in BB
291     //
292     for( ; MII != MIVec.end(); ++MII) {  
293
294       const MachineInstr *MInst = *MII; 
295
296       // get the LV set after the instruction
297       //
298       const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
299     
300       const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
301
302       if( isCallInst ) {
303         // set the isCallInterference flag of each live range wich extends
304         // accross this call instruction. This information is used by graph
305         // coloring algo to avoid allocating volatile colors to live ranges
306         // that span across calls (since they have to be saved/restored)
307         //
308         setCallInterferences(MInst, &LVSetAI);
309       }
310
311
312       // iterate over all MI operands to find defs
313       //
314       for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
315              OpE = MInst->end(); OpI != OpE; ++OpI) {
316         if (OpI.isDef())    // create a new LR iff this operand is a def
317           addInterference(*OpI, &LVSetAI, isCallInst);
318
319         // Calculate the spill cost of each live range
320         //
321         LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
322         if (LR) LR->addSpillCost(BBLoopDepthCost);
323       } 
324
325
326       // if there are multiple defs in this instruction e.g. in SETX
327       //   
328       if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
329         addInterf4PseudoInstr(MInst);
330
331
332       // Also add interference for any implicit definitions in a machine
333       // instr (currently, only calls have this).
334       //
335       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
336       if(  NumOfImpRefs > 0 ) {
337         for(unsigned z=0; z < NumOfImpRefs; z++) 
338           if( MInst->implicitRefIsDefined(z) )
339             addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
340       }
341
342
343     } // for all machine instructions in BB
344   } // for all BBs in function
345
346
347   // add interferences for function arguments. Since there are no explict 
348   // defs in the function for args, we have to add them manually
349   //  
350   addInterferencesForArgs();          
351
352   if( DEBUG_RA)
353     cerr << "Interference graphs calculted!\n";
354
355 }
356
357
358
359 //--------------------------------------------------------------------------
360 // Pseudo instructions will be exapnded to multiple instructions by the
361 // assembler. Consequently, all the opernds must get distinct registers.
362 // Therefore, we mark all operands of a pseudo instruction as they interfere
363 // with one another.
364 //--------------------------------------------------------------------------
365 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
366
367   bool setInterf = false;
368
369   // iterate over  MI operands to find defs
370   //
371   for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
372          ItE = MInst->end(); It1 != ItE; ++It1) {
373     const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1); 
374     assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
375
376     MachineInstr::const_val_op_iterator It2 = It1;
377     for(++It2; It2 != ItE; ++It2) {
378       const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2); 
379
380       if (LROfOp2) {
381         RegClass *RCOfOp1 = LROfOp1->getRegClass(); 
382         RegClass *RCOfOp2 = LROfOp2->getRegClass(); 
383  
384         if( RCOfOp1 == RCOfOp2 ){ 
385           RCOfOp1->setInterference( LROfOp1, LROfOp2 );  
386           setInterf = true;
387         }
388       } // if Op2 has a LR
389     } // for all other defs in machine instr
390   } // for all operands in an instruction
391
392   if (!setInterf && MInst->getNumOperands() > 2) {
393     cerr << "\nInterf not set for any operand in pseudo instr:\n";
394     cerr << *MInst;
395     assert(0 && "Interf not set for pseudo instr with > 2 operands" );
396   }
397
398
399
400
401 //----------------------------------------------------------------------------
402 // This method will add interferences for incoming arguments to a function.
403 //----------------------------------------------------------------------------
404 void PhyRegAlloc::addInterferencesForArgs() {
405   // get the InSet of root BB
406   const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());  
407
408   // get the argument list
409   const Function::ArgumentListType &ArgList = Meth->getArgumentList();  
410
411   // get an iterator to arg list
412   Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();          
413
414
415   for( ; ArgIt != ArgList.end() ; ++ArgIt) {  // for each argument
416     addInterference((Value*)*ArgIt, &InSet, false);// add interferences between 
417                                               // args and LVars at start
418     if( DEBUG_RA > 1)
419       cerr << " - %% adding interference for  argument "
420            << RAV((const Value *)*ArgIt) << "\n";
421   }
422 }
423
424
425 //----------------------------------------------------------------------------
426 // This method is called after register allocation is complete to set the
427 // allocated reisters in the machine code. This code will add register numbers
428 // to MachineOperands that contain a Value. Also it calls target specific
429 // methods to produce caller saving instructions. At the end, it adds all
430 // additional instructions produced by the register allocator to the 
431 // instruction stream. 
432 //----------------------------------------------------------------------------
433
434 //-----------------------------
435 // Utility functions used below
436 //-----------------------------
437 inline void
438 PrependInstructions(std::deque<MachineInstr *> &IBef,
439                     MachineCodeForBasicBlock& MIVec,
440                     MachineCodeForBasicBlock::iterator& MII,
441                     const std::string& msg)
442 {
443   if (!IBef.empty())
444     {
445       MachineInstr* OrigMI = *MII;
446       std::deque<MachineInstr *>::iterator AdIt; 
447       for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
448         {
449           if (DEBUG_RA) {
450             if (OrigMI) cerr << "For MInst: " << *OrigMI;
451             cerr << msg << " PREPENDed instr: " << **AdIt << "\n";
452           }
453           MII = MIVec.insert(MII, *AdIt);
454           ++MII;
455         }
456     }
457 }
458
459 inline void
460 AppendInstructions(std::deque<MachineInstr *> &IAft,
461                    MachineCodeForBasicBlock& MIVec,
462                    MachineCodeForBasicBlock::iterator& MII,
463                    const std::string& msg)
464 {
465   if (!IAft.empty())
466     {
467       MachineInstr* OrigMI = *MII;
468       std::deque<MachineInstr *>::iterator AdIt; 
469       for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
470         {
471           if(DEBUG_RA) {
472             if (OrigMI) cerr << "For MInst: " << *OrigMI;
473             cerr << msg << " APPENDed instr: "  << **AdIt << "\n";
474           }
475           ++MII;    // insert before the next instruction
476           MII = MIVec.insert(MII, *AdIt);
477         }
478     }
479 }
480
481
482 void PhyRegAlloc::updateMachineCode()
483 {
484   const BasicBlock* entryBB = Meth->getEntryNode();
485   if (entryBB) {
486     MachineCodeForBasicBlock& MIVec = entryBB->getMachineInstrVec();
487     MachineCodeForBasicBlock::iterator MII = MIVec.begin();
488     
489     // Insert any instructions needed at method entry
490     PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
491                         "At function entry: \n");
492     assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
493            "InstrsAfter should be unnecessary since we are just inserting at "
494            "the function entry point here.");
495   }
496   
497   for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
498        BBI != BBE; ++BBI) {
499     
500     // iterate over all the machine instructions in BB
501     MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
502     for(MachineCodeForBasicBlock::iterator MII = MIVec.begin();
503         MII != MIVec.end(); ++MII) {  
504       
505       MachineInstr *MInst = *MII; 
506       
507       unsigned Opcode =  MInst->getOpCode();
508     
509       // do not process Phis
510       if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
511         continue;
512
513       // Now insert speical instructions (if necessary) for call/return
514       // instructions. 
515       //
516       if (TM.getInstrInfo().isCall(Opcode) ||
517           TM.getInstrInfo().isReturn(Opcode)) {
518
519         AddedInstrns &AI = AddedInstrMap[MInst];
520         
521         // Tmp stack poistions are needed by some calls that have spilled args
522         // So reset it before we call each such method
523         //
524         mcInfo.popAllTempValues(TM);  
525         
526         if (TM.getInstrInfo().isCall(Opcode))
527           MRI.colorCallArgs(MInst, LRI, &AI, *this, *BBI);
528         else if (TM.getInstrInfo().isReturn(Opcode))
529           MRI.colorRetValue(MInst, LRI, &AI);
530       }
531       
532
533       /* -- Using above code instead of this
534
535       // if this machine instr is call, insert caller saving code
536
537       if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
538         MRI.insertCallerSavingCode(MInst,  *BBI, *this );
539         
540       */
541
542       
543       // reset the stack offset for temporary variables since we may
544       // need that to spill
545       // mcInfo.popAllTempValues(TM);
546       // TODO ** : do later
547       
548       //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
549
550
551       // Now replace set the registers for operands in the machine instruction
552       //
553       for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
554
555         MachineOperand& Op = MInst->getOperand(OpNum);
556
557         if( Op.getOperandType() ==  MachineOperand::MO_VirtualRegister || 
558             Op.getOperandType() ==  MachineOperand::MO_CCRegister) {
559
560           const Value *const Val =  Op.getVRegValue();
561
562           // delete this condition checking later (must assert if Val is null)
563           if( !Val) {
564             if (DEBUG_RA)
565               cerr << "Warning: NULL Value found for operand\n";
566             continue;
567           }
568           assert( Val && "Value is NULL");   
569
570           LiveRange *const LR = LRI.getLiveRangeForValue(Val);
571
572           if ( !LR ) {
573
574             // nothing to worry if it's a const or a label
575
576             if (DEBUG_RA) {
577               cerr << "*NO LR for operand : " << Op ;
578               cerr << " [reg:" <<  Op.getAllocatedRegNum() << "]";
579               cerr << " in inst:\t" << *MInst << "\n";
580             }
581
582             // if register is not allocated, mark register as invalid
583             if( Op.getAllocatedRegNum() == -1)
584               Op.setRegForValue( MRI.getInvalidRegNum()); 
585             
586
587             continue;
588           }
589         
590           unsigned RCID = (LR->getRegClass())->getID();
591
592           if( LR->hasColor() ) {
593             Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
594           }
595           else {
596
597             // LR did NOT receive a color (register). Now, insert spill code
598             // for spilled opeands in this machine instruction
599
600             //assert(0 && "LR must be spilled");
601             insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
602
603           }
604         }
605
606       } // for each operand
607
608
609       // Now add instructions that the register allocator inserts before/after 
610       // this machine instructions (done only for calls/rets/incoming args)
611       // We do this here, to ensure that spill for an instruction is inserted
612       // closest as possible to an instruction (see above insertCode4Spill...)
613       // 
614       // If there are instructions to be added, *before* this machine
615       // instruction, add them now.
616       //      
617       if(AddedInstrMap.count(MInst)) {
618         PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
619       }
620       
621       // If there are instructions to be added *after* this machine
622       // instruction, add them now
623       //
624       if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
625
626         // if there are delay slots for this instruction, the instructions
627         // added after it must really go after the delayed instruction(s)
628         // So, we move the InstrAfter of the current instruction to the 
629         // corresponding delayed instruction
630         
631         unsigned delay;
632         if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){ 
633           move2DelayedInstr(MInst,  *(MII+delay) );
634
635           if(DEBUG_RA)  cerr<< "\nMoved an added instr after the delay slot";
636         }
637        
638         else {
639           // Here we can add the "instructions after" to the current
640           // instruction since there are no delay slots for this instruction
641           AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
642         }  // if not delay
643         
644       }
645       
646     } // for each machine instruction
647   }
648 }
649
650
651
652 //----------------------------------------------------------------------------
653 // This method inserts spill code for AN operand whose LR was spilled.
654 // This method may be called several times for a single machine instruction
655 // if it contains many spilled operands. Each time it is called, it finds
656 // a register which is not live at that instruction and also which is not
657 // used by other spilled operands of the same instruction. Then it uses
658 // this register temporarily to accomodate the spilled value.
659 //----------------------------------------------------------------------------
660 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR, 
661                                        MachineInstr *MInst,
662                                        const BasicBlock *BB,
663                                        const unsigned OpNum) {
664
665   assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
666          (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
667          "Arg of a call/ret must be handled elsewhere");
668
669   MachineOperand& Op = MInst->getOperand(OpNum);
670   bool isDef =  MInst->operandIsDefined(OpNum);
671   unsigned RegType = MRI.getRegType( LR );
672   int SpillOff = LR->getSpillOffFromFP();
673   RegClass *RC = LR->getRegClass();
674   const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
675
676   mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
677   
678   MachineInstr *MIBef=NULL,  *AdIMid=NULL, *MIAft=NULL;
679   
680   int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
681   
682   // get the added instructions for this instruciton
683   AddedInstrns &AI = AddedInstrMap[MInst];
684     
685   if (!isDef) {
686     // for a USE, we have to load the value of LR from stack to a TmpReg
687     // and use the TmpReg as one operand of instruction
688
689     // actual loading instruction
690     AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
691
692     if(MIBef)
693       AI.InstrnsBefore.push_back(MIBef);
694
695     AI.InstrnsBefore.push_back(AdIMid);
696
697     if(MIAft)
698       AI.InstrnsAfter.push_front(MIAft);
699     
700   } else {   // if this is a Def
701     // for a DEF, we have to store the value produced by this instruction
702     // on the stack position allocated for this LR
703
704     // actual storing instruction
705     AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
706
707     if (MIBef)
708       AI.InstrnsBefore.push_back(MIBef);
709
710     AI.InstrnsAfter.push_front(AdIMid);
711
712     if (MIAft)
713       AI.InstrnsAfter.push_front(MIAft);
714
715   }  // if !DEF
716
717   cerr << "\nFor Inst " << *MInst;
718   cerr << " - SPILLED LR: "; printSet(*LR);
719   cerr << "\n - Added Instructions:";
720   if (MIBef) cerr <<  *MIBef;
721   cerr <<  *AdIMid;
722   if (MIAft) cerr <<  *MIAft;
723
724   Op.setRegForValue(TmpRegU);    // set the opearnd
725 }
726
727
728
729 //----------------------------------------------------------------------------
730 // We can use the following method to get a temporary register to be used
731 // BEFORE any given machine instruction. If there is a register available,
732 // this method will simply return that register and set MIBef = MIAft = NULL.
733 // Otherwise, it will return a register and MIAft and MIBef will contain
734 // two instructions used to free up this returned register.
735 // Returned register number is the UNIFIED register number
736 //----------------------------------------------------------------------------
737
738 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC, 
739                                   const int RegType,
740                                   const MachineInstr *MInst, 
741                                   const ValueSet *LVSetBef,
742                                   MachineInstr *&MIBef,
743                                   MachineInstr *&MIAft) {
744
745   int RegU =  getUnusedUniRegAtMI(RC, MInst, LVSetBef);
746
747
748   if( RegU != -1) {
749     // we found an unused register, so we can simply use it
750     MIBef = MIAft = NULL;
751   }
752   else {
753     // we couldn't find an unused register. Generate code to free up a reg by
754     // saving it on stack and restoring after the instruction
755
756     int TmpOff = mcInfo.pushTempValue(TM,  MRI.getSpilledRegSize(RegType) );
757     
758     RegU = getUniRegNotUsedByThisInst(RC, MInst);
759     MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
760     MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
761   }
762
763   return RegU;
764 }
765
766 //----------------------------------------------------------------------------
767 // This method is called to get a new unused register that can be used to
768 // accomodate a spilled value. 
769 // This method may be called several times for a single machine instruction
770 // if it contains many spilled operands. Each time it is called, it finds
771 // a register which is not live at that instruction and also which is not
772 // used by other spilled operands of the same instruction.
773 // Return register number is relative to the register class. NOT
774 // unified number
775 //----------------------------------------------------------------------------
776 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, 
777                                   const MachineInstr *MInst, 
778                                   const ValueSet *LVSetBef) {
779
780   unsigned NumAvailRegs =  RC->getNumOfAvailRegs();
781   
782   bool *IsColorUsedArr = RC->getIsColorUsedArr();
783   
784   for(unsigned i=0; i <  NumAvailRegs; i++)     // Reset array
785       IsColorUsedArr[i] = false;
786       
787   ValueSet::const_iterator LIt = LVSetBef->begin();
788
789   // for each live var in live variable set after machine inst
790   for( ; LIt != LVSetBef->end(); ++LIt) {
791
792    //  get the live range corresponding to live var
793     LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );    
794
795     // LR can be null if it is a const since a const 
796     // doesn't have a dominating def - see Assumptions above
797     if( LRofLV )     
798       if( LRofLV->hasColor() ) 
799         IsColorUsedArr[ LRofLV->getColor() ] = true;
800   }
801
802   // It is possible that one operand of this MInst was already spilled
803   // and it received some register temporarily. If that's the case,
804   // it is recorded in machine operand. We must skip such registers.
805
806   setRelRegsUsedByThisInst(RC, MInst);
807
808   unsigned c;                         // find first unused color
809   for( c=0; c < NumAvailRegs; c++)  
810      if( ! IsColorUsedArr[ c ] ) break;
811    
812   if(c < NumAvailRegs) 
813     return  MRI.getUnifiedRegNum(RC->getID(), c);
814   else 
815     return -1;
816
817
818 }
819
820
821 //----------------------------------------------------------------------------
822 // Get any other register in a register class, other than what is used
823 // by operands of a machine instruction. Returns the unified reg number.
824 //----------------------------------------------------------------------------
825 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC, 
826                                          const MachineInstr *MInst) {
827
828   bool *IsColorUsedArr = RC->getIsColorUsedArr();
829   unsigned NumAvailRegs =  RC->getNumOfAvailRegs();
830
831
832   for(unsigned i=0; i < NumAvailRegs ; i++)   // Reset array
833     IsColorUsedArr[i] = false;
834
835   setRelRegsUsedByThisInst(RC, MInst);
836
837   unsigned c;                         // find first unused color
838   for( c=0; c <  RC->getNumOfAvailRegs(); c++)  
839      if( ! IsColorUsedArr[ c ] ) break;
840    
841   if(c < NumAvailRegs) 
842     return  MRI.getUnifiedRegNum(RC->getID(), c);
843   else 
844     assert( 0 && "FATAL: No free register could be found in reg class!!");
845   return 0;
846 }
847
848
849 //----------------------------------------------------------------------------
850 // This method modifies the IsColorUsedArr of the register class passed to it.
851 // It sets the bits corresponding to the registers used by this machine
852 // instructions. Both explicit and implicit operands are set.
853 //----------------------------------------------------------------------------
854 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, 
855                                        const MachineInstr *MInst ) {
856
857  bool *IsColorUsedArr = RC->getIsColorUsedArr();
858   
859  for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
860     
861    const MachineOperand& Op = MInst->getOperand(OpNum);
862
863     if( Op.getOperandType() ==  MachineOperand::MO_VirtualRegister || 
864         Op.getOperandType() ==  MachineOperand::MO_CCRegister ) {
865
866       const Value *const Val =  Op.getVRegValue();
867
868       if( Val ) 
869         if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {   
870           int Reg;
871           if( (Reg=Op.getAllocatedRegNum()) != -1) {
872             IsColorUsedArr[ Reg ] = true;
873           }
874           else {
875             // it is possilbe that this operand still is not marked with
876             // a register but it has a LR and that received a color
877
878             LiveRange *LROfVal =  LRI.getLiveRangeForValue(Val);
879             if( LROfVal) 
880               if( LROfVal->hasColor() )
881                 IsColorUsedArr[ LROfVal->getColor() ] = true;
882           }
883         
884         } // if reg classes are the same
885     }
886     else if (Op.getOperandType() ==  MachineOperand::MO_MachineRegister) {
887       IsColorUsedArr[ Op.getMachineRegNum() ] = true;
888     }
889  }
890  
891  // If there are implicit references, mark them as well
892
893  for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
894
895    LiveRange *const LRofImpRef = 
896      LRI.getLiveRangeForValue( MInst->getImplicitRef(z)  );    
897    
898    if(LRofImpRef && LRofImpRef->hasColor())
899      IsColorUsedArr[LRofImpRef->getColor()] = true;
900  }
901 }
902
903
904
905
906
907
908
909
910 //----------------------------------------------------------------------------
911 // If there are delay slots for an instruction, the instructions
912 // added after it must really go after the delayed instruction(s).
913 // So, we move the InstrAfter of that instruction to the 
914 // corresponding delayed instruction using the following method.
915
916 //----------------------------------------------------------------------------
917 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
918                                     const MachineInstr *DelayedMI) {
919
920   // "added after" instructions of the original instr
921   std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
922
923   // "added instructions" of the delayed instr
924   AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
925
926   // "added after" instructions of the delayed instr
927   std::deque<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
928
929   // go thru all the "added after instructions" of the original instruction
930   // and append them to the "addded after instructions" of the delayed
931   // instructions
932   DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
933
934   // empty the "added after instructions" of the original instruction
935   OrigAft.clear();
936 }
937
938 //----------------------------------------------------------------------------
939 // This method prints the code with registers after register allocation is
940 // complete.
941 //----------------------------------------------------------------------------
942 void PhyRegAlloc::printMachineCode()
943 {
944
945   cerr << "\n;************** Function " << Meth->getName()
946        << " *****************\n";
947
948   for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
949        BBI != BBE; ++BBI) {
950     cerr << "\n"; printLabel(*BBI); cerr << ": ";
951
952     // get the iterator for machine instructions
953     MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
954     MachineCodeForBasicBlock::iterator MII = MIVec.begin();
955
956     // iterate over all the machine instructions in BB
957     for( ; MII != MIVec.end(); ++MII) {  
958       MachineInstr *const MInst = *MII; 
959
960       cerr << "\n\t";
961       cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
962
963       for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
964         MachineOperand& Op = MInst->getOperand(OpNum);
965
966         if( Op.getOperandType() ==  MachineOperand::MO_VirtualRegister || 
967             Op.getOperandType() ==  MachineOperand::MO_CCRegister /*|| 
968             Op.getOperandType() ==  MachineOperand::MO_PCRelativeDisp*/ ) {
969
970           const Value *const Val = Op.getVRegValue () ;
971           // ****this code is temporary till NULL Values are fixed
972           if( ! Val ) {
973             cerr << "\t<*NULL*>";
974             continue;
975           }
976
977           // if a label or a constant
978           if(isa<BasicBlock>(Val)) {
979             cerr << "\t"; printLabel(   Op.getVRegValue () );
980           } else {
981             // else it must be a register value
982             const int RegNum = Op.getAllocatedRegNum();
983
984             cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
985             if (Val->hasName() )
986               cerr << "(" << Val->getName() << ")";
987             else 
988               cerr << "(" << Val << ")";
989
990             if( Op.opIsDef() )
991               cerr << "*";
992
993             const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
994             if( LROfVal )
995               if( LROfVal->hasSpillOffset() )
996                 cerr << "$";
997           }
998
999         } 
1000         else if(Op.getOperandType() ==  MachineOperand::MO_MachineRegister) {
1001           cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1002         }
1003
1004         else 
1005           cerr << "\t" << Op;      // use dump field
1006       }
1007
1008     
1009
1010       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
1011       if( NumOfImpRefs > 0) {
1012         cerr << "\tImplicit:";
1013
1014         for(unsigned z=0; z < NumOfImpRefs; z++)
1015           cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1016       }
1017
1018     } // for all machine instructions
1019
1020     cerr << "\n";
1021
1022   } // for all BBs
1023
1024   cerr << "\n";
1025 }
1026
1027
1028 #if 0
1029
1030 //----------------------------------------------------------------------------
1031 //
1032 //----------------------------------------------------------------------------
1033
1034 void PhyRegAlloc::colorCallRetArgs()
1035 {
1036
1037   CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1038   CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1039
1040   for( ; It != CallRetInstList.end(); ++It ) {
1041
1042     const MachineInstr *const CRMI = *It;
1043     unsigned OpCode =  CRMI->getOpCode();
1044  
1045     // get the added instructions for this Call/Ret instruciton
1046     AddedInstrns &AI = AddedInstrMap[CRMI];
1047
1048     // Tmp stack positions are needed by some calls that have spilled args
1049     // So reset it before we call each such method
1050     //mcInfo.popAllTempValues(TM);  
1051
1052     
1053     if (TM.getInstrInfo().isCall(OpCode))
1054       MRI.colorCallArgs(CRMI, LRI, &AI, *this);
1055     else if (TM.getInstrInfo().isReturn(OpCode)) 
1056       MRI.colorRetValue(CRMI, LRI, &AI);
1057     else
1058       assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1059   }
1060 }
1061
1062 #endif 
1063
1064 //----------------------------------------------------------------------------
1065
1066 //----------------------------------------------------------------------------
1067 void PhyRegAlloc::colorIncomingArgs()
1068 {
1069   const BasicBlock *const FirstBB = Meth->front();
1070   const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1071   assert(FirstMI && "No machine instruction in entry BB");
1072
1073   MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
1074 }
1075
1076
1077 //----------------------------------------------------------------------------
1078 // Used to generate a label for a basic block
1079 //----------------------------------------------------------------------------
1080 void PhyRegAlloc::printLabel(const Value *const Val) {
1081   if (Val->hasName())
1082     cerr  << Val->getName();
1083   else
1084     cerr << "Label" <<  Val;
1085 }
1086
1087
1088 //----------------------------------------------------------------------------
1089 // This method calls setSugColorUsable method of each live range. This
1090 // will determine whether the suggested color of LR is  really usable.
1091 // A suggested color is not usable when the suggested color is volatile
1092 // AND when there are call interferences
1093 //----------------------------------------------------------------------------
1094
1095 void PhyRegAlloc::markUnusableSugColors()
1096 {
1097   if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1098
1099   // hash map iterator
1100   LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
1101   LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
1102
1103     for(; HMI != HMIEnd ; ++HMI ) {
1104       if (HMI->first) { 
1105         LiveRange *L = HMI->second;      // get the LiveRange
1106         if (L) { 
1107           if(L->hasSuggestedColor()) {
1108             int RCID = L->getRegClass()->getID();
1109             if( MRI.isRegVolatile( RCID,  L->getSuggestedColor()) &&
1110                 L->isCallInterference() )
1111               L->setSuggestedColorUsable( false );
1112             else
1113               L->setSuggestedColorUsable( true );
1114           }
1115         } // if L->hasSuggestedColor()
1116       }
1117     } // for all LR's in hash map
1118 }
1119
1120
1121
1122 //----------------------------------------------------------------------------
1123 // The following method will set the stack offsets of the live ranges that
1124 // are decided to be spillled. This must be called just after coloring the
1125 // LRs using the graph coloring algo. For each live range that is spilled,
1126 // this method allocate a new spill position on the stack.
1127 //----------------------------------------------------------------------------
1128
1129 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1130   if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1131
1132   LiveRangeMapType::const_iterator HMI    = LRI.getLiveRangeMap()->begin();   
1133   LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();   
1134
1135   for( ; HMI != HMIEnd ; ++HMI) {
1136     if (HMI->first && HMI->second) {
1137       LiveRange *L = HMI->second;      // get the LiveRange
1138       if (!L->hasColor())   //  NOTE: ** allocating the size of long Type **
1139         L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1140     }
1141   } // for all LR's in hash map
1142 }
1143
1144
1145
1146 //----------------------------------------------------------------------------
1147 // The entry pont to Register Allocation
1148 //----------------------------------------------------------------------------
1149
1150 void PhyRegAlloc::allocateRegisters()
1151 {
1152
1153   // make sure that we put all register classes into the RegClassList 
1154   // before we call constructLiveRanges (now done in the constructor of 
1155   // PhyRegAlloc class).
1156   //
1157   LRI.constructLiveRanges();            // create LR info
1158
1159   if (DEBUG_RA)
1160     LRI.printLiveRanges();
1161   
1162   createIGNodeListsAndIGs();            // create IGNode list and IGs
1163
1164   buildInterferenceGraphs();            // build IGs in all reg classes
1165   
1166   
1167   if (DEBUG_RA) {
1168     // print all LRs in all reg classes
1169     for( unsigned int rc=0; rc < NumOfRegClasses  ; rc++)  
1170       RegClassList[ rc ]->printIGNodeList(); 
1171     
1172     // print IGs in all register classes
1173     for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
1174       RegClassList[ rc ]->printIG();       
1175   }
1176   
1177
1178   LRI.coalesceLRs();                    // coalesce all live ranges
1179   
1180
1181   if( DEBUG_RA) {
1182     // print all LRs in all reg classes
1183     for( unsigned int rc=0; rc < NumOfRegClasses  ; rc++)  
1184       RegClassList[ rc ]->printIGNodeList(); 
1185     
1186     // print IGs in all register classes
1187     for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
1188       RegClassList[ rc ]->printIG();       
1189   }
1190
1191
1192   // mark un-usable suggested color before graph coloring algorithm.
1193   // When this is done, the graph coloring algo will not reserve
1194   // suggested color unnecessarily - they can be used by another LR
1195   //
1196   markUnusableSugColors(); 
1197
1198   // color all register classes using the graph coloring algo
1199   for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
1200     RegClassList[ rc ]->colorAllRegs();    
1201
1202   // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1203   // a poistion for such spilled LRs
1204   //
1205   allocateStackSpace4SpilledLRs();
1206
1207   mcInfo.popAllTempValues(TM);  // TODO **Check
1208
1209   // color incoming args - if the correct color was not received
1210   // insert code to copy to the correct register
1211   //
1212   colorIncomingArgs();
1213
1214   // Now update the machine code with register names and add any 
1215   // additional code inserted by the register allocator to the instruction
1216   // stream
1217   //
1218   updateMachineCode(); 
1219
1220   if (DEBUG_RA) {
1221     MachineCodeForMethod::get(Meth).dump();
1222     printMachineCode();                   // only for DEBUGGING
1223   }
1224 }
1225
1226
1227