Added support for PIC code with "explicit relocations" *only*.
[oota-llvm.git] / lib / Target / Mips / MipsRegisterInfo.cpp
1 //===- MipsRegisterInfo.cpp - MIPS Register Information -== -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Bruno Cardoso Lopes and is distributed under the 
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the MIPS implementation of the MRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "mips-reg-info"
15
16 #include "Mips.h"
17 #include "MipsRegisterInfo.h"
18 #include "MipsMachineFunction.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Type.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/ValueTypes.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLocation.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 //#include "MipsSubtarget.h"
36
37 using namespace llvm;
38
39 // TODO: add subtarget support
40 MipsRegisterInfo::MipsRegisterInfo(const TargetInstrInfo &tii)
41   : MipsGenRegisterInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP),
42   TII(tii) {}
43
44 /// getRegisterNumbering - Given the enum value for some register, e.g.
45 /// Mips::RA, return the number that it corresponds to (e.g. 31).
46 unsigned MipsRegisterInfo::
47 getRegisterNumbering(unsigned RegEnum) 
48 {
49   switch (RegEnum) {
50     case Mips::ZERO : return 0;
51     case Mips::AT   : return 1;
52     case Mips::V0   : return 2;
53     case Mips::V1   : return 3;
54     case Mips::A0   : return 4;
55     case Mips::A1   : return 5;
56     case Mips::A2   : return 6;
57     case Mips::A3   : return 7;
58     case Mips::T0   : return 8;
59     case Mips::T1   : return 9;
60     case Mips::T2   : return 10;
61     case Mips::T3   : return 11;
62     case Mips::T4   : return 12;
63     case Mips::T5   : return 13;
64     case Mips::T6   : return 14;
65     case Mips::T7   : return 15;
66     case Mips::T8   : return 16;
67     case Mips::T9   : return 17;
68     case Mips::S0   : return 18;
69     case Mips::S1   : return 19;
70     case Mips::S2   : return 20;
71     case Mips::S3   : return 21;
72     case Mips::S4   : return 22;
73     case Mips::S5   : return 23;
74     case Mips::S6   : return 24;
75     case Mips::S7   : return 25;
76     case Mips::K0   : return 26;
77     case Mips::K1   : return 27;
78     case Mips::GP   : return 28;
79     case Mips::SP   : return 29;
80     case Mips::FP   : return 30;
81     case Mips::RA   : return 31;
82     default: assert(0 && "Unknown register number!");
83   }    
84 }
85
86 void MipsRegisterInfo::
87 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
88           unsigned SrcReg, int FI, 
89           const TargetRegisterClass *RC) const 
90 {
91   if (RC == Mips::CPURegsRegisterClass)
92     BuildMI(MBB, I, TII.get(Mips::SW)).addReg(SrcReg, false, false, true)
93           .addImm(0).addFrameIndex(FI);
94   else
95     assert(0 && "Can't store this register to stack slot");
96 }
97
98 void MipsRegisterInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
99                                       SmallVectorImpl<MachineOperand> &Addr,
100                                       const TargetRegisterClass *RC,
101                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
102   if (RC != Mips::CPURegsRegisterClass)
103     assert(0 && "Can't store this register");
104   MachineInstrBuilder MIB = BuildMI(TII.get(Mips::SW))
105     .addReg(SrcReg, false, false, true);
106   for (unsigned i = 0, e = Addr.size(); i != e; ++i) {
107     MachineOperand &MO = Addr[i];
108     if (MO.isRegister())
109       MIB.addReg(MO.getReg());
110     else if (MO.isImmediate())
111       MIB.addImm(MO.getImmedValue());
112     else
113       MIB.addFrameIndex(MO.getFrameIndex());
114   }
115   NewMIs.push_back(MIB);
116   return;
117 }
118
119 void MipsRegisterInfo::
120 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
121                      unsigned DestReg, int FI,
122                      const TargetRegisterClass *RC) const 
123 {
124   if (RC == Mips::CPURegsRegisterClass)
125     BuildMI(MBB, I, TII.get(Mips::LW), DestReg).addImm(0).addFrameIndex(FI);
126   else
127     assert(0 && "Can't load this register from stack slot");
128 }
129
130 void MipsRegisterInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
131                                        SmallVectorImpl<MachineOperand> &Addr,
132                                        const TargetRegisterClass *RC,
133                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
134   if (RC != Mips::CPURegsRegisterClass)
135     assert(0 && "Can't load this register");
136   MachineInstrBuilder MIB = BuildMI(TII.get(Mips::LW), DestReg);
137   for (unsigned i = 0, e = Addr.size(); i != e; ++i) {
138     MachineOperand &MO = Addr[i];
139     if (MO.isRegister())
140       MIB.addReg(MO.getReg());
141     else if (MO.isImmediate())
142       MIB.addImm(MO.getImmedValue());
143     else
144       MIB.addFrameIndex(MO.getFrameIndex());
145   }
146   NewMIs.push_back(MIB);
147   return;
148 }
149
150 void MipsRegisterInfo::
151 copyRegToReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
152              unsigned DestReg, unsigned SrcReg,
153              const TargetRegisterClass *DestRC,
154              const TargetRegisterClass *SrcRC) const
155 {
156   if (DestRC != SrcRC) {
157     cerr << "Not yet supported!";
158     abort();
159   }
160
161   if (DestRC == Mips::CPURegsRegisterClass)
162     BuildMI(MBB, I, TII.get(Mips::ADDu), DestReg).addReg(Mips::ZERO)
163       .addReg(SrcReg);
164   else
165     assert (0 && "Can't copy this register");
166 }
167
168 void MipsRegisterInfo::reMaterialize(MachineBasicBlock &MBB, 
169                                       MachineBasicBlock::iterator I,
170                                       unsigned DestReg, 
171                                       const MachineInstr *Orig) const 
172 {
173     MachineInstr *MI = Orig->clone();
174     MI->getOperand(0).setReg(DestReg);
175     MBB.insert(I, MI);
176 }
177
178 MachineInstr *MipsRegisterInfo::
179 foldMemoryOperand(MachineInstr* MI, unsigned OpNum, int FI) const 
180 {
181   MachineInstr *NewMI = NULL;
182
183   switch (MI->getOpcode()) 
184   {
185     case Mips::ADDu:
186       if ((MI->getOperand(0).isRegister()) &&
187         (MI->getOperand(1).isRegister()) && 
188         (MI->getOperand(1).getReg() == Mips::ZERO) &&
189         (MI->getOperand(2).isRegister())) 
190       {
191         if (OpNum == 0)    // COPY -> STORE
192           NewMI = BuildMI(TII.get(Mips::SW)).addFrameIndex(FI)
193                   .addImm(0).addReg(MI->getOperand(2).getReg());
194         else               // COPY -> LOAD
195           NewMI = BuildMI(TII.get(Mips::LW), MI->getOperand(0)
196                   .getReg()).addImm(0).addFrameIndex(FI);
197       }
198       break;
199   }
200
201   if (NewMI)
202     NewMI->copyKillDeadInfo(MI);
203   return NewMI;
204 }
205
206 MachineInstr *MipsRegisterInfo::
207 foldMemoryOperand(MachineInstr* MI, unsigned OpNum,
208                                 MachineInstr* LoadMI) const {
209   return NULL;
210 }
211
212 //===----------------------------------------------------------------------===//
213 //
214 // Callee Saved Registers methods 
215 //
216 //===----------------------------------------------------------------------===//
217
218 /// Mips Callee Saved Registers
219 const unsigned* MipsRegisterInfo::
220 getCalleeSavedRegs(const MachineFunction *MF) const 
221 {
222   // Mips calle-save register range is $16-$26(s0-s7)
223   static const unsigned CalleeSavedRegs[] = {  
224     Mips::S0, Mips::S1, Mips::S2, Mips::S3, 
225     Mips::S4, Mips::S5, Mips::S6, Mips::S7, 0
226   };
227   return CalleeSavedRegs;
228 }
229
230 /// Mips Callee Saved Register Classes
231 const TargetRegisterClass* const* 
232 MipsRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const 
233 {
234   static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
235     &Mips::CPURegsRegClass, &Mips::CPURegsRegClass,
236     &Mips::CPURegsRegClass, &Mips::CPURegsRegClass,
237     &Mips::CPURegsRegClass, &Mips::CPURegsRegClass,
238     &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, 0 
239   };
240   return CalleeSavedRegClasses;
241 }
242
243 BitVector MipsRegisterInfo::
244 getReservedRegs(const MachineFunction &MF) const
245 {
246   BitVector Reserved(getNumRegs());
247   Reserved.set(Mips::ZERO);
248   Reserved.set(Mips::AT);
249   Reserved.set(Mips::K0);
250   Reserved.set(Mips::K1);
251   Reserved.set(Mips::GP);
252   Reserved.set(Mips::SP);
253   Reserved.set(Mips::FP);
254   Reserved.set(Mips::RA);
255   return Reserved;
256 }
257
258 //===----------------------------------------------------------------------===//
259 //
260 // Stack Frame Processing methods
261 // +----------------------------+
262 //
263 // The stack is allocated decrementing the stack pointer on
264 // the first instruction of a function prologue. Once decremented,
265 // all stack referencesare are done thought a positive offset
266 // from the stack/frame pointer, so the stack is considering
267 // to grow up! Otherwise terrible hacks would have to be made
268 // to get this stack ABI compliant :)
269 //
270 //  The stack frame required by the ABI:
271 //  Offset
272 //
273 //  0                 ----------
274 //  4                 Args to pass
275 //  .                 saved $GP  (used in PIC - not supported yet)
276 //  .                 Local Area
277 //  .                 saved "Callee Saved" Registers
278 //  .                 saved FP
279 //  .                 saved RA
280 //  StackSize         -----------
281 //
282 // Offset - offset from sp after stack allocation on function prologue
283 //
284 // The sp is the stack pointer subtracted/added from the stack size
285 // at the Prologue/Epilogue
286 //
287 // References to the previous stack (to obtain arguments) are done
288 // with offsets that exceeds the stack size: (stacksize+(4*(num_arg-1))
289 //
290 // Examples:
291 // - reference to the actual stack frame
292 //   for any local area var there is smt like : FI >= 0, StackOffset: 4
293 //     sw REGX, 4(SP)
294 //
295 // - reference to previous stack frame
296 //   suppose there's a load to the 5th arguments : FI < 0, StackOffset: 16.
297 //   The emitted instruction will be something like:
298 //     lw REGX, 16+StackSize(SP)
299 //
300 // Since the total stack size is unknown on LowerFORMAL_ARGUMENTS, all
301 // stack references (ObjectOffset) created to reference the function 
302 // arguments, are negative numbers. This way, on eliminateFrameIndex it's
303 // possible to detect those references and the offsets are adjusted to
304 // their real location.
305 //
306 //
307 //
308 //===----------------------------------------------------------------------===//
309
310 // hasFP - Return true if the specified function should have a dedicated frame
311 // pointer register.  This is true if the function has variable sized allocas or
312 // if frame pointer elimination is disabled.
313 bool MipsRegisterInfo::
314 hasFP(const MachineFunction &MF) const {
315   return (NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects());
316 }
317
318 // This function eliminate ADJCALLSTACKDOWN, 
319 // ADJCALLSTACKUP pseudo instructions
320 void MipsRegisterInfo::
321 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
322                               MachineBasicBlock::iterator I) const {
323   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
324   MBB.erase(I);
325 }
326
327 // FrameIndex represent objects inside a abstract stack.
328 // We must replace FrameIndex with an stack/frame pointer
329 // direct reference.
330 void MipsRegisterInfo::
331 eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, 
332                     RegScavenger *RS) const 
333 {
334   MachineInstr &MI = *II;
335   MachineFunction &MF = *MI.getParent()->getParent();
336
337   unsigned i = 0;
338   while (!MI.getOperand(i).isFrameIndex()) {
339     ++i;
340     assert(i < MI.getNumOperands() && 
341            "Instr doesn't have FrameIndex operand!");
342   }
343
344   int FrameIndex = MI.getOperand(i).getFrameIndex();
345   int stackSize  = MF.getFrameInfo()->getStackSize();
346   int spOffset   = MF.getFrameInfo()->getObjectOffset(FrameIndex);
347
348   #ifndef NDEBUG
349   DOUT << "\nFunction : " << MF.getFunction()->getName() << "\n";
350   DOUT << "<--------->\n";
351   MI.print(DOUT);
352   DOUT << "FrameIndex : " << FrameIndex << "\n";
353   DOUT << "spOffset   : " << spOffset << "\n";
354   DOUT << "stackSize  : " << stackSize << "\n";
355   #endif
356
357   // as explained on LowerFORMAL_ARGUMENTS, detect negative offsets 
358   // and adjust SPOffsets considering the final stack size.
359   int Offset = ((spOffset < 0) ? (stackSize + (-(spOffset+4))) : (spOffset));
360   Offset    += MI.getOperand(i-1).getImm();
361
362   #ifndef NDEBUG
363   DOUT << "Offset     : " << Offset << "\n";
364   DOUT << "<--------->\n";
365   #endif
366
367   MI.getOperand(i-1).ChangeToImmediate(Offset);
368   MI.getOperand(i).ChangeToRegister(getFrameRegister(MF), false);
369 }
370
371 void MipsRegisterInfo::
372 emitPrologue(MachineFunction &MF) const 
373 {
374   MachineBasicBlock &MBB   = MF.front();
375   MachineFrameInfo *MFI    = MF.getFrameInfo();
376   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
377   MachineBasicBlock::iterator MBBI = MBB.begin();
378   bool isPIC = (MF.getTarget().getRelocationModel() == Reloc::PIC_);
379
380   // Replace the dummy '0' SPOffset by the negative 
381   // offsets, as explained on LowerFORMAL_ARGUMENTS
382   MipsFI->adjustLoadArgsFI(MFI);
383   MipsFI->adjustStoreVarArgsFI(MFI); 
384
385   // Get the number of bytes to allocate from the FrameInfo.
386   int NumBytes = (int) MFI->getStackSize();
387
388   #ifndef NDEBUG
389   DOUT << "\n<--- EMIT PROLOGUE --->\n";
390   DOUT << "Actual Stack size :" << NumBytes << "\n";
391   #endif
392
393   // No need to allocate space on the stack.
394   if (NumBytes == 0) return;
395
396   int FPOffset, RAOffset;
397   
398   // Allocate space for saved RA and FP when needed 
399   if ((hasFP(MF)) && (MFI->hasCalls())) {
400     FPOffset = NumBytes;
401     RAOffset = (NumBytes+4);
402     NumBytes += 8;
403   } else if ((!hasFP(MF)) && (MFI->hasCalls())) {
404     FPOffset = 0;
405     RAOffset = NumBytes;
406     NumBytes += 4;
407   } else if ((hasFP(MF)) && (!MFI->hasCalls())) {
408     FPOffset = NumBytes;
409     RAOffset = 0;
410     NumBytes += 4;
411   }
412
413   MFI->setObjectOffset(MFI->CreateStackObject(4,4), FPOffset);
414   MFI->setObjectOffset(MFI->CreateStackObject(4,4), RAOffset);
415   MipsFI->setFPStackOffset(FPOffset);
416   MipsFI->setRAStackOffset(RAOffset);
417
418   // Align stack. 
419   unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
420   NumBytes = ((NumBytes+Align-1)/Align*Align);
421
422   #ifndef NDEBUG
423   DOUT << "FPOffset :" << FPOffset << "\n";
424   DOUT << "RAOffset :" << RAOffset << "\n";
425   DOUT << "New stack size :" << NumBytes << "\n\n";
426   #endif
427
428   // Update frame info
429   MFI->setStackSize(NumBytes);
430
431   // PIC speficic function prologue
432   if (isPIC)
433     BuildMI(MBB, MBBI, TII.get(Mips::CPLOAD)).addReg(Mips::T9);
434
435   // Adjust stack : addi sp, sp, (-imm)
436   BuildMI(MBB, MBBI, TII.get(Mips::ADDiu), Mips::SP)
437       .addReg(Mips::SP).addImm(-NumBytes);
438
439   // Save the return address only if the function isnt a leaf one.
440   // sw  $ra, stack_loc($sp)
441   if (MFI->hasCalls()) { 
442     BuildMI(MBB, MBBI, TII.get(Mips::SW))
443         .addReg(Mips::RA).addImm(RAOffset).addReg(Mips::SP);
444   }
445
446   // if framepointer enabled, save it and set it
447   // to point to the stack pointer
448   if (hasFP(MF)) {
449     // sw  $fp,stack_loc($sp)
450     BuildMI(MBB, MBBI, TII.get(Mips::SW))
451       .addReg(Mips::FP).addImm(FPOffset).addReg(Mips::SP);
452
453     // move $fp, $sp
454     BuildMI(MBB, MBBI, TII.get(Mips::ADDu), Mips::FP)
455       .addReg(Mips::SP).addReg(Mips::ZERO);
456   }
457
458   // PIC speficic function prologue
459   if ((isPIC) && (MFI->hasCalls()))
460     BuildMI(MBB, MBBI, TII.get(Mips::CPRESTORE))
461       .addImm(MipsFI->getGPStackOffset());
462 }
463
464 void MipsRegisterInfo::
465 emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const 
466 {
467   MachineBasicBlock::iterator MBBI = prior(MBB.end());
468   MachineFrameInfo *MFI            = MF.getFrameInfo();
469   MipsFunctionInfo *MipsFI         = MF.getInfo<MipsFunctionInfo>();
470
471   // Get the number of bytes from FrameInfo
472   int NumBytes = (int) MFI->getStackSize();
473
474   // Get the FI's where RA and FP are saved.
475   int FPOffset = MipsFI->getFPStackOffset();
476   int RAOffset = MipsFI->getRAStackOffset();
477
478   // if framepointer enabled, restore it and restore the
479   // stack pointer
480   if (hasFP(MF)) {
481     // move $sp, $fp
482     BuildMI(MBB, MBBI, TII.get(Mips::ADDu), Mips::SP)
483       .addReg(Mips::FP).addReg(Mips::ZERO);
484
485     // lw  $fp,stack_loc($sp)
486     BuildMI(MBB, MBBI, TII.get(Mips::LW))
487       .addReg(Mips::FP).addImm(FPOffset).addReg(Mips::SP);
488   }
489
490   // Restore the return address only if the function isnt a leaf one.
491   // lw  $ra, stack_loc($sp)
492   if (MFI->hasCalls()) { 
493     BuildMI(MBB, MBBI, TII.get(Mips::LW))
494         .addReg(Mips::RA).addImm(RAOffset).addReg(Mips::SP);
495   }
496
497   // adjust stack  : insert addi sp, sp, (imm)
498   if (NumBytes) {
499     BuildMI(MBB, MBBI, TII.get(Mips::ADDiu), Mips::SP)
500       .addReg(Mips::SP).addImm(NumBytes);
501   }
502 }
503
504 void MipsRegisterInfo::
505 processFunctionBeforeFrameFinalized(MachineFunction &MF) const {
506   // Set the SPOffset on the FI where GP must be saved/loaded.
507   MachineFrameInfo *MFI = MF.getFrameInfo();
508   if (MFI->hasCalls()) { 
509     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
510     #ifndef NDEBUG
511     DOUT << "processFunctionBeforeFrameFinalized\n";
512     DOUT << "GPOffset :" << MipsFI->getGPStackOffset() << "\n";
513     DOUT << "FI :" << MipsFI->getGPFI() << "\n";
514     #endif
515     MFI->setObjectOffset(MipsFI->getGPFI(), MipsFI->getGPStackOffset());
516   }    
517 }
518
519 unsigned MipsRegisterInfo::
520 getRARegister() const {
521   return Mips::RA;
522 }
523
524 unsigned MipsRegisterInfo::
525 getFrameRegister(MachineFunction &MF) const {
526   return hasFP(MF) ? Mips::FP : Mips::SP;
527 }
528
529 unsigned MipsRegisterInfo::
530 getEHExceptionRegister() const {
531   assert(0 && "What is the exception register");
532   return 0;
533 }
534
535 unsigned MipsRegisterInfo::
536 getEHHandlerRegister() const {
537   assert(0 && "What is the exception handler register");
538   return 0;
539 }
540
541 #include "MipsGenRegisterInfo.inc"
542