1//===-- LoongArchFrameLowering.cpp - LoongArch Frame Information -*- C++ -*-==//
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
7//===----------------------------------------------------------------------===//
9// This file contains the LoongArch implementation of TargetFrameLowering class.
11//===----------------------------------------------------------------------===//
28 #define DEBUG_TYPE "loongarch-frame-lowering"
30// Return true if the specified function should have a dedicated frame
31// pointer register. This is true if frame pointer elimination is
32// disabled, if it needs dynamic stack realignment, if the function has
33// variable sized allocas, or if the frame address is taken.
57 unsigned Addi = IsLA64 ? LoongArch::ADDI_D : LoongArch::ADDI_W;
59 if (DestReg == SrcReg && Val == 0)
63 // addi.w/d $DstReg, $SrcReg, Val
71 // Try to split the offset across two ADDIs. We need to keep the stack pointer
72 // aligned after each ADDI. We need to determine the maximum value we can put
73 // in each ADDI. In the negative direction, we can use -2048 which is always
74 // sufficiently aligned. In the positive direction, we need to find the
75 // largest 12-bit immediate that is aligned. Exclude -4096 since it can be
76 // created with LU12I.W.
79 if (Val > -4096 && Val <= (2 * MaxPosAdjStep)) {
80 int64_t FirstAdj = Val < 0 ? -2048 : MaxPosAdjStep;
93 unsigned Opc = IsLA64 ? LoongArch::ADD_D : LoongArch::ADD_W;
96 Opc = IsLA64 ? LoongArch::SUB_D : LoongArch::SUB_W;
100 Register ScratchReg =
MRI.createVirtualRegister(&LoongArch::GPRRegClass);
108// Determine the size of the frame and maximum call frame size.
109void LoongArchFrameLowering::determineFrameLayout(
MachineFunction &MF)
const {
112 // Get the number of bytes to allocate from the FrameInfo.
115 // Make sure the frame is aligned.
118 // Update frame info.
127 FuncSize +=
TII->getInstSizeInBytes(
MI);
136 if (
MI.getOpcode() == LoongArch::PseudoST_CFR)
150 unsigned ScavSlotsNum = 0;
152 // Far branches beyond 27-bit offset require a spill slot for scratch
158 // estimateStackSize has been observed to under-estimate the final stack
159 // size, so give ourselves wiggle-room by checking for stack size
160 // representable an 11-bit signed field rather than 12-bits.
161 // For [x]vstelm.{b/h/w/d} memory instructions with 8 imm offset, 7-bit
162 // signed field is fine.
163 unsigned EstimateStackSize = MFI.estimateStackSize(MF);
167 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
173 // Create emergency spill slots.
174 for (
unsigned i = 0; i < ScavSlotsNum; ++i) {
176 MFI.CreateSpillStackObject(RI->getSpillSize(RC), RI->getSpillAlign(RC));
177 RS->addScavengingFrameIndex(FI);
181 <<
") as the emergency spill slot.\n");
192 bool IsLA64 = STI.is64Bit();
197 // Debug location must be unknown since the first debug location is used
198 // to determine the end of the prologue.
200 // All calls are tail calls in GHC calling conv, and functions have no
201 // prologue/epilogue.
204 // Determine the correct frame layout
205 determineFrameLayout(MF);
207 // First, compute final stack size.
211 // Early exit if there is no need to allocate space in the stack.
216 // Split the SP adjustment to reduce the offsets of callee saved spill.
217 if (FirstSPAdjustAmount)
218 StackSize = FirstSPAdjustAmount;
222 // Emit ".cfi_def_cfa_offset StackSize".
231 // The frame pointer is callee-saved, and code has been generated for us to
232 // save it to the stack. We need to skip over the storing of callee-saved
233 // registers as the frame pointer must be modified after it has been saved
234 // to the stack, not before.
235 std::advance(
MBBI, CSI.size());
237 // Iterate over list of callee-saved registers and emit .cfi_offset
239 for (
const auto &Entry : CSI) {
242 nullptr, RI->getDwarfRegNum(Entry.getReg(),
true),
Offset));
251 StackSize - LoongArchFI->getVarArgsSaveSize(),
254 // Emit ".cfi_def_cfa $fp, LoongArchFI->getVarArgsSaveSize()"
257 LoongArchFI->getVarArgsSaveSize()));
263 // Emit the second SP adjustment after saving callee saved registers.
264 if (FirstSPAdjustAmount) {
265 uint64_t SecondSPAdjustAmount = RealStackSize - FirstSPAdjustAmount;
266 assert(SecondSPAdjustAmount > 0 &&
267 "SecondSPAdjustAmount should be greater than zero");
272 // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
273 // don't emit an sp-based .cfi_def_cfa_offset
274 // Emit ".cfi_def_cfa_offset RealStackSize"
285 if (RI->hasStackRealignment(MF)) {
287 assert(
Align > 0 &&
"The stack realignment size is invalid!");
289 TII->get(IsLA64 ? LoongArch::BSTRINS_D : LoongArch::BSTRINS_W),
296 // FP will be used to restore the frame in the epilogue, so we need
297 // another base register BP to record SP after re-alignment. SP will
298 // track the current stack after allocating variable sized objects.
317 // All calls are tail calls in GHC calling conv, and functions have no
318 // prologue/epilogue.
325 // Skip to before the restores of callee-saved registers.
326 auto LastFrameDestroy =
MBBI;
328 LastFrameDestroy = std::prev(
MBBI, CSI.size());
330 // Get the number of bytes from FrameInfo.
333 // Restore the stack pointer.
335 assert(
hasFP(MF) &&
"frame pointer should not have been eliminated");
336 adjustReg(
MBB, LastFrameDestroy,
DL,
SPReg, LoongArch::R22,
337 -StackSize + LoongArchFI->getVarArgsSaveSize(),
342 if (FirstSPAdjustAmount) {
343 uint64_t SecondSPAdjustAmount = StackSize - FirstSPAdjustAmount;
344 assert(SecondSPAdjustAmount > 0 &&
345 "SecondSPAdjustAmount should be greater than zero");
347 adjustReg(
MBB, LastFrameDestroy,
DL,
SPReg,
SPReg, SecondSPAdjustAmount,
349 StackSize = FirstSPAdjustAmount;
356// We would like to split the SP adjustment to reduce prologue/epilogue
357// as following instructions. In this way, the offset of the callee saved
358// register could fit in a single store.
360// addi.d $sp, $sp, -2032
361// st.d $ra, $sp, 2024
362// st.d $fp, $sp, 2016
363// addi.d $sp, $sp, -16
369 // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
370 // 12-bit and there exists a callee-saved register needing to be pushed.
372 // FirstSPAdjustAmount is chosen as (2048 - StackAlign) because 2048 will
373 // cause sp = sp + 2048 in the epilogue to be split into multiple
374 // instructions. Offsets smaller than 2048 can fit in a single load/store
375 // instruction, and we have to stick with the stack alignment.
376 // So (2048 - StackAlign) will satisfy the stack alignment.
386 // Unconditionally spill RA and FP only if the function uses a frame
389 SavedRegs.
set(LoongArch::R1);
390 SavedRegs.
set(LoongArch::R22);
392 // Mark BP as used if function has dedicated base pointer.
397// Do not preserve stack space within prologue for outgoing variables if the
398// function contains variable size objects.
399// Let eliminateCallFramePseudoInstr preserve stack space for it.
405// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
414 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
415 // ADJCALLSTACKUP must be converted to instructions manipulating the stack
416 // pointer. This is necessary when there is a variable length stack
417 // allocation (e.g. alloca), which means it's not possible to allocate
418 // space for outgoing arguments from within the function prologue.
419 int64_t Amount =
MI->getOperand(0).getImm();
422 // Ensure the stack remains aligned after adjustment.
425 if (
MI->getOpcode() == LoongArch::ADJCALLSTACKDOWN)
432 return MBB.erase(
MI);
444 // Insert the spill to the stack frame.
445 for (
auto &CS : CSI) {
447 // If the register is RA and the return address is taken by method
448 // LoongArchTargetLowering::lowerRETURNADDR, don't set kill flag.
450 !(Reg == LoongArch::R1 && MF->
getFrameInfo().isReturnAddressTaken());
452 TII.storeRegToStackSlot(
MBB,
MI, Reg, IsKill, CS.getFrameIdx(), RC,
TRI,
467 // Callee-saved registers should be referenced relative to the stack
468 // pointer (positive offset), otherwise use the frame pointer (negative
478 MinCSFI = CSI[0].getFrameIdx();
479 MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
482 if (FI >= MinCSFI && FI <= MaxCSFI) {
483 FrameReg = LoongArch::R3;
484 if (FirstSPAdjustAmount)
489 // If the stack was realigned, the frame pointer is set in order to allow
490 // SP to be restored, so we need another base register to record the stack
491 // after realignment.
507 // Keep the conventional code flow when not optimizing.
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
const HexagonInstrInfo * TII
static uint64_t estimateFunctionSizeInBytes(const LoongArchInstrInfo *TII, const MachineFunction &MF)
static bool needScavSlotForCFR(MachineFunction &MF)
Register const TargetRegisterInfo * TRI
Promote Memory to Register
static constexpr MCPhysReg FPReg
static constexpr MCPhysReg SPReg
This file declares the machine register scavenger class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
empty - Check if the array is empty.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
bool hasOptNone() const
Do not optimize this function (-O0).
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
uint64_t getFirstSPAdjustAmount(const MachineFunction &MF) const
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
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 determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
bool hasFPImpl(const MachineFunction &MF) const override
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
bool hasBP(const MachineFunction &MF) const
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
LoongArchMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private Lo...
int getBranchRelaxationSpillFrameIndex()
void setBranchRelaxationSpillFrameIndex(int Index)
const LoongArchInstrInfo * getInstrInfo() const override
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.
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.
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Wrapper class representing physical registers. Should be passed by value.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
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 ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
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.
void setStackSize(uint64_t Size)
Set the size of the stack.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
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.
Wrapper class representing virtual and physical registers.
StackOffset holds a fixed and a scalable offset in bytes.
int64_t getFixed() const
Returns the fixed component of the stack.
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
TargetInstrInfo - Interface to description of machine instruction set.
LLVM_ABI 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...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual Register getFrameRegister(const MachineFunction &MF) const =0
Debug information queries.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
@ Kill
The last use of a register.
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
unsigned Log2(Align A)
Returns the log2 of the alignment.
This struct is a compact representation of a valid (non-zero power of two) alignment.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.