Output to cerr rather than cout so that debug info doesn't mess up assembly generation
[oota-llvm.git] / lib / CodeGen / RegAlloc / PhyRegAlloc.cpp
1 #include "llvm/CodeGen/PhyRegAlloc.h"
2
3 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
4   "enable register allocation debugging information",
5   clEnumValN(RA_DEBUG_None   , "n", "disable debug output"),
6   clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
7   clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
8
9
10 //----------------------------------------------------------------------------
11 // Constructor: Init local composite objects and create register classes.
12 //----------------------------------------------------------------------------
13 PhyRegAlloc::PhyRegAlloc(const Method *const M, 
14                          const TargetMachine& tm, 
15                          MethodLiveVarInfo *const Lvi) 
16                         : RegClassList(),
17                           Meth(M), TM(tm), LVI(Lvi), LRI(M, tm, RegClassList), 
18                           MRI( tm.getRegInfo() ),
19                           NumOfRegClasses(MRI.getNumOfRegClasses()),
20                           AddedInstrMap()
21
22 {
23   // **TODO: use an actual reserved color list 
24   ReservedColorListType *RCL = new ReservedColorListType();
25
26   // create each RegisterClass and put in RegClassList
27   for( unsigned int rc=0; rc < NumOfRegClasses; rc++)  
28     RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc), RCL) );
29
30 }
31
32 //----------------------------------------------------------------------------
33 // This method initally creates interference graphs (one in each reg class)
34 // and IGNodeList (one in each IG). The actual nodes will be pushed later. 
35 //----------------------------------------------------------------------------
36
37 void PhyRegAlloc::createIGNodeListsAndIGs()
38 {
39   if(DEBUG_RA ) cerr << "Creating LR lists ..." << endl;
40
41   // hash map iterator
42   LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
43
44   // hash map end
45   LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
46
47     for(  ; HMI != HMIEnd ; ++HMI ) {
48       
49       if( (*HMI).first ) { 
50
51         LiveRange *L = (*HMI).second;      // get the LiveRange
52
53         if( !L) { 
54           if( DEBUG_RA) {
55             cerr << "\n*?!?Warning: Null liver range found for: ";
56             printValue( (*HMI).first) ; cerr << endl;
57           }
58           continue;
59         }
60                                         // if the Value * is not null, and LR  
61                                         // is not yet written to the IGNodeList
62        if( !(L->getUserIGNode())  ) {  
63                                    
64          RegClass *const RC =           // RegClass of first value in the LR
65            //RegClassList [MRI.getRegClassIDOfValue(*(L->begin()))];
66            RegClassList[ L->getRegClass()->getID() ];
67
68          RC-> addLRToIG( L );           // add this LR to an IG
69        }
70     }
71   }
72
73                                         // init RegClassList
74   for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
75     RegClassList[ rc ]->createInterferenceGraph();
76
77   if( DEBUG_RA)
78     cerr << "LRLists Created!" << endl;
79 }
80
81
82
83 //----------------------------------------------------------------------------
84 // This method will add all interferences at for a given instruction.
85 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg 
86 // class as that of live var. The live var passed to this function is the 
87 // LVset AFTER the instruction
88 //----------------------------------------------------------------------------
89
90 void PhyRegAlloc::addInterference(const Value *const Def, 
91                                   const LiveVarSet *const LVSet,
92                                   const bool isCallInst) {
93
94   LiveVarSet::const_iterator LIt = LVSet->begin();
95
96   // get the live range of instruction
97   const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );   
98
99   IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
100   assert( IGNodeOfDef );
101
102   RegClass *const RCOfDef = LROfDef->getRegClass(); 
103
104   // for each live var in live variable set
105   for( ; LIt != LVSet->end(); ++LIt) {
106
107     if( DEBUG_RA > 1) {
108       cerr << "< Def="; printValue(Def);     
109       cerr << ", Lvar=";  printValue( *LIt); cerr  << "> ";
110     }
111
112     //  get the live range corresponding to live var
113     LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );    
114
115     // LROfVar can be null if it is a const since a const 
116     // doesn't have a dominating def - see Assumptions above
117     if( LROfVar)   {  
118
119       if(LROfDef == LROfVar)            // do not set interf for same LR
120         continue;
121
122       // if 2 reg classes are the same set interference
123       if( RCOfDef == LROfVar->getRegClass() ){ 
124         RCOfDef->setInterference( LROfDef, LROfVar);  
125
126       }
127
128       //the live range of this var interferes with this call
129       if( isCallInst ) 
130         LROfVar->addCallInterference( (const Instruction *const) Def );   
131       
132     }
133     else if(DEBUG_RA > 1)  { 
134       // we will not have LRs for values not explicitly allocated in the
135       // instruction stream (e.g., constants)
136       cerr << " warning: no live range for " ; 
137       printValue( *LIt); cerr << endl; }
138     
139   }
140  
141 }
142
143 //----------------------------------------------------------------------------
144 // This method will walk thru code and create interferences in the IG of
145 // each RegClass.
146 //----------------------------------------------------------------------------
147
148 void PhyRegAlloc::buildInterferenceGraphs()
149 {
150
151   if(DEBUG_RA) cerr << "Creating interference graphs ..." << endl;
152
153   Method::const_iterator BBI = Meth->begin();  // random iterator for BBs   
154
155   for( ; BBI != Meth->end(); ++BBI) {          // traverse BBs in random order
156
157     // get the iterator for machine instructions
158     const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
159     MachineCodeForBasicBlock::const_iterator 
160       MInstIterator = MIVec.begin();
161
162     // iterate over all the machine instructions in BB
163     for( ; MInstIterator != MIVec.end(); ++MInstIterator) {  
164
165       const MachineInstr *const MInst = *MInstIterator; 
166
167       // get the LV set after the instruction
168       const LiveVarSet *const LVSetAI = 
169         LVI->getLiveVarSetAfterMInst(MInst, *BBI);
170     
171       const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
172
173       // iterate over  MI operands to find defs
174       for( MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done(); ++OpI) {
175         
176         if( OpI.isDef() ) {     
177           // create a new LR iff this operand is a def
178           addInterference(*OpI, LVSetAI, isCallInst );
179
180         } //if this is a def
181
182       } // for all operands
183
184     } // for all machine instructions in BB
185
186
187 #if 0
188
189     // go thru LLVM instructions in the basic block and record all CALL
190     // instructions and Return instructions in the CallInstrList
191     // This is done because since there are no reverse pointers in machine
192     // instructions to find the llvm instruction, when we encounter a call
193     // or a return whose args must be specailly colored (e.g., %o's for args)
194     BasicBlock::const_iterator InstIt = (*BBI)->begin();
195
196     for( ; InstIt != (*BBI)->end() ; ++ InstIt) {
197       unsigned OpCode =  (*InstIt)->getOpcode();
198
199       if( OpCode == Instruction::Call )
200         CallInstrList.push_back( *InstIt );      
201
202       else if( OpCode == Instruction::Ret )
203         RetInstrList.push_back( *InstIt );
204    }
205
206 #endif
207
208     
209   } // for all BBs in method
210
211
212   // add interferences for method arguments. Since there are no explict 
213   // defs in method for args, we have to add them manually
214           
215   addInterferencesForArgs();            // add interference for method args
216
217   if( DEBUG_RA)
218     cerr << "Interference graphs calculted!" << endl;
219
220 }
221
222
223
224
225 //----------------------------------------------------------------------------
226 // This method will add interferences for incoming arguments to a method.
227 //----------------------------------------------------------------------------
228 void PhyRegAlloc::addInterferencesForArgs()
229 {
230                                               // get the InSet of root BB
231   const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );  
232
233                                               // get the argument list
234   const Method::ArgumentListType& ArgList = Meth->getArgumentList();  
235
236                                               // get an iterator to arg list
237   Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();          
238
239
240   for( ; ArgIt != ArgList.end() ; ++ArgIt) {  // for each argument
241     addInterference( *ArgIt, InSet, false );  // add interferences between 
242                                               // args and LVars at start
243     if( DEBUG_RA > 1) {
244       cerr << " - %% adding interference for  argument ";    
245       printValue( (const Value *) *ArgIt); cerr  << endl;
246     }
247   }
248 }
249
250
251 #if 0
252 //----------------------------------------------------------------------------
253
254 //----------------------------------------------------------------------------
255
256
257 void PhyRegAlloc::insertCallerSavingCode(const MachineInstr *MInst, 
258                                          const BasicBlock *BB  ) 
259 {
260   assert( (TM.getInstrInfo()).isCall( MInst->getOpCode() ) );
261
262   int StackOff = 10;  // ****TODO : Change
263   set<unsigned> PushedRegSet();
264
265   // Now find the LR of the return value of the call
266   // The last *implicit operand* is the return value of a call
267   // Insert it to to he PushedRegSet since we must not save that register
268   // and restore it after the call.
269   // We do this because, we look at the LV set *after* the instruction
270   // to determine, which LRs must be saved across calls. The return value
271   // of the call is live in this set - but we must not save/restore it.
272
273   unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
274   if(  NumOfImpRefs > 0 ) {
275     
276     if(  MInst->implicitRefIsDefined(NumOfImpRefs-1) ) {
277
278       const Value *RetVal = CallMI->getImplicitRef(NumOfImpRefs-1); 
279       LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
280       assert( RetValLR && "No LR for RetValue of call");
281
282       PushedRegSet.insert(  
283         MRI.getUnifiedRegNum((RetValLR->getRegClass())->getID(), 
284                              RetValLR->getColor() ) );
285     }
286
287   }
288
289
290   LiveVarSet *LVSetAft =  LVI->getLiveVarSetAfterMInst(MInst, BB);
291
292   LiveVarSet::const_iterator LIt = LVSetAft->begin();
293
294   // for each live var in live variable set after machine inst
295   for( ; LIt != LVSetAft->end(); ++LIt) {
296
297    //  get the live range corresponding to live var
298     LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );    
299
300     // LROfVar can be null if it is a const since a const 
301     // doesn't have a dominating def - see Assumptions above
302     if( LR )   {  
303       
304       if( LR->hasColor() ) {
305
306         unsigned RCID = (LR->getRegClass())->getID();
307         unsigned Color = LR->getColor();
308
309         if ( MRI.isRegVolatile(RCID, Color) ) {
310
311           // if the value is in both LV sets (i.e., live before and after 
312           // the call machine instruction)
313           
314           unsigned Reg =   MRI.getUnifiedRegNum(RCID, Color);
315           
316           if( PuhsedRegSet.find(Reg) == PhusedRegSet.end() ) {
317             
318             // if we haven't already pushed that register
319             
320             MachineInstr *AdI = 
321               MRI.saveRegOnStackMI(Reg, MRI.getFPReg(), StackOff ); 
322             
323             ((AddedInstrMap[MInst])->InstrnsBefore).push_front(AdI);
324             ((AddedInstrMap[MInst])->InstrnsAfter).push_back(AdI);
325             
326             
327             PushedRegSet.insert( Reg );
328             StackOff += 4; // ****TODO: Correct ??????
329             cerr << "Inserted caller saving instr");
330             
331           } // if not already pushed
332
333         } // if LR has a volatile color
334         
335       } // if LR has color
336
337     } // if there is a LR for Var
338     
339   } // for each value in the LV set after instruction
340   
341 }
342
343 #endif
344
345 //----------------------------------------------------------------------------
346 // This method is called after register allocation is complete to set the
347 // allocated reisters in the machine code. This code will add register numbers
348 // to MachineOperands that contain a Value.
349 //----------------------------------------------------------------------------
350
351 void PhyRegAlloc::updateMachineCode()
352 {
353
354   Method::const_iterator BBI = Meth->begin();  // random iterator for BBs   
355
356   for( ; BBI != Meth->end(); ++BBI) {          // traverse BBs in random order
357
358     // get the iterator for machine instructions
359     MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
360     MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
361
362     // iterate over all the machine instructions in BB
363     for( ; MInstIterator != MIVec.end(); ++MInstIterator) {  
364       
365       MachineInstr *MInst = *MInstIterator; 
366
367
368       // If there are instructions before to be added, add them now
369       // ***TODO: Add InstrnsAfter as well
370       if( AddedInstrMap[ MInst ] ) {
371
372         deque<MachineInstr *> &IBef =
373           (AddedInstrMap[MInst])->InstrnsBefore;
374
375         if( ! IBef.empty() ) {
376
377           deque<MachineInstr *>::iterator AdIt; 
378
379           for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
380
381             cerr << "*ADDED instr opcode: ";
382             cerr << TargetInstrDescriptors[(*AdIt)->getOpCode()].opCodeString;
383             cerr << endl;
384             
385             MInstIterator = MIVec.insert( MInstIterator, *AdIt );
386             ++MInstIterator;
387           }
388
389         }
390
391         // restart from the topmost instruction added
392         //MInst = *MInstIterator;
393
394       }
395
396
397
398       //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
399
400       for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
401
402         MachineOperand& Op = MInst->getOperand(OpNum);
403
404         if( Op.getOperandType() ==  MachineOperand::MO_VirtualRegister || 
405             Op.getOperandType() ==  MachineOperand::MO_CCRegister) {
406
407           const Value *const Val =  Op.getVRegValue();
408
409           // delete this condition checking later (must assert if Val is null)
410           if( !Val) {
411             if (DEBUG_RA)
412               cerr << "Warning: NULL Value found for operand" << endl;
413             continue;
414           }
415           assert( Val && "Value is NULL");   
416
417           const LiveRange *const LR = LRI.getLiveRangeForValue(Val);
418
419           if ( !LR ) {
420
421             // nothing to worry if it's a const or a label
422
423             if (DEBUG_RA) {
424               cerr << "*NO LR for inst opcode: ";
425               cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
426             }
427
428             if( Op.getAllocatedRegNum() == -1)
429               Op.setRegForValue( 1000 ); // mark register as invalid
430             
431 #if 0
432             if(  ((Val->getType())->isLabelType()) || 
433                  (Val->getValueType() == Value::ConstantVal)  )
434               ;                         // do nothing
435             
436             // The return address is not explicitly defined within a
437             // method. So, it is not colored by usual algorithm. In that case
438             // color it here.
439             
440             //else if (TM.getInstrInfo().isCall(MInst->getOpCode())) 
441             //Op.setRegForValue( MRI.getCallAddressReg() );
442
443             //TM.getInstrInfo().isReturn(MInst->getOpCode())
444             else if(TM.getInstrInfo().isReturn(MInst->getOpCode()) ) {
445               if (DEBUG_RA) cerr << endl << "RETURN found" << endl;
446               Op.setRegForValue( MRI.getReturnAddressReg() );
447
448             }
449
450             if (Val->getValueType() == Value::InstructionVal)
451             {
452               cerr << "!Warning: No LiveRange for: ";
453               printValue( Val); cerr << " Type: " << Val->getValueType();
454               cerr << " RegVal=" <<  Op.getAllocatedRegNum() << endl;
455             }
456
457 #endif
458
459             continue;
460           }
461         
462           unsigned RCID = (LR->getRegClass())->getID();
463
464           Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
465
466           int RegNum = MRI.getUnifiedRegNum(RCID, LR->getColor());
467
468         }
469
470       }
471
472     }
473   }
474 }
475
476
477
478
479 //----------------------------------------------------------------------------
480 // This method prints the code with registers after register allocation is
481 // complete.
482 //----------------------------------------------------------------------------
483 void PhyRegAlloc::printMachineCode()
484 {
485
486   cerr << endl << ";************** Method ";
487   cerr << Meth->getName() << " *****************" << endl;
488
489   Method::const_iterator BBI = Meth->begin();  // random iterator for BBs   
490
491   for( ; BBI != Meth->end(); ++BBI) {          // traverse BBs in random order
492
493     cerr << endl ; printLabel( *BBI); cerr << ": ";
494
495     // get the iterator for machine instructions
496     MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
497     MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
498
499     // iterate over all the machine instructions in BB
500     for( ; MInstIterator != MIVec.end(); ++MInstIterator) {  
501       
502       MachineInstr *const MInst = *MInstIterator; 
503
504
505       cerr << endl << "\t";
506       cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
507       
508
509       //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
510
511       for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
512
513         MachineOperand& Op = MInst->getOperand(OpNum);
514
515         if( Op.getOperandType() ==  MachineOperand::MO_VirtualRegister || 
516             Op.getOperandType() ==  MachineOperand::MO_CCRegister || 
517             Op.getOperandType() ==  MachineOperand::MO_PCRelativeDisp ) {
518
519           const Value *const Val = Op.getVRegValue () ;
520           // ****this code is temporary till NULL Values are fixed
521           if( ! Val ) {
522             cerr << "\t<*NULL*>";
523             continue;
524           }
525
526           // if a label or a constant
527           if( (Val->getValueType() == Value::BasicBlockVal)  ) {
528
529             cerr << "\t"; printLabel(   Op.getVRegValue () );
530           }
531           else {
532             // else it must be a register value
533             const int RegNum = Op.getAllocatedRegNum();
534
535             //if( RegNum != 1000)
536
537               cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
538             // else cerr << "\t<*NoReg*>";
539
540           }
541
542         } 
543         else if(Op.getOperandType() ==  MachineOperand::MO_MachineRegister) {
544           cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
545         }
546
547         else 
548           cerr << "\t" << Op;      // use dump field
549       }
550
551     }
552
553     cerr << endl;
554
555   }
556
557   cerr << endl;
558 }
559
560
561 //----------------------------------------------------------------------------
562 //
563 //----------------------------------------------------------------------------
564
565 void PhyRegAlloc::colorCallRetArgs()
566 {
567
568   CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
569   CallRetInstrListType::const_iterator It = CallRetInstList.begin();
570
571   for( ; It != CallRetInstList.end(); ++It ) {
572
573     const MachineInstr *const CRMI = *It;
574     unsigned OpCode =  CRMI->getOpCode();
575  
576     // get the added instructions for this Call/Ret instruciton
577     AddedInstrns *AI = AddedInstrMap[ CRMI ];
578     if ( !AI ) { 
579       AI = new AddedInstrns();
580       AddedInstrMap[ CRMI ] = AI;
581     }
582
583     if( (TM.getInstrInfo()).isCall( OpCode ) )
584       MRI.colorCallArgs( CRMI, LRI, AI );
585     
586     else if (  (TM.getInstrInfo()).isReturn(OpCode) ) 
587       MRI.colorRetValue( CRMI, LRI, AI );
588     
589     else assert( 0 && "Non Call/Ret instrn in CallRetInstrList\n" );
590
591   }
592
593 }
594
595 //----------------------------------------------------------------------------
596
597 //----------------------------------------------------------------------------
598 void PhyRegAlloc::colorIncomingArgs()
599 {
600   const BasicBlock *const FirstBB = Meth->front();
601   const MachineInstr *FirstMI = *((FirstBB->getMachineInstrVec()).begin());
602   assert( FirstMI && "No machine instruction in entry BB");
603
604   AddedInstrns *AI = AddedInstrMap[ FirstMI ];
605   if ( !AI ) { 
606     AI = new AddedInstrns();
607     AddedInstrMap[ FirstMI  ] = AI;
608   }
609
610   MRI.colorMethodArgs(Meth, LRI, AI );
611 }
612
613
614 //----------------------------------------------------------------------------
615 // Used to generate a label for a basic block
616 //----------------------------------------------------------------------------
617 void PhyRegAlloc::printLabel(const Value *const Val)
618 {
619   if( Val->hasName() )
620     cerr  << Val->getName();
621   else
622     cerr << "Label" <<  Val;
623 }
624
625
626 //----------------------------------------------------------------------------
627 // The entry pont to Register Allocation
628 //----------------------------------------------------------------------------
629
630 void PhyRegAlloc::allocateRegisters()
631 {
632
633   // make sure that we put all register classes into the RegClassList 
634   // before we call constructLiveRanges (now done in the constructor of 
635   // PhyRegAlloc class).
636
637   constructLiveRanges();                // create LR info
638
639   if( DEBUG_RA )
640     LRI.printLiveRanges();
641   
642   createIGNodeListsAndIGs();            // create IGNode list and IGs
643
644   buildInterferenceGraphs();            // build IGs in all reg classes
645   
646   
647   if( DEBUG_RA ) {
648     // print all LRs in all reg classes
649     for( unsigned int rc=0; rc < NumOfRegClasses  ; rc++)  
650       RegClassList[ rc ]->printIGNodeList(); 
651     
652     // print IGs in all register classes
653     for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
654       RegClassList[ rc ]->printIG();       
655   }
656   
657   LRI.coalesceLRs();                    // coalesce all live ranges
658   
659   if( DEBUG_RA) {
660     // print all LRs in all reg classes
661     for( unsigned int rc=0; rc < NumOfRegClasses  ; rc++)  
662       RegClassList[ rc ]->printIGNodeList(); 
663     
664     // print IGs in all register classes
665     for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
666       RegClassList[ rc ]->printIG();       
667   }
668
669   // color all register classes
670   for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
671     RegClassList[ rc ]->colorAllRegs();    
672
673
674   // color incoming args and call args
675   colorIncomingArgs();
676   colorCallRetArgs();
677
678
679   updateMachineCode(); 
680   if (DEBUG_RA) {
681     // PrintMachineInstructions(Meth);
682     printMachineCode();                   // only for DEBUGGING
683   }
684 }
685
686
687
688