Convert AddedInstrMapType to contain AddedInstrns by value instead of by
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9RegInfo.cpp
1 //===-- SparcRegInfo.cpp - Sparc Target Register Information --------------===//
2 //
3 // This file contains implementation of Sparc specific helper methods
4 // used for register allocation.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "SparcInternals.h"
9 #include "SparcRegClassInfo.h"
10 #include "llvm/Target/Sparc.h"
11 #include "llvm/CodeGen/MachineCodeForMethod.h"
12 #include "llvm/CodeGen/PhyRegAlloc.h"
13 #include "llvm/CodeGen/MachineInstr.h"
14 #include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
15 #include "llvm/iTerminators.h"
16 #include "llvm/iOther.h"
17 #include "llvm/DerivedTypes.h"
18 #include <iostream>
19 using std::cerr;
20
21 UltraSparcRegInfo::UltraSparcRegInfo(const UltraSparc &tgt)
22   : MachineRegInfo(tgt), UltraSparcInfo(&tgt), NumOfIntArgRegs(6), 
23     NumOfFloatArgRegs(32), InvalidRegNum(1000) {
24    
25   MachineRegClassArr.push_back(new SparcIntRegClass(IntRegClassID));
26   MachineRegClassArr.push_back(new SparcFloatRegClass(FloatRegClassID));
27   MachineRegClassArr.push_back(new SparcIntCCRegClass(IntCCRegClassID));
28   MachineRegClassArr.push_back(new SparcFloatCCRegClass(FloatCCRegClassID));
29
30   assert(SparcFloatRegOrder::StartOfNonVolatileRegs == 32 && 
31          "32 Float regs are used for float arg passing");
32 }
33
34
35 // getZeroRegNum - returns the register that contains always zero.
36 // this is the unified register number
37 //
38 int UltraSparcRegInfo::getZeroRegNum() const {
39   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
40                                 SparcIntRegOrder::g0);
41 }
42
43 // getCallAddressReg - returns the reg used for pushing the address when a
44 // method is called. This can be used for other purposes between calls
45 //
46 unsigned UltraSparcRegInfo::getCallAddressReg() const {
47   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
48                                 SparcIntRegOrder::o7);
49 }
50
51 // Returns the register containing the return address.
52 // It should be made sure that this  register contains the return 
53 // value when a return instruction is reached.
54 //
55 unsigned UltraSparcRegInfo::getReturnAddressReg() const {
56   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
57                                 SparcIntRegOrder::i7);
58 }
59
60 // given the unified register number, this gives the name
61 // for generating assembly code or debugging.
62 //
63 const std::string UltraSparcRegInfo::getUnifiedRegName(int reg) const {
64   if( reg < 32 ) 
65     return SparcIntRegOrder::getRegName(reg);
66   else if ( reg < (64 + 32) )
67     return SparcFloatRegOrder::getRegName( reg  - 32);                  
68   else if( reg < (64+32+4) )
69     return SparcFloatCCRegOrder::getRegName( reg -32 - 64);
70   else if( reg < (64+32+4+2) )    // two names: %xcc and %ccr
71     return SparcIntCCRegOrder::getRegName( reg -32 - 64 - 4);             
72   else if (reg== InvalidRegNum)       //****** TODO: Remove */
73     return "<*NoReg*>";
74   else 
75     assert(0 && "Invalid register number");
76   return "";
77 }
78
79 // Get unified reg number for frame pointer
80 unsigned UltraSparcRegInfo::getFramePointer() const {
81   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
82                                 SparcIntRegOrder::i6);
83 }
84
85 // Get unified reg number for stack pointer
86 unsigned UltraSparcRegInfo::getStackPointer() const {
87   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
88                                 SparcIntRegOrder::o6);
89 }
90
91
92
93 //---------------------------------------------------------------------------
94 // Finds the return value of a sparc specific call instruction
95 //---------------------------------------------------------------------------
96
97 const Value * 
98 UltraSparcRegInfo::getCallInstRetVal(const MachineInstr *CallMI) const {
99   unsigned OpCode = CallMI->getOpCode();
100   unsigned NumOfImpRefs = CallMI->getNumImplicitRefs();
101
102   if (OpCode == CALL) {
103
104     // The one before the last implicit operand is the return value of 
105     // a CALL instr
106     //
107     if( NumOfImpRefs > 1 )
108       if (CallMI->implicitRefIsDefined(NumOfImpRefs-2)) 
109         return CallMI->getImplicitRef(NumOfImpRefs-2); 
110
111   } else if (OpCode == JMPLCALL) {
112
113     // The last implicit operand is the return value of a JMPL
114     // 
115     if(NumOfImpRefs > 0)
116       if (CallMI->implicitRefIsDefined(NumOfImpRefs-1))
117         return CallMI->getImplicitRef(NumOfImpRefs-1); 
118   } else
119     assert(0 && "OpCode must be CALL/JMPL for a call instr");
120
121   return NULL;
122 }
123
124
125 const Value * 
126 UltraSparcRegInfo::getCallInstIndirectAddrVal(const MachineInstr *CallMI) const
127 {
128   return (CallMI->getOpCode() == JMPLCALL)?
129     CallMI->getOperand(0).getVRegValue() : NULL;
130 }
131
132
133 //---------------------------------------------------------------------------
134 // Finds the return address of a call sparc specific call instruction
135 //---------------------------------------------------------------------------
136 const Value *
137 UltraSparcRegInfo::getCallInstRetAddr(const MachineInstr *CallMI) const {
138   unsigned OpCode = CallMI->getOpCode();
139
140   if (OpCode == CALL) {
141     unsigned NumOfImpRefs =  CallMI->getNumImplicitRefs();
142
143     assert( NumOfImpRefs && "CALL instr must have at least on ImpRef");
144
145     // The last implicit operand is the return address of a CALL instr
146     //
147     return CallMI->getImplicitRef(NumOfImpRefs-1); 
148
149   } else if(OpCode == JMPLCALL) {
150     MachineOperand &MO = (MachineOperand &)CallMI->getOperand(2);
151     return MO.getVRegValue();
152   }
153   
154   assert(0 && "OpCode must be CALL/JMPL for a call instr");
155   return 0;
156 }
157
158 // The following 3  methods are used to find the RegType (see enum above)
159 // of a LiveRange, Value and using the unified RegClassID
160 //
161 int UltraSparcRegInfo::getRegType(const LiveRange *LR) const {
162   switch (LR->getRegClass()->getID()) {
163   case IntRegClassID: return IntRegType; 
164   case FloatRegClassID: {
165     const Type *Typ = LR->getType();
166     if (Typ == Type::FloatTy) 
167       return FPSingleRegType;
168     else if (Typ == Type::DoubleTy)
169       return FPDoubleRegType;
170     assert(0 && "Unknown type in FloatRegClass");
171   }
172   case IntCCRegClassID: return IntCCRegType; 
173   case FloatCCRegClassID: return FloatCCRegType; 
174   default: assert( 0 && "Unknown reg class ID");
175     return 0;
176   }
177 }
178
179 int UltraSparcRegInfo::getRegType(const Value *Val) const {
180   unsigned Typ;
181   
182   switch (getRegClassIDOfValue(Val)) {
183   case IntRegClassID: return IntRegType; 
184   case FloatRegClassID: 
185     Typ = Val->getType()->getPrimitiveID();
186     if (Typ == Type::FloatTyID)
187       return FPSingleRegType;
188     else if (Typ == Type::DoubleTyID)
189       return FPDoubleRegType;
190     assert(0 && "Unknown type in FloatRegClass");
191     
192   case IntCCRegClassID: return IntCCRegType; 
193   case FloatCCRegClassID: return FloatCCRegType ; 
194   default: assert(0 && "Unknown reg class ID");
195     return 0;
196   }
197 }
198
199 int UltraSparcRegInfo::getRegType(int reg) const {
200   if (reg < 32) 
201     return IntRegType;
202   else if (reg < (32 + 32))
203     return FPSingleRegType;
204   else if (reg < (64 + 32))
205     return FPDoubleRegType;
206   else if (reg < (64+32+4))
207     return FloatCCRegType;
208   else if (reg < (64+32+4+2))  
209     return IntCCRegType;             
210   else 
211     assert(0 && "Invalid register number in getRegType");
212   return 0;
213 }
214
215
216
217
218
219 //---------------------------------------------------------------------------
220 // Finds the # of actual arguments of the call instruction
221 //---------------------------------------------------------------------------
222 unsigned 
223 UltraSparcRegInfo::getCallInstNumArgs(const MachineInstr *CallMI) const {
224
225   unsigned OpCode = CallMI->getOpCode();
226   unsigned NumOfImpRefs = CallMI->getNumImplicitRefs();
227
228   if (OpCode == CALL) {
229     switch (NumOfImpRefs) {
230     case 0: assert(0 && "A CALL inst must have at least one ImpRef (RetAddr)");
231     case 1: return 0;
232     default:  // two or more implicit refs
233       if (CallMI->implicitRefIsDefined(NumOfImpRefs-2)) 
234         return NumOfImpRefs - 2;
235       else 
236         return NumOfImpRefs - 1;
237     }
238   } else if (OpCode == JMPLCALL) {
239
240     // The last implicit operand is the return value of a JMPL instr
241     if( NumOfImpRefs > 0 ) {
242       if (CallMI->implicitRefIsDefined(NumOfImpRefs-1)) 
243         return NumOfImpRefs - 1;
244       else 
245         return NumOfImpRefs;
246     }
247     else 
248       return NumOfImpRefs;
249   }
250
251   assert(0 && "OpCode must be CALL/JMPL for a call instr");
252   return 0;
253 }
254
255
256
257 //---------------------------------------------------------------------------
258 // Finds whether a call is an indirect call
259 //---------------------------------------------------------------------------
260 bool UltraSparcRegInfo::isVarArgCall(const MachineInstr *CallMI) const {
261
262   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
263
264   const MachineOperand & calleeOp = CallMI->getOperand(0);
265   Value *calleeVal =  calleeOp.getVRegValue();
266
267   PointerType *PT =  cast<PointerType>(calleeVal->getType());
268   return cast<FunctionType>(PT->getElementType())->isVarArg();
269 }
270
271
272
273
274 //---------------------------------------------------------------------------
275 // Suggests a register for the ret address in the RET machine instruction.
276 // We always suggest %i7 by convention.
277 //---------------------------------------------------------------------------
278 void UltraSparcRegInfo::suggestReg4RetAddr(const MachineInstr *RetMI, 
279                                            LiveRangeInfo& LRI) const {
280
281   assert( (RetMI->getNumOperands() >= 2)
282           && "JMPL/RETURN must have 3 and 2 operands respectively");
283   
284   MachineOperand & MO  = ( MachineOperand &) RetMI->getOperand(0);
285
286   // return address is always mapped to i7
287   //
288   MO.setRegForValue( getUnifiedRegNum( IntRegClassID, SparcIntRegOrder::i7) );
289   
290   // Possible Optimization: 
291   // Instead of setting the color, we can suggest one. In that case,
292   // we have to test later whether it received the suggested color.
293   // In that case, a LR has to be created at the start of method.
294   // It has to be done as follows (remove the setRegVal above):
295
296   // const Value *RetAddrVal = MO.getVRegValue();
297   // assert( RetAddrVal && "LR for ret address must be created at start");
298   // LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);  
299   // RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID, 
300   // SparcIntRegOrdr::i7) );
301 }
302
303
304 //---------------------------------------------------------------------------
305 // Suggests a register for the ret address in the JMPL/CALL machine instr.
306 // Sparc ABI dictates that %o7 be used for this purpose.
307 //---------------------------------------------------------------------------
308 void UltraSparcRegInfo::suggestReg4CallAddr(const MachineInstr * CallMI,
309                                             LiveRangeInfo& LRI,
310                                          std::vector<RegClass *> RCList) const {
311
312
313   const Value *RetAddrVal = getCallInstRetAddr( CallMI );
314
315   // RetAddrVal cannot be NULL (asserted in  getCallInstRetAddr)
316   // create a new LR for the return address and color it
317   
318   LiveRange * RetAddrLR = new LiveRange();  
319   RetAddrLR->insert( RetAddrVal );
320   unsigned RegClassID = getRegClassIDOfValue( RetAddrVal );
321   RetAddrLR->setRegClass( RCList[RegClassID] );
322   RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID,SparcIntRegOrder::o7));
323   LRI.addLRToMap( RetAddrVal, RetAddrLR);
324   
325 }
326
327
328
329
330 //---------------------------------------------------------------------------
331 //  This method will suggest colors to incoming args to a method. 
332 //  According to the Sparc ABI, the first 6 incoming args are in 
333 //  %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
334 //  If the arg is passed on stack due to the lack of regs, NOTHING will be
335 //  done - it will be colored (or spilled) as a normal live range.
336 //---------------------------------------------------------------------------
337 void UltraSparcRegInfo::suggestRegs4MethodArgs(const Function *Meth, 
338                                                LiveRangeInfo& LRI) const 
339 {
340
341                                                  // get the argument list
342   const Function::ArgumentListType& ArgList = Meth->getArgumentList();
343                                                  // get an iterator to arg list
344   Function::ArgumentListType::const_iterator ArgIt = ArgList.begin(); 
345
346   // for each argument
347   for( unsigned argNo=0; ArgIt != ArgList.end() ; ++ArgIt, ++argNo) {    
348
349     // get the LR of arg
350     LiveRange *const LR = LRI.getLiveRangeForValue((const Value *) *ArgIt); 
351     assert( LR && "No live range found for method arg");
352
353     unsigned RegType = getRegType( LR );
354
355
356     // if the arg is in int class - allocate a reg for an int arg
357     //
358     if( RegType == IntRegType ) {
359
360       if( argNo < NumOfIntArgRegs) {
361         LR->setSuggestedColor( SparcIntRegOrder::i0 + argNo );
362       }
363       else {
364         // Do NOTHING as this will be colored as a normal value.
365         if (DEBUG_RA) cerr << " Int Regr not suggested for method arg\n";
366       }
367      
368     }
369     else if( RegType==FPSingleRegType && (argNo*2+1) < NumOfFloatArgRegs) 
370       LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2 + 1) );
371     
372  
373     else if( RegType == FPDoubleRegType && (argNo*2) < NumOfFloatArgRegs) 
374       LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2) ); 
375     
376   }
377 }
378
379
380
381 //---------------------------------------------------------------------------
382 // This method is called after graph coloring to move incoming args to
383 // the correct hardware registers if they did not receive the correct
384 // (suggested) color through graph coloring.
385 //---------------------------------------------------------------------------
386 void UltraSparcRegInfo::colorMethodArgs(const Function *Meth, 
387                                         LiveRangeInfo &LRI,
388                                         AddedInstrns *FirstAI) const {
389
390                                                  // get the argument list
391   const Function::ArgumentListType& ArgList = Meth->getArgumentList();
392                                                  // get an iterator to arg list
393   Function::ArgumentListType::const_iterator ArgIt = ArgList.begin(); 
394   MachineInstr *AdMI;
395
396
397   // for each argument
398   for( unsigned argNo=0; ArgIt != ArgList.end() ; ++ArgIt, ++argNo) {    
399
400     // get the LR of arg
401     LiveRange *LR = LRI.getLiveRangeForValue(*ArgIt); 
402     assert( LR && "No live range found for method arg");
403
404
405     unsigned RegType = getRegType( LR );
406     unsigned RegClassID = (LR->getRegClass())->getID();
407
408     // Find whether this argument is coming in a register (if not, on stack)
409     // Also find the correct register that the argument must go (UniArgReg)
410     //
411     bool isArgInReg = false;
412     unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
413
414     if( (RegType== IntRegType && argNo <  NumOfIntArgRegs)) {
415       isArgInReg = true;
416       UniArgReg = getUnifiedRegNum( RegClassID, SparcIntRegOrder::i0 + argNo );
417     }
418     else if(RegType == FPSingleRegType && argNo < NumOfFloatArgRegs)  { 
419       isArgInReg = true;
420       UniArgReg = getUnifiedRegNum( RegClassID, 
421                                     SparcFloatRegOrder::f0 + argNo*2 + 1 ) ;
422     }
423     else if(RegType == FPDoubleRegType && argNo < NumOfFloatArgRegs)  { 
424       isArgInReg = true;
425       UniArgReg = getUnifiedRegNum(RegClassID, SparcFloatRegOrder::f0+argNo*2);
426     }
427
428     
429     if( LR->hasColor() ) {              // if this arg received a register
430
431       unsigned UniLRReg = getUnifiedRegNum(  RegClassID, LR->getColor() );
432
433       // if LR received the correct color, nothing to do
434       //
435       if( UniLRReg == UniArgReg )
436         continue;
437
438       // We are here because the LR did not receive the suggested 
439       // but LR received another register.
440       // Now we have to copy the %i reg (or stack pos of arg) 
441       // to the register the LR was colored with.
442       
443       // if the arg is coming in UniArgReg register, it MUST go into
444       // the UniLRReg register
445       //
446       if( isArgInReg ) 
447         AdMI = cpReg2RegMI( UniArgReg, UniLRReg, RegType );
448
449       else {
450
451         // Now the arg is coming on stack. Since the LR recieved a register,
452         // we just have to load the arg on stack into that register
453         //
454         const MachineFrameInfo& frameInfo = target.getFrameInfo();
455         assert(frameInfo.argsOnStackHaveFixedSize()); 
456         
457         bool growUp;                    // find the offset of arg in stack frame
458         int firstArg =
459           frameInfo.getFirstIncomingArgOffset(MachineCodeForMethod::get(Meth), 
460                                               growUp);
461         int offsetFromFP =
462           growUp? firstArg + argNo * frameInfo.getSizeOfEachArgOnStack()
463                 : firstArg - argNo * frameInfo.getSizeOfEachArgOnStack();
464         
465         AdMI = cpMem2RegMI(getFramePointer(), offsetFromFP, 
466                            UniLRReg, RegType );
467       }
468
469       FirstAI->InstrnsBefore.push_back( AdMI );   
470       
471     } // if LR received a color
472
473     else {                             
474
475       // Now, the LR did not receive a color. But it has a stack offset for
476       // spilling.
477       // So, if the arg is coming in UniArgReg register,  we can just move
478       // that on to the stack pos of LR
479
480       if( isArgInReg ) {
481         cpReg2MemMI(UniArgReg, getFramePointer(), 
482                     LR->getSpillOffFromFP(), RegType );
483
484         FirstAI->InstrnsBefore.push_back( AdMI );   
485       }
486
487       else {
488
489         // Now the arg is coming on stack. Since the LR did NOT 
490         // recieved a register as well, it is allocated a stack position. We
491         // can simply change the stack poistion of the LR. We can do this,
492         // since this method is called before any other method that makes
493         // uses of the stack pos of the LR (e.g., updateMachineInstr)
494
495         const MachineFrameInfo& frameInfo = target.getFrameInfo();
496         assert(frameInfo.argsOnStackHaveFixedSize()); 
497         
498         bool growUp;
499         int firstArg = frameInfo.getFirstIncomingArgOffset(MachineCodeForMethod::get(Meth), growUp);
500         int offsetFromFP =
501           growUp? firstArg + argNo * frameInfo.getSizeOfEachArgOnStack()
502                 : firstArg - argNo * frameInfo.getSizeOfEachArgOnStack();
503         
504         LR->modifySpillOffFromFP( offsetFromFP );
505       }
506
507     }
508
509   }  // for each incoming argument
510
511 }
512
513
514
515 //---------------------------------------------------------------------------
516 // This method is called before graph coloring to suggest colors to the
517 // outgoing call args and the return value of the call.
518 //---------------------------------------------------------------------------
519 void UltraSparcRegInfo::suggestRegs4CallArgs(const MachineInstr *CallMI, 
520                                              LiveRangeInfo& LRI,
521                                          std::vector<RegClass *> RCList) const {
522
523   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
524
525   suggestReg4CallAddr(CallMI, LRI, RCList);
526
527
528   // First color the return value of the call instruction. The return value
529   // will be in %o0 if the value is an integer type, or in %f0 if the 
530   // value is a float type.
531
532   // the return value cannot have a LR in machine instruction since it is
533   // only defined by the call instruction
534
535   // if type is not void,  create a new live range and set its 
536   // register class and add to LRI
537
538
539   const Value *RetVal = getCallInstRetVal( CallMI );
540
541
542   if (RetVal) {
543     assert ((!LRI.getLiveRangeForValue(RetVal)) && 
544             "LR for ret Value of call already definded!");
545
546     // create a new LR for the return value
547     LiveRange *RetValLR = new LiveRange();  
548     RetValLR->insert(RetVal);
549     unsigned RegClassID = getRegClassIDOfValue(RetVal);
550     RetValLR->setRegClass(RCList[RegClassID]);
551     LRI.addLRToMap(RetVal, RetValLR);
552     
553     // now suggest a register depending on the register class of ret arg
554
555     if( RegClassID == IntRegClassID ) 
556       RetValLR->setSuggestedColor(SparcIntRegOrder::o0);
557     else if (RegClassID == FloatRegClassID ) 
558       RetValLR->setSuggestedColor(SparcFloatRegOrder::f0 );
559     else assert( 0 && "Unknown reg class for return value of call\n");
560   }
561
562   
563   // Now suggest colors for arguments (operands) of the call instruction.
564   // Colors are suggested only if the arg number is smaller than the
565   // the number of registers allocated for argument passing.
566   // Now, go thru call args - implicit operands of the call MI
567
568   unsigned NumOfCallArgs =  getCallInstNumArgs( CallMI );
569   
570   for(unsigned argNo=0, i=0; i < NumOfCallArgs; ++i, ++argNo ) {
571
572     const Value *CallArg = CallMI->getImplicitRef(i);
573     
574     // get the LR of call operand (parameter)
575     LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
576
577     // not possible to have a null LR since all args (even consts)  
578     // must be defined before
579     if (!LR) {          
580       cerr << " ERROR: In call instr, no LR for arg: " << RAV(CallArg) << "\n";
581       assert(0 && "NO LR for call arg");  
582     }
583     
584     unsigned RegType = getRegType( LR );
585
586     // if the arg is in int class - allocate a reg for an int arg
587     if( RegType == IntRegType ) {
588
589       if( argNo < NumOfIntArgRegs) 
590         LR->setSuggestedColor( SparcIntRegOrder::o0 + argNo );
591
592       else if (DEBUG_RA) 
593         // Do NOTHING as this will be colored as a normal value.
594         cerr << " Regr not suggested for int call arg\n";
595       
596     }
597     else if( RegType == FPSingleRegType &&  (argNo*2 +1)< NumOfFloatArgRegs) 
598       LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2 + 1) );
599     
600  
601     else if( RegType == FPDoubleRegType && (argNo*2) < NumOfFloatArgRegs) 
602       LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2) ); 
603     
604
605   } // for all call arguments
606
607 }
608
609
610 //---------------------------------------------------------------------------
611 // After graph coloring, we have call this method to see whehter the return
612 // value and the call args received the correct colors. If not, we have
613 // to instert copy instructions.
614 //---------------------------------------------------------------------------
615
616 void UltraSparcRegInfo::colorCallArgs(const MachineInstr *CallMI,
617                                       LiveRangeInfo &LRI,
618                                       AddedInstrns *CallAI,
619                                       PhyRegAlloc &PRA,
620                                       const BasicBlock *BB) const {
621
622   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
623
624   // Reset the optional args area in the stack frame
625   // since that is reused for each call
626   // 
627   PRA.mcInfo.resetOptionalArgs(target);
628   
629   // First color the return value of the call.
630   // If there is a LR for the return value, it means this
631   // method returns a value
632   
633   MachineInstr *AdMI;
634
635   const Value *RetVal = getCallInstRetVal( CallMI );
636
637   if (RetVal) {
638     LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
639
640     if (!RetValLR) {
641       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
642       assert(0 && "ERR:No LR for non-void return value");
643     }
644
645     unsigned RegClassID = (RetValLR->getRegClass())->getID();    
646     bool recvCorrectColor = false;
647
648     unsigned CorrectCol;                // correct color for ret value
649     if(RegClassID == IntRegClassID)
650       CorrectCol = SparcIntRegOrder::o0;
651     else if(RegClassID == FloatRegClassID)
652       CorrectCol = SparcFloatRegOrder::f0;
653     else {
654       assert( 0 && "Unknown RegClass");
655       return;
656     }
657
658     // if the LR received the correct color, NOTHING to do
659
660     if(  RetValLR->hasColor() )
661       if( RetValLR->getColor() == CorrectCol )
662         recvCorrectColor = true;
663
664
665     // if we didn't receive the correct color for some reason, 
666     // put copy instruction
667     
668     if( !recvCorrectColor ) {
669
670       unsigned RegType = getRegType( RetValLR );
671
672       // the  reg that LR must be colored with 
673       unsigned UniRetReg = getUnifiedRegNum( RegClassID, CorrectCol);   
674       
675       if( RetValLR->hasColor() ) {
676         
677         unsigned 
678           UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
679         
680         // the return value is coming in UniRetReg but has to go into
681         // the UniRetLRReg
682
683         AdMI = cpReg2RegMI( UniRetReg, UniRetLRReg, RegType );  
684
685       } // if LR has color
686       else {
687
688         // if the LR did NOT receive a color, we have to move the return
689         // value coming in UniRetReg to the stack pos of spilled LR
690         
691         AdMI =  cpReg2MemMI(UniRetReg, getFramePointer(), 
692                             RetValLR->getSpillOffFromFP(), RegType );
693       }
694
695       CallAI->InstrnsAfter.push_back( AdMI );
696       
697     } // the LR didn't receive the suggested color  
698     
699   } // if there a return value
700   
701
702   //-------------------------------------------
703   // Now color all args of the call instruction
704   //-------------------------------------------
705
706   std::vector<MachineInstr *> AddedInstrnsBefore;
707
708   unsigned NumOfCallArgs =  getCallInstNumArgs( CallMI );
709
710   bool VarArgCall = isVarArgCall( CallMI );
711
712   if(VarArgCall) cerr << "\nVar arg call found!!\n";
713
714   for(unsigned argNo=0, i=0; i < NumOfCallArgs; ++i, ++argNo ) {
715
716     const Value *CallArg = CallMI->getImplicitRef(i);
717
718     // get the LR of call operand (parameter)
719     LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
720
721     unsigned RegType = getRegType( CallArg );
722     unsigned RegClassID =  getRegClassIDOfValue( CallArg);
723     
724     // find whether this argument is coming in a register (if not, on stack)
725
726     bool isArgInReg = false;
727     unsigned UniArgReg = InvalidRegNum;  // reg that LR must be colored with
728
729     if( (RegType== IntRegType && argNo <  NumOfIntArgRegs)) {
730       isArgInReg = true;
731       UniArgReg = getUnifiedRegNum(RegClassID, SparcIntRegOrder::o0 + argNo );
732     }
733     else if(RegType == FPSingleRegType && argNo < NumOfFloatArgRegs)  { 
734       isArgInReg = true;
735
736       if( !VarArgCall )
737         UniArgReg = getUnifiedRegNum(RegClassID, 
738                                      SparcFloatRegOrder::f0 + (argNo*2 + 1) );
739       else {                   
740         // a variable argument call - must pass float arg in %o's
741         if( argNo <  NumOfIntArgRegs)
742           UniArgReg=getUnifiedRegNum(IntRegClassID,SparcIntRegOrder::o0+argNo);
743         else    
744           isArgInReg = false;
745       }   
746
747     }
748     else if(RegType == FPDoubleRegType && argNo < NumOfFloatArgRegs)  { 
749       isArgInReg = true;
750
751       if( !VarArgCall )
752         UniArgReg =getUnifiedRegNum(RegClassID,SparcFloatRegOrder::f0+argNo*2);
753       else {                   
754         // a variable argument call - must pass float arg in %o's
755         if( argNo <  NumOfIntArgRegs)
756           UniArgReg=getUnifiedRegNum(IntRegClassID,SparcIntRegOrder::o0+argNo);
757         else    
758           isArgInReg = false;
759       }   
760     }
761
762     // not possible to have a null LR since all args (even consts)  
763     // must be defined before
764     if (!LR) {          
765       cerr << " ERROR: In call instr, no LR for arg:  " << RAV(CallArg) << "\n";
766       assert(0 && "NO LR for call arg");  
767     }
768
769
770     if (LR->hasColor()) {
771       unsigned UniLRReg = getUnifiedRegNum( RegClassID,  LR->getColor() );
772
773       // if LR received the correct color, nothing to do
774       if( UniLRReg == UniArgReg )
775         continue;
776
777       // We are here because though the LR is allocated a register, it
778       // was not allocated the suggested register. So, we have to copy %ix reg 
779       // (or stack pos of arg) to the register it was colored with
780
781       // the LR is colored with UniLRReg but has to go into  UniArgReg
782       // to pass it as an argument
783
784       if( isArgInReg ) {
785
786         if( VarArgCall && RegClassID == FloatRegClassID ) {
787
788   
789           // for a variable argument call, the float reg must go in a %o reg.
790           // We have to move a float reg to an int reg via memory.
791           // The store instruction will be directly added to  
792           // CallAI->InstrnsBefore since it does not need reordering
793           // 
794           int TmpOff = PRA.mcInfo.pushTempValue(target,  
795                                                getSpilledRegSize(RegType));
796
797           AdMI = cpReg2MemMI(UniLRReg, getFramePointer(), TmpOff, RegType );
798           CallAI->InstrnsBefore.push_back( AdMI ); 
799
800           AdMI = cpMem2RegMI(getFramePointer(), TmpOff, UniArgReg, IntRegType);
801           AddedInstrnsBefore.push_back( AdMI ); 
802         }
803
804         else {  
805           AdMI = cpReg2RegMI(UniLRReg, UniArgReg, RegType );
806           AddedInstrnsBefore.push_back( AdMI ); 
807         }
808
809       } else {
810         // Now, we have to pass the arg on stack. Since LR received a register
811         // we just have to move that register to the stack position where
812         // the argument must be passed
813
814         int argOffset = PRA.mcInfo.allocateOptionalArg(target, LR->getType()); 
815
816         AdMI = cpReg2MemMI(UniLRReg, getStackPointer(), argOffset, RegType );
817
818         // Now add the instruction. We can directly add to
819         // CallAI->InstrnsBefore since we are just saving a reg on stack
820         //
821         CallAI->InstrnsBefore.push_back( AdMI ); 
822
823         //cerr << "\nCaution: Passing a reg on stack";
824       }
825
826
827     } else {                          // LR is not colored (i.e., spilled)      
828       
829       if( isArgInReg ) {
830
831         // Now the LR did NOT recieve a register but has a stack poistion.
832         // Since, the outgoing arg goes in a register we just have to insert
833         // a load instruction to load the LR to outgoing register
834
835         if( VarArgCall && RegClassID == FloatRegClassID ) 
836           AdMI = cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(),
837                              UniArgReg, IntRegType );
838         else
839           AdMI = cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(),
840                              UniArgReg, RegType );
841         
842         cerr << "\nCaution: Loading a spilled val to a reg as a call arg";
843         AddedInstrnsBefore.push_back( AdMI );  // Now add the instruction
844       }
845       
846       else {
847         // Now, we have to pass the arg on stack. Since LR  also did NOT
848         // receive a register we have to move an argument in memory to 
849         // outgoing parameter on stack.
850         
851         // Optoimize: Optimize when reverse pointers in MahineInstr are
852         // introduced. 
853         // call PRA.getUnusedRegAtMI(....) to get an unused reg. Only if this
854         // fails, then use the following code. Currently, we cannot call the
855         // above method since we cannot find LVSetBefore without the BB 
856         
857         int TReg = PRA.getUniRegNotUsedByThisInst( LR->getRegClass(), CallMI );
858
859         int TmpOff = PRA.mcInfo.pushTempValue(target,  
860                                     getSpilledRegSize(getRegType(LR)) );
861
862         
863         int argOffset = PRA.mcInfo.allocateOptionalArg(target, LR->getType()); 
864         
865         MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
866         
867         // Sequence:
868         // (1) Save TReg on stack    
869         // (2) Load LR value into TReg from stack pos of LR
870         // (3) Store Treg on outgoing Arg pos on stack
871         // (4) Load the old value of TReg from stack to TReg (restore it)
872
873         Ad1 = cpReg2MemMI(TReg, getFramePointer(), TmpOff, RegType );
874         Ad2 = cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(), 
875                           TReg, RegType ); 
876         Ad3 = cpReg2MemMI(TReg, getStackPointer(), argOffset, RegType );
877         Ad4 = cpMem2RegMI(getFramePointer(), TmpOff, TReg, RegType ); 
878
879         // We directly add to CallAI->InstrnsBefore instead of adding to
880         // AddedInstrnsBefore since these instructions must not be
881         // reordered.
882         
883         CallAI->InstrnsBefore.push_back( Ad1 );  
884         CallAI->InstrnsBefore.push_back( Ad2 );  
885         CallAI->InstrnsBefore.push_back( Ad3 );  
886         CallAI->InstrnsBefore.push_back( Ad4 );  
887
888         cerr << "\nCaution: Call arg moved from stack2stack for: " << *CallMI ;
889       }
890     }
891   }  // for each parameter in call instruction
892
893
894   // if we added any instruction before the call instruction, verify
895   // that they are in the proper order and if not, reorder them
896
897   if (!AddedInstrnsBefore.empty()) {
898
899     if (DEBUG_RA) {
900       cerr << "\nCalling reorder with instrns: \n";
901       for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
902         cerr  << *(AddedInstrnsBefore[i]);
903     }
904
905     std::vector<MachineInstr *> TmpVec;
906     OrderAddedInstrns(AddedInstrnsBefore, TmpVec, PRA);
907
908     if (DEBUG_RA) {
909       cerr << "\nAfter reordering instrns: \n";
910       for(unsigned i = 0; i < TmpVec.size(); i++)
911         cerr << *TmpVec[i];
912     }
913
914     // copy the results back from TmpVec to InstrnsBefore
915     for(unsigned i=0; i < TmpVec.size(); i++)
916       CallAI->InstrnsBefore.push_back( TmpVec[i] );
917   }
918
919
920   // now insert caller saving code for this call instruction
921   //
922   insertCallerSavingCode(CallMI, BB, PRA);
923
924   // Reset optional args area again to be safe
925   PRA.mcInfo.resetOptionalArgs(target);
926 }
927
928 //---------------------------------------------------------------------------
929 // This method is called for an LLVM return instruction to identify which
930 // values will be returned from this method and to suggest colors.
931 //---------------------------------------------------------------------------
932 void UltraSparcRegInfo::suggestReg4RetValue(const MachineInstr *RetMI, 
933                                             LiveRangeInfo &LRI) const {
934
935   assert( (UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode() ) );
936
937     suggestReg4RetAddr(RetMI, LRI);
938
939   // if there is an implicit ref, that has to be the ret value
940   if(  RetMI->getNumImplicitRefs() > 0 ) {
941
942     // The first implicit operand is the return value of a return instr
943     const Value *RetVal =  RetMI->getImplicitRef(0);
944
945     LiveRange *const LR = LRI.getLiveRangeForValue( RetVal ); 
946
947     if (!LR) {
948       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
949       assert(0 && "No LR for return value of non-void method");
950     }
951
952     unsigned RegClassID = (LR->getRegClass())->getID();
953       
954     if (RegClassID == IntRegClassID) 
955       LR->setSuggestedColor(SparcIntRegOrder::i0);
956     else if (RegClassID == FloatRegClassID) 
957       LR->setSuggestedColor(SparcFloatRegOrder::f0);
958   }
959 }
960
961
962
963 //---------------------------------------------------------------------------
964 // Colors the return value of a method to %i0 or %f0, if possible. If it is
965 // not possilbe to directly color the LR, insert a copy instruction to move
966 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we 
967 // have to put a load instruction.
968 //---------------------------------------------------------------------------
969 void UltraSparcRegInfo::colorRetValue(const MachineInstr *RetMI, 
970                                       LiveRangeInfo &LRI,
971                                       AddedInstrns *RetAI) const {
972
973   assert((UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode()));
974
975   // if there is an implicit ref, that has to be the ret value
976   if(RetMI->getNumImplicitRefs() > 0) {
977
978     // The first implicit operand is the return value of a return instr
979     const Value *RetVal =  RetMI->getImplicitRef(0);
980
981     LiveRange *LR = LRI.getLiveRangeForValue(RetVal); 
982
983     if (!LR) {
984       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
985       // assert( LR && "No LR for return value of non-void method");
986       return;
987     }
988
989     unsigned RegClassID =  getRegClassIDOfValue(RetVal);
990     unsigned RegType = getRegType( RetVal );
991
992     unsigned CorrectCol;
993     if(RegClassID == IntRegClassID)
994       CorrectCol = SparcIntRegOrder::i0;
995     else if(RegClassID == FloatRegClassID)
996       CorrectCol = SparcFloatRegOrder::f0;
997     else {
998       assert (0 && "Unknown RegClass");
999       return;
1000     }
1001
1002     // if the LR received the correct color, NOTHING to do
1003
1004     if (LR->hasColor() && LR->getColor() == CorrectCol)
1005       return;
1006
1007     unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
1008
1009     if (LR->hasColor()) {
1010
1011       // We are here because the LR was allocted a regiter
1012       // It may be the suggested register or not
1013
1014       // copy the LR of retun value to i0 or f0
1015
1016       unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
1017
1018       // the LR received  UniLRReg but must be colored with UniRetReg
1019       // to pass as the return value
1020       RetAI->InstrnsBefore.push_back(cpReg2RegMI(UniLRReg, UniRetReg, RegType));
1021     }
1022     else {                              // if the LR is spilled
1023       MachineInstr *AdMI = cpMem2RegMI(getFramePointer(),
1024                                        LR->getSpillOffFromFP(), 
1025                                        UniRetReg, RegType); 
1026       RetAI->InstrnsBefore.push_back(AdMI);
1027       cerr << "\nCopied the return value from stack\n";
1028     }
1029   
1030   } // if there is a return value
1031
1032 }
1033
1034
1035 //---------------------------------------------------------------------------
1036 // Copy from a register to register. Register number must be the unified
1037 // register number
1038 //---------------------------------------------------------------------------
1039
1040 MachineInstr * UltraSparcRegInfo::cpReg2RegMI(unsigned SrcReg, unsigned DestReg,
1041                                               int RegType) const {
1042
1043   assert( ((int)SrcReg != InvalidRegNum) && ((int)DestReg != InvalidRegNum) &&
1044           "Invalid Register");
1045   
1046   MachineInstr * MI = NULL;
1047
1048   switch( RegType ) {
1049     
1050   case IntRegType:
1051   case IntCCRegType:
1052   case FloatCCRegType: 
1053     MI = new MachineInstr(ADD, 3);
1054     MI->SetMachineOperandReg(0, SrcReg, false);
1055     MI->SetMachineOperandReg(1, this->getZeroRegNum(), false);
1056     MI->SetMachineOperandReg(2, DestReg, true);
1057     break;
1058
1059   case FPSingleRegType:
1060     MI = new MachineInstr(FMOVS, 2);
1061     MI->SetMachineOperandReg(0, SrcReg, false);
1062     MI->SetMachineOperandReg(1, DestReg, true);
1063     break;
1064
1065   case FPDoubleRegType:
1066     MI = new MachineInstr(FMOVD, 2);
1067     MI->SetMachineOperandReg(0, SrcReg, false);    
1068     MI->SetMachineOperandReg(1, DestReg, true);
1069     break;
1070
1071   default:
1072     assert(0 && "Unknow RegType");
1073   }
1074
1075   return MI;
1076 }
1077
1078
1079 //---------------------------------------------------------------------------
1080 // Copy from a register to memory (i.e., Store). Register number must 
1081 // be the unified register number
1082 //---------------------------------------------------------------------------
1083
1084
1085 MachineInstr * UltraSparcRegInfo::cpReg2MemMI(unsigned SrcReg, 
1086                                               unsigned DestPtrReg,
1087                                               int Offset, int RegType) const {
1088   MachineInstr * MI = NULL;
1089   switch( RegType ) {
1090   case IntRegType:
1091   case FloatCCRegType: 
1092     MI = new MachineInstr(STX, 3);
1093     MI->SetMachineOperandReg(0, SrcReg, false);
1094     MI->SetMachineOperandReg(1, DestPtrReg, false);
1095     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1096                                (int64_t) Offset);
1097     break;
1098
1099   case FPSingleRegType:
1100     MI = new MachineInstr(ST, 3);
1101     MI->SetMachineOperandReg(0, SrcReg, false);
1102     MI->SetMachineOperandReg(1, DestPtrReg, false);
1103     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1104                                (int64_t) Offset);
1105     break;
1106
1107   case FPDoubleRegType:
1108     MI = new MachineInstr(STD, 3);
1109     MI->SetMachineOperandReg(0, SrcReg, false);
1110     MI->SetMachineOperandReg(1, DestPtrReg, false);
1111     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1112                                (int64_t) Offset);
1113     break;
1114
1115   case IntCCRegType:
1116     assert( 0 && "Cannot directly store %ccr to memory");
1117     
1118   default:
1119     assert(0 && "Unknow RegType in cpReg2MemMI");
1120   }
1121
1122   return MI;
1123 }
1124
1125
1126 //---------------------------------------------------------------------------
1127 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1128 // register number
1129 //---------------------------------------------------------------------------
1130
1131
1132 MachineInstr * UltraSparcRegInfo::cpMem2RegMI(unsigned SrcPtrReg,       
1133                                               int Offset,
1134                                               unsigned DestReg,
1135                                               int RegType) const {
1136   MachineInstr * MI = NULL;
1137   switch (RegType) {
1138   case IntRegType:
1139   case FloatCCRegType: 
1140     MI = new MachineInstr(LDX, 3);
1141     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1142     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1143                                (int64_t) Offset);
1144     MI->SetMachineOperandReg(2, DestReg, true);
1145     break;
1146
1147   case FPSingleRegType:
1148     MI = new MachineInstr(LD, 3);
1149     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1150     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1151                                (int64_t) Offset);
1152     MI->SetMachineOperandReg(2, DestReg, true);
1153
1154     break;
1155
1156   case FPDoubleRegType:
1157     MI = new MachineInstr(LDD, 3);
1158     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1159     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1160                                (int64_t) Offset);
1161     MI->SetMachineOperandReg(2, DestReg, true);
1162     break;
1163
1164   case IntCCRegType:
1165     assert( 0 && "Cannot directly load into %ccr from memory");
1166
1167   default:
1168     assert(0 && "Unknown RegType in cpMem2RegMI");
1169   }
1170
1171   return MI;
1172 }
1173
1174
1175
1176
1177
1178 //---------------------------------------------------------------------------
1179 // Generate a copy instruction to copy a value to another. Temporarily
1180 // used by PhiElimination code.
1181 //---------------------------------------------------------------------------
1182
1183
1184 MachineInstr *UltraSparcRegInfo::cpValue2Value(Value *Src, Value *Dest) const {
1185   int RegType = getRegType( Src );
1186
1187   assert( (RegType==getRegType(Src))  && "Src & Dest are diff types");
1188
1189   MachineInstr * MI = NULL;
1190
1191   switch( RegType ) {
1192   case IntRegType:
1193     MI = new MachineInstr(ADD, 3);
1194     MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1195     MI->SetMachineOperandReg(1, this->getZeroRegNum(), false);
1196     MI->SetMachineOperandVal(2, MachineOperand:: MO_VirtualRegister, Dest, true);
1197     break;
1198
1199   case FPSingleRegType:
1200     MI = new MachineInstr(FMOVS, 2);
1201     MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1202     MI->SetMachineOperandVal(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1203     break;
1204
1205
1206   case FPDoubleRegType:
1207     MI = new MachineInstr(FMOVD, 2);
1208     MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1209     MI->SetMachineOperandVal(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1210     break;
1211
1212   default:
1213     assert(0 && "Unknow RegType in CpValu2Value");
1214   }
1215
1216   return MI;
1217 }
1218
1219
1220
1221
1222
1223
1224 //----------------------------------------------------------------------------
1225 // This method inserts caller saving/restoring instructons before/after
1226 // a call machine instruction. The caller saving/restoring instructions are
1227 // inserted like:
1228 //
1229 //    ** caller saving instructions
1230 //    other instructions inserted for the call by ColorCallArg
1231 //    CALL instruction
1232 //    other instructions inserted for the call ColorCallArg
1233 //    ** caller restoring instructions
1234 //
1235 //----------------------------------------------------------------------------
1236
1237
1238 void UltraSparcRegInfo::insertCallerSavingCode(const MachineInstr *MInst, 
1239                                                const BasicBlock *BB,
1240                                                PhyRegAlloc &PRA) const {
1241
1242   // has set to record which registers were saved/restored
1243   //
1244   std::hash_set<unsigned> PushedRegSet;
1245
1246   // Now find the LR of the return value of the call
1247   // The last *implicit operand* is the return value of a call
1248   // Insert it to to he PushedRegSet since we must not save that register
1249   // and restore it after the call.
1250   // We do this because, we look at the LV set *after* the instruction
1251   // to determine, which LRs must be saved across calls. The return value
1252   // of the call is live in this set - but we must not save/restore it.
1253
1254
1255   const Value *RetVal = getCallInstRetVal( MInst );
1256
1257   if (RetVal) {
1258     LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( RetVal );
1259     assert(RetValLR && "No LR for RetValue of call");
1260
1261     if (RetValLR->hasColor())
1262       PushedRegSet.insert(
1263          getUnifiedRegNum((RetValLR->getRegClass())->getID(), 
1264                                       RetValLR->getColor() ) );
1265   }
1266
1267
1268   const ValueSet &LVSetAft =  PRA.LVI->getLiveVarSetAfterMInst(MInst, BB);
1269   ValueSet::const_iterator LIt = LVSetAft.begin();
1270
1271   // for each live var in live variable set after machine inst
1272   for( ; LIt != LVSetAft.end(); ++LIt) {
1273
1274    //  get the live range corresponding to live var
1275     LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );    
1276
1277     // LR can be null if it is a const since a const 
1278     // doesn't have a dominating def - see Assumptions above
1279     if( LR )   {  
1280       
1281       if( LR->hasColor() ) {
1282
1283         unsigned RCID = (LR->getRegClass())->getID();
1284         unsigned Color = LR->getColor();
1285
1286         if ( isRegVolatile(RCID, Color) ) {
1287
1288           // if the value is in both LV sets (i.e., live before and after 
1289           // the call machine instruction)
1290
1291           unsigned Reg = getUnifiedRegNum(RCID, Color);
1292           
1293           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1294             
1295             // if we haven't already pushed that register
1296
1297             unsigned RegType = getRegType( LR );
1298
1299             // Now get two instructions - to push on stack and pop from stack
1300             // and add them to InstrnsBefore and InstrnsAfter of the
1301             // call instruction
1302
1303
1304             int StackOff =  PRA.mcInfo.pushTempValue(target,  
1305                                                getSpilledRegSize(RegType));
1306
1307             
1308             MachineInstr *AdIBefCC=NULL, *AdIAftCC=NULL, *AdICpCC;
1309             MachineInstr *AdIBef=NULL, *AdIAft=NULL;
1310
1311             //---- Insert code for pushing the reg on stack ----------
1312                   
1313             if( RegType == IntCCRegType ) {
1314
1315               // Handle IntCCRegType specially since we cannot directly 
1316               // push %ccr on to the stack
1317
1318               const ValueSet &LVSetBef = 
1319                 PRA.LVI->getLiveVarSetBeforeMInst(MInst, BB);
1320
1321               // get a free INTEGER register
1322               int FreeIntReg = 
1323                 PRA.getUsableUniRegAtMI(PRA.getRegClassByID(IntRegClassID) /*LR->getRegClass()*/,
1324                                         IntRegType, MInst, &LVSetBef, AdIBefCC, AdIAftCC);
1325               
1326               // insert the instructions in reverse order since we are
1327               // adding them to the front of InstrnsBefore
1328
1329               if(AdIAftCC)
1330                 PRA.AddedInstrMap[MInst].InstrnsBefore.push_front(AdIAftCC);
1331
1332               AdICpCC = cpCCR2IntMI(FreeIntReg);
1333               PRA.AddedInstrMap[MInst].InstrnsBefore.push_front(AdICpCC);
1334
1335               if(AdIBefCC)
1336                 PRA.AddedInstrMap[MInst].InstrnsBefore.push_front(AdIBefCC);
1337
1338               if(DEBUG_RA) {
1339                 cerr << "\n!! Inserted caller saving (push) inst for %ccr:";
1340                 if(AdIBefCC) cerr << "\t" <<  *(AdIBefCC);
1341                 cerr  << "\t" << *AdICpCC;
1342                 if(AdIAftCC) cerr  << "\t" << *(AdIAftCC);
1343               }
1344
1345             } else  {  
1346               // for any other register type, just add the push inst
1347               AdIBef = cpReg2MemMI(Reg, getFramePointer(), StackOff, RegType );
1348               PRA.AddedInstrMap[MInst].InstrnsBefore.push_front(AdIBef);
1349             }
1350
1351
1352             //---- Insert code for popping the reg from the stack ----------
1353
1354             if (RegType == IntCCRegType) {
1355
1356               // Handle IntCCRegType specially since we cannot directly 
1357               // pop %ccr on from the stack
1358               
1359               // get a free INT register
1360               int FreeIntReg = 
1361                 PRA.getUsableUniRegAtMI(PRA.getRegClassByID(IntRegClassID) /* LR->getRegClass()*/,
1362                                         IntRegType, MInst, &LVSetAft, AdIBefCC, AdIAftCC);
1363               
1364               if(AdIBefCC)
1365                 PRA.AddedInstrMap[MInst].InstrnsAfter.push_back(AdIBefCC);
1366
1367               AdICpCC = cpInt2CCRMI(FreeIntReg);
1368               PRA.AddedInstrMap[MInst].InstrnsAfter.push_back(AdICpCC);
1369             
1370               if(AdIAftCC)
1371                 PRA.AddedInstrMap[MInst].InstrnsAfter.push_back(AdIAftCC);
1372
1373               if(DEBUG_RA) {
1374
1375                 cerr << "\n!! Inserted caller saving (pop) inst for %ccr:";
1376                 if(AdIBefCC) cerr << "\t" <<  *(AdIBefCC);
1377                 cerr  << "\t" << *AdICpCC;
1378                 if(AdIAftCC) cerr  << "\t" << *(AdIAftCC);
1379               }
1380
1381             } else {
1382               // for any other register type, just add the pop inst
1383               AdIAft = cpMem2RegMI(getFramePointer(), StackOff, Reg, RegType );
1384               PRA.AddedInstrMap[MInst].InstrnsAfter.push_back(AdIAft);
1385             }
1386             
1387             PushedRegSet.insert(Reg);
1388
1389             if(DEBUG_RA) {
1390               cerr << "\nFor call inst:" << *MInst;
1391               cerr << " -inserted caller saving instrs:\n\t ";
1392               if( RegType == IntCCRegType ) {
1393                 if(AdIBefCC) cerr << *AdIBefCC << "\t";
1394                 if(AdIAftCC) cerr << *AdIAftCC;
1395               }
1396               else {
1397                 if(AdIBef) cerr << *AdIBef << "\t";
1398                 if(AdIAft) cerr << *AdIAft;
1399               }
1400             }       
1401           } // if not already pushed
1402
1403         } // if LR has a volatile color
1404         
1405       } // if LR has color
1406
1407     } // if there is a LR for Var
1408     
1409   } // for each value in the LV set after instruction
1410   
1411 }
1412
1413 //---------------------------------------------------------------------------
1414 // Copies %ccr into an integer register. IntReg is the UNIFIED register
1415 // number.
1416 //---------------------------------------------------------------------------
1417
1418 MachineInstr * UltraSparcRegInfo::cpCCR2IntMI(unsigned IntReg) const {
1419   MachineInstr * MI = new MachineInstr(RDCCR, 2);
1420   MI->SetMachineOperandReg(0, this->getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
1421                                                      SparcIntCCRegOrder::ccr),
1422                            false, true);
1423   MI->SetMachineOperandReg(1, IntReg, true);
1424   return MI;
1425 }
1426
1427 //---------------------------------------------------------------------------
1428 // Copies an integer register into  %ccr. IntReg is the UNIFIED register
1429 // number.
1430 //---------------------------------------------------------------------------
1431
1432 MachineInstr *UltraSparcRegInfo::cpInt2CCRMI(unsigned IntReg) const {
1433   MachineInstr *MI = new MachineInstr(WRCCR, 3);
1434   MI->SetMachineOperandReg(0, IntReg, false);
1435   MI->SetMachineOperandReg(1, this->getZeroRegNum(), false);
1436   MI->SetMachineOperandReg(2, this->getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID, SparcIntCCRegOrder::ccr),
1437                            true, true);
1438   return MI;
1439 }
1440
1441
1442
1443
1444 //---------------------------------------------------------------------------
1445 // Print the register assigned to a LR
1446 //---------------------------------------------------------------------------
1447
1448 void UltraSparcRegInfo::printReg(const LiveRange *LR) {
1449   unsigned RegClassID = (LR->getRegClass())->getID();
1450   cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1451
1452   if (!LR->hasColor()) {
1453     cerr << " - could not find a color\n";
1454     return;
1455   }
1456   
1457   // if a color is found
1458
1459   cerr << " colored with color "<< LR->getColor();
1460
1461   if (RegClassID == IntRegClassID) {
1462     cerr<< " [" << SparcIntRegOrder::getRegName(LR->getColor()) << "]\n";
1463
1464   } else if (RegClassID == FloatRegClassID) {
1465     cerr << "[" << SparcFloatRegOrder::getRegName(LR->getColor());
1466     if( LR->getType() == Type::DoubleTy)
1467       cerr << "+" << SparcFloatRegOrder::getRegName(LR->getColor()+1);
1468     cerr << "]\n";
1469   }
1470 }
1471
1472 //---------------------------------------------------------------------------
1473 // This method examines instructions inserted by RegAlloc code before a
1474 // machine instruction to detect invalid orders that destroy values before
1475 // they are used. If it detects such conditions, it reorders the instructions.
1476 //
1477 // The unordered instructions come in the UnordVec. These instructions are
1478 // instructions inserted by RegAlloc. All such instruction MUST have 
1479 // their USES BEFORE THE DEFS after reordering.
1480
1481 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1482 // this method is called.
1483
1484 // This method uses two vectors for efficiency in accessing
1485
1486 // Since instructions are inserted in RegAlloc, this assumes that the 
1487 // first operand is the source reg and the last operand is the dest reg.
1488
1489 // All the uses are before THE def to a register
1490
1491
1492 //---------------------------------------------------------------------------
1493 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr *> &UnordVec,
1494                                           std::vector<MachineInstr *> &OrdVec,
1495                                           PhyRegAlloc &PRA) const{
1496
1497   /*
1498     Problem: We can have instructions inserted by RegAlloc like
1499     1. add %ox %g0 %oy
1500     2. add %oy %g0 %oz, where z!=x or z==x
1501
1502     This is wrong since %oy used by 2 is overwritten by 1
1503   
1504     Solution:
1505     We re-order the instructions so that the uses are before the defs
1506
1507     Algorithm:
1508     
1509     do
1510       for each instruction 'DefInst' in the UnOrdVec
1511          for each instruction 'UseInst' that follows the DefInst
1512            if the reg defined by DefInst is used by UseInst
1513              mark DefInst as not movable in this iteration
1514          If DefInst is not marked as not-movable, move DefInst to OrdVec
1515     while all instructions in DefInst are moved to OrdVec
1516     
1517     For moving, we call the move2OrdVec(). It checks whether there is a def
1518     in it for the uses in the instruction to be added to OrdVec. If there
1519     are no preceding defs, it just appends the instruction. If there is a
1520     preceding def, it puts two instructions to save the reg on stack before
1521     the load and puts a restore at use.
1522
1523   */
1524
1525   bool CouldMoveAll;
1526   bool DebugPrint = false;
1527
1528   do {
1529     CouldMoveAll = true;
1530     std::vector<MachineInstr *>::iterator DefIt = UnordVec.begin();
1531
1532     for( ; DefIt !=  UnordVec.end(); ++DefIt ) {
1533
1534       // for each instruction in the UnordVec do ...
1535
1536       MachineInstr *DefInst = *DefIt;
1537
1538       if( DefInst == NULL) continue;
1539
1540       //cerr << "\nInst in UnordVec = " <<  *DefInst;
1541       
1542       // last operand is the def (unless for a store which has no def reg)
1543       MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1544       
1545       if( DefOp.opIsDef() &&  
1546           DefOp.getOperandType() ==  MachineOperand::MO_MachineRegister) {
1547         
1548         // If the operand in DefInst is a def ...
1549         
1550         bool DefEqUse = false;
1551         
1552         std::vector<MachineInstr *>::iterator UseIt = DefIt;
1553         UseIt++;
1554         
1555         for( ; UseIt !=  UnordVec.end(); ++UseIt ) {
1556
1557           MachineInstr *UseInst = *UseIt;
1558           if( UseInst == NULL) continue;
1559           
1560           // for each inst (UseInst) that is below the DefInst do ...
1561           MachineOperand& UseOp = UseInst->getOperand(0);
1562           
1563           if( ! UseOp.opIsDef() &&  
1564               UseOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1565             
1566             // if use is a register ...
1567             
1568             if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1569               
1570               // if Def and this use are the same, it means that this use
1571               // is destroyed by a def before it is used
1572               
1573               // cerr << "\nCouldn't move " << *DefInst;
1574
1575               DefEqUse = true;
1576               CouldMoveAll = false;     
1577               DebugPrint = true;
1578               break;
1579             } // if two registers are equal
1580             
1581           } // if use is a register
1582           
1583         }// for all use instructions
1584         
1585         if( ! DefEqUse ) {
1586           
1587           // after examining all the instructions that follow the DefInst
1588           // if there are no dependencies, we can move it to the OrdVec
1589
1590           // cerr << "Moved to Ord: " << *DefInst;
1591
1592           moveInst2OrdVec(OrdVec, DefInst, PRA);
1593
1594           //OrdVec.push_back(DefInst);
1595
1596           // mark the pos of DefInst with NULL to indicate that it is
1597           // empty
1598           *DefIt = NULL;
1599         }
1600     
1601       } // if Def is a machine register
1602       
1603     } // for all instructions in the UnordVec
1604     
1605
1606   } while(!CouldMoveAll);
1607
1608   if (DebugPrint) {
1609     cerr << "\nAdded instructions were reordered to:\n";
1610     for(unsigned int i=0; i < OrdVec.size(); i++)
1611       cerr << *(OrdVec[i]);
1612   }
1613 }
1614
1615
1616
1617
1618
1619 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
1620                                         MachineInstr *UnordInst,
1621                                         PhyRegAlloc &PRA) const {
1622   MachineOperand& UseOp = UnordInst->getOperand(0);
1623
1624   if( ! UseOp.opIsDef() &&  
1625       UseOp.getOperandType() ==  MachineOperand::MO_MachineRegister) {
1626
1627     // for the use of UnordInst, see whether there is a defining instr
1628     // before in the OrdVec
1629     bool DefEqUse = false;
1630
1631     std::vector<MachineInstr *>::iterator OrdIt = OrdVec.begin();
1632   
1633     for( ; OrdIt !=  OrdVec.end(); ++OrdIt ) {
1634
1635       MachineInstr *OrdInst = *OrdIt ;
1636
1637       MachineOperand& DefOp = 
1638         OrdInst->getOperand(OrdInst->getNumOperands()-1);
1639
1640       if( DefOp.opIsDef() &&  
1641           DefOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1642
1643         //cerr << "\nDefining Ord Inst: " <<  *OrdInst;
1644           
1645         if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1646
1647           // we are here because there is a preceding def in the OrdVec 
1648           // for the use in this intr we are going to insert. This
1649           // happened because the original code was like:
1650           // 1. add %ox %g0 %oy
1651           // 2. add %oy %g0 %ox
1652           // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1653           // Now we are processing %ox of 1.
1654           // We have to 
1655               
1656           const int UReg = DefOp.getMachineRegNum();
1657           const int RegType = getRegType(UReg);
1658           MachineInstr *AdIBef, *AdIAft;
1659               
1660           const int StackOff =  PRA.mcInfo.pushTempValue(target,
1661                                          getSpilledRegSize(RegType));
1662           
1663           // Save the UReg (%ox) on stack before it's destroyed
1664           AdIBef=cpReg2MemMI(UReg, getFramePointer(), StackOff, RegType);
1665           OrdIt = OrdVec.insert( OrdIt, AdIBef);
1666           OrdIt++;  // points to current instr we processed
1667           
1668           // Load directly into DReg (%oy)
1669           MachineOperand&  DOp=
1670             (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1671           assert(DOp.opIsDef() && "Last operand is not the def");
1672           const int DReg = DOp.getMachineRegNum();
1673           
1674           AdIAft=cpMem2RegMI(getFramePointer(), StackOff, DReg, RegType);
1675           OrdVec.push_back(AdIAft);
1676             
1677           cerr << "\nFixed CIRCULAR references by reordering";
1678
1679           if( DEBUG_RA ) {
1680             cerr << "\nBefore CIRCULAR Reordering:\n";
1681             cerr << *UnordInst;
1682             cerr << *OrdInst;
1683           
1684             cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1685             for(unsigned i=0; i < OrdVec.size(); i++)
1686               cerr << *(OrdVec[i]);
1687           }
1688           
1689           // Do not copy the UseInst to OrdVec
1690           DefEqUse = true;
1691           break;  
1692           
1693         }// if two registers are equal
1694
1695       } // if Def is a register
1696
1697     } // for each instr in OrdVec
1698
1699     if(!DefEqUse) {  
1700
1701       // We didn't find a def in the OrdVec, so just append this inst
1702       OrdVec.push_back( UnordInst );  
1703       //cerr << "Reordered Inst (Moved Dn): " <<  *UnordInst;
1704     }
1705     
1706   }// if the operand in UnordInst is a use
1707 }