[Sparc] Support user-specified stack object overalignment.
[oota-llvm.git] / lib / Target / Sparc / SparcFrameLowering.cpp
1 //===-- SparcFrameLowering.cpp - Sparc Frame Information ------------------===//
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 Sparc implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SparcFrameLowering.h"
15 #include "SparcInstrInfo.h"
16 #include "SparcMachineFunctionInfo.h"
17 #include "SparcSubtarget.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/IR/DataLayout.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Target/TargetOptions.h"
27
28 using namespace llvm;
29
30 static cl::opt<bool>
31 DisableLeafProc("disable-sparc-leaf-proc",
32                 cl::init(false),
33                 cl::desc("Disable Sparc leaf procedure optimization."),
34                 cl::Hidden);
35
36 SparcFrameLowering::SparcFrameLowering(const SparcSubtarget &ST)
37     : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
38                           ST.is64Bit() ? 16 : 8, 0, ST.is64Bit() ? 16 : 8) {}
39
40 void SparcFrameLowering::emitSPAdjustment(MachineFunction &MF,
41                                           MachineBasicBlock &MBB,
42                                           MachineBasicBlock::iterator MBBI,
43                                           int NumBytes,
44                                           unsigned ADDrr,
45                                           unsigned ADDri) const {
46
47   DebugLoc dl = (MBBI != MBB.end()) ? MBBI->getDebugLoc() : DebugLoc();
48   const SparcInstrInfo &TII =
49       *static_cast<const SparcInstrInfo *>(MF.getSubtarget().getInstrInfo());
50
51   if (NumBytes >= -4096 && NumBytes < 4096) {
52     BuildMI(MBB, MBBI, dl, TII.get(ADDri), SP::O6)
53       .addReg(SP::O6).addImm(NumBytes);
54     return;
55   }
56
57   // Emit this the hard way.  This clobbers G1 which we always know is
58   // available here.
59   if (NumBytes >= 0) {
60     // Emit nonnegative numbers with sethi + or.
61     // sethi %hi(NumBytes), %g1
62     // or %g1, %lo(NumBytes), %g1
63     // add %sp, %g1, %sp
64     BuildMI(MBB, MBBI, dl, TII.get(SP::SETHIi), SP::G1)
65       .addImm(HI22(NumBytes));
66     BuildMI(MBB, MBBI, dl, TII.get(SP::ORri), SP::G1)
67       .addReg(SP::G1).addImm(LO10(NumBytes));
68     BuildMI(MBB, MBBI, dl, TII.get(ADDrr), SP::O6)
69       .addReg(SP::O6).addReg(SP::G1);
70     return ;
71   }
72
73   // Emit negative numbers with sethi + xor.
74   // sethi %hix(NumBytes), %g1
75   // xor %g1, %lox(NumBytes), %g1
76   // add %sp, %g1, %sp
77   BuildMI(MBB, MBBI, dl, TII.get(SP::SETHIi), SP::G1)
78     .addImm(HIX22(NumBytes));
79   BuildMI(MBB, MBBI, dl, TII.get(SP::XORri), SP::G1)
80     .addReg(SP::G1).addImm(LOX10(NumBytes));
81   BuildMI(MBB, MBBI, dl, TII.get(ADDrr), SP::O6)
82     .addReg(SP::O6).addReg(SP::G1);
83 }
84
85 void SparcFrameLowering::emitPrologue(MachineFunction &MF,
86                                       MachineBasicBlock &MBB) const {
87   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
88
89   assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
90   MachineFrameInfo *MFI = MF.getFrameInfo();
91   const SparcInstrInfo &TII =
92       *static_cast<const SparcInstrInfo *>(MF.getSubtarget().getInstrInfo());
93   const SparcRegisterInfo &RegInfo =
94       *static_cast<const SparcRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
95   MachineBasicBlock::iterator MBBI = MBB.begin();
96   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
97   bool NeedsStackRealignment = RegInfo.needsStackRealignment(MF);
98
99   // FIXME: unfortunately, returning false from canRealignStack
100   // actually just causes needsStackRealignment to return false,
101   // rather than reporting an error, as would be sensible. This is
102   // poor, but fixing that bogosity is going to be a large project.
103   // For now, just see if it's lied, and report an error here.
104   if (!NeedsStackRealignment && MFI->getMaxAlignment() > getStackAlignment())
105     report_fatal_error("Function \"" + Twine(MF.getName()) + "\" required "
106                        "stack re-alignment, but LLVM couldn't handle it "
107                        "(probably because it has a dynamic alloca).");
108
109   // Get the number of bytes to allocate from the FrameInfo
110   int NumBytes = (int) MFI->getStackSize();
111
112   unsigned SAVEri = SP::SAVEri;
113   unsigned SAVErr = SP::SAVErr;
114   if (FuncInfo->isLeafProc()) {
115     if (NumBytes == 0)
116       return;
117     SAVEri = SP::ADDri;
118     SAVErr = SP::ADDrr;
119   }
120
121   NumBytes = MF.getSubtarget<SparcSubtarget>().getAdjustedFrameSize(NumBytes);
122   MFI->setStackSize(NumBytes); // Update stack size with corrected value.
123
124   emitSPAdjustment(MF, MBB, MBBI, -NumBytes, SAVErr, SAVEri);
125
126   MachineModuleInfo &MMI = MF.getMMI();
127   unsigned regFP = RegInfo.getDwarfRegNum(SP::I6, true);
128
129   // Emit ".cfi_def_cfa_register 30".
130   unsigned CFIIndex =
131       MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, regFP));
132   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
133       .addCFIIndex(CFIIndex);
134
135   // Emit ".cfi_window_save".
136   CFIIndex = MMI.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
137   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
138       .addCFIIndex(CFIIndex);
139
140   unsigned regInRA = RegInfo.getDwarfRegNum(SP::I7, true);
141   unsigned regOutRA = RegInfo.getDwarfRegNum(SP::O7, true);
142   // Emit ".cfi_register 15, 31".
143   CFIIndex = MMI.addFrameInst(
144       MCCFIInstruction::createRegister(nullptr, regOutRA, regInRA));
145   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
146       .addCFIIndex(CFIIndex);
147
148   if (NeedsStackRealignment) {
149     // andn %o6, MaxAlign-1, %o6
150     int MaxAlign = MFI->getMaxAlignment();
151     BuildMI(MBB, MBBI, dl, TII.get(SP::ANDNri), SP::O6).addReg(SP::O6).addImm(MaxAlign - 1);
152   }
153 }
154
155 void SparcFrameLowering::
156 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
157                               MachineBasicBlock::iterator I) const {
158   if (!hasReservedCallFrame(MF)) {
159     MachineInstr &MI = *I;
160     int Size = MI.getOperand(0).getImm();
161     if (MI.getOpcode() == SP::ADJCALLSTACKDOWN)
162       Size = -Size;
163
164     if (Size)
165       emitSPAdjustment(MF, MBB, I, Size, SP::ADDrr, SP::ADDri);
166   }
167   MBB.erase(I);
168 }
169
170
171 void SparcFrameLowering::emitEpilogue(MachineFunction &MF,
172                                   MachineBasicBlock &MBB) const {
173   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
174   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
175   const SparcInstrInfo &TII =
176       *static_cast<const SparcInstrInfo *>(MF.getSubtarget().getInstrInfo());
177   DebugLoc dl = MBBI->getDebugLoc();
178   assert(MBBI->getOpcode() == SP::RETL &&
179          "Can only put epilog before 'retl' instruction!");
180   if (!FuncInfo->isLeafProc()) {
181     BuildMI(MBB, MBBI, dl, TII.get(SP::RESTORErr), SP::G0).addReg(SP::G0)
182       .addReg(SP::G0);
183     return;
184   }
185   MachineFrameInfo *MFI = MF.getFrameInfo();
186
187   int NumBytes = (int) MFI->getStackSize();
188   if (NumBytes == 0)
189     return;
190
191   emitSPAdjustment(MF, MBB, MBBI, NumBytes, SP::ADDrr, SP::ADDri);
192 }
193
194 bool SparcFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
195   // Reserve call frame if there are no variable sized objects on the stack.
196   return !MF.getFrameInfo()->hasVarSizedObjects();
197 }
198
199 // hasFP - Return true if the specified function should have a dedicated frame
200 // pointer register.  This is true if the function has variable sized allocas or
201 // if frame pointer elimination is disabled.
202 bool SparcFrameLowering::hasFP(const MachineFunction &MF) const {
203   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
204
205   const MachineFrameInfo *MFI = MF.getFrameInfo();
206   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
207       RegInfo->needsStackRealignment(MF) ||
208       MFI->hasVarSizedObjects() ||
209       MFI->isFrameAddressTaken();
210 }
211
212
213 int SparcFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
214                                                unsigned &FrameReg) const {
215   const SparcSubtarget &Subtarget = MF.getSubtarget<SparcSubtarget>();
216   const MachineFrameInfo *MFI = MF.getFrameInfo();
217   const SparcRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
218   const SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
219   bool isFixed = MFI->isFixedObjectIndex(FI);
220
221   // Addressable stack objects are accessed using neg. offsets from
222   // %fp, or positive offsets from %sp.
223   bool UseFP;
224
225   // Sparc uses FP-based references in general, even when "hasFP" is
226   // false. That function is rather a misnomer, because %fp is
227   // actually always available, unless isLeafProc.
228   if (FuncInfo->isLeafProc()) {
229     // If there's a leaf proc, all offsets need to be %sp-based,
230     // because we haven't caused %fp to actually point to our frame.
231     UseFP = false;
232   } else if (isFixed) {
233     // Otherwise, argument access should always use %fp.
234     UseFP = true;
235   } else if (RegInfo->needsStackRealignment(MF)) {
236     // If there is dynamic stack realignment, all local object
237     // references need to be via %sp, to take account of the
238     // re-alignment.
239     UseFP = false;
240   } else {
241     // Finally, default to using %fp.
242     UseFP = true;
243   }
244
245   int64_t FrameOffset = MF.getFrameInfo()->getObjectOffset(FI) +
246       Subtarget.getStackPointerBias();
247
248   if (UseFP) {
249     FrameReg = RegInfo->getFrameRegister(MF);
250     return FrameOffset;
251   } else {
252     FrameReg = SP::O6; // %sp
253     return FrameOffset + MF.getFrameInfo()->getStackSize();
254   }
255 }
256
257 static bool LLVM_ATTRIBUTE_UNUSED verifyLeafProcRegUse(MachineRegisterInfo *MRI)
258 {
259
260   for (unsigned reg = SP::I0; reg <= SP::I7; ++reg)
261     if (!MRI->reg_nodbg_empty(reg))
262       return false;
263
264   for (unsigned reg = SP::L0; reg <= SP::L7; ++reg)
265     if (!MRI->reg_nodbg_empty(reg))
266       return false;
267
268   return true;
269 }
270
271 bool SparcFrameLowering::isLeafProc(MachineFunction &MF) const
272 {
273
274   MachineRegisterInfo &MRI = MF.getRegInfo();
275   MachineFrameInfo    *MFI = MF.getFrameInfo();
276
277   return !(MFI->hasCalls()                 // has calls
278            || !MRI.reg_nodbg_empty(SP::L0) // Too many registers needed
279            || !MRI.reg_nodbg_empty(SP::O6) // %SP is used
280            || hasFP(MF));                  // need %FP
281 }
282
283 void SparcFrameLowering::remapRegsForLeafProc(MachineFunction &MF) const {
284   MachineRegisterInfo &MRI = MF.getRegInfo();
285   // Remap %i[0-7] to %o[0-7].
286   for (unsigned reg = SP::I0; reg <= SP::I7; ++reg) {
287     if (MRI.reg_nodbg_empty(reg))
288       continue;
289
290     unsigned mapped_reg = reg - SP::I0 + SP::O0;
291     assert(MRI.reg_nodbg_empty(mapped_reg));
292
293     // Replace I register with O register.
294     MRI.replaceRegWith(reg, mapped_reg);
295
296     // Also replace register pair super-registers.
297     if ((reg - SP::I0) % 2 == 0) {
298       unsigned preg = (reg - SP::I0) / 2 + SP::I0_I1;
299       unsigned mapped_preg = preg - SP::I0_I1 + SP::O0_O1;
300       MRI.replaceRegWith(preg, mapped_preg);
301     }
302   }
303
304   // Rewrite MBB's Live-ins.
305   for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
306        MBB != E; ++MBB) {
307     for (unsigned reg = SP::I0_I1; reg <= SP::I6_I7; ++reg) {
308       if (!MBB->isLiveIn(reg))
309         continue;
310       MBB->removeLiveIn(reg);
311       MBB->addLiveIn(reg - SP::I0_I1 + SP::O0_O1);
312     }
313     for (unsigned reg = SP::I0; reg <= SP::I7; ++reg) {
314       if (!MBB->isLiveIn(reg))
315         continue;
316       MBB->removeLiveIn(reg);
317       MBB->addLiveIn(reg - SP::I0 + SP::O0);
318     }
319   }
320
321   assert(verifyLeafProcRegUse(&MRI));
322 #ifdef XDEBUG
323   MF.verify(0, "After LeafProc Remapping");
324 #endif
325 }
326
327 void SparcFrameLowering::determineCalleeSaves(MachineFunction &MF,
328                                               BitVector &SavedRegs,
329                                               RegScavenger *RS) const {
330   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
331   if (!DisableLeafProc && isLeafProc(MF)) {
332     SparcMachineFunctionInfo *MFI = MF.getInfo<SparcMachineFunctionInfo>();
333     MFI->setLeafProc(true);
334
335     remapRegsForLeafProc(MF);
336   }
337
338 }