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