1 //===-- RISCVFrameLowering.cpp - RISCV 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 RISCV implementation of TargetFrameLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RISCVFrameLowering.h"
14 #include "RISCVMachineFunctionInfo.h"
15 #include "RISCVSubtarget.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/RegisterScavenging.h"
21 #include "llvm/IR/DiagnosticInfo.h"
22 #include "llvm/MC/MCDwarf.h"
23 
24 using namespace llvm;
25 
26 // For now we use x18, a.k.a s2, as pointer to shadow call stack.
27 // User should explicitly set -ffixed-x18 and not use x18 in their asm.
28 static void emitSCSPrologue(MachineFunction &MF, MachineBasicBlock &MBB,
29                             MachineBasicBlock::iterator MI,
30                             const DebugLoc &DL) {
31   if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
32     return;
33 
34   const auto &STI = MF.getSubtarget<RISCVSubtarget>();
35   Register RAReg = STI.getRegisterInfo()->getRARegister();
36 
37   // Do not save RA to the SCS if it's not saved to the regular stack,
38   // i.e. RA is not at risk of being overwritten.
39   std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
40   if (std::none_of(CSI.begin(), CSI.end(),
41                    [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
42     return;
43 
44   Register SCSPReg = RISCVABI::getSCSPReg();
45 
46   auto &Ctx = MF.getFunction().getContext();
47   if (!STI.isRegisterReservedByUser(SCSPReg)) {
48     Ctx.diagnose(DiagnosticInfoUnsupported{
49         MF.getFunction(), "x18 not reserved by user for Shadow Call Stack."});
50     return;
51   }
52 
53   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
54   if (RVFI->useSaveRestoreLibCalls(MF)) {
55     Ctx.diagnose(DiagnosticInfoUnsupported{
56         MF.getFunction(),
57         "Shadow Call Stack cannot be combined with Save/Restore LibCalls."});
58     return;
59   }
60 
61   const RISCVInstrInfo *TII = STI.getInstrInfo();
62   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
63   int64_t SlotSize = STI.getXLen() / 8;
64   // Store return address to shadow call stack
65   // s[w|d]  ra, 0(s2)
66   // addi    s2, s2, [4|8]
67   BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
68       .addReg(RAReg)
69       .addReg(SCSPReg)
70       .addImm(0)
71       .setMIFlag(MachineInstr::FrameSetup);
72   BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
73       .addReg(SCSPReg, RegState::Define)
74       .addReg(SCSPReg)
75       .addImm(SlotSize)
76       .setMIFlag(MachineInstr::FrameSetup);
77 }
78 
79 static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB,
80                             MachineBasicBlock::iterator MI,
81                             const DebugLoc &DL) {
82   if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
83     return;
84 
85   const auto &STI = MF.getSubtarget<RISCVSubtarget>();
86   Register RAReg = STI.getRegisterInfo()->getRARegister();
87 
88   // See emitSCSPrologue() above.
89   std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
90   if (std::none_of(CSI.begin(), CSI.end(),
91                    [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
92     return;
93 
94   Register SCSPReg = RISCVABI::getSCSPReg();
95 
96   auto &Ctx = MF.getFunction().getContext();
97   if (!STI.isRegisterReservedByUser(SCSPReg)) {
98     Ctx.diagnose(DiagnosticInfoUnsupported{
99         MF.getFunction(), "x18 not reserved by user for Shadow Call Stack."});
100     return;
101   }
102 
103   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
104   if (RVFI->useSaveRestoreLibCalls(MF)) {
105     Ctx.diagnose(DiagnosticInfoUnsupported{
106         MF.getFunction(),
107         "Shadow Call Stack cannot be combined with Save/Restore LibCalls."});
108     return;
109   }
110 
111   const RISCVInstrInfo *TII = STI.getInstrInfo();
112   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
113   int64_t SlotSize = STI.getXLen() / 8;
114   // Load return address from shadow call stack
115   // l[w|d]  ra, -[4|8](s2)
116   // addi    s2, s2, -[4|8]
117   BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::LD : RISCV::LW))
118       .addReg(RAReg, RegState::Define)
119       .addReg(SCSPReg)
120       .addImm(-SlotSize)
121       .setMIFlag(MachineInstr::FrameDestroy);
122   BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
123       .addReg(SCSPReg, RegState::Define)
124       .addReg(SCSPReg)
125       .addImm(-SlotSize)
126       .setMIFlag(MachineInstr::FrameDestroy);
127 }
128 
129 // Get the ID of the libcall used for spilling and restoring callee saved
130 // registers. The ID is representative of the number of registers saved or
131 // restored by the libcall, except it is zero-indexed - ID 0 corresponds to a
132 // single register.
133 static int getLibCallID(const MachineFunction &MF,
134                         const std::vector<CalleeSavedInfo> &CSI) {
135   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
136 
137   if (CSI.empty() || !RVFI->useSaveRestoreLibCalls(MF))
138     return -1;
139 
140   Register MaxReg = RISCV::NoRegister;
141   for (auto &CS : CSI)
142     // RISCVRegisterInfo::hasReservedSpillSlot assigns negative frame indexes to
143     // registers which can be saved by libcall.
144     if (CS.getFrameIdx() < 0)
145       MaxReg = std::max(MaxReg.id(), CS.getReg().id());
146 
147   if (MaxReg == RISCV::NoRegister)
148     return -1;
149 
150   switch (MaxReg) {
151   default:
152     llvm_unreachable("Something has gone wrong!");
153   case /*s11*/ RISCV::X27: return 12;
154   case /*s10*/ RISCV::X26: return 11;
155   case /*s9*/  RISCV::X25: return 10;
156   case /*s8*/  RISCV::X24: return 9;
157   case /*s7*/  RISCV::X23: return 8;
158   case /*s6*/  RISCV::X22: return 7;
159   case /*s5*/  RISCV::X21: return 6;
160   case /*s4*/  RISCV::X20: return 5;
161   case /*s3*/  RISCV::X19: return 4;
162   case /*s2*/  RISCV::X18: return 3;
163   case /*s1*/  RISCV::X9:  return 2;
164   case /*s0*/  RISCV::X8:  return 1;
165   case /*ra*/  RISCV::X1:  return 0;
166   }
167 }
168 
169 // Get the name of the libcall used for spilling callee saved registers.
170 // If this function will not use save/restore libcalls, then return a nullptr.
171 static const char *
172 getSpillLibCallName(const MachineFunction &MF,
173                     const std::vector<CalleeSavedInfo> &CSI) {
174   static const char *const SpillLibCalls[] = {
175     "__riscv_save_0",
176     "__riscv_save_1",
177     "__riscv_save_2",
178     "__riscv_save_3",
179     "__riscv_save_4",
180     "__riscv_save_5",
181     "__riscv_save_6",
182     "__riscv_save_7",
183     "__riscv_save_8",
184     "__riscv_save_9",
185     "__riscv_save_10",
186     "__riscv_save_11",
187     "__riscv_save_12"
188   };
189 
190   int LibCallID = getLibCallID(MF, CSI);
191   if (LibCallID == -1)
192     return nullptr;
193   return SpillLibCalls[LibCallID];
194 }
195 
196 // Get the name of the libcall used for restoring callee saved registers.
197 // If this function will not use save/restore libcalls, then return a nullptr.
198 static const char *
199 getRestoreLibCallName(const MachineFunction &MF,
200                       const std::vector<CalleeSavedInfo> &CSI) {
201   static const char *const RestoreLibCalls[] = {
202     "__riscv_restore_0",
203     "__riscv_restore_1",
204     "__riscv_restore_2",
205     "__riscv_restore_3",
206     "__riscv_restore_4",
207     "__riscv_restore_5",
208     "__riscv_restore_6",
209     "__riscv_restore_7",
210     "__riscv_restore_8",
211     "__riscv_restore_9",
212     "__riscv_restore_10",
213     "__riscv_restore_11",
214     "__riscv_restore_12"
215   };
216 
217   int LibCallID = getLibCallID(MF, CSI);
218   if (LibCallID == -1)
219     return nullptr;
220   return RestoreLibCalls[LibCallID];
221 }
222 
223 // Return true if the specified function should have a dedicated frame
224 // pointer register.  This is true if frame pointer elimination is
225 // disabled, if it needs dynamic stack realignment, if the function has
226 // variable sized allocas, or if the frame address is taken.
227 bool RISCVFrameLowering::hasFP(const MachineFunction &MF) const {
228   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
229 
230   const MachineFrameInfo &MFI = MF.getFrameInfo();
231   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
232          RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
233          MFI.isFrameAddressTaken();
234 }
235 
236 bool RISCVFrameLowering::hasBP(const MachineFunction &MF) const {
237   const MachineFrameInfo &MFI = MF.getFrameInfo();
238   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
239 
240   // If we do not reserve stack space for outgoing arguments in prologue,
241   // we will adjust the stack pointer before call instruction. After the
242   // adjustment, we can not use SP to access the stack objects for the
243   // arguments. Instead, use BP to access these stack objects.
244   return (MFI.hasVarSizedObjects() ||
245           (!hasReservedCallFrame(MF) && (!MFI.isMaxCallFrameSizeComputed() ||
246                                          MFI.getMaxCallFrameSize() != 0))) &&
247          TRI->hasStackRealignment(MF);
248 }
249 
250 // Determines the size of the frame and maximum call frame size.
251 void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
252   MachineFrameInfo &MFI = MF.getFrameInfo();
253   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
254 
255   // Get the number of bytes to allocate from the FrameInfo.
256   uint64_t FrameSize = MFI.getStackSize();
257 
258   // Get the alignment.
259   Align StackAlign = getStackAlign();
260 
261   // Make sure the frame is aligned.
262   FrameSize = alignTo(FrameSize, StackAlign);
263 
264   // Update frame info.
265   MFI.setStackSize(FrameSize);
266 
267   // When using SP or BP to access stack objects, we may require extra padding
268   // to ensure the bottom of the RVV stack is correctly aligned within the main
269   // stack. We calculate this as the amount required to align the scalar local
270   // variable section up to the RVV alignment.
271   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
272   if (RVFI->getRVVStackSize() && (!hasFP(MF) || TRI->hasStackRealignment(MF))) {
273     int ScalarLocalVarSize = FrameSize - RVFI->getCalleeSavedStackSize() -
274                              RVFI->getVarArgsSaveSize();
275     if (auto RVVPadding =
276             offsetToAlignment(ScalarLocalVarSize, RVFI->getRVVStackAlign()))
277       RVFI->setRVVPadding(RVVPadding);
278   }
279 }
280 
281 // Returns the stack size including RVV padding (when required), rounded back
282 // up to the required stack alignment.
283 uint64_t RISCVFrameLowering::getStackSizeWithRVVPadding(
284     const MachineFunction &MF) const {
285   const MachineFrameInfo &MFI = MF.getFrameInfo();
286   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
287   return alignTo(MFI.getStackSize() + RVFI->getRVVPadding(), getStackAlign());
288 }
289 
290 void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB,
291                                    MachineBasicBlock::iterator MBBI,
292                                    const DebugLoc &DL, Register DestReg,
293                                    Register SrcReg, int64_t Val,
294                                    MachineInstr::MIFlag Flag) const {
295   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
296   const RISCVInstrInfo *TII = STI.getInstrInfo();
297 
298   if (DestReg == SrcReg && Val == 0)
299     return;
300 
301   if (isInt<12>(Val)) {
302     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
303         .addReg(SrcReg)
304         .addImm(Val)
305         .setMIFlag(Flag);
306     return;
307   }
308 
309   // Try to split the offset across two ADDIs. We need to keep the stack pointer
310   // aligned after each ADDI. We need to determine the maximum value we can put
311   // in each ADDI. In the negative direction, we can use -2048 which is always
312   // sufficiently aligned. In the positive direction, we need to find the
313   // largest 12-bit immediate that is aligned. Exclude -4096 since it can be
314   // created with LUI.
315   assert(getStackAlign().value() < 2048 && "Stack alignment too large");
316   int64_t MaxPosAdjStep = 2048 - getStackAlign().value();
317   if (Val > -4096 && Val <= (2 * MaxPosAdjStep)) {
318     int64_t FirstAdj = Val < 0 ? -2048 : MaxPosAdjStep;
319     Val -= FirstAdj;
320     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
321         .addReg(SrcReg)
322         .addImm(FirstAdj)
323         .setMIFlag(Flag);
324     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
325         .addReg(DestReg, RegState::Kill)
326         .addImm(Val)
327         .setMIFlag(Flag);
328     return;
329   }
330 
331   unsigned Opc = RISCV::ADD;
332   if (Val < 0) {
333     Val = -Val;
334     Opc = RISCV::SUB;
335   }
336 
337   Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
338   TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
339   BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
340       .addReg(SrcReg)
341       .addReg(ScratchReg, RegState::Kill)
342       .setMIFlag(Flag);
343 }
344 
345 // Returns the register used to hold the frame pointer.
346 static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
347 
348 // Returns the register used to hold the stack pointer.
349 static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
350 
351 static SmallVector<CalleeSavedInfo, 8>
352 getNonLibcallCSI(const MachineFunction &MF,
353                  const std::vector<CalleeSavedInfo> &CSI) {
354   const MachineFrameInfo &MFI = MF.getFrameInfo();
355   SmallVector<CalleeSavedInfo, 8> NonLibcallCSI;
356 
357   for (auto &CS : CSI) {
358     int FI = CS.getFrameIdx();
359     if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::Default)
360       NonLibcallCSI.push_back(CS);
361   }
362 
363   return NonLibcallCSI;
364 }
365 
366 void RISCVFrameLowering::adjustStackForRVV(MachineFunction &MF,
367                                            MachineBasicBlock &MBB,
368                                            MachineBasicBlock::iterator MBBI,
369                                            const DebugLoc &DL, int64_t Amount,
370                                            MachineInstr::MIFlag Flag) const {
371   assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
372 
373   const RISCVInstrInfo *TII = STI.getInstrInfo();
374   Register SPReg = getSPReg(STI);
375   unsigned Opc = RISCV::ADD;
376   if (Amount < 0) {
377     Amount = -Amount;
378     Opc = RISCV::SUB;
379   }
380   // 1. Multiply the number of v-slots to the length of registers
381   Register FactorRegister =
382       TII->getVLENFactoredAmount(MF, MBB, MBBI, DL, Amount, Flag);
383   // 2. SP = SP - RVV stack size
384   BuildMI(MBB, MBBI, DL, TII->get(Opc), SPReg)
385       .addReg(SPReg)
386       .addReg(FactorRegister, RegState::Kill)
387       .setMIFlag(Flag);
388 }
389 
390 void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
391                                       MachineBasicBlock &MBB) const {
392   MachineFrameInfo &MFI = MF.getFrameInfo();
393   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
394   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
395   const RISCVInstrInfo *TII = STI.getInstrInfo();
396   MachineBasicBlock::iterator MBBI = MBB.begin();
397 
398   Register FPReg = getFPReg(STI);
399   Register SPReg = getSPReg(STI);
400   Register BPReg = RISCVABI::getBPReg();
401 
402   // Debug location must be unknown since the first debug location is used
403   // to determine the end of the prologue.
404   DebugLoc DL;
405 
406   // All calls are tail calls in GHC calling conv, and functions have no
407   // prologue/epilogue.
408   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
409     return;
410 
411   // Emit prologue for shadow call stack.
412   emitSCSPrologue(MF, MBB, MBBI, DL);
413 
414   // Since spillCalleeSavedRegisters may have inserted a libcall, skip past
415   // any instructions marked as FrameSetup
416   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
417     ++MBBI;
418 
419   // Determine the correct frame layout
420   determineFrameLayout(MF);
421 
422   // If libcalls are used to spill and restore callee-saved registers, the frame
423   // has two sections; the opaque section managed by the libcalls, and the
424   // section managed by MachineFrameInfo which can also hold callee saved
425   // registers in fixed stack slots, both of which have negative frame indices.
426   // This gets even more complicated when incoming arguments are passed via the
427   // stack, as these too have negative frame indices. An example is detailed
428   // below:
429   //
430   //  | incoming arg | <- FI[-3]
431   //  | libcallspill |
432   //  | calleespill  | <- FI[-2]
433   //  | calleespill  | <- FI[-1]
434   //  | this_frame   | <- FI[0]
435   //
436   // For negative frame indices, the offset from the frame pointer will differ
437   // depending on which of these groups the frame index applies to.
438   // The following calculates the correct offset knowing the number of callee
439   // saved registers spilt by the two methods.
440   if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
441     // Calculate the size of the frame managed by the libcall. The libcalls are
442     // implemented such that the stack will always be 16 byte aligned.
443     unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
444     RVFI->setLibCallStackSize(LibCallFrameSize);
445   }
446 
447   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
448   // investigation. Get the number of bytes to allocate from the FrameInfo.
449   uint64_t StackSize = getStackSizeWithRVVPadding(MF);
450   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
451   uint64_t RVVStackSize = RVFI->getRVVStackSize();
452 
453   // Early exit if there is no need to allocate on the stack
454   if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
455     return;
456 
457   // If the stack pointer has been marked as reserved, then produce an error if
458   // the frame requires stack allocation
459   if (STI.isRegisterReservedByUser(SPReg))
460     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
461         MF.getFunction(), "Stack pointer required, but has been reserved."});
462 
463   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
464   // Split the SP adjustment to reduce the offsets of callee saved spill.
465   if (FirstSPAdjustAmount) {
466     StackSize = FirstSPAdjustAmount;
467     RealStackSize = FirstSPAdjustAmount;
468   }
469 
470   // Allocate space on the stack if necessary.
471   adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
472 
473   // Emit ".cfi_def_cfa_offset RealStackSize"
474   unsigned CFIIndex = MF.addFrameInst(
475       MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
476   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
477       .addCFIIndex(CFIIndex)
478       .setMIFlag(MachineInstr::FrameSetup);
479 
480   const auto &CSI = MFI.getCalleeSavedInfo();
481 
482   // The frame pointer is callee-saved, and code has been generated for us to
483   // save it to the stack. We need to skip over the storing of callee-saved
484   // registers as the frame pointer must be modified after it has been saved
485   // to the stack, not before.
486   // FIXME: assumes exactly one instruction is used to save each callee-saved
487   // register.
488   std::advance(MBBI, getNonLibcallCSI(MF, CSI).size());
489 
490   // Iterate over list of callee-saved registers and emit .cfi_offset
491   // directives.
492   for (const auto &Entry : CSI) {
493     int FrameIdx = Entry.getFrameIdx();
494     int64_t Offset;
495     // Offsets for objects with fixed locations (IE: those saved by libcall) are
496     // simply calculated from the frame index.
497     if (FrameIdx < 0)
498       Offset = FrameIdx * (int64_t) STI.getXLen() / 8;
499     else
500       Offset = MFI.getObjectOffset(Entry.getFrameIdx()) -
501                RVFI->getLibCallStackSize();
502     Register Reg = Entry.getReg();
503     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
504         nullptr, RI->getDwarfRegNum(Reg, true), Offset));
505     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
506         .addCFIIndex(CFIIndex)
507         .setMIFlag(MachineInstr::FrameSetup);
508   }
509 
510   // Generate new FP.
511   if (hasFP(MF)) {
512     if (STI.isRegisterReservedByUser(FPReg))
513       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
514           MF.getFunction(), "Frame pointer required, but has been reserved."});
515 
516     adjustReg(MBB, MBBI, DL, FPReg, SPReg,
517               RealStackSize - RVFI->getVarArgsSaveSize(),
518               MachineInstr::FrameSetup);
519 
520     // Emit ".cfi_def_cfa $fp, RVFI->getVarArgsSaveSize()"
521     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
522         nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
523     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
524         .addCFIIndex(CFIIndex)
525         .setMIFlag(MachineInstr::FrameSetup);
526   }
527 
528   // Emit the second SP adjustment after saving callee saved registers.
529   if (FirstSPAdjustAmount) {
530     uint64_t SecondSPAdjustAmount =
531         getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
532     assert(SecondSPAdjustAmount > 0 &&
533            "SecondSPAdjustAmount should be greater than zero");
534     adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount,
535               MachineInstr::FrameSetup);
536 
537     // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
538     // don't emit an sp-based .cfi_def_cfa_offset
539     if (!hasFP(MF)) {
540       // Emit ".cfi_def_cfa_offset StackSize"
541       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(
542           nullptr, getStackSizeWithRVVPadding(MF)));
543       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
544           .addCFIIndex(CFIIndex)
545           .setMIFlag(MachineInstr::FrameSetup);
546     }
547   }
548 
549   if (RVVStackSize)
550     adjustStackForRVV(MF, MBB, MBBI, DL, -RVVStackSize,
551                       MachineInstr::FrameSetup);
552 
553   if (hasFP(MF)) {
554     // Realign Stack
555     const RISCVRegisterInfo *RI = STI.getRegisterInfo();
556     if (RI->hasStackRealignment(MF)) {
557       Align MaxAlignment = MFI.getMaxAlign();
558 
559       const RISCVInstrInfo *TII = STI.getInstrInfo();
560       if (isInt<12>(-(int)MaxAlignment.value())) {
561         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
562             .addReg(SPReg)
563             .addImm(-(int)MaxAlignment.value())
564             .setMIFlag(MachineInstr::FrameSetup);
565       } else {
566         unsigned ShiftAmount = Log2(MaxAlignment);
567         Register VR =
568             MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
569         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
570             .addReg(SPReg)
571             .addImm(ShiftAmount)
572             .setMIFlag(MachineInstr::FrameSetup);
573         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
574             .addReg(VR)
575             .addImm(ShiftAmount)
576             .setMIFlag(MachineInstr::FrameSetup);
577       }
578       // FP will be used to restore the frame in the epilogue, so we need
579       // another base register BP to record SP after re-alignment. SP will
580       // track the current stack after allocating variable sized objects.
581       if (hasBP(MF)) {
582         // move BP, SP
583         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
584             .addReg(SPReg)
585             .addImm(0)
586             .setMIFlag(MachineInstr::FrameSetup);
587       }
588     }
589   }
590 }
591 
592 void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
593                                       MachineBasicBlock &MBB) const {
594   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
595   MachineFrameInfo &MFI = MF.getFrameInfo();
596   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
597   Register FPReg = getFPReg(STI);
598   Register SPReg = getSPReg(STI);
599 
600   // All calls are tail calls in GHC calling conv, and functions have no
601   // prologue/epilogue.
602   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
603     return;
604 
605   // Get the insert location for the epilogue. If there were no terminators in
606   // the block, get the last instruction.
607   MachineBasicBlock::iterator MBBI = MBB.end();
608   DebugLoc DL;
609   if (!MBB.empty()) {
610     MBBI = MBB.getLastNonDebugInstr();
611     if (MBBI != MBB.end())
612       DL = MBBI->getDebugLoc();
613 
614     MBBI = MBB.getFirstTerminator();
615 
616     // If callee-saved registers are saved via libcall, place stack adjustment
617     // before this call.
618     while (MBBI != MBB.begin() &&
619            std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
620       --MBBI;
621   }
622 
623   const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
624 
625   // Skip to before the restores of callee-saved registers
626   // FIXME: assumes exactly one instruction is used to restore each
627   // callee-saved register.
628   auto LastFrameDestroy = MBBI;
629   if (!CSI.empty())
630     LastFrameDestroy = std::prev(MBBI, CSI.size());
631 
632   uint64_t StackSize = getStackSizeWithRVVPadding(MF);
633   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
634   uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
635   uint64_t RVVStackSize = RVFI->getRVVStackSize();
636 
637   // Restore the stack pointer using the value of the frame pointer. Only
638   // necessary if the stack pointer was modified, meaning the stack size is
639   // unknown.
640   if (RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects()) {
641     assert(hasFP(MF) && "frame pointer should not have been eliminated");
642     adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset,
643               MachineInstr::FrameDestroy);
644   } else {
645     if (RVVStackSize)
646       adjustStackForRVV(MF, MBB, LastFrameDestroy, DL, RVVStackSize,
647                         MachineInstr::FrameDestroy);
648   }
649 
650   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
651   if (FirstSPAdjustAmount) {
652     uint64_t SecondSPAdjustAmount =
653         getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
654     assert(SecondSPAdjustAmount > 0 &&
655            "SecondSPAdjustAmount should be greater than zero");
656 
657     adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
658               MachineInstr::FrameDestroy);
659   }
660 
661   if (FirstSPAdjustAmount)
662     StackSize = FirstSPAdjustAmount;
663 
664   // Deallocate stack
665   adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
666 
667   // Emit epilogue for shadow call stack.
668   emitSCSEpilogue(MF, MBB, MBBI, DL);
669 }
670 
671 StackOffset
672 RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
673                                            Register &FrameReg) const {
674   const MachineFrameInfo &MFI = MF.getFrameInfo();
675   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
676   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
677 
678   // Callee-saved registers should be referenced relative to the stack
679   // pointer (positive offset), otherwise use the frame pointer (negative
680   // offset).
681   const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
682   int MinCSFI = 0;
683   int MaxCSFI = -1;
684   StackOffset Offset;
685   auto StackID = MFI.getStackID(FI);
686 
687   assert((StackID == TargetStackID::Default ||
688           StackID == TargetStackID::ScalableVector) &&
689          "Unexpected stack ID for the frame object.");
690   if (StackID == TargetStackID::Default) {
691     Offset =
692         StackOffset::getFixed(MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
693                               MFI.getOffsetAdjustment());
694   } else if (StackID == TargetStackID::ScalableVector) {
695     Offset = StackOffset::getScalable(MFI.getObjectOffset(FI));
696   }
697 
698   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
699 
700   if (CSI.size()) {
701     MinCSFI = CSI[0].getFrameIdx();
702     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
703   }
704 
705   if (FI >= MinCSFI && FI <= MaxCSFI) {
706     FrameReg = RISCV::X2;
707 
708     if (FirstSPAdjustAmount)
709       Offset += StackOffset::getFixed(FirstSPAdjustAmount);
710     else
711       Offset += StackOffset::getFixed(getStackSizeWithRVVPadding(MF));
712     return Offset;
713   }
714 
715   if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
716     // If the stack was realigned, the frame pointer is set in order to allow
717     // SP to be restored, so we need another base register to record the stack
718     // after realignment.
719     // |--------------------------| -- <-- FP
720     // | callee-allocated save    | | <----|
721     // | area for register varargs| |      |
722     // |--------------------------| |      |
723     // | callee-saved registers   | |      |
724     // |--------------------------| --     |
725     // | realignment (the size of | |      |
726     // | this area is not counted | |      |
727     // | in MFI.getStackSize())   | |      |
728     // |--------------------------| --     |-- MFI.getStackSize()
729     // | RVV alignment padding    | |      |
730     // | (not counted in          | |      |
731     // | MFI.getStackSize() but   | |      |
732     // | counted in               | |      |
733     // | RVFI.getRVVStackSize())  | |      |
734     // |--------------------------| --     |
735     // | RVV objects              | |      |
736     // | (not counted in          | |      |
737     // | MFI.getStackSize())      | |      |
738     // |--------------------------| --     |
739     // | padding before RVV       | |      |
740     // | (not counted in          | |      |
741     // | MFI.getStackSize() or in | |      |
742     // | RVFI.getRVVStackSize())  | |      |
743     // |--------------------------| --     |
744     // | scalar local variables   | | <----'
745     // |--------------------------| -- <-- BP (if var sized objects present)
746     // | VarSize objects          | |
747     // |--------------------------| -- <-- SP
748     if (hasBP(MF)) {
749       FrameReg = RISCVABI::getBPReg();
750     } else {
751       // VarSize objects must be empty in this case!
752       assert(!MFI.hasVarSizedObjects());
753       FrameReg = RISCV::X2;
754     }
755   } else {
756     FrameReg = RI->getFrameRegister(MF);
757   }
758 
759   if (FrameReg == getFPReg(STI)) {
760     Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
761     if (FI >= 0)
762       Offset -= StackOffset::getFixed(RVFI->getLibCallStackSize());
763     // When using FP to access scalable vector objects, we need to minus
764     // the frame size.
765     //
766     // |--------------------------| -- <-- FP
767     // | callee-allocated save    | |
768     // | area for register varargs| |
769     // |--------------------------| |
770     // | callee-saved registers   | |
771     // |--------------------------| | MFI.getStackSize()
772     // | scalar local variables   | |
773     // |--------------------------| -- (Offset of RVV objects is from here.)
774     // | RVV objects              |
775     // |--------------------------|
776     // | VarSize objects          |
777     // |--------------------------| <-- SP
778     if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
779       assert(!RI->hasStackRealignment(MF) &&
780              "Can't index across variable sized realign");
781       // We don't expect any extra RVV alignment padding, as the stack size
782       // and RVV object sections should be correct aligned in their own
783       // right.
784       assert(MFI.getStackSize() == getStackSizeWithRVVPadding(MF) &&
785              "Inconsistent stack layout");
786       Offset -= StackOffset::getFixed(MFI.getStackSize());
787     }
788     return Offset;
789   }
790 
791   // This case handles indexing off both SP and BP.
792   // If indexing off SP, there must not be any var sized objects
793   assert(FrameReg == RISCVABI::getBPReg() || !MFI.hasVarSizedObjects());
794 
795   // When using SP to access frame objects, we need to add RVV stack size.
796   //
797   // |--------------------------| -- <-- FP
798   // | callee-allocated save    | | <----|
799   // | area for register varargs| |      |
800   // |--------------------------| |      |
801   // | callee-saved registers   | |      |
802   // |--------------------------| --     |
803   // | RVV alignment padding    | |      |
804   // | (not counted in          | |      |
805   // | MFI.getStackSize() but   | |      |
806   // | counted in               | |      |
807   // | RVFI.getRVVStackSize())  | |      |
808   // |--------------------------| --     |
809   // | RVV objects              | |      |-- MFI.getStackSize()
810   // | (not counted in          | |      |
811   // | MFI.getStackSize())      | |      |
812   // |--------------------------| --     |
813   // | padding before RVV       | |      |
814   // | (not counted in          | |      |
815   // | MFI.getStackSize())      | |      |
816   // |--------------------------| --     |
817   // | scalar local variables   | | <----'
818   // |--------------------------| -- <-- BP (if var sized objects present)
819   // | VarSize objects          | |
820   // |--------------------------| -- <-- SP
821   //
822   // The total amount of padding surrounding RVV objects is described by
823   // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
824   // objects to the required alignment.
825   if (MFI.getStackID(FI) == TargetStackID::Default) {
826     if (MFI.isFixedObjectIndex(FI)) {
827       assert(!RI->hasStackRealignment(MF) &&
828              "Can't index across variable sized realign");
829       Offset += StackOffset::get(getStackSizeWithRVVPadding(MF) +
830                                  RVFI->getLibCallStackSize(),
831                                  RVFI->getRVVStackSize());
832     } else {
833       Offset += StackOffset::getFixed(MFI.getStackSize());
834     }
835   } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
836     // Ensure the base of the RVV stack is correctly aligned: add on the
837     // alignment padding.
838     int ScalarLocalVarSize =
839       MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
840       RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
841     Offset += StackOffset::get(ScalarLocalVarSize, RVFI->getRVVStackSize());
842   }
843   return Offset;
844 }
845 
846 void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
847                                               BitVector &SavedRegs,
848                                               RegScavenger *RS) const {
849   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
850   // Unconditionally spill RA and FP only if the function uses a frame
851   // pointer.
852   if (hasFP(MF)) {
853     SavedRegs.set(RISCV::X1);
854     SavedRegs.set(RISCV::X8);
855   }
856   // Mark BP as used if function has dedicated base pointer.
857   if (hasBP(MF))
858     SavedRegs.set(RISCVABI::getBPReg());
859 
860   // If interrupt is enabled and there are calls in the handler,
861   // unconditionally save all Caller-saved registers and
862   // all FP registers, regardless whether they are used.
863   MachineFrameInfo &MFI = MF.getFrameInfo();
864 
865   if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
866 
867     static const MCPhysReg CSRegs[] = { RISCV::X1,      /* ra */
868       RISCV::X5, RISCV::X6, RISCV::X7,                  /* t0-t2 */
869       RISCV::X10, RISCV::X11,                           /* a0-a1, a2-a7 */
870       RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
871       RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */
872     };
873 
874     for (unsigned i = 0; CSRegs[i]; ++i)
875       SavedRegs.set(CSRegs[i]);
876 
877     if (MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
878 
879       // If interrupt is enabled, this list contains all FP registers.
880       const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
881 
882       for (unsigned i = 0; Regs[i]; ++i)
883         if (RISCV::FPR16RegClass.contains(Regs[i]) ||
884             RISCV::FPR32RegClass.contains(Regs[i]) ||
885             RISCV::FPR64RegClass.contains(Regs[i]))
886           SavedRegs.set(Regs[i]);
887     }
888   }
889 }
890 
891 std::pair<int64_t, Align>
892 RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFrameInfo &MFI) const {
893   // Create a buffer of RVV objects to allocate.
894   SmallVector<int, 8> ObjectsToAllocate;
895   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
896     unsigned StackID = MFI.getStackID(I);
897     if (StackID != TargetStackID::ScalableVector)
898       continue;
899     if (MFI.isDeadObjectIndex(I))
900       continue;
901 
902     ObjectsToAllocate.push_back(I);
903   }
904 
905   // Allocate all RVV locals and spills
906   int64_t Offset = 0;
907   // The minimum alignment is 16 bytes.
908   Align RVVStackAlign(16);
909   for (int FI : ObjectsToAllocate) {
910     // ObjectSize in bytes.
911     int64_t ObjectSize = MFI.getObjectSize(FI);
912     auto ObjectAlign = std::max(Align(8), MFI.getObjectAlign(FI));
913     // If the data type is the fractional vector type, reserve one vector
914     // register for it.
915     if (ObjectSize < 8)
916       ObjectSize = 8;
917     Offset = alignTo(Offset + ObjectSize, ObjectAlign);
918     MFI.setObjectOffset(FI, -Offset);
919     // Update the maximum alignment of the RVV stack section
920     RVVStackAlign = std::max(RVVStackAlign, ObjectAlign);
921   }
922 
923   // Ensure the alignment of the RVV stack. Since we want the most-aligned
924   // object right at the bottom (i.e., any padding at the top of the frame),
925   // readjust all RVV objects down by the alignment padding.
926   uint64_t StackSize = Offset;
927   if (auto AlignmentPadding = offsetToAlignment(StackSize, RVVStackAlign)) {
928     StackSize += AlignmentPadding;
929     for (int FI : ObjectsToAllocate)
930       MFI.setObjectOffset(FI, MFI.getObjectOffset(FI) - AlignmentPadding);
931   }
932 
933   return std::make_pair(StackSize, RVVStackAlign);
934 }
935 
936 static bool hasRVVSpillWithFIs(MachineFunction &MF, const RISCVInstrInfo &TII) {
937   if (!MF.getSubtarget<RISCVSubtarget>().hasVInstructions())
938     return false;
939   return any_of(MF, [&TII](const MachineBasicBlock &MBB) {
940     return any_of(MBB, [&TII](const MachineInstr &MI) {
941       return TII.isRVVSpill(MI, /*CheckFIs*/ true);
942     });
943   });
944 }
945 
946 void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
947     MachineFunction &MF, RegScavenger *RS) const {
948   const RISCVRegisterInfo *RegInfo =
949       MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
950   MachineFrameInfo &MFI = MF.getFrameInfo();
951   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
952   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
953 
954   int64_t RVVStackSize;
955   Align RVVStackAlign;
956   std::tie(RVVStackSize, RVVStackAlign) = assignRVVStackObjectOffsets(MFI);
957 
958   RVFI->setRVVStackSize(RVVStackSize);
959   RVFI->setRVVStackAlign(RVVStackAlign);
960 
961   // Ensure the entire stack is aligned to at least the RVV requirement: some
962   // scalable-vector object alignments are not considered by the
963   // target-independent code.
964   MFI.ensureMaxAlignment(RVVStackAlign);
965 
966   const RISCVInstrInfo &TII = *MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
967 
968   // estimateStackSize has been observed to under-estimate the final stack
969   // size, so give ourselves wiggle-room by checking for stack size
970   // representable an 11-bit signed field rather than 12-bits.
971   // FIXME: It may be possible to craft a function with a small stack that
972   // still needs an emergency spill slot for branch relaxation. This case
973   // would currently be missed.
974   // RVV loads & stores have no capacity to hold the immediate address offsets
975   // so we must always reserve an emergency spill slot if the MachineFunction
976   // contains any RVV spills.
977   if (!isInt<11>(MFI.estimateStackSize(MF)) || hasRVVSpillWithFIs(MF, TII)) {
978     int RegScavFI = MFI.CreateStackObject(RegInfo->getSpillSize(*RC),
979                                           RegInfo->getSpillAlign(*RC), false);
980     RS->addScavengingFrameIndex(RegScavFI);
981     // For RVV, scalable stack offsets require up to two scratch registers to
982     // compute the final offset. Reserve an additional emergency spill slot.
983     if (RVVStackSize != 0) {
984       int RVVRegScavFI = MFI.CreateStackObject(
985           RegInfo->getSpillSize(*RC), RegInfo->getSpillAlign(*RC), false);
986       RS->addScavengingFrameIndex(RVVRegScavFI);
987     }
988   }
989 
990   if (MFI.getCalleeSavedInfo().empty() || RVFI->useSaveRestoreLibCalls(MF)) {
991     RVFI->setCalleeSavedStackSize(0);
992     return;
993   }
994 
995   unsigned Size = 0;
996   for (const auto &Info : MFI.getCalleeSavedInfo()) {
997     int FrameIdx = Info.getFrameIdx();
998     if (MFI.getStackID(FrameIdx) != TargetStackID::Default)
999       continue;
1000 
1001     Size += MFI.getObjectSize(FrameIdx);
1002   }
1003   RVFI->setCalleeSavedStackSize(Size);
1004 }
1005 
1006 static bool hasRVVFrameObject(const MachineFunction &MF) {
1007   // Originally, the function will scan all the stack objects to check whether
1008   // if there is any scalable vector object on the stack or not. However, it
1009   // causes errors in the register allocator. In issue 53016, it returns false
1010   // before RA because there is no RVV stack objects. After RA, it returns true
1011   // because there are spilling slots for RVV values during RA. It will not
1012   // reserve BP during register allocation and generate BP access in the PEI
1013   // pass due to the inconsistent behavior of the function.
1014   //
1015   // The function is changed to use hasVInstructions() as the return value. It
1016   // is not precise, but it can make the register allocation correct.
1017   //
1018   // FIXME: Find a better way to make the decision or revisit the solution in
1019   // D103622.
1020   //
1021   // Refer to https://github.com/llvm/llvm-project/issues/53016.
1022   return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
1023 }
1024 
1025 // Not preserve stack space within prologue for outgoing variables when the
1026 // function contains variable size objects or there are vector objects accessed
1027 // by the frame pointer.
1028 // Let eliminateCallFramePseudoInstr preserve stack space for it.
1029 bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
1030   return !MF.getFrameInfo().hasVarSizedObjects() &&
1031          !(hasFP(MF) && hasRVVFrameObject(MF));
1032 }
1033 
1034 // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
1035 MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
1036     MachineFunction &MF, MachineBasicBlock &MBB,
1037     MachineBasicBlock::iterator MI) const {
1038   Register SPReg = RISCV::X2;
1039   DebugLoc DL = MI->getDebugLoc();
1040 
1041   if (!hasReservedCallFrame(MF)) {
1042     // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
1043     // ADJCALLSTACKUP must be converted to instructions manipulating the stack
1044     // pointer. This is necessary when there is a variable length stack
1045     // allocation (e.g. alloca), which means it's not possible to allocate
1046     // space for outgoing arguments from within the function prologue.
1047     int64_t Amount = MI->getOperand(0).getImm();
1048 
1049     if (Amount != 0) {
1050       // Ensure the stack remains aligned after adjustment.
1051       Amount = alignSPAdjust(Amount);
1052 
1053       if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
1054         Amount = -Amount;
1055 
1056       adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
1057     }
1058   }
1059 
1060   return MBB.erase(MI);
1061 }
1062 
1063 // We would like to split the SP adjustment to reduce prologue/epilogue
1064 // as following instructions. In this way, the offset of the callee saved
1065 // register could fit in a single store.
1066 //   add     sp,sp,-2032
1067 //   sw      ra,2028(sp)
1068 //   sw      s0,2024(sp)
1069 //   sw      s1,2020(sp)
1070 //   sw      s3,2012(sp)
1071 //   sw      s4,2008(sp)
1072 //   add     sp,sp,-64
1073 uint64_t
1074 RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
1075   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1076   const MachineFrameInfo &MFI = MF.getFrameInfo();
1077   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
1078   uint64_t StackSize = getStackSizeWithRVVPadding(MF);
1079 
1080   // Disable SplitSPAdjust if save-restore libcall is used. The callee-saved
1081   // registers will be pushed by the save-restore libcalls, so we don't have to
1082   // split the SP adjustment in this case.
1083   if (RVFI->getLibCallStackSize())
1084     return 0;
1085 
1086   // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
1087   // 12-bit and there exists a callee-saved register needing to be pushed.
1088   if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
1089     // FirstSPAdjustAmount is chosen as (2048 - StackAlign) because 2048 will
1090     // cause sp = sp + 2048 in the epilogue to be split into multiple
1091     // instructions. Offsets smaller than 2048 can fit in a single load/store
1092     // instruction, and we have to stick with the stack alignment. 2048 has
1093     // 16-byte alignment. The stack alignment for RV32 and RV64 is 16 and for
1094     // RV32E it is 4. So (2048 - StackAlign) will satisfy the stack alignment.
1095     return 2048 - getStackAlign().value();
1096   }
1097   return 0;
1098 }
1099 
1100 bool RISCVFrameLowering::spillCalleeSavedRegisters(
1101     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1102     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1103   if (CSI.empty())
1104     return true;
1105 
1106   MachineFunction *MF = MBB.getParent();
1107   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1108   DebugLoc DL;
1109   if (MI != MBB.end() && !MI->isDebugInstr())
1110     DL = MI->getDebugLoc();
1111 
1112   const char *SpillLibCall = getSpillLibCallName(*MF, CSI);
1113   if (SpillLibCall) {
1114     // Add spill libcall via non-callee-saved register t0.
1115     BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
1116         .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
1117         .setMIFlag(MachineInstr::FrameSetup);
1118 
1119     // Add registers spilled in libcall as liveins.
1120     for (auto &CS : CSI)
1121       MBB.addLiveIn(CS.getReg());
1122   }
1123 
1124   // Manually spill values not spilled by libcall.
1125   const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
1126   for (auto &CS : NonLibcallCSI) {
1127     // Insert the spill to the stack frame.
1128     Register Reg = CS.getReg();
1129     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1130     TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg), CS.getFrameIdx(),
1131                             RC, TRI);
1132   }
1133 
1134   return true;
1135 }
1136 
1137 bool RISCVFrameLowering::restoreCalleeSavedRegisters(
1138     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1139     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1140   if (CSI.empty())
1141     return true;
1142 
1143   MachineFunction *MF = MBB.getParent();
1144   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1145   DebugLoc DL;
1146   if (MI != MBB.end() && !MI->isDebugInstr())
1147     DL = MI->getDebugLoc();
1148 
1149   // Manually restore values not restored by libcall.
1150   // Keep the same order as in the prologue. There is no need to reverse the
1151   // order in the epilogue. In addition, the return address will be restored
1152   // first in the epilogue. It increases the opportunity to avoid the
1153   // load-to-use data hazard between loading RA and return by RA.
1154   // loadRegFromStackSlot can insert multiple instructions.
1155   const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
1156   for (auto &CS : NonLibcallCSI) {
1157     Register Reg = CS.getReg();
1158     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1159     TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI);
1160     assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
1161   }
1162 
1163   const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
1164   if (RestoreLibCall) {
1165     // Add restore libcall via tail call.
1166     MachineBasicBlock::iterator NewMI =
1167         BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
1168             .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
1169             .setMIFlag(MachineInstr::FrameDestroy);
1170 
1171     // Remove trailing returns, since the terminator is now a tail call to the
1172     // restore function.
1173     if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
1174       NewMI->copyImplicitOps(*MF, *MI);
1175       MI->eraseFromParent();
1176     }
1177   }
1178 
1179   return true;
1180 }
1181 
1182 bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
1183   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1184   const MachineFunction *MF = MBB.getParent();
1185   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1186 
1187   if (!RVFI->useSaveRestoreLibCalls(*MF))
1188     return true;
1189 
1190   // Inserting a call to a __riscv_save libcall requires the use of the register
1191   // t0 (X5) to hold the return address. Therefore if this register is already
1192   // used we can't insert the call.
1193 
1194   RegScavenger RS;
1195   RS.enterBasicBlock(*TmpMBB);
1196   return !RS.isRegUsed(RISCV::X5);
1197 }
1198 
1199 bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1200   const MachineFunction *MF = MBB.getParent();
1201   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1202   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1203 
1204   if (!RVFI->useSaveRestoreLibCalls(*MF))
1205     return true;
1206 
1207   // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
1208   // This means if we still need to continue executing code within this function
1209   // the restore cannot take place in this basic block.
1210 
1211   if (MBB.succ_size() > 1)
1212     return false;
1213 
1214   MachineBasicBlock *SuccMBB =
1215       MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
1216 
1217   // Doing a tail call should be safe if there are no successors, because either
1218   // we have a returning block or the end of the block is unreachable, so the
1219   // restore will be eliminated regardless.
1220   if (!SuccMBB)
1221     return true;
1222 
1223   // The successor can only contain a return, since we would effectively be
1224   // replacing the successor with our own tail return at the end of our block.
1225   return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
1226 }
1227 
1228 bool RISCVFrameLowering::isSupportedStackID(TargetStackID::Value ID) const {
1229   switch (ID) {
1230   case TargetStackID::Default:
1231   case TargetStackID::ScalableVector:
1232     return true;
1233   case TargetStackID::NoAlloc:
1234   case TargetStackID::SGPRSpill:
1235   case TargetStackID::WasmLocal:
1236     return false;
1237   }
1238   llvm_unreachable("Invalid TargetStackID::Value");
1239 }
1240 
1241 TargetStackID::Value RISCVFrameLowering::getStackIDForScalableVectors() const {
1242   return TargetStackID::ScalableVector;
1243 }
1244