Insert instructions that copy $sp to or from $fp at the right locations.
[oota-llvm.git] / lib / Target / Mips / MipsFrameLowering.cpp
1 //=======- MipsFrameLowering.cpp - Mips Frame Information ------*- C++ -*-====//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the Mips implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MipsFrameLowering.h"
15 #include "MipsInstrInfo.h"
16 #include "MipsMachineFunction.h"
17 #include "llvm/Function.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Support/CommandLine.h"
26
27 using namespace llvm;
28
29
30 //===----------------------------------------------------------------------===//
31 //
32 // Stack Frame Processing methods
33 // +----------------------------+
34 //
35 // The stack is allocated decrementing the stack pointer on
36 // the first instruction of a function prologue. Once decremented,
37 // all stack references are done thought a positive offset
38 // from the stack/frame pointer, so the stack is considering
39 // to grow up! Otherwise terrible hacks would have to be made
40 // to get this stack ABI compliant :)
41 //
42 //  The stack frame required by the ABI (after call):
43 //  Offset
44 //
45 //  0                 ----------
46 //  4                 Args to pass
47 //  .                 saved $GP  (used in PIC)
48 //  .                 Alloca allocations
49 //  .                 Local Area
50 //  .                 CPU "Callee Saved" Registers
51 //  .                 saved FP
52 //  .                 saved RA
53 //  .                 FPU "Callee Saved" Registers
54 //  StackSize         -----------
55 //
56 // Offset - offset from sp after stack allocation on function prologue
57 //
58 // The sp is the stack pointer subtracted/added from the stack size
59 // at the Prologue/Epilogue
60 //
61 // References to the previous stack (to obtain arguments) are done
62 // with offsets that exceeds the stack size: (stacksize+(4*(num_arg-1))
63 //
64 // Examples:
65 // - reference to the actual stack frame
66 //   for any local area var there is smt like : FI >= 0, StackOffset: 4
67 //     sw REGX, 4(SP)
68 //
69 // - reference to previous stack frame
70 //   suppose there's a load to the 5th arguments : FI < 0, StackOffset: 16.
71 //   The emitted instruction will be something like:
72 //     lw REGX, 16+StackSize(SP)
73 //
74 // Since the total stack size is unknown on LowerFormalArguments, all
75 // stack references (ObjectOffset) created to reference the function
76 // arguments, are negative numbers. This way, on eliminateFrameIndex it's
77 // possible to detect those references and the offsets are adjusted to
78 // their real location.
79 //
80 //===----------------------------------------------------------------------===//
81
82 // hasFP - Return true if the specified function should have a dedicated frame
83 // pointer register.  This is true if the function has variable sized allocas or
84 // if frame pointer elimination is disabled.
85 bool MipsFrameLowering::hasFP(const MachineFunction &MF) const {
86   const MachineFrameInfo *MFI = MF.getFrameInfo();
87   return DisableFramePointerElim(MF) || MFI->hasVarSizedObjects();
88 }
89
90 void MipsFrameLowering::adjustMipsStackFrame(MachineFunction &MF) const {
91   MachineFrameInfo *MFI = MF.getFrameInfo();
92   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
93   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
94   unsigned StackAlign = getStackAlignment();
95   unsigned RegSize = STI.isGP32bit() ? 4 : 8;
96   bool HasGP = MipsFI->needGPSaveRestore();
97
98   // Min and Max CSI FrameIndex.
99   int MinCSFI = -1, MaxCSFI = -1;
100
101   // See the description at MipsMachineFunction.h
102   int TopCPUSavedRegOff = -1, TopFPUSavedRegOff = -1;
103
104   // Replace the dummy '0' SPOffset by the negative offsets, as explained on
105   // LowerFormalArguments. Leaving '0' for while is necessary to avoid the
106   // approach done by calculateFrameObjectOffsets to the stack frame.
107   MipsFI->adjustLoadArgsFI(MFI);
108   MipsFI->adjustStoreVarArgsFI(MFI);
109
110   // It happens that the default stack frame allocation order does not directly
111   // map to the convention used for mips. So we must fix it. We move the callee
112   // save register slots after the local variables area, as described in the
113   // stack frame above.
114   unsigned CalleeSavedAreaSize = 0;
115   if (!CSI.empty()) {
116     MinCSFI = CSI[0].getFrameIdx();
117     MaxCSFI = CSI[CSI.size()-1].getFrameIdx();
118   }
119   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
120     CalleeSavedAreaSize += MFI->getObjectAlignment(CSI[i].getFrameIdx());
121
122   unsigned StackOffset = HasGP ? (MipsFI->getGPStackOffset()+RegSize)
123                 : (STI.isABI_O32() ? 16 : 0);
124
125   // Adjust local variables. They should come on the stack right
126   // after the arguments.
127   int LastOffsetFI = -1;
128   for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
129     if (i >= MinCSFI && i <= MaxCSFI)
130       continue;
131     if (MFI->isDeadObjectIndex(i))
132       continue;
133     unsigned Offset =
134       StackOffset + MFI->getObjectOffset(i) - CalleeSavedAreaSize;
135     if (LastOffsetFI == -1)
136       LastOffsetFI = i;
137     if (Offset > MFI->getObjectOffset(LastOffsetFI))
138       LastOffsetFI = i;
139     MFI->setObjectOffset(i, Offset);
140   }
141
142   // Adjust CPU Callee Saved Registers Area. Registers RA and FP must
143   // be saved in this CPU Area. This whole area must be aligned to the
144   // default Stack Alignment requirements.
145   if (LastOffsetFI >= 0)
146     StackOffset = MFI->getObjectOffset(LastOffsetFI)+
147                   MFI->getObjectSize(LastOffsetFI);
148   StackOffset = ((StackOffset+StackAlign-1)/StackAlign*StackAlign);
149
150   for (unsigned i = 0, e = CSI.size(); i != e ; ++i) {
151     unsigned Reg = CSI[i].getReg();
152     if (!Mips::CPURegsRegisterClass->contains(Reg))
153       break;
154     MFI->setObjectOffset(CSI[i].getFrameIdx(), StackOffset);
155     TopCPUSavedRegOff = StackOffset;
156     StackOffset += MFI->getObjectAlignment(CSI[i].getFrameIdx());
157   }
158
159   StackOffset = ((StackOffset+StackAlign-1)/StackAlign*StackAlign);
160
161   // Adjust FPU Callee Saved Registers Area. This Area must be
162   // aligned to the default Stack Alignment requirements.
163   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
164     unsigned Reg = CSI[i].getReg();
165     if (Mips::CPURegsRegisterClass->contains(Reg))
166       continue;
167     MFI->setObjectOffset(CSI[i].getFrameIdx(), StackOffset);
168     TopFPUSavedRegOff = StackOffset;
169     StackOffset += MFI->getObjectAlignment(CSI[i].getFrameIdx());
170   }
171   StackOffset = ((StackOffset+StackAlign-1)/StackAlign*StackAlign);
172
173   // Update frame info
174   MFI->setStackSize(StackOffset);
175
176   // Recalculate the final tops offset. The final values must be '0'
177   // if there isn't a callee saved register for CPU or FPU, otherwise
178   // a negative offset is needed.
179   if (TopCPUSavedRegOff >= 0)
180     MipsFI->setCPUTopSavedRegOff(TopCPUSavedRegOff-StackOffset);
181
182   if (TopFPUSavedRegOff >= 0)
183     MipsFI->setFPUTopSavedRegOff(TopFPUSavedRegOff-StackOffset);
184 }
185
186
187 // expand pair of register and immediate if the immediate doesn't fit in the
188 // 16-bit offset field.
189 // e.g.
190 //  if OrigImm = 0x10000, OrigReg = $sp:
191 //    generate the following sequence of instrs:
192 //      lui  $at, hi(0x10000)
193 //      addu $at, $sp, $at
194 //
195 //    (NewReg, NewImm) = ($at, lo(Ox10000))
196 //    return true
197 static bool expandRegLargeImmPair(unsigned OrigReg, int OrigImm,
198                                   unsigned& NewReg, int& NewImm,
199                                   MachineBasicBlock& MBB,
200                                   MachineBasicBlock::iterator I) {
201   // OrigImm fits in the 16-bit field
202   if (OrigImm < 0x8000 && OrigImm >= -0x8000) {
203     NewReg = OrigReg;
204     NewImm = OrigImm;
205     return false;
206   }
207
208   MachineFunction* MF = MBB.getParent();
209   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
210   DebugLoc DL = I->getDebugLoc();
211   int ImmLo = OrigImm & 0xffff;
212   int ImmHi = (((unsigned)OrigImm & 0xffff0000) >> 16) +
213               ((OrigImm & 0x8000) != 0);
214
215   // FIXME: change this when mips goes MC".
216   BuildMI(MBB, I, DL, TII->get(Mips::NOAT));
217   BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::AT).addImm(ImmHi);
218   BuildMI(MBB, I, DL, TII->get(Mips::ADDu), Mips::AT).addReg(OrigReg)
219                                                      .addReg(Mips::AT);
220   NewReg = Mips::AT;
221   NewImm = ImmLo;
222
223   return true;
224 }
225
226 void MipsFrameLowering::emitPrologue(MachineFunction &MF) const {
227   MachineBasicBlock &MBB   = MF.front();
228   MachineFrameInfo *MFI    = MF.getFrameInfo();
229   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
230   const MipsRegisterInfo *RegInfo =
231     static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo());
232   const MipsInstrInfo &TII =
233     *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo());
234   MachineBasicBlock::iterator MBBI = MBB.begin();
235   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
236   bool isPIC = (MF.getTarget().getRelocationModel() == Reloc::PIC_);
237   unsigned NewReg = 0;
238   int NewImm = 0;
239   bool ATUsed;
240
241   // Get the right frame order for Mips.
242   adjustMipsStackFrame(MF);
243
244   // Get the number of bytes to allocate from the FrameInfo.
245   unsigned StackSize = MFI->getStackSize();
246
247   BuildMI(MBB, MBBI, dl, TII.get(Mips::NOREORDER));
248
249   // TODO: check need from GP here.
250   if (isPIC && STI.isABI_O32())
251     BuildMI(MBB, MBBI, dl, TII.get(Mips::CPLOAD))
252       .addReg(RegInfo->getPICCallReg());
253   BuildMI(MBB, MBBI, dl, TII.get(Mips::NOMACRO));
254
255   // No need to allocate space on the stack.
256   if (StackSize == 0 && !MFI->adjustsStack()) return;
257
258   // Adjust stack : addi sp, sp, (-imm)
259   ATUsed = expandRegLargeImmPair(Mips::SP, -StackSize, NewReg, NewImm, MBB,
260                                  MBBI);
261   BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP)
262     .addReg(NewReg).addImm(NewImm);
263
264   // FIXME: change this when mips goes MC".
265   if (ATUsed)
266     BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO));
267
268   // if framepointer enabled, set it to point to the stack pointer.
269   if (hasFP(MF)) {
270     // Find the instruction past the last instruction that saves a callee-saved
271     // register to the stack.
272     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
273   
274     for (unsigned i = 0; i < CSI.size(); ++i)
275       ++MBBI;
276  
277     // Insert instruction "move $fp, $sp" at this location.    
278     BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDu), Mips::FP)
279       .addReg(Mips::SP).addReg(Mips::ZERO);
280   }
281
282   // Restore GP from the saved stack location
283   if (MipsFI->needGPSaveRestore())
284     BuildMI(MBB, MBBI, dl, TII.get(Mips::CPRESTORE))
285       .addImm(MipsFI->getGPStackOffset());
286 }
287
288 void MipsFrameLowering::emitEpilogue(MachineFunction &MF,
289                                  MachineBasicBlock &MBB) const {
290   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
291   MachineFrameInfo *MFI            = MF.getFrameInfo();
292   const MipsInstrInfo &TII =
293     *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo());
294   DebugLoc dl = MBBI->getDebugLoc();
295
296   // Get the number of bytes from FrameInfo
297   unsigned StackSize = MFI->getStackSize();
298
299   unsigned NewReg = 0;
300   int NewImm = 0;
301   bool ATUsed = false;
302
303   // if framepointer enabled, restore the stack pointer.
304   if (hasFP(MF)) {
305     // Find the first instruction that restores a callee-saved register.
306     MachineBasicBlock::iterator I = MBBI;
307     
308     for (unsigned i = 0; i < MFI->getCalleeSavedInfo().size(); ++i)
309       --I;
310
311     // Insert instruction "move $sp, $fp" at this location.
312     BuildMI(MBB, I, dl, TII.get(Mips::ADDu), Mips::SP)
313       .addReg(Mips::FP).addReg(Mips::ZERO);
314   }
315
316   // adjust stack  : insert addi sp, sp, (imm)
317   if (StackSize) {
318     ATUsed = expandRegLargeImmPair(Mips::SP, StackSize, NewReg, NewImm, MBB,
319                                    MBBI);
320     BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP)
321       .addReg(NewReg).addImm(NewImm);
322
323     // FIXME: change this when mips goes MC".
324     if (ATUsed)
325       BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO));
326   }
327 }
328
329 void MipsFrameLowering::
330 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
331                                      RegScavenger *RS) const {
332   MachineRegisterInfo& MRI = MF.getRegInfo();
333   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
334
335   // FIXME: remove this code if register allocator can correctly mark
336   //        $fp and $ra used or unused.
337
338   // Mark $fp and $ra as used or unused.
339   if (hasFP(MF))
340     MRI.setPhysRegUsed(Mips::FP);
341
342   // The register allocator might determine $ra is used after seeing 
343   // instruction "jr $ra", but we do not want PrologEpilogInserter to insert
344   // instructions to save/restore $ra unless there is a function call.
345   // To correct this, $ra is explicitly marked unused if there is no
346   // function call.
347   if (MipsFI->hasCall())
348     MRI.setPhysRegUsed(Mips::RA);
349   else
350     MRI.setPhysRegUnused(Mips::RA);
351 }
352
353 void MipsFrameLowering::
354 processFunctionBeforeFrameFinalized(MachineFunction &MF) const {
355   const MipsRegisterInfo *RegInfo =
356     static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo());
357   RegInfo->processFunctionBeforeFrameFinalized(MF);
358 }