LLVM 20.0.0git
MSP430FrameLowering.cpp
Go to the documentation of this file.
1//===-- MSP430FrameLowering.cpp - MSP430 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 MSP430 implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MSP430FrameLowering.h"
14#include "MSP430InstrInfo.h"
16#include "MSP430Subtarget.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Function.h"
25
26using namespace llvm;
27
29 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, Align(2), -2,
30 Align(2)),
31 STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {}
32
34 const MachineFrameInfo &MFI = MF.getFrameInfo();
35
36 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
39}
40
42 return !MF.getFrameInfo().hasVarSizedObjects();
43}
44
47 const DebugLoc &DL,
48 const MCCFIInstruction &CFIInst,
49 MachineInstr::MIFlag Flag) const {
51 unsigned CFIIndex = MF.addFrameInst(CFIInst);
52 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
53 .addCFIIndex(CFIIndex)
54 .setMIFlag(Flag);
55}
56
59 const DebugLoc &DL, bool IsPrologue) const {
63
64 // Add callee saved registers to move list.
65 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
66
67 // Calculate offsets.
68 for (const CalleeSavedInfo &I : CSI) {
69 int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
70 Register Reg = I.getReg();
71 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
72
73 if (IsPrologue) {
75 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
76 } else {
78 MCCFIInstruction::createRestore(nullptr, DwarfReg));
79 }
80 }
81}
82
84 MachineBasicBlock &MBB) const {
85 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
88 const MSP430InstrInfo &TII =
89 *static_cast<const MSP430InstrInfo *>(MF.getSubtarget().getInstrInfo());
90
92 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
93
94 // Get the number of bytes to allocate from the FrameInfo.
95 uint64_t StackSize = MFI.getStackSize();
96 int stackGrowth = -2;
97
98 uint64_t NumBytes = 0;
99 if (hasFP(MF)) {
100 // Calculate required stack adjustment
101 uint64_t FrameSize = StackSize - 2;
102 NumBytes = FrameSize - MSP430FI->getCalleeSavedFrameSize();
103
104 // Get the offset of the stack slot for the EBP register... which is
105 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
106 // Update the frame offset adjustment.
107 MFI.setOffsetAdjustment(-NumBytes);
108
109 // Save FP into the appropriate stack slot...
110 BuildMI(MBB, MBBI, DL, TII.get(MSP430::PUSH16r))
111 .addReg(MSP430::R4, RegState::Kill)
113
114 // Mark the place where FP was saved.
115 // Define the current CFA rule to use the provided offset.
117 MCCFIInstruction::cfiDefCfaOffset(nullptr, -2 * stackGrowth),
119
120 // Change the rule for the FramePtr to be an "offset" rule.
121 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MSP430::R4, true);
122 BuildCFI(
123 MBB, MBBI, DL,
124 MCCFIInstruction::createOffset(nullptr, DwarfFramePtr, 2 * stackGrowth),
126
127 // Update FP with the new base value...
128 BuildMI(MBB, MBBI, DL, TII.get(MSP430::MOV16rr), MSP430::R4)
129 .addReg(MSP430::SP)
131
132 // Mark effective beginning of when frame pointer becomes valid.
133 // Define the current CFA to use the FP register.
135 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr),
137
138 // Mark the FramePtr as live-in in every block except the entry.
139 for (MachineBasicBlock &MBBJ : llvm::drop_begin(MF))
140 MBBJ.addLiveIn(MSP430::R4);
141 } else
142 NumBytes = StackSize - MSP430FI->getCalleeSavedFrameSize();
143
144 // Skip the callee-saved push instructions.
145 int StackOffset = 2 * stackGrowth;
146 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup) &&
147 (MBBI->getOpcode() == MSP430::PUSH16r)) {
148 ++MBBI;
149
150 if (!hasFP(MF)) {
151 // Mark callee-saved push instruction.
152 // Define the current CFA rule to use the provided offset.
153 assert(StackSize && "Expected stack frame");
157 StackOffset += stackGrowth;
158 }
159 }
160
161 if (MBBI != MBB.end())
162 DL = MBBI->getDebugLoc();
163
164 if (NumBytes) { // adjust stack pointer: SP -= numbytes
165 // If there is an SUB16ri of SP immediately before this instruction, merge
166 // the two.
167 //NumBytes -= mergeSPUpdates(MBB, MBBI, true);
168 // If there is an ADD16ri or SUB16ri of SP immediately after this
169 // instruction, merge the two instructions.
170 // mergeSPUpdatesDown(MBB, MBBI, &NumBytes);
171
172 if (NumBytes) {
174 BuildMI(MBB, MBBI, DL, TII.get(MSP430::SUB16ri), MSP430::SP)
175 .addReg(MSP430::SP)
176 .addImm(NumBytes)
178 // The SRW implicit def is dead.
179 MI->getOperand(3).setIsDead();
180 }
181 if (!hasFP(MF)) {
182 // Adjust the previous CFA value if CFA was not redefined by FP
183 BuildCFI(
184 MBB, MBBI, DL,
185 MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize - stackGrowth),
187 }
188 }
189
191}
192
194 MachineBasicBlock &MBB) const {
195 const MachineFrameInfo &MFI = MF.getFrameInfo();
197 const MSP430InstrInfo &TII =
198 *static_cast<const MSP430InstrInfo *>(MF.getSubtarget().getInstrInfo());
199
201 unsigned RetOpcode = MBBI->getOpcode();
202 DebugLoc DL = MBBI->getDebugLoc();
203
204 switch (RetOpcode) {
205 case MSP430::RET:
206 case MSP430::RETI: break; // These are ok
207 default:
208 llvm_unreachable("Can only insert epilog into returning blocks");
209 }
210
211 // Get the number of bytes to allocate from the FrameInfo
212 uint64_t StackSize = MFI.getStackSize();
213 unsigned CSSize = MSP430FI->getCalleeSavedFrameSize();
214 uint64_t NumBytes = 0;
215
217 if (hasFP(MF)) {
218 // Calculate required stack adjustment
219 uint64_t FrameSize = StackSize - 2;
220 NumBytes = FrameSize - CSSize;
221
222 // pop FP.
223 BuildMI(MBB, MBBI, DL, TII.get(MSP430::POP16r), MSP430::R4)
225 unsigned DwarfStackPtr = TRI->getDwarfRegNum(MSP430::SP, true);
227 MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, 2),
229 --MBBI;
230 if (!MBB.succ_empty() && !MBB.isReturnBlock()) {
231 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MSP430::R4, true);
232 BuildCFI(MBB, AfterPop, DL,
233 MCCFIInstruction::createRestore(nullptr, DwarfFramePtr),
235 --MBBI;
236 --AfterPop;
237 }
238 } else
239 NumBytes = StackSize - CSSize;
240
241 // Skip the callee-saved pop instructions.
243 while (MBBI != MBB.begin()) {
244 MachineBasicBlock::iterator PI = std::prev(MBBI);
245 unsigned Opc = PI->getOpcode();
246 if ((Opc != MSP430::POP16r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
247 !PI->isTerminator())
248 break;
249 FirstCSPop = PI;
250 --MBBI;
251 }
252 MBBI = FirstCSPop;
253
254 DL = MBBI->getDebugLoc();
255
256 // If there is an ADD16ri or SUB16ri of SP immediately before this
257 // instruction, merge the two instructions.
258 //if (NumBytes || MFI.hasVarSizedObjects())
259 // mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
260
261 if (MFI.hasVarSizedObjects()) {
262 BuildMI(MBB, MBBI, DL, TII.get(MSP430::MOV16rr), MSP430::SP)
263 .addReg(MSP430::R4)
265 if (CSSize) {
267 BuildMI(MBB, MBBI, DL, TII.get(MSP430::SUB16ri), MSP430::SP)
268 .addReg(MSP430::SP)
269 .addImm(CSSize)
271 // The SRW implicit def is dead.
272 MI->getOperand(3).setIsDead();
273 }
274 } else {
275 // adjust stack pointer back: SP += numbytes
276 if (NumBytes) {
278 BuildMI(MBB, MBBI, DL, TII.get(MSP430::ADD16ri), MSP430::SP)
279 .addReg(MSP430::SP)
280 .addImm(NumBytes)
282 // The SRW implicit def is dead.
283 MI->getOperand(3).setIsDead();
284
285 if (!hasFP(MF)) {
286 // Adjust CFA value if it was defined by SP
288 MCCFIInstruction::cfiDefCfaOffset(nullptr, CSSize + 2),
290 }
291 }
292 }
293
294 if (!hasFP(MF)) {
295 MBBI = FirstCSPop;
296 int64_t Offset = -(int64_t)CSSize - 2;
297 // Mark callee-saved pop instruction.
298 // Define the current CFA rule to use the provided offset.
299 while (MBBI != MBB.end()) {
301 unsigned Opc = PI->getOpcode();
302 ++MBBI;
303 if (Opc == MSP430::POP16r) {
304 Offset += 2;
308 }
309 }
310 }
311 emitCalleeSavedFrameMoves(MBB, AfterPop, DL, false);
312}
313
314// FIXME: Can we eleminate these in favour of generic code?
318 if (CSI.empty())
319 return false;
320
321 DebugLoc DL;
322 if (MI != MBB.end()) DL = MI->getDebugLoc();
323
327 MFI->setCalleeSavedFrameSize(CSI.size() * 2);
328
329 for (const CalleeSavedInfo &I : CSI) {
330 Register Reg = I.getReg();
331 // Add the callee-saved register as live-in. It's killed at the spill.
332 MBB.addLiveIn(Reg);
333 BuildMI(MBB, MI, DL, TII.get(MSP430::PUSH16r))
336 }
337 return true;
338}
339
343 if (CSI.empty())
344 return false;
345
346 DebugLoc DL;
347 if (MI != MBB.end()) DL = MI->getDebugLoc();
348
351
352 for (const CalleeSavedInfo &I : llvm::reverse(CSI))
353 BuildMI(MBB, MI, DL, TII.get(MSP430::POP16r), I.getReg())
355
356 return true;
357}
358
362 const MSP430InstrInfo &TII =
363 *static_cast<const MSP430InstrInfo *>(MF.getSubtarget().getInstrInfo());
364 if (!hasReservedCallFrame(MF)) {
365 // If the stack pointer can be changed after prologue, turn the
366 // adjcallstackup instruction into a 'sub SP, <amt>' and the
367 // adjcallstackdown instruction into 'add SP, <amt>'
368 // TODO: consider using push / pop instead of sub + store / add
369 MachineInstr &Old = *I;
370 uint64_t Amount = TII.getFrameSize(Old);
371 if (Amount != 0) {
372 // We need to keep the stack aligned properly. To do this, we round the
373 // amount of space needed for the outgoing arguments up to the next
374 // alignment boundary.
375 Amount = alignTo(Amount, getStackAlign());
376
377 MachineInstr *New = nullptr;
378 if (Old.getOpcode() == TII.getCallFrameSetupOpcode()) {
379 New =
380 BuildMI(MF, Old.getDebugLoc(), TII.get(MSP430::SUB16ri), MSP430::SP)
381 .addReg(MSP430::SP)
382 .addImm(Amount);
383 } else {
384 assert(Old.getOpcode() == TII.getCallFrameDestroyOpcode());
385 // factor out the amount the callee already popped.
386 Amount -= TII.getFramePoppedByCallee(Old);
387 if (Amount)
388 New = BuildMI(MF, Old.getDebugLoc(), TII.get(MSP430::ADD16ri),
389 MSP430::SP)
390 .addReg(MSP430::SP)
391 .addImm(Amount);
392 }
393
394 if (New) {
395 // The SRW implicit def is dead.
396 New->getOperand(3).setIsDead();
397
398 // Replace the pseudo instruction with a new instruction...
399 MBB.insert(I, New);
400 }
401 }
402 } else if (I->getOpcode() == TII.getCallFrameDestroyOpcode()) {
403 // If we are performing frame pointer elimination and if the callee pops
404 // something off the stack pointer, add it back.
405 if (uint64_t CalleeAmt = TII.getFramePoppedByCallee(*I)) {
406 MachineInstr &Old = *I;
407 MachineInstr *New =
408 BuildMI(MF, Old.getDebugLoc(), TII.get(MSP430::SUB16ri), MSP430::SP)
409 .addReg(MSP430::SP)
410 .addImm(CalleeAmt);
411 if (!hasFP(MF)) {
412 DebugLoc DL = I->getDebugLoc();
413 BuildCFI(MBB, I, DL,
414 MCCFIInstruction::createAdjustCfaOffset(nullptr, CalleeAmt));
415 }
416 // The SRW implicit def is dead.
417 New->getOperand(3).setIsDead();
418
419 MBB.insert(I, New);
420 }
421 }
422
423 return MBB.erase(I);
424}
425
426void
428 RegScavenger *) const {
429 // Create a frame entry for the FP register that must be saved.
430 if (hasFP(MF)) {
431 int FrameIdx = MF.getFrameInfo().CreateFixedObject(2, -4, true);
432 (void)FrameIdx;
433 assert(FrameIdx == MF.getFrameInfo().getObjectIndexBegin() &&
434 "Slot for FP register must be last in order to be found!");
435 }
436}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
A debug info location.
Definition: DebugLoc.h:33
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition: MCDwarf.h:565
static MCCFIInstruction createRestore(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_restore says that the rule for Register is now the same as it was at the beginning of the functi...
Definition: MCDwarf.h:633
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition: MCDwarf.h:558
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition: MCDwarf.h:600
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition: MCDwarf.h:573
static MCCFIInstruction createAdjustCfaOffset(MCSymbol *L, int64_t Adjustment, SMLoc Loc={})
.cfi_adjust_cfa_offset Same as .cfi_def_cfa_offset, but Offset is a relative value that is added/subt...
Definition: MCDwarf.h:581
const MCRegisterInfo * getRegisterInfo() const
Definition: MCContext.h:414
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
MSP430FrameLowering(const MSP430Subtarget &STI)
bool hasFP(const MachineFunction &MF) const override
hasFP - Return true if the specified function should have a dedicated frame pointer register.
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
void emitCalleeSavedFrameMoves(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool IsPrologue) const
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
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...
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
const MSP430RegisterInfo * TRI
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
void BuildCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCCFIInstruction &CFIInst, MachineInstr::MIFlag Flag=MachineInstr::NoFlags) const
Wraps up getting a CFI index and building a MachineInstr for it.
const MSP430InstrInfo & TII
int64_t getFramePoppedByCallee(const MachineInstr &I) const
MSP430MachineFunctionInfo - This class is derived from MachineFunction and contains private MSP430 ta...
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
int getObjectIndexBegin() const
Return the minimum frame object index.
void setOffsetAdjustment(int64_t Adj)
Set the correction for frame offsets.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:569
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:498
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:307
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
StackOffset holds a fixed and a scalable offset in bytes.
Definition: TypeSize.h:33
Information about stack frame layout on the target.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetInstrInfo - Interface to description of machine instruction set.
TargetOptions Options
bool DisableFramePointerElim(const MachineFunction &MF) const
DisableFramePointerElim - This returns true if frame pointer elimination optimization should be disab...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Kill
The last use of a register.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
@ Offset
Definition: DWP.cpp:480
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39