Added function getCallInstIndirectAddrVal() to set call interference
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9Internals.h
1 // $Id$ -*- C++ -*--
2 //***************************************************************************
3 // File:
4 //      SparcInternals.h
5 // 
6 // Purpose:
7 //       This file defines stuff that is to be private to the Sparc
8 //       backend, but is shared among different portions of the backend.
9 //**************************************************************************/
10
11
12 #ifndef SPARC_INTERNALS_H
13 #define SPARC_INTERNALS_H
14
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/MachineInstrInfo.h"
17 #include "llvm/Target/MachineSchedInfo.h"
18 #include "llvm/Target/MachineFrameInfo.h"
19 #include "llvm/Target/MachineCacheInfo.h"
20 #include "llvm/Target/MachineRegInfo.h"
21 #include "llvm/Type.h"
22 #include <sys/types.h>
23
24 class LiveRange;
25 class UltraSparc;
26 class PhyRegAlloc;
27
28
29 // OpCodeMask definitions for the Sparc V9
30 // 
31 const OpCodeMask        Immed           = 0x00002000; // immed or reg operand?
32 const OpCodeMask        Annul           = 0x20000000; // annul delay instr?
33 const OpCodeMask        PredictTaken    = 0x00080000; // predict branch taken?
34
35
36 enum SparcInstrSchedClass {
37   SPARC_NONE,           /* Instructions with no scheduling restrictions */
38   SPARC_IEUN,           /* Integer class that can use IEU0 or IEU1 */
39   SPARC_IEU0,           /* Integer class IEU0 */
40   SPARC_IEU1,           /* Integer class IEU1 */
41   SPARC_FPM,            /* FP Multiply or Divide instructions */
42   SPARC_FPA,            /* All other FP instructions */ 
43   SPARC_CTI,            /* Control-transfer instructions */
44   SPARC_LD,             /* Load instructions */
45   SPARC_ST,             /* Store instructions */
46   SPARC_SINGLE,         /* Instructions that must issue by themselves */
47   
48   SPARC_INV,            /* This should stay at the end for the next value */
49   SPARC_NUM_SCHED_CLASSES = SPARC_INV
50 };
51
52
53 //---------------------------------------------------------------------------
54 // enum SparcMachineOpCode. 
55 // const MachineInstrDescriptor SparcMachineInstrDesc[]
56 // 
57 // Purpose:
58 //   Description of UltraSparc machine instructions.
59 // 
60 //---------------------------------------------------------------------------
61
62 enum SparcMachineOpCode {
63 #define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
64           NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS)             \
65    ENUM,
66 #include "SparcInstr.def"
67
68   // End-of-array marker
69   INVALID_OPCODE,
70   NUM_REAL_OPCODES = PHI,               // number of valid opcodes
71   NUM_TOTAL_OPCODES = INVALID_OPCODE
72 };
73
74
75 // Array of machine instruction descriptions...
76 extern const MachineInstrDescriptor SparcMachineInstrDesc[];
77
78
79 //---------------------------------------------------------------------------
80 // class UltraSparcInstrInfo 
81 // 
82 // Purpose:
83 //   Information about individual instructions.
84 //   Most information is stored in the SparcMachineInstrDesc array above.
85 //   Other information is computed on demand, and most such functions
86 //   default to member functions in base class MachineInstrInfo. 
87 //---------------------------------------------------------------------------
88
89 class UltraSparcInstrInfo : public MachineInstrInfo {
90 public:
91   /*ctor*/      UltraSparcInstrInfo(const TargetMachine& tgt);
92
93   //
94   // All immediate constants are in position 1 except the
95   // store instructions.
96   // 
97   virtual int getImmedConstantPos(MachineOpCode opCode) const {
98     bool ignore;
99     if (this->maxImmedConstant(opCode, ignore) != 0)
100       {
101         assert(! this->isStore((MachineOpCode) STB - 1)); // first store is STB
102         assert(! this->isStore((MachineOpCode) STD + 1)); // last  store is STD
103         return (opCode >= STB && opCode <= STD)? 2 : 1;
104       }
105     else
106       return -1;
107   }
108   
109   virtual bool          hasResultInterlock      (MachineOpCode opCode) const
110   {
111     // All UltraSPARC instructions have interlocks (note that delay slots
112     // are not considered here).
113     // However, instructions that use the result of an FCMP produce a
114     // 9-cycle stall if they are issued less than 3 cycles after the FCMP.
115     // Force the compiler to insert a software interlock (i.e., gap of
116     // 2 other groups, including NOPs if necessary).
117     return (opCode == FCMPS || opCode == FCMPD || opCode == FCMPQ);
118   }
119
120   //-------------------------------------------------------------------------
121   // Code generation support for creating individual machine instructions
122   //-------------------------------------------------------------------------
123   
124   // Create an instruction sequence to put the constant `val' into
125   // the virtual register `dest'.  The generated instructions are
126   // returned in `minstrVec'.  Any temporary registers (TmpInstruction)
127   // created are returned in `tempVec'.
128   // 
129   virtual void  CreateCodeToLoadConst(Method* method,
130                                       Value* val,
131                                       Instruction* dest,
132                                       std::vector<MachineInstr*>& minstrVec,
133                                       std::vector<TmpInstruction*>& tmp) const;
134
135   
136   // Create an instruction sequence to copy an integer value `val'
137   // to a floating point value `dest' by copying to memory and back.
138   // val must be an integral type.  dest must be a Float or Double.
139   // The generated instructions are returned in `minstrVec'.
140   // Any temp. registers (TmpInstruction) created are returned in `tempVec'.
141   // 
142   virtual void  CreateCodeToCopyIntToFloat(Method* method,
143                                            Value* val,
144                                            Instruction* dest,
145                                            std::vector<MachineInstr*>& minstr,
146                                            std::vector<TmpInstruction*>& temp,
147                                            TargetMachine& target) const;
148
149   // Similarly, create an instruction sequence to copy an FP value
150   // `val' to an integer value `dest' by copying to memory and back.
151   // See the previous function for information about return values.
152   // 
153   virtual void  CreateCodeToCopyFloatToInt(Method* method,
154                                            Value* val,
155                                            Instruction* dest,
156                                            std::vector<MachineInstr*>& minstr,
157                                            std::vector<TmpInstruction*>& temp,
158                                            TargetMachine& target) const;
159
160  // create copy instruction(s)
161   virtual void CreateCopyInstructionsByType(const TargetMachine& target,
162                                             Method* method,
163                                             Value* src,
164                                             Instruction* dest,
165                                             std::vector<MachineInstr*>& minstr) const;
166 };
167
168
169 //----------------------------------------------------------------------------
170 // class UltraSparcRegInfo
171 //
172 // This class implements the virtual class MachineRegInfo for Sparc.
173 //
174 //----------------------------------------------------------------------------
175
176 class UltraSparcRegInfo : public MachineRegInfo {
177   // The actual register classes in the Sparc
178   //
179   enum RegClassIDs { 
180     IntRegClassID,                      // Integer
181     FloatRegClassID,                    // Float (both single/double)
182     IntCCRegClassID,                    // Int Condition Code
183     FloatCCRegClassID                   // Float Condition code
184   };
185
186
187   // Type of registers available in Sparc. There can be several reg types
188   // in the same class. For instace, the float reg class has Single/Double
189   // types
190   //
191   enum RegTypes {
192     IntRegType,
193     FPSingleRegType,
194     FPDoubleRegType,
195     IntCCRegType,
196     FloatCCRegType
197   };
198
199   // **** WARNING: If the above enum order is changed, also modify 
200   // getRegisterClassOfValue method below since it assumes this particular 
201   // order for efficiency.
202
203
204   // reverse pointer to get info about the ultra sparc machine
205   //
206   const UltraSparc *const UltraSparcInfo;
207
208   // Number of registers used for passing int args (usually 6: %o0 - %o5)
209   //
210   unsigned const NumOfIntArgRegs;
211
212   // Number of registers used for passing float args (usually 32: %f0 - %f31)
213   //
214   unsigned const NumOfFloatArgRegs;
215
216   // An out of bound register number that can be used to initialize register
217   // numbers. Useful for error detection.
218   //
219   int const InvalidRegNum;
220
221
222   // ========================  Private Methods =============================
223
224   // The following methods are used to color special live ranges (e.g.
225   // method args and return values etc.) with specific hardware registers
226   // as required. See SparcRegInfo.cpp for the implementation.
227   //
228   void setCallOrRetArgCol(LiveRange *LR, unsigned RegNo,
229                           const MachineInstr *MI, 
230                           std::hash_map<const MachineInstr *,
231                                         AddedInstrns *> &AIMap) const;
232
233   MachineInstr *getCopy2RegMI(const Value *SrcVal, unsigned Reg,
234                               unsigned RegClassID) const;
235
236   void suggestReg4RetAddr(const MachineInstr *RetMI, 
237                           LiveRangeInfo &LRI) const;
238
239   void suggestReg4CallAddr(const MachineInstr *CallMI, LiveRangeInfo &LRI,
240                            std::vector<RegClass *> RCList) const;
241
242
243
244   // The following methods are used to find the addresses etc. contained
245   // in specail machine instructions like CALL/RET
246   //
247   Value *getValue4ReturnAddr(const MachineInstr *MInst) const;
248   const Value *getCallInstRetAddr(const MachineInstr *CallMI) const;
249   unsigned getCallInstNumArgs(const MachineInstr *CallMI) const;
250
251
252   // The following 3  methods are used to find the RegType (see enum above)
253   // of a LiveRange, Value and using the unified RegClassID
254   int getRegType(const LiveRange *LR) const;
255   int getRegType(const Value *Val) const;
256   int getRegType(int reg) const;
257
258
259   // The following methods are used to generate copy instructions to move
260   // data between condition code registers
261   //
262   MachineInstr *cpCCR2IntMI(unsigned IntReg) const;
263   MachineInstr *cpInt2CCRMI(unsigned IntReg) const;
264
265   // Used to generate a copy instruction based on the register class of
266   // value.
267   //
268   MachineInstr *cpValue2RegMI(Value *Val,  unsigned DestReg,
269                               int RegType) const;
270
271
272   // The following 2 methods are used to order the instructions addeed by
273   // the register allocator in association with method calling. See
274   // SparcRegInfo.cpp for more details
275   //
276   void moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
277                        MachineInstr *UnordInst,
278                        PhyRegAlloc &PRA) const;
279
280   void OrderAddedInstrns(std::vector<MachineInstr *> &UnordVec, 
281                          std::vector<MachineInstr *> &OrdVec,
282                          PhyRegAlloc &PRA) const;
283
284
285   // To find whether a particular call is to a var arg method
286   //
287   bool isVarArgCall(const MachineInstr *CallMI) const;
288
289
290 public:
291   UltraSparcRegInfo(const UltraSparc &tgt);
292
293   // To get complete machine information structure using the machine register
294   // information
295   //
296   inline const UltraSparc &getUltraSparcInfo() const { 
297     return *UltraSparcInfo;
298   }
299
300   // To find the register class used for a specified Type
301   //
302   inline unsigned getRegClassIDOfType(const Type *type,
303                                       bool isCCReg = false) const {
304     Type::PrimitiveID ty = type->getPrimitiveID();
305     unsigned res;
306     
307     // FIXME: Comparing types like this isn't very safe...
308     if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
309         (ty == Type::FunctionTyID) ||  (ty == Type::PointerTyID) )
310       res = IntRegClassID;             // sparc int reg (ty=0: void)
311     else if (ty <= Type::DoubleTyID)
312       res = FloatRegClassID;           // sparc float reg class
313     else { 
314       //std::cerr << "TypeID: " << ty << "\n";
315       assert(0 && "Cannot resolve register class for type");
316       return 0;
317     }
318
319     if(isCCReg)
320       return res + 2;      // corresponidng condition code regiser 
321     else 
322       return res;
323   }
324
325   // To find the register class of a Value
326   //
327   inline unsigned getRegClassIDOfValue(const Value *Val,
328                                        bool isCCReg = false) const {
329     return getRegClassIDOfType(Val->getType(), isCCReg);
330   }
331
332   
333
334   // getZeroRegNum - returns the register that contains always zero this is the
335   // unified register number
336   //
337   virtual int getZeroRegNum() const;
338
339   // getCallAddressReg - returns the reg used for pushing the address when a
340   // method is called. This can be used for other purposes between calls
341   //
342   unsigned getCallAddressReg() const;
343
344   // Returns the register containing the return address.
345   // It should be made sure that this  register contains the return 
346   // value when a return instruction is reached.
347   //
348   unsigned getReturnAddressReg() const;
349
350
351
352   // The following methods are used to color special live ranges (e.g.
353   // method args and return values etc.) with specific hardware registers
354   // as required. See SparcRegInfo.cpp for the implementation for Sparc.
355   //
356   void suggestRegs4MethodArgs(const Method *Meth, 
357                               LiveRangeInfo& LRI) const;
358
359   void suggestRegs4CallArgs(const MachineInstr *CallMI, 
360                             LiveRangeInfo& LRI,
361                             std::vector<RegClass *> RCL) const; 
362
363   void suggestReg4RetValue(const MachineInstr *RetMI, 
364                            LiveRangeInfo& LRI) const;
365
366
367   void colorMethodArgs(const Method *Meth,  LiveRangeInfo &LRI,
368                        AddedInstrns *FirstAI) const;
369
370   void colorCallArgs(const MachineInstr *CallMI, LiveRangeInfo &LRI,
371                      AddedInstrns *CallAI,  PhyRegAlloc &PRA,
372                      const BasicBlock *BB) const;
373
374   void colorRetValue(const MachineInstr *RetI,   LiveRangeInfo& LRI,
375                      AddedInstrns *RetAI) const;
376
377
378
379   // method used for printing a register for debugging purposes
380   //
381   static void printReg(const LiveRange *LR);
382
383   // this method provides a unique number for each register 
384   //
385   inline int getUnifiedRegNum(int RegClassID, int reg) const {
386
387     if( RegClassID == IntRegClassID && reg < 32 ) 
388       return reg;
389     else if ( RegClassID == FloatRegClassID && reg < 64)
390       return reg + 32;                  // we have 32 int regs
391     else if( RegClassID == FloatCCRegClassID && reg < 4)
392       return reg + 32 + 64;             // 32 int, 64 float
393     else if( RegClassID == IntCCRegClassID ) 
394       return reg + 4+ 32 + 64;                // only int cc reg
395     else if (reg==InvalidRegNum)                
396       return InvalidRegNum;
397     else  
398       assert(0 && "Invalid register class or reg number");
399     return 0;
400   }
401
402   // given the unified register number, this gives the name
403   // for generating assembly code or debugging.
404   //
405   virtual const std::string getUnifiedRegName(int reg) const;
406
407
408   // returns the # of bytes of stack space allocated for each register
409   // type. For Sparc, currently we allocate 8 bytes on stack for all 
410   // register types. We can optimize this later if necessary to save stack
411   // space (However, should make sure that stack alignment is correct)
412   //
413   inline int getSpilledRegSize(int RegType) const {
414     return 8;
415   }
416
417
418   // To obtain the return value and the indirect call address (if any)
419   // contained in a CALL machine instruction
420   //
421   const Value * getCallInstRetVal(const MachineInstr *CallMI) const;
422   const Value * getCallInstIndirectAddrVal(const MachineInstr *CallMI) const;
423
424
425   // The following methods are used to generate "copy" machine instructions
426   // for an architecture.
427   //
428   MachineInstr * cpReg2RegMI(unsigned SrcReg, unsigned DestReg,
429                              int RegType) const;
430
431   MachineInstr * cpReg2MemMI(unsigned SrcReg, unsigned DestPtrReg,
432                              int Offset, int RegType) const;
433
434   MachineInstr * cpMem2RegMI(unsigned SrcPtrReg, int Offset,
435                              unsigned DestReg, int RegType) const;
436
437   MachineInstr* cpValue2Value(Value *Src, Value *Dest) const;
438
439
440   // To see whether a register is a volatile (i.e., whehter it must be
441   // preserved acorss calls)
442   //
443   inline bool isRegVolatile(int RegClassID, int Reg) const {
444     return MachineRegClassArr[RegClassID]->isRegVolatile(Reg);
445   }
446
447
448   virtual unsigned getFramePointer() const;
449   virtual unsigned getStackPointer() const;
450
451   virtual int getInvalidRegNum() const {
452     return InvalidRegNum;
453   }
454
455   // This method inserts the caller saving code for call instructions
456   //
457   void insertCallerSavingCode(const MachineInstr *MInst, 
458                               const BasicBlock *BB, PhyRegAlloc &PRA ) const;
459 };
460
461
462
463
464 //---------------------------------------------------------------------------
465 // class UltraSparcSchedInfo
466 // 
467 // Purpose:
468 //   Interface to instruction scheduling information for UltraSPARC.
469 //   The parameter values above are based on UltraSPARC IIi.
470 //---------------------------------------------------------------------------
471
472
473 class UltraSparcSchedInfo: public MachineSchedInfo {
474 public:
475   UltraSparcSchedInfo(const TargetMachine &tgt);
476 protected:
477   virtual void initializeResources();
478 };
479
480
481 //---------------------------------------------------------------------------
482 // class UltraSparcFrameInfo 
483 // 
484 // Purpose:
485 //   Interface to stack frame layout info for the UltraSPARC.
486 //   Starting offsets for each area of the stack frame are aligned at
487 //   a multiple of getStackFrameSizeAlignment().
488 //---------------------------------------------------------------------------
489
490 class UltraSparcFrameInfo: public MachineFrameInfo {
491 public:
492   UltraSparcFrameInfo(const TargetMachine &tgt) : MachineFrameInfo(tgt) {}
493   
494 public:
495   int  getStackFrameSizeAlignment   () const { return StackFrameSizeAlignment;}
496   int  getMinStackFrameSize         () const { return MinStackFrameSize; }
497   int  getNumFixedOutgoingArgs      () const { return NumFixedOutgoingArgs; }
498   int  getSizeOfEachArgOnStack      () const { return SizeOfEachArgOnStack; }
499   bool argsOnStackHaveFixedSize     () const { return true; }
500
501   //
502   // These methods compute offsets using the frame contents for a
503   // particular method.  The frame contents are obtained from the
504   // MachineCodeInfoForMethod object for the given method.
505   // 
506   int getFirstIncomingArgOffset  (MachineCodeForMethod& mcInfo,
507                                   bool& pos) const
508   {
509     pos = true;                         // arguments area grows upwards
510     return FirstIncomingArgOffsetFromFP;
511   }
512   int getFirstOutgoingArgOffset  (MachineCodeForMethod& mcInfo,
513                                   bool& pos) const
514   {
515     pos = true;                         // arguments area grows upwards
516     return FirstOutgoingArgOffsetFromSP;
517   }
518   int getFirstOptionalOutgoingArgOffset(MachineCodeForMethod& mcInfo,
519                                         bool& pos)const
520   {
521     pos = true;                         // arguments area grows upwards
522     return FirstOptionalOutgoingArgOffsetFromSP;
523   }
524   
525   int getFirstAutomaticVarOffset (MachineCodeForMethod& mcInfo,
526                                   bool& pos) const;
527   int getRegSpillAreaOffset      (MachineCodeForMethod& mcInfo,
528                                   bool& pos) const;
529   int getTmpAreaOffset           (MachineCodeForMethod& mcInfo,
530                                   bool& pos) const;
531   int getDynamicAreaOffset       (MachineCodeForMethod& mcInfo,
532                                   bool& pos) const;
533
534   //
535   // These methods specify the base register used for each stack area
536   // (generally FP or SP)
537   // 
538   virtual int getIncomingArgBaseRegNum()               const {
539     return (int) target.getRegInfo().getFramePointer();
540   }
541   virtual int getOutgoingArgBaseRegNum()               const {
542     return (int) target.getRegInfo().getStackPointer();
543   }
544   virtual int getOptionalOutgoingArgBaseRegNum()       const {
545     return (int) target.getRegInfo().getStackPointer();
546   }
547   virtual int getAutomaticVarBaseRegNum()              const {
548     return (int) target.getRegInfo().getFramePointer();
549   }
550   virtual int getRegSpillAreaBaseRegNum()              const {
551     return (int) target.getRegInfo().getFramePointer();
552   }
553   virtual int getDynamicAreaBaseRegNum()               const {
554     return (int) target.getRegInfo().getStackPointer();
555   }
556   
557 private:
558   // All stack addresses must be offset by 0x7ff (2047) on Sparc V9.
559   static const int OFFSET                                  = (int) 0x7ff;
560   static const int StackFrameSizeAlignment                 =  16;
561   static const int MinStackFrameSize                       = 176;
562   static const int NumFixedOutgoingArgs                    =   6;
563   static const int SizeOfEachArgOnStack                    =   8;
564   static const int StaticAreaOffsetFromFP                  =  0 + OFFSET;
565   static const int FirstIncomingArgOffsetFromFP            = 128 + OFFSET;
566   static const int FirstOptionalIncomingArgOffsetFromFP    = 176 + OFFSET;
567   static const int FirstOutgoingArgOffsetFromSP            = 128 + OFFSET;
568   static const int FirstOptionalOutgoingArgOffsetFromSP    = 176 + OFFSET;
569 };
570
571
572 //---------------------------------------------------------------------------
573 // class UltraSparcCacheInfo 
574 // 
575 // Purpose:
576 //   Interface to cache parameters for the UltraSPARC.
577 //   Just use defaults for now.
578 //---------------------------------------------------------------------------
579
580 class UltraSparcCacheInfo: public MachineCacheInfo {
581 public:
582   UltraSparcCacheInfo(const TargetMachine &T) : MachineCacheInfo(T) {} 
583 };
584
585
586 //---------------------------------------------------------------------------
587 // class UltraSparcMachine 
588 // 
589 // Purpose:
590 //   Primary interface to machine description for the UltraSPARC.
591 //   Primarily just initializes machine-dependent parameters in
592 //   class TargetMachine, and creates machine-dependent subclasses
593 //   for classes such as InstrInfo, SchedInfo and RegInfo. 
594 //---------------------------------------------------------------------------
595
596 class UltraSparc : public TargetMachine {
597 private:
598   UltraSparcInstrInfo instrInfo;
599   UltraSparcSchedInfo schedInfo;
600   UltraSparcRegInfo   regInfo;
601   UltraSparcFrameInfo frameInfo;
602   UltraSparcCacheInfo cacheInfo;
603 public:
604   UltraSparc();
605   
606   virtual const MachineInstrInfo &getInstrInfo() const { return instrInfo; }
607   virtual const MachineSchedInfo &getSchedInfo() const { return schedInfo; }
608   virtual const MachineRegInfo   &getRegInfo()   const { return regInfo; }
609   virtual const MachineFrameInfo &getFrameInfo() const { return frameInfo; }
610   virtual const MachineCacheInfo &getCacheInfo() const { return cacheInfo; }
611
612   //
613   // addPassesToEmitAssembly - Add passes to the specified pass manager to get
614   // assembly langage code emited.  For sparc, we have to do ...
615   //
616   virtual void addPassesToEmitAssembly(PassManager &PM, std::ostream &Out);
617
618 private:
619   Pass *getMethodAsmPrinterPass(PassManager &PM, std::ostream &Out);
620   Pass *getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out);
621   Pass *getEmitBytecodeToAsmPass(std::ostream &Out);
622 };
623
624 #endif