LLVM  9.0.0svn
SparcFrameLowering.cpp
Go to the documentation of this file.
1 //===-- SparcFrameLowering.cpp - Sparc Frame Information ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the Sparc implementation of TargetFrameLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SparcFrameLowering.h"
14 #include "SparcInstrInfo.h"
16 #include "SparcSubtarget.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
26 
27 using namespace llvm;
28 
29 static cl::opt<bool>
30 DisableLeafProc("disable-sparc-leaf-proc",
31  cl::init(false),
32  cl::desc("Disable Sparc leaf procedure optimization."),
33  cl::Hidden);
34 
36  : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
37  ST.is64Bit() ? 16 : 8, 0, ST.is64Bit() ? 16 : 8) {}
38 
39 void SparcFrameLowering::emitSPAdjustment(MachineFunction &MF,
40  MachineBasicBlock &MBB,
42  int NumBytes,
43  unsigned ADDrr,
44  unsigned ADDri) const {
45 
46  DebugLoc dl;
47  const SparcInstrInfo &TII =
48  *static_cast<const SparcInstrInfo *>(MF.getSubtarget().getInstrInfo());
49 
50  if (NumBytes >= -4096 && NumBytes < 4096) {
51  BuildMI(MBB, MBBI, dl, TII.get(ADDri), SP::O6)
52  .addReg(SP::O6).addImm(NumBytes);
53  return;
54  }
55 
56  // Emit this the hard way. This clobbers G1 which we always know is
57  // available here.
58  if (NumBytes >= 0) {
59  // Emit nonnegative numbers with sethi + or.
60  // sethi %hi(NumBytes), %g1
61  // or %g1, %lo(NumBytes), %g1
62  // add %sp, %g1, %sp
63  BuildMI(MBB, MBBI, dl, TII.get(SP::SETHIi), SP::G1)
64  .addImm(HI22(NumBytes));
65  BuildMI(MBB, MBBI, dl, TII.get(SP::ORri), SP::G1)
66  .addReg(SP::G1).addImm(LO10(NumBytes));
67  BuildMI(MBB, MBBI, dl, TII.get(ADDrr), SP::O6)
68  .addReg(SP::O6).addReg(SP::G1);
69  return ;
70  }
71 
72  // Emit negative numbers with sethi + xor.
73  // sethi %hix(NumBytes), %g1
74  // xor %g1, %lox(NumBytes), %g1
75  // add %sp, %g1, %sp
76  BuildMI(MBB, MBBI, dl, TII.get(SP::SETHIi), SP::G1)
77  .addImm(HIX22(NumBytes));
78  BuildMI(MBB, MBBI, dl, TII.get(SP::XORri), SP::G1)
79  .addReg(SP::G1).addImm(LOX10(NumBytes));
80  BuildMI(MBB, MBBI, dl, TII.get(ADDrr), SP::O6)
81  .addReg(SP::O6).addReg(SP::G1);
82 }
83 
85  MachineBasicBlock &MBB) const {
87 
88  assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
89  MachineFrameInfo &MFI = MF.getFrameInfo();
90  const SparcSubtarget &Subtarget = MF.getSubtarget<SparcSubtarget>();
91  const SparcInstrInfo &TII =
92  *static_cast<const SparcInstrInfo *>(Subtarget.getInstrInfo());
93  const SparcRegisterInfo &RegInfo =
94  *static_cast<const SparcRegisterInfo *>(Subtarget.getRegisterInfo());
96  // Debug location must be unknown since the first debug location is used
97  // to determine the end of the prologue.
98  DebugLoc dl;
99  bool NeedsStackRealignment = RegInfo.needsStackRealignment(MF);
100 
101  // FIXME: unfortunately, returning false from canRealignStack
102  // actually just causes needsStackRealignment to return false,
103  // rather than reporting an error, as would be sensible. This is
104  // poor, but fixing that bogosity is going to be a large project.
105  // For now, just see if it's lied, and report an error here.
106  if (!NeedsStackRealignment && MFI.getMaxAlignment() > getStackAlignment())
107  report_fatal_error("Function \"" + Twine(MF.getName()) + "\" required "
108  "stack re-alignment, but LLVM couldn't handle it "
109  "(probably because it has a dynamic alloca).");
110 
111  // Get the number of bytes to allocate from the FrameInfo
112  int NumBytes = (int) MFI.getStackSize();
113 
114  unsigned SAVEri = SP::SAVEri;
115  unsigned SAVErr = SP::SAVErr;
116  if (FuncInfo->isLeafProc()) {
117  if (NumBytes == 0)
118  return;
119  SAVEri = SP::ADDri;
120  SAVErr = SP::ADDrr;
121  }
122 
123  // The SPARC ABI is a bit odd in that it requires a reserved 92-byte
124  // (128 in v9) area in the user's stack, starting at %sp. Thus, the
125  // first part of the stack that can actually be used is located at
126  // %sp + 92.
127  //
128  // We therefore need to add that offset to the total stack size
129  // after all the stack objects are placed by
130  // PrologEpilogInserter calculateFrameObjectOffsets. However, since the stack needs to be
131  // aligned *after* the extra size is added, we need to disable
132  // calculateFrameObjectOffsets's built-in stack alignment, by having
133  // targetHandlesStackFrameRounding return true.
134 
135 
136  // Add the extra call frame stack size, if needed. (This is the same
137  // code as in PrologEpilogInserter, but also gets disabled by
138  // targetHandlesStackFrameRounding)
139  if (MFI.adjustsStack() && hasReservedCallFrame(MF))
140  NumBytes += MFI.getMaxCallFrameSize();
141 
142  // Adds the SPARC subtarget-specific spill area to the stack
143  // size. Also ensures target-required alignment.
144  NumBytes = Subtarget.getAdjustedFrameSize(NumBytes);
145 
146  // Finally, ensure that the size is sufficiently aligned for the
147  // data on the stack.
148  if (MFI.getMaxAlignment() > 0) {
149  NumBytes = alignTo(NumBytes, MFI.getMaxAlignment());
150  }
151 
152  // Update stack size with corrected value.
153  MFI.setStackSize(NumBytes);
154 
155  emitSPAdjustment(MF, MBB, MBBI, -NumBytes, SAVErr, SAVEri);
156 
157  unsigned regFP = RegInfo.getDwarfRegNum(SP::I6, true);
158 
159  // Emit ".cfi_def_cfa_register 30".
160  unsigned CFIIndex =
162  BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
163  .addCFIIndex(CFIIndex);
164 
165  // Emit ".cfi_window_save".
166  CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
167  BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
168  .addCFIIndex(CFIIndex);
169 
170  unsigned regInRA = RegInfo.getDwarfRegNum(SP::I7, true);
171  unsigned regOutRA = RegInfo.getDwarfRegNum(SP::O7, true);
172  // Emit ".cfi_register 15, 31".
173  CFIIndex = MF.addFrameInst(
174  MCCFIInstruction::createRegister(nullptr, regOutRA, regInRA));
175  BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
176  .addCFIIndex(CFIIndex);
177 
178  if (NeedsStackRealignment) {
179  int64_t Bias = Subtarget.getStackPointerBias();
180  unsigned regUnbiased;
181  if (Bias) {
182  // This clobbers G1 which we always know is available here.
183  regUnbiased = SP::G1;
184  // add %o6, BIAS, %g1
185  BuildMI(MBB, MBBI, dl, TII.get(SP::ADDri), regUnbiased)
186  .addReg(SP::O6).addImm(Bias);
187  } else
188  regUnbiased = SP::O6;
189 
190  // andn %regUnbiased, MaxAlign-1, %regUnbiased
191  int MaxAlign = MFI.getMaxAlignment();
192  BuildMI(MBB, MBBI, dl, TII.get(SP::ANDNri), regUnbiased)
193  .addReg(regUnbiased).addImm(MaxAlign - 1);
194 
195  if (Bias) {
196  // add %g1, -BIAS, %o6
197  BuildMI(MBB, MBBI, dl, TII.get(SP::ADDri), SP::O6)
198  .addReg(regUnbiased).addImm(-Bias);
199  }
200  }
201 }
202 
206  if (!hasReservedCallFrame(MF)) {
207  MachineInstr &MI = *I;
208  int Size = MI.getOperand(0).getImm();
209  if (MI.getOpcode() == SP::ADJCALLSTACKDOWN)
210  Size = -Size;
211 
212  if (Size)
213  emitSPAdjustment(MF, MBB, I, Size, SP::ADDrr, SP::ADDri);
214  }
215  return MBB.erase(I);
216 }
217 
218 
220  MachineBasicBlock &MBB) const {
223  const SparcInstrInfo &TII =
224  *static_cast<const SparcInstrInfo *>(MF.getSubtarget().getInstrInfo());
225  DebugLoc dl = MBBI->getDebugLoc();
226  assert(MBBI->getOpcode() == SP::RETL &&
227  "Can only put epilog before 'retl' instruction!");
228  if (!FuncInfo->isLeafProc()) {
229  BuildMI(MBB, MBBI, dl, TII.get(SP::RESTORErr), SP::G0).addReg(SP::G0)
230  .addReg(SP::G0);
231  return;
232  }
233  MachineFrameInfo &MFI = MF.getFrameInfo();
234 
235  int NumBytes = (int) MFI.getStackSize();
236  if (NumBytes == 0)
237  return;
238 
239  emitSPAdjustment(MF, MBB, MBBI, NumBytes, SP::ADDrr, SP::ADDri);
240 }
241 
243  // Reserve call frame if there are no variable sized objects on the stack.
244  return !MF.getFrameInfo().hasVarSizedObjects();
245 }
246 
247 // hasFP - Return true if the specified function should have a dedicated frame
248 // pointer register. This is true if the function has variable sized allocas or
249 // if frame pointer elimination is disabled.
251  const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
252 
253  const MachineFrameInfo &MFI = MF.getFrameInfo();
254  return MF.getTarget().Options.DisableFramePointerElim(MF) ||
255  RegInfo->needsStackRealignment(MF) ||
256  MFI.hasVarSizedObjects() ||
257  MFI.isFrameAddressTaken();
258 }
259 
260 
262  unsigned &FrameReg) const {
263  const SparcSubtarget &Subtarget = MF.getSubtarget<SparcSubtarget>();
264  const MachineFrameInfo &MFI = MF.getFrameInfo();
265  const SparcRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
267  bool isFixed = MFI.isFixedObjectIndex(FI);
268 
269  // Addressable stack objects are accessed using neg. offsets from
270  // %fp, or positive offsets from %sp.
271  bool UseFP;
272 
273  // Sparc uses FP-based references in general, even when "hasFP" is
274  // false. That function is rather a misnomer, because %fp is
275  // actually always available, unless isLeafProc.
276  if (FuncInfo->isLeafProc()) {
277  // If there's a leaf proc, all offsets need to be %sp-based,
278  // because we haven't caused %fp to actually point to our frame.
279  UseFP = false;
280  } else if (isFixed) {
281  // Otherwise, argument access should always use %fp.
282  UseFP = true;
283  } else if (RegInfo->needsStackRealignment(MF)) {
284  // If there is dynamic stack realignment, all local object
285  // references need to be via %sp, to take account of the
286  // re-alignment.
287  UseFP = false;
288  } else {
289  // Finally, default to using %fp.
290  UseFP = true;
291  }
292 
293  int64_t FrameOffset = MF.getFrameInfo().getObjectOffset(FI) +
294  Subtarget.getStackPointerBias();
295 
296  if (UseFP) {
297  FrameReg = RegInfo->getFrameRegister(MF);
298  return FrameOffset;
299  } else {
300  FrameReg = SP::O6; // %sp
301  return FrameOffset + MF.getFrameInfo().getStackSize();
302  }
303 }
304 
306 {
307 
308  for (unsigned reg = SP::I0; reg <= SP::I7; ++reg)
309  if (MRI->isPhysRegUsed(reg))
310  return false;
311 
312  for (unsigned reg = SP::L0; reg <= SP::L7; ++reg)
313  if (MRI->isPhysRegUsed(reg))
314  return false;
315 
316  return true;
317 }
318 
319 bool SparcFrameLowering::isLeafProc(MachineFunction &MF) const
320 {
321 
323  MachineFrameInfo &MFI = MF.getFrameInfo();
324 
325  return !(MFI.hasCalls() // has calls
326  || MRI.isPhysRegUsed(SP::L0) // Too many registers needed
327  || MRI.isPhysRegUsed(SP::O6) // %sp is used
328  || hasFP(MF)); // need %fp
329 }
330 
331 void SparcFrameLowering::remapRegsForLeafProc(MachineFunction &MF) const {
333  // Remap %i[0-7] to %o[0-7].
334  for (unsigned reg = SP::I0; reg <= SP::I7; ++reg) {
335  if (!MRI.isPhysRegUsed(reg))
336  continue;
337 
338  unsigned mapped_reg = reg - SP::I0 + SP::O0;
339 
340  // Replace I register with O register.
341  MRI.replaceRegWith(reg, mapped_reg);
342 
343  // Also replace register pair super-registers.
344  if ((reg - SP::I0) % 2 == 0) {
345  unsigned preg = (reg - SP::I0) / 2 + SP::I0_I1;
346  unsigned mapped_preg = preg - SP::I0_I1 + SP::O0_O1;
347  MRI.replaceRegWith(preg, mapped_preg);
348  }
349  }
350 
351  // Rewrite MBB's Live-ins.
352  for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
353  MBB != E; ++MBB) {
354  for (unsigned reg = SP::I0_I1; reg <= SP::I6_I7; ++reg) {
355  if (!MBB->isLiveIn(reg))
356  continue;
357  MBB->removeLiveIn(reg);
358  MBB->addLiveIn(reg - SP::I0_I1 + SP::O0_O1);
359  }
360  for (unsigned reg = SP::I0; reg <= SP::I7; ++reg) {
361  if (!MBB->isLiveIn(reg))
362  continue;
363  MBB->removeLiveIn(reg);
364  MBB->addLiveIn(reg - SP::I0 + SP::O0);
365  }
366  }
367 
369 #ifdef EXPENSIVE_CHECKS
370  MF.verify(0, "After LeafProc Remapping");
371 #endif
372 }
373 
375  BitVector &SavedRegs,
376  RegScavenger *RS) const {
378  if (!DisableLeafProc && isLeafProc(MF)) {
380  MFI->setLeafProc(true);
381 
382  remapRegsForLeafProc(MF);
383  }
384 
385 }
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
unsigned getFrameRegister(const MachineFunction &MF) const override
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
bool hasFP(const MachineFunction &MF) const override
hasFP - Return true if the specified function should have a dedicated frame pointer register...
int getFrameIndexReference(const MachineFunction &MF, int FI, unsigned &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
A debug info location.
Definition: DebugLoc.h:33
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:684
const SparcInstrInfo * getInstrInfo() const override
static unsigned LO10(int64_t imm)
Definition: Sparc.h:153
void removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
const HexagonInstrInfo * TII
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
LLVM_NODISCARD unsigned addFrameInst(const MCCFIInstruction &Inst)
static unsigned HIX22(int64_t imm)
Definition: Sparc.h:157
bool DisableFramePointerElim(const MachineFunction &MF) const
DisableFramePointerElim - This returns true if frame pointer elimination optimization should be disab...
static unsigned HI22(int64_t imm)
Definition: Sparc.h:149
int64_t getStackPointerBias() const
The 64-bit ABI uses biased stack and frame pointers, so the stack frame of the current function is th...
iterator getLastNonDebugInstr()
Returns an iterator to the last non-debug instruction in the basic block, or end().
virtual const TargetInstrInfo * getInstrInfo() const
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
int getAdjustedFrameSize(int stackSize) const
Given a actual stack size as determined by FrameInfo, this function returns adjusted framesize which ...
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
static unsigned LOX10(int64_t imm)
Definition: Sparc.h:161
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register)
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition: MCDwarf.h:467
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
static MCCFIInstruction createWindowSave(MCSymbol *L)
.cfi_window_save SPARC register window is saved.
Definition: MCDwarf.h:508
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool is64Bit(const char *name)
static cl::opt< bool > DisableLeafProc("disable-sparc-leaf-proc", cl::init(false), cl::desc("Disable Sparc leaf procedure optimization."), cl::Hidden)
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:159
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
const MachineBasicBlock & front() const
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
const SparcRegisterInfo * getRegisterInfo() const override
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required, we reserve argument space for call sites in the function immediately on entry to the current function.
static bool LLVM_ATTRIBUTE_UNUSED verifyLeafProcRegUse(MachineRegisterInfo *MRI)
Iterator for intrusive lists based on ilist_node.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
Information about stack frame layout on the target.
int64_t getImm() const
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
bool isPhysRegUsed(unsigned PhysReg) const
Return true if the specified register is modified or read in this function.
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:63
SparcFrameLowering(const SparcSubtarget &ST)
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use...
TargetOptions Options
Definition: TargetMachine.h:96
#define I(x, y, z)
Definition: MD5.cpp:58
uint32_t Size
Definition: Profile.cpp:46
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool needsStackRealignment(const MachineFunction &MF) const
True if storage within the function requires the stack pointer to be aligned more than the normal cal...
IRTranslator LLVM IR MI
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects...
static MCCFIInstruction createRegister(MCSymbol *L, unsigned Register1, unsigned Register2)
.cfi_register Previous value of Register1 is saved in register Register2.
Definition: MCDwarf.h:502
bool hasCalls() const
Return true if the current function has any function calls.