- Added some SSE2 128-bit packed integer ops.
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9RegInfo.cpp
1 //===-- SparcV9RegInfo.cpp - SparcV9 Target Register Information ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains implementations of SparcV9 specific helper methods
11 // used for register allocation.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "MachineFunctionInfo.h"
18 #include "MachineCodeForInstruction.h"
19 #include "MachineInstrAnnot.h"
20 #include "RegAlloc/LiveRangeInfo.h"
21 #include "RegAlloc/LiveRange.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "SparcV9Internals.h"
26 #include "SparcV9RegClassInfo.h"
27 #include "SparcV9RegInfo.h"
28 #include "SparcV9FrameInfo.h"
29 #include "SparcV9TargetMachine.h"
30 #include "SparcV9TmpInstr.h"
31 #include <iostream>
32
33 namespace llvm {
34
35 enum {
36   BadRegClass = ~0
37 };
38
39 SparcV9RegInfo::SparcV9RegInfo(const SparcV9TargetMachine &tgt)
40   : target (tgt), NumOfIntArgRegs (6), NumOfFloatArgRegs (32)
41 {
42   MachineRegClassArr.push_back(new SparcV9IntRegClass(IntRegClassID));
43   MachineRegClassArr.push_back(new SparcV9FloatRegClass(FloatRegClassID));
44   MachineRegClassArr.push_back(new SparcV9IntCCRegClass(IntCCRegClassID));
45   MachineRegClassArr.push_back(new SparcV9FloatCCRegClass(FloatCCRegClassID));
46   MachineRegClassArr.push_back(new SparcV9SpecialRegClass(SpecialRegClassID));
47
48   assert(SparcV9FloatRegClass::StartOfNonVolatileRegs == 32 &&
49          "32 Float regs are used for float arg passing");
50 }
51
52
53 // getZeroRegNum - returns the register that contains always zero.
54 // this is the unified register number
55 //
56 unsigned SparcV9RegInfo::getZeroRegNum() const {
57   return getUnifiedRegNum(SparcV9RegInfo::IntRegClassID,
58                           SparcV9IntRegClass::g0);
59 }
60
61 // getCallAddressReg - returns the reg used for pushing the address when a
62 // method is called. This can be used for other purposes between calls
63 //
64 unsigned SparcV9RegInfo::getCallAddressReg() const {
65   return getUnifiedRegNum(SparcV9RegInfo::IntRegClassID,
66                           SparcV9IntRegClass::o7);
67 }
68
69 // Returns the register containing the return address.
70 // It should be made sure that this  register contains the return
71 // value when a return instruction is reached.
72 //
73 unsigned SparcV9RegInfo::getReturnAddressReg() const {
74   return getUnifiedRegNum(SparcV9RegInfo::IntRegClassID,
75                           SparcV9IntRegClass::i7);
76 }
77
78 // Register get name implementations...
79
80 // Int register names in same order as enum in class SparcV9IntRegClass
81 static const char * const IntRegNames[] = {
82   "o0", "o1", "o2", "o3", "o4", "o5",       "o7",
83   "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
84   "i0", "i1", "i2", "i3", "i4", "i5",
85   "i6", "i7",
86   "g0", "g1", "g2", "g3", "g4", "g5",  "g6", "g7",
87   "o6"
88 };
89
90 const char * const SparcV9IntRegClass::getRegName(unsigned reg) const {
91   assert(reg < NumOfAllRegs);
92   return IntRegNames[reg];
93 }
94
95 static const char * const FloatRegNames[] = {
96   "f0",  "f1",  "f2",  "f3",  "f4",  "f5",  "f6",  "f7",  "f8",  "f9",
97   "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19",
98   "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29",
99   "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39",
100   "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49",
101   "f50", "f51", "f52", "f53", "f54", "f55", "f56", "f57", "f58", "f59",
102   "f60", "f61", "f62", "f63"
103 };
104
105 const char * const SparcV9FloatRegClass::getRegName(unsigned reg) const {
106   assert (reg < NumOfAllRegs);
107   return FloatRegNames[reg];
108 }
109
110 static const char * const IntCCRegNames[] = {
111   "xcc",  "icc",  "ccr"
112 };
113
114 const char * const SparcV9IntCCRegClass::getRegName(unsigned reg) const {
115   assert(reg < 3);
116   return IntCCRegNames[reg];
117 }
118
119 static const char * const FloatCCRegNames[] = {
120   "fcc0", "fcc1",  "fcc2",  "fcc3"
121 };
122
123 const char * const SparcV9FloatCCRegClass::getRegName(unsigned reg) const {
124   assert (reg < 4);
125   return FloatCCRegNames[reg];
126 }
127
128 static const char * const SpecialRegNames[] = {
129   "fsr"
130 };
131
132 const char * const SparcV9SpecialRegClass::getRegName(unsigned reg) const {
133   assert (reg < 1);
134   return SpecialRegNames[reg];
135 }
136
137 // Get unified reg number for frame pointer
138 unsigned SparcV9RegInfo::getFramePointer() const {
139   return getUnifiedRegNum(SparcV9RegInfo::IntRegClassID,
140                           SparcV9IntRegClass::i6);
141 }
142
143 // Get unified reg number for stack pointer
144 unsigned SparcV9RegInfo::getStackPointer() const {
145   return getUnifiedRegNum(SparcV9RegInfo::IntRegClassID,
146                           SparcV9IntRegClass::o6);
147 }
148
149
150 //---------------------------------------------------------------------------
151 // Finds whether a call is an indirect call
152 //---------------------------------------------------------------------------
153
154 inline bool
155 isVarArgsFunction(const Type *funcType) {
156   return cast<FunctionType>(cast<PointerType>(funcType)
157                             ->getElementType())->isVarArg();
158 }
159
160 inline bool
161 isVarArgsCall(const MachineInstr *CallMI) {
162   Value* callee = CallMI->getOperand(0).getVRegValue();
163   // const Type* funcType = isa<Function>(callee)? callee->getType()
164   //   : cast<PointerType>(callee->getType())->getElementType();
165   const Type* funcType = callee->getType();
166   return isVarArgsFunction(funcType);
167 }
168
169
170 // Get the register number for the specified argument #argNo,
171 //
172 // Return value:
173 //      getInvalidRegNum(),  if there is no int register available for the arg.
174 //      regNum,              otherwise (this is NOT the unified reg. num).
175 //                           regClassId is set to the register class ID.
176 //
177 int
178 SparcV9RegInfo::regNumForIntArg(bool inCallee, bool isVarArgsCall,
179                                    unsigned argNo, unsigned& regClassId) const
180 {
181   regClassId = IntRegClassID;
182   if (argNo >= NumOfIntArgRegs)
183     return getInvalidRegNum();
184   else
185     return argNo + (inCallee? SparcV9IntRegClass::i0 : SparcV9IntRegClass::o0);
186 }
187
188 // Get the register number for the specified FP argument #argNo,
189 // Use INT regs for FP args if this is a varargs call.
190 //
191 // Return value:
192 //      getInvalidRegNum(),  if there is no int register available for the arg.
193 //      regNum,              otherwise (this is NOT the unified reg. num).
194 //                           regClassId is set to the register class ID.
195 //
196 int
197 SparcV9RegInfo::regNumForFPArg(unsigned regType,
198                                   bool inCallee, bool isVarArgsCall,
199                                   unsigned argNo, unsigned& regClassId) const
200 {
201   if (isVarArgsCall)
202     return regNumForIntArg(inCallee, isVarArgsCall, argNo, regClassId);
203   else
204     {
205       regClassId = FloatRegClassID;
206       if (regType == FPSingleRegType)
207         return (argNo*2+1 >= NumOfFloatArgRegs)?
208           getInvalidRegNum() : SparcV9FloatRegClass::f0 + (argNo * 2 + 1);
209       else if (regType == FPDoubleRegType)
210         return (argNo*2 >= NumOfFloatArgRegs)?
211           getInvalidRegNum() : SparcV9FloatRegClass::f0 + (argNo * 2);
212       else
213         assert(0 && "Illegal FP register type");
214         return 0;
215     }
216 }
217
218
219 //---------------------------------------------------------------------------
220 // Finds the return address of a call sparc specific call instruction
221 //---------------------------------------------------------------------------
222
223 // The following 4  methods are used to find the RegType (SparcV9Internals.h)
224 // of a V9LiveRange, a Value, and for a given register unified reg number.
225 //
226 int SparcV9RegInfo::getRegTypeForClassAndType(unsigned regClassID,
227                                                  const Type* type) const
228 {
229   switch (regClassID) {
230   case IntRegClassID:                   return IntRegType;
231   case FloatRegClassID:
232     if (type == Type::FloatTy)          return FPSingleRegType;
233     else if (type == Type::DoubleTy)    return FPDoubleRegType;
234     assert(0 && "Unknown type in FloatRegClass"); return 0;
235   case IntCCRegClassID:                 return IntCCRegType;
236   case FloatCCRegClassID:               return FloatCCRegType;
237   case SpecialRegClassID:               return SpecialRegType;
238   default: assert( 0 && "Unknown reg class ID"); return 0;
239   }
240 }
241
242 int SparcV9RegInfo::getRegTypeForDataType(const Type* type) const
243 {
244   return getRegTypeForClassAndType(getRegClassIDOfType(type), type);
245 }
246
247 int SparcV9RegInfo::getRegTypeForLR(const V9LiveRange *LR) const
248 {
249   return getRegTypeForClassAndType(LR->getRegClassID(), LR->getType());
250 }
251
252 int SparcV9RegInfo::getRegType(int unifiedRegNum) const
253 {
254   if (unifiedRegNum < 32)
255     return IntRegType;
256   else if (unifiedRegNum < (32 + 32))
257     return FPSingleRegType;
258   else if (unifiedRegNum < (64 + 32))
259     return FPDoubleRegType;
260   else if (unifiedRegNum < (64+32+3))
261     return IntCCRegType;
262   else if (unifiedRegNum < (64+32+3+4))
263     return FloatCCRegType;
264   else if (unifiedRegNum < (64+32+3+4+1))
265     return SpecialRegType;
266   else
267     assert(0 && "Invalid unified register number in getRegType");
268   return 0;
269 }
270
271
272 // To find the register class used for a specified Type
273 //
274 unsigned SparcV9RegInfo::getRegClassIDOfType(const Type *type,
275                                                 bool isCCReg) const {
276   Type::TypeID ty = type->getTypeID();
277   unsigned res;
278
279   // FIXME: Comparing types like this isn't very safe...
280   if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
281       (ty == Type::FunctionTyID) ||  (ty == Type::PointerTyID) )
282     res = IntRegClassID;             // sparc int reg (ty=0: void)
283   else if (ty <= Type::DoubleTyID)
284     res = FloatRegClassID;           // sparc float reg class
285   else {
286     //std::cerr << "TypeID: " << ty << "\n";
287     assert(0 && "Cannot resolve register class for type");
288     return 0;
289   }
290
291   if (isCCReg)
292     return res + 2;      // corresponding condition code register
293   else
294     return res;
295 }
296
297 unsigned SparcV9RegInfo::getRegClassIDOfRegType(int regType) const {
298   switch(regType) {
299   case IntRegType:      return IntRegClassID;
300   case FPSingleRegType:
301   case FPDoubleRegType: return FloatRegClassID;
302   case IntCCRegType:    return IntCCRegClassID;
303   case FloatCCRegType:  return FloatCCRegClassID;
304   case SpecialRegType:  return SpecialRegClassID;
305   default:
306     assert(0 && "Invalid register type in getRegClassIDOfRegType");
307     return 0;
308   }
309 }
310
311 //---------------------------------------------------------------------------
312 // Suggests a register for the ret address in the RET machine instruction.
313 // We always suggest %i7 by convention.
314 //---------------------------------------------------------------------------
315 void SparcV9RegInfo::suggestReg4RetAddr(MachineInstr *RetMI,
316                                            LiveRangeInfo& LRI) const {
317
318   assert(target.getInstrInfo()->isReturn(RetMI->getOpcode()));
319
320   // return address is always mapped to i7 so set it immediately
321   RetMI->SetRegForOperand(0, getUnifiedRegNum(IntRegClassID,
322                                               SparcV9IntRegClass::i7));
323
324   // Possible Optimization:
325   // Instead of setting the color, we can suggest one. In that case,
326   // we have to test later whether it received the suggested color.
327   // In that case, a LR has to be created at the start of method.
328   // It has to be done as follows (remove the setRegVal above):
329
330   // MachineOperand & MO  = RetMI->getOperand(0);
331   // const Value *RetAddrVal = MO.getVRegValue();
332   // assert( RetAddrVal && "LR for ret address must be created at start");
333   // V9LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);
334   // RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID,
335   //                              SparcV9IntRegOrdr::i7) );
336 }
337
338
339 //---------------------------------------------------------------------------
340 // Suggests a register for the ret address in the JMPL/CALL machine instr.
341 // SparcV9 ABI dictates that %o7 be used for this purpose.
342 //---------------------------------------------------------------------------
343 void
344 SparcV9RegInfo::suggestReg4CallAddr(MachineInstr * CallMI,
345                                        LiveRangeInfo& LRI) const
346 {
347   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
348   const Value *RetAddrVal = argDesc->getReturnAddrReg();
349   assert(RetAddrVal && "INTERNAL ERROR: Return address value is required");
350
351   // A LR must already exist for the return address.
352   V9LiveRange *RetAddrLR = LRI.getLiveRangeForValue(RetAddrVal);
353   assert(RetAddrLR && "INTERNAL ERROR: No LR for return address of call!");
354
355   unsigned RegClassID = RetAddrLR->getRegClassID();
356   RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID, SparcV9IntRegClass::o7));
357 }
358
359
360
361 //---------------------------------------------------------------------------
362 //  This method will suggest colors to incoming args to a method.
363 //  According to the SparcV9 ABI, the first 6 incoming args are in
364 //  %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
365 //  If the arg is passed on stack due to the lack of regs, NOTHING will be
366 //  done - it will be colored (or spilled) as a normal live range.
367 //---------------------------------------------------------------------------
368 void SparcV9RegInfo::suggestRegs4MethodArgs(const Function *Meth,
369                                                LiveRangeInfo& LRI) const
370 {
371   // Check if this is a varArgs function. needed for choosing regs.
372   bool isVarArgs = isVarArgsFunction(Meth->getType());
373
374   // Count the arguments, *ignoring* whether they are int or FP args.
375   // Use this common arg numbering to pick the right int or fp register.
376   unsigned argNo=0;
377   for(Function::const_arg_iterator I = Meth->arg_begin(), E = Meth->arg_end();
378       I != E; ++I, ++argNo) {
379     V9LiveRange *LR = LRI.getLiveRangeForValue(I);
380     assert(LR && "No live range found for method arg");
381
382     unsigned regType = getRegTypeForLR(LR);
383     unsigned regClassIDOfArgReg = BadRegClass; // for chosen reg (unused)
384
385     int regNum = (regType == IntRegType)
386       ? regNumForIntArg(/*inCallee*/ true, isVarArgs, argNo, regClassIDOfArgReg)
387       : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs, argNo,
388                        regClassIDOfArgReg);
389
390     if (regNum != getInvalidRegNum())
391       LR->setSuggestedColor(regNum);
392   }
393 }
394
395
396 //---------------------------------------------------------------------------
397 // This method is called after graph coloring to move incoming args to
398 // the correct hardware registers if they did not receive the correct
399 // (suggested) color through graph coloring.
400 //---------------------------------------------------------------------------
401 void SparcV9RegInfo::colorMethodArgs(const Function *Meth,
402                             LiveRangeInfo &LRI,
403                             std::vector<MachineInstr*>& InstrnsBefore,
404                             std::vector<MachineInstr*>& InstrnsAfter) const {
405
406   // check if this is a varArgs function. needed for choosing regs.
407   bool isVarArgs = isVarArgsFunction(Meth->getType());
408   MachineInstr *AdMI;
409
410   // for each argument
411   // for each argument.  count INT and FP arguments separately.
412   unsigned argNo=0, intArgNo=0, fpArgNo=0;
413   for(Function::const_arg_iterator I = Meth->arg_begin(), E = Meth->arg_end();
414       I != E; ++I, ++argNo) {
415     // get the LR of arg
416     V9LiveRange *LR = LRI.getLiveRangeForValue(I);
417     assert( LR && "No live range found for method arg");
418
419     unsigned regType = getRegTypeForLR(LR);
420     unsigned RegClassID = LR->getRegClassID();
421
422     // Find whether this argument is coming in a register (if not, on stack)
423     // Also find the correct register the argument must use (UniArgReg)
424     //
425     bool isArgInReg = false;
426     unsigned UniArgReg = getInvalidRegNum(); // reg that LR MUST be colored with
427     unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
428
429     int regNum = (regType == IntRegType)
430       ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
431                         argNo, regClassIDOfArgReg)
432       : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
433                        argNo, regClassIDOfArgReg);
434
435     if(regNum != getInvalidRegNum()) {
436       isArgInReg = true;
437       UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
438     }
439
440     if( ! LR->isMarkedForSpill() ) {    // if this arg received a register
441
442       unsigned UniLRReg = getUnifiedRegNum(  RegClassID, LR->getColor() );
443
444       // if LR received the correct color, nothing to do
445       //
446       if( UniLRReg == UniArgReg )
447         continue;
448
449       // We are here because the LR did not receive the suggested
450       // but LR received another register.
451       // Now we have to copy the %i reg (or stack pos of arg)
452       // to the register the LR was colored with.
453
454       // if the arg is coming in UniArgReg register, it MUST go into
455       // the UniLRReg register
456       //
457       if( isArgInReg ) {
458         if( regClassIDOfArgReg != RegClassID ) {
459           // NOTE: This code has not been well-tested.
460
461           // It is a variable argument call: the float reg must go in a %o reg.
462           // We have to move an int reg to a float reg via memory.
463           //
464           assert(isVarArgs &&
465                  RegClassID == FloatRegClassID &&
466                  regClassIDOfArgReg == IntRegClassID &&
467                  "This should only be an Int register for an FP argument");
468
469           int TmpOff = MachineFunction::get(Meth).getInfo<SparcV9FunctionInfo>()->pushTempValue(
470                                                 getSpilledRegSize(regType));
471           cpReg2MemMI(InstrnsBefore,
472                       UniArgReg, getFramePointer(), TmpOff, IntRegType);
473
474           cpMem2RegMI(InstrnsBefore,
475                       getFramePointer(), TmpOff, UniLRReg, regType);
476         }
477         else {
478           cpReg2RegMI(InstrnsBefore, UniArgReg, UniLRReg, regType);
479         }
480       }
481       else {
482
483         // Now the arg is coming on stack. Since the LR received a register,
484         // we just have to load the arg on stack into that register
485         //
486         const TargetFrameInfo& frameInfo = *target.getFrameInfo();
487         int offsetFromFP =
488           frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
489                                          argNo);
490
491         // float arguments on stack are right justified so adjust the offset!
492         // int arguments are also right justified but they are always loaded as
493         // a full double-word so the offset does not need to be adjusted.
494         if (regType == FPSingleRegType) {
495           unsigned argSize = target.getTargetData().getTypeSize(LR->getType());
496           unsigned slotSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
497           assert(argSize <= slotSize && "Insufficient slot size!");
498           offsetFromFP += slotSize - argSize;
499         }
500
501         cpMem2RegMI(InstrnsBefore,
502                     getFramePointer(), offsetFromFP, UniLRReg, regType);
503       }
504
505     } // if LR received a color
506
507     else {
508
509       // Now, the LR did not receive a color. But it has a stack offset for
510       // spilling.
511       // So, if the arg is coming in UniArgReg register,  we can just move
512       // that on to the stack pos of LR
513
514       if( isArgInReg ) {
515
516         if( regClassIDOfArgReg != RegClassID ) {
517           assert(0 &&
518                  "FP arguments to a varargs function should be explicitly "
519                  "copied to/from int registers by instruction selection!");
520
521           // It must be a float arg for a variable argument call, which
522           // must come in a %o reg.  Move the int reg to the stack.
523           //
524           assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
525                  "This should only be an Int register for an FP argument");
526
527           cpReg2MemMI(InstrnsBefore, UniArgReg,
528                       getFramePointer(), LR->getSpillOffFromFP(), IntRegType);
529         }
530         else {
531            cpReg2MemMI(InstrnsBefore, UniArgReg,
532                        getFramePointer(), LR->getSpillOffFromFP(), regType);
533         }
534       }
535
536       else {
537
538         // Now the arg is coming on stack. Since the LR did NOT
539         // received a register as well, it is allocated a stack position. We
540         // can simply change the stack position of the LR. We can do this,
541         // since this method is called before any other method that makes
542         // uses of the stack pos of the LR (e.g., updateMachineInstr)
543         //
544         const TargetFrameInfo& frameInfo = *target.getFrameInfo();
545         int offsetFromFP =
546           frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
547                                          argNo);
548
549         // FP arguments on stack are right justified so adjust offset!
550         // int arguments are also right justified but they are always loaded as
551         // a full double-word so the offset does not need to be adjusted.
552         if (regType == FPSingleRegType) {
553           unsigned argSize = target.getTargetData().getTypeSize(LR->getType());
554           unsigned slotSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
555           assert(argSize <= slotSize && "Insufficient slot size!");
556           offsetFromFP += slotSize - argSize;
557         }
558
559         LR->modifySpillOffFromFP( offsetFromFP );
560       }
561
562     }
563
564   }  // for each incoming argument
565
566 }
567
568
569
570 //---------------------------------------------------------------------------
571 // This method is called before graph coloring to suggest colors to the
572 // outgoing call args and the return value of the call.
573 //---------------------------------------------------------------------------
574 void SparcV9RegInfo::suggestRegs4CallArgs(MachineInstr *CallMI,
575                                              LiveRangeInfo& LRI) const {
576   assert ( (target.getInstrInfo())->isCall(CallMI->getOpcode()) );
577
578   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
579
580   suggestReg4CallAddr(CallMI, LRI);
581
582   // First color the return value of the call instruction, if any.
583   // The return value will be in %o0 if the value is an integer type,
584   // or in %f0 if the value is a float type.
585   //
586   if (const Value *RetVal = argDesc->getReturnValue()) {
587     V9LiveRange *RetValLR = LRI.getLiveRangeForValue(RetVal);
588     assert(RetValLR && "No LR for return Value of call!");
589
590     unsigned RegClassID = RetValLR->getRegClassID();
591
592     // now suggest a register depending on the register class of ret arg
593     if( RegClassID == IntRegClassID )
594       RetValLR->setSuggestedColor(SparcV9IntRegClass::o0);
595     else if (RegClassID == FloatRegClassID )
596       RetValLR->setSuggestedColor(SparcV9FloatRegClass::f0 );
597     else assert( 0 && "Unknown reg class for return value of call\n");
598   }
599
600   // Now suggest colors for arguments (operands) of the call instruction.
601   // Colors are suggested only if the arg number is smaller than the
602   // the number of registers allocated for argument passing.
603   // Now, go thru call args - implicit operands of the call MI
604
605   unsigned NumOfCallArgs = argDesc->getNumArgs();
606
607   for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
608        i < NumOfCallArgs; ++i, ++argNo) {
609
610     const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
611
612     // get the LR of call operand (parameter)
613     V9LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
614     if (!LR)
615       continue;                    // no live ranges for constants and labels
616
617     unsigned regType = getRegTypeForLR(LR);
618     unsigned regClassIDOfArgReg = BadRegClass; // chosen reg class (unused)
619
620     // Choose a register for this arg depending on whether it is
621     // an INT or FP value.  Here we ignore whether or not it is a
622     // varargs calls, because FP arguments will be explicitly copied
623     // to an integer Value and handled under (argCopy != NULL) below.
624     int regNum = (regType == IntRegType)
625       ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
626                         argNo, regClassIDOfArgReg)
627       : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
628                        argNo, regClassIDOfArgReg);
629
630     // If a register could be allocated, use it.
631     // If not, do NOTHING as this will be colored as a normal value.
632     if(regNum != getInvalidRegNum())
633       LR->setSuggestedColor(regNum);
634   } // for all call arguments
635 }
636
637
638 //---------------------------------------------------------------------------
639 // this method is called for an LLVM return instruction to identify which
640 // values will be returned from this method and to suggest colors.
641 //---------------------------------------------------------------------------
642 void SparcV9RegInfo::suggestReg4RetValue(MachineInstr *RetMI,
643                                             LiveRangeInfo& LRI) const {
644
645   assert( target.getInstrInfo()->isReturn( RetMI->getOpcode() ) );
646
647   suggestReg4RetAddr(RetMI, LRI);
648
649   // To find the return value (if any), we can get the LLVM return instr.
650   // from the return address register, which is the first operand
651   Value* tmpI = RetMI->getOperand(0).getVRegValue();
652   ReturnInst* retI=cast<ReturnInst>(cast<TmpInstruction>(tmpI)->getOperand(0));
653   if (const Value *RetVal = retI->getReturnValue())
654     if (V9LiveRange *const LR = LRI.getLiveRangeForValue(RetVal))
655       LR->setSuggestedColor(LR->getRegClassID() == IntRegClassID
656                             ? (unsigned) SparcV9IntRegClass::i0
657                             : (unsigned) SparcV9FloatRegClass::f0);
658 }
659
660 //---------------------------------------------------------------------------
661 // Check if a specified register type needs a scratch register to be
662 // copied to/from memory.  If it does, the reg. type that must be used
663 // for scratch registers is returned in scratchRegType.
664 //
665 // Only the int CC register needs such a scratch register.
666 // The FP CC registers can (and must) be copied directly to/from memory.
667 //---------------------------------------------------------------------------
668
669 bool
670 SparcV9RegInfo::regTypeNeedsScratchReg(int RegType,
671                                           int& scratchRegType) const
672 {
673   if (RegType == IntCCRegType)
674     {
675       scratchRegType = IntRegType;
676       return true;
677     }
678   return false;
679 }
680
681 //---------------------------------------------------------------------------
682 // Copy from a register to register. Register number must be the unified
683 // register number.
684 //---------------------------------------------------------------------------
685
686 void
687 SparcV9RegInfo::cpReg2RegMI(std::vector<MachineInstr*>& mvec,
688                                unsigned SrcReg,
689                                unsigned DestReg,
690                                int RegType) const {
691   assert( ((int)SrcReg != getInvalidRegNum()) &&
692           ((int)DestReg != getInvalidRegNum()) &&
693           "Invalid Register");
694
695   MachineInstr * MI = NULL;
696
697   switch( RegType ) {
698
699   case IntCCRegType:
700     if (getRegType(DestReg) == IntRegType) {
701       // copy intCC reg to int reg
702       MI = (BuildMI(V9::RDCCR, 2)
703             .addMReg(getUnifiedRegNum(SparcV9RegInfo::IntCCRegClassID,
704                                       SparcV9IntCCRegClass::ccr))
705             .addMReg(DestReg,MachineOperand::Def));
706     } else {
707       // copy int reg to intCC reg
708       assert(getRegType(SrcReg) == IntRegType
709              && "Can only copy CC reg to/from integer reg");
710       MI = (BuildMI(V9::WRCCRr, 3)
711             .addMReg(SrcReg)
712             .addMReg(SparcV9IntRegClass::g0)
713             .addMReg(getUnifiedRegNum(SparcV9RegInfo::IntCCRegClassID,
714                                       SparcV9IntCCRegClass::ccr),
715                      MachineOperand::Def));
716     }
717     break;
718
719   case FloatCCRegType:
720     assert(0 && "Cannot copy FPCC register to any other register");
721     break;
722
723   case IntRegType:
724     MI = BuildMI(V9::ADDr, 3).addMReg(SrcReg).addMReg(getZeroRegNum())
725       .addMReg(DestReg, MachineOperand::Def);
726     break;
727
728   case FPSingleRegType:
729     MI = BuildMI(V9::FMOVS, 2).addMReg(SrcReg)
730            .addMReg(DestReg, MachineOperand::Def);
731     break;
732
733   case FPDoubleRegType:
734     MI = BuildMI(V9::FMOVD, 2).addMReg(SrcReg)
735            .addMReg(DestReg, MachineOperand::Def);
736     break;
737
738   default:
739     assert(0 && "Unknown RegType");
740     break;
741   }
742
743   if (MI)
744     mvec.push_back(MI);
745 }
746
747 /// cpReg2MemMI - Generate SparcV9 MachineInstrs to store a register
748 /// (SrcReg) to memory, at [PtrReg + Offset].  Register numbers must be the
749 /// unified register numbers.  RegType must be the SparcV9 register type
750 /// of SrcReg. When SrcReg is %ccr, scratchReg must be the
751 /// number of a free integer register.  The newly-generated MachineInstrs
752 /// are appended to mvec.
753 ///
754 void SparcV9RegInfo::cpReg2MemMI(std::vector<MachineInstr*>& mvec,
755                                  unsigned SrcReg, unsigned PtrReg, int Offset,
756                                  int RegType, int scratchReg) const {
757   unsigned OffReg = SparcV9::g4; // Use register g4 for holding large offsets
758   bool useImmediateOffset = true;
759
760   // If the Offset will not fit in the signed-immediate field, we put it in
761   // register g4. This takes advantage of the fact that all the opcodes
762   // used below have the same size immed. field.
763   if (RegType != IntCCRegType
764       && !target.getInstrInfo()->constantFitsInImmedField(V9::LDXi, Offset)) {
765     // Put the offset into a register. We could do this in fewer steps,
766     // in some cases (see CreateSETSWConst()) but we're being lazy.
767     MachineInstr *MI = BuildMI(V9::SETHI, 2).addZImm(Offset).addMReg(OffReg,
768       MachineOperand::Def);
769     MI->getOperand(0).markHi32();
770     mvec.push_back(MI);
771     MI = BuildMI(V9::ORi,3).addMReg(OffReg).addZImm(Offset).addMReg(OffReg,
772       MachineOperand::Def);
773     MI->getOperand(1).markLo32();
774     mvec.push_back(MI);
775     MI = BuildMI(V9::SRAi5,3).addMReg(OffReg).addZImm(0).addMReg(OffReg,
776       MachineOperand::Def);
777     mvec.push_back(MI);
778     useImmediateOffset = false;
779   }
780
781   MachineInstr *MI = 0;
782   switch (RegType) {
783   case IntRegType:
784     if (useImmediateOffset)
785       MI = BuildMI(V9::STXi,3).addMReg(SrcReg).addMReg(PtrReg).addSImm(Offset);
786     else
787       MI = BuildMI(V9::STXr,3).addMReg(SrcReg).addMReg(PtrReg).addMReg(OffReg);
788     break;
789
790   case FPSingleRegType:
791     if (useImmediateOffset)
792       MI = BuildMI(V9::STFi, 3).addMReg(SrcReg).addMReg(PtrReg).addSImm(Offset);
793     else
794       MI = BuildMI(V9::STFr, 3).addMReg(SrcReg).addMReg(PtrReg).addMReg(OffReg);
795     break;
796
797   case FPDoubleRegType:
798     if (useImmediateOffset)
799       MI = BuildMI(V9::STDFi,3).addMReg(SrcReg).addMReg(PtrReg).addSImm(Offset);
800     else
801       MI = BuildMI(V9::STDFr,3).addMReg(SrcReg).addMReg(PtrReg).addSImm(OffReg);
802     break;
803
804   case IntCCRegType:
805     assert(scratchReg >= 0 && getRegType(scratchReg) == IntRegType
806            && "Need a scratch reg of integer type to load or store %ccr");
807     MI = BuildMI(V9::RDCCR, 2).addMReg(SparcV9::ccr)
808            .addMReg(scratchReg, MachineOperand::Def);
809     mvec.push_back(MI);
810     cpReg2MemMI(mvec, scratchReg, PtrReg, Offset, IntRegType);
811     return;
812
813   case SpecialRegType: // used only for %fsr itself.
814   case FloatCCRegType: {
815     if (useImmediateOffset)
816       MI = BuildMI(V9::STXFSRi,3).addMReg(SparcV9::fsr).addMReg(PtrReg)
817              .addSImm(Offset);
818     else
819       MI = BuildMI(V9::STXFSRr,3).addMReg(SparcV9::fsr).addMReg(PtrReg)
820              .addMReg(OffReg);
821     break;
822   }
823   default:
824     assert(0 && "Unknown RegType in cpReg2MemMI");
825   }
826   mvec.push_back(MI);
827 }
828
829 /// cpMem2RegMI - Generate SparcV9 MachineInstrs to load a register
830 /// (DestReg) from memory, at [PtrReg + Offset].  Register numbers must be the
831 /// unified register numbers.  RegType must be the SparcV9 register type
832 /// of DestReg. When DestReg is %ccr, scratchReg must be the
833 /// number of a free integer register.  The newly-generated MachineInstrs
834 /// are appended to mvec.
835 ///
836 void SparcV9RegInfo::cpMem2RegMI(std::vector<MachineInstr*>& mvec,
837                                  unsigned PtrReg, int Offset, unsigned DestReg,
838                                  int RegType, int scratchReg) const {
839   unsigned OffReg = SparcV9::g4; // Use register g4 for holding large offsets
840   bool useImmediateOffset = true;
841
842   // If the Offset will not fit in the signed-immediate field, we put it in
843   // register g4. This takes advantage of the fact that all the opcodes
844   // used below have the same size immed. field.
845   if (RegType != IntCCRegType
846       && !target.getInstrInfo()->constantFitsInImmedField(V9::LDXi, Offset)) {
847     MachineInstr *MI = BuildMI(V9::SETHI, 2).addZImm(Offset).addMReg(OffReg,
848       MachineOperand::Def);
849     MI->getOperand(0).markHi32();
850     mvec.push_back(MI);
851     MI = BuildMI(V9::ORi,3).addMReg(OffReg).addZImm(Offset).addMReg(OffReg,
852       MachineOperand::Def);
853     MI->getOperand(1).markLo32();
854     mvec.push_back(MI);
855     MI = BuildMI(V9::SRAi5,3).addMReg(OffReg).addZImm(0).addMReg(OffReg,
856       MachineOperand::Def);
857     mvec.push_back(MI);
858     useImmediateOffset = false;
859   }
860
861   MachineInstr *MI = 0;
862   switch (RegType) {
863   case IntRegType:
864     if (useImmediateOffset)
865       MI = BuildMI(V9::LDXi, 3).addMReg(PtrReg).addSImm(Offset)
866           .addMReg(DestReg, MachineOperand::Def);
867     else
868       MI = BuildMI(V9::LDXr, 3).addMReg(PtrReg).addMReg(OffReg)
869           .addMReg(DestReg, MachineOperand::Def);
870     break;
871
872   case FPSingleRegType:
873     if (useImmediateOffset)
874       MI = BuildMI(V9::LDFi, 3).addMReg(PtrReg).addSImm(Offset)
875           .addMReg(DestReg, MachineOperand::Def);
876     else
877       MI = BuildMI(V9::LDFr, 3).addMReg(PtrReg).addMReg(OffReg)
878           .addMReg(DestReg, MachineOperand::Def);
879     break;
880
881   case FPDoubleRegType:
882     if (useImmediateOffset)
883       MI= BuildMI(V9::LDDFi, 3).addMReg(PtrReg).addSImm(Offset)
884           .addMReg(DestReg, MachineOperand::Def);
885     else
886       MI= BuildMI(V9::LDDFr, 3).addMReg(PtrReg).addMReg(OffReg)
887           .addMReg(DestReg, MachineOperand::Def);
888     break;
889
890   case IntCCRegType:
891     assert(scratchReg >= 0 && getRegType(scratchReg) == IntRegType
892            && "Need a scratch reg of integer type to load or store %ccr");
893     cpMem2RegMI(mvec, PtrReg, Offset, scratchReg, IntRegType);
894     MI = BuildMI(V9::WRCCRr, 3).addMReg(scratchReg).addMReg(SparcV9::g0)
895            .addMReg(SparcV9::ccr, MachineOperand::Def);
896     break;
897
898   case SpecialRegType: // used only for %fsr itself
899   case FloatCCRegType: {
900     if (useImmediateOffset)
901       MI = BuildMI(V9::LDXFSRi, 3).addMReg(PtrReg).addSImm(Offset)
902         .addMReg(SparcV9::fsr, MachineOperand::Def);
903     else
904       MI = BuildMI(V9::LDXFSRr, 3).addMReg(PtrReg).addMReg(OffReg)
905         .addMReg(SparcV9::fsr, MachineOperand::Def);
906     break;
907   }
908   default:
909     assert(0 && "Unknown RegType in cpMem2RegMI");
910   }
911   mvec.push_back(MI);
912 }
913
914
915 //---------------------------------------------------------------------------
916 // Generate a copy instruction to copy a value to another. Temporarily
917 // used by PhiElimination code.
918 //---------------------------------------------------------------------------
919
920
921 void
922 SparcV9RegInfo::cpValue2Value(Value *Src, Value *Dest,
923                               std::vector<MachineInstr*>& mvec) const {
924   int RegType = getRegTypeForDataType(Src->getType());
925   MachineInstr * MI = NULL;
926
927   switch (RegType) {
928   case IntRegType:
929     MI = BuildMI(V9::ADDr, 3).addReg(Src).addMReg(getZeroRegNum())
930       .addRegDef(Dest);
931     break;
932   case FPSingleRegType:
933     MI = BuildMI(V9::FMOVS, 2).addReg(Src).addRegDef(Dest);
934     break;
935   case FPDoubleRegType:
936     MI = BuildMI(V9::FMOVD, 2).addReg(Src).addRegDef(Dest);
937     break;
938   default:
939     assert(0 && "Unknown RegType in cpValue2Value");
940   }
941
942   mvec.push_back(MI);
943 }
944
945
946
947 //---------------------------------------------------------------------------
948 // Print the register assigned to a LR
949 //---------------------------------------------------------------------------
950
951 void SparcV9RegInfo::printReg(const V9LiveRange *LR) const {
952   unsigned RegClassID = LR->getRegClassID();
953   std::cerr << " Node ";
954
955   if (!LR->hasColor()) {
956     std::cerr << " - could not find a color\n";
957     return;
958   }
959
960   // if a color is found
961
962   std::cerr << " colored with color "<< LR->getColor();
963
964   unsigned uRegName = getUnifiedRegNum(RegClassID, LR->getColor());
965
966   std::cerr << "[";
967   std::cerr<< getUnifiedRegName(uRegName);
968   if (RegClassID == FloatRegClassID && LR->getType() == Type::DoubleTy)
969     std::cerr << "+" << getUnifiedRegName(uRegName+1);
970   std::cerr << "]\n";
971 }
972
973 } // End llvm namespace