xref: /freebsd/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
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.getMaxCallFrameSize() != 0)) &&
246          TRI->hasStackRealignment(MF);
247 }
248 
249 // Determines the size of the frame and maximum call frame size.
250 void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
251   MachineFrameInfo &MFI = MF.getFrameInfo();
252 
253   // Get the number of bytes to allocate from the FrameInfo.
254   uint64_t FrameSize = MFI.getStackSize();
255 
256   // Get the alignment.
257   Align StackAlign = getStackAlign();
258 
259   // Make sure the frame is aligned.
260   FrameSize = alignTo(FrameSize, StackAlign);
261 
262   // Update frame info.
263   MFI.setStackSize(FrameSize);
264 }
265 
266 void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB,
267                                    MachineBasicBlock::iterator MBBI,
268                                    const DebugLoc &DL, Register DestReg,
269                                    Register SrcReg, int64_t Val,
270                                    MachineInstr::MIFlag Flag) const {
271   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
272   const RISCVInstrInfo *TII = STI.getInstrInfo();
273 
274   if (DestReg == SrcReg && Val == 0)
275     return;
276 
277   if (isInt<12>(Val)) {
278     BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
279         .addReg(SrcReg)
280         .addImm(Val)
281         .setMIFlag(Flag);
282   } else {
283     unsigned Opc = RISCV::ADD;
284     bool isSub = Val < 0;
285     if (isSub) {
286       Val = -Val;
287       Opc = RISCV::SUB;
288     }
289 
290     Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
291     TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
292     BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
293         .addReg(SrcReg)
294         .addReg(ScratchReg, RegState::Kill)
295         .setMIFlag(Flag);
296   }
297 }
298 
299 // Returns the register used to hold the frame pointer.
300 static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
301 
302 // Returns the register used to hold the stack pointer.
303 static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
304 
305 static SmallVector<CalleeSavedInfo, 8>
306 getNonLibcallCSI(const MachineFunction &MF,
307                  const std::vector<CalleeSavedInfo> &CSI) {
308   const MachineFrameInfo &MFI = MF.getFrameInfo();
309   SmallVector<CalleeSavedInfo, 8> NonLibcallCSI;
310 
311   for (auto &CS : CSI) {
312     int FI = CS.getFrameIdx();
313     if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::Default)
314       NonLibcallCSI.push_back(CS);
315   }
316 
317   return NonLibcallCSI;
318 }
319 
320 void RISCVFrameLowering::adjustStackForRVV(MachineFunction &MF,
321                                            MachineBasicBlock &MBB,
322                                            MachineBasicBlock::iterator MBBI,
323                                            const DebugLoc &DL, int64_t Amount,
324                                            MachineInstr::MIFlag Flag) const {
325   assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
326 
327   const RISCVInstrInfo *TII = STI.getInstrInfo();
328   Register SPReg = getSPReg(STI);
329   unsigned Opc = RISCV::ADD;
330   if (Amount < 0) {
331     Amount = -Amount;
332     Opc = RISCV::SUB;
333   }
334   // 1. Multiply the number of v-slots to the length of registers
335   Register FactorRegister =
336       TII->getVLENFactoredAmount(MF, MBB, MBBI, DL, Amount, Flag);
337   // 2. SP = SP - RVV stack size
338   BuildMI(MBB, MBBI, DL, TII->get(Opc), SPReg)
339       .addReg(SPReg)
340       .addReg(FactorRegister, RegState::Kill)
341       .setMIFlag(Flag);
342 }
343 
344 void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
345                                       MachineBasicBlock &MBB) const {
346   MachineFrameInfo &MFI = MF.getFrameInfo();
347   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
348   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
349   const RISCVInstrInfo *TII = STI.getInstrInfo();
350   MachineBasicBlock::iterator MBBI = MBB.begin();
351 
352   Register FPReg = getFPReg(STI);
353   Register SPReg = getSPReg(STI);
354   Register BPReg = RISCVABI::getBPReg();
355 
356   // Debug location must be unknown since the first debug location is used
357   // to determine the end of the prologue.
358   DebugLoc DL;
359 
360   // All calls are tail calls in GHC calling conv, and functions have no
361   // prologue/epilogue.
362   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
363     return;
364 
365   // Emit prologue for shadow call stack.
366   emitSCSPrologue(MF, MBB, MBBI, DL);
367 
368   // Since spillCalleeSavedRegisters may have inserted a libcall, skip past
369   // any instructions marked as FrameSetup
370   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
371     ++MBBI;
372 
373   // Determine the correct frame layout
374   determineFrameLayout(MF);
375 
376   // If libcalls are used to spill and restore callee-saved registers, the frame
377   // has two sections; the opaque section managed by the libcalls, and the
378   // section managed by MachineFrameInfo which can also hold callee saved
379   // registers in fixed stack slots, both of which have negative frame indices.
380   // This gets even more complicated when incoming arguments are passed via the
381   // stack, as these too have negative frame indices. An example is detailed
382   // below:
383   //
384   //  | incoming arg | <- FI[-3]
385   //  | libcallspill |
386   //  | calleespill  | <- FI[-2]
387   //  | calleespill  | <- FI[-1]
388   //  | this_frame   | <- FI[0]
389   //
390   // For negative frame indices, the offset from the frame pointer will differ
391   // depending on which of these groups the frame index applies to.
392   // The following calculates the correct offset knowing the number of callee
393   // saved registers spilt by the two methods.
394   if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
395     // Calculate the size of the frame managed by the libcall. The libcalls are
396     // implemented such that the stack will always be 16 byte aligned.
397     unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
398     RVFI->setLibCallStackSize(LibCallFrameSize);
399   }
400 
401   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
402   // investigation. Get the number of bytes to allocate from the FrameInfo.
403   uint64_t StackSize = MFI.getStackSize() + RVFI->getRVVPadding();
404   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
405   uint64_t RVVStackSize = RVFI->getRVVStackSize();
406 
407   // Early exit if there is no need to allocate on the stack
408   if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
409     return;
410 
411   // If the stack pointer has been marked as reserved, then produce an error if
412   // the frame requires stack allocation
413   if (STI.isRegisterReservedByUser(SPReg))
414     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
415         MF.getFunction(), "Stack pointer required, but has been reserved."});
416 
417   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
418   // Split the SP adjustment to reduce the offsets of callee saved spill.
419   if (FirstSPAdjustAmount) {
420     StackSize = FirstSPAdjustAmount;
421     RealStackSize = FirstSPAdjustAmount;
422   }
423 
424   // Allocate space on the stack if necessary.
425   adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
426 
427   // Emit ".cfi_def_cfa_offset RealStackSize"
428   unsigned CFIIndex = MF.addFrameInst(
429       MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
430   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
431       .addCFIIndex(CFIIndex)
432       .setMIFlag(MachineInstr::FrameSetup);
433 
434   const auto &CSI = MFI.getCalleeSavedInfo();
435 
436   // The frame pointer is callee-saved, and code has been generated for us to
437   // save it to the stack. We need to skip over the storing of callee-saved
438   // registers as the frame pointer must be modified after it has been saved
439   // to the stack, not before.
440   // FIXME: assumes exactly one instruction is used to save each callee-saved
441   // register.
442   std::advance(MBBI, getNonLibcallCSI(MF, CSI).size());
443 
444   // Iterate over list of callee-saved registers and emit .cfi_offset
445   // directives.
446   for (const auto &Entry : CSI) {
447     int FrameIdx = Entry.getFrameIdx();
448     int64_t Offset;
449     // Offsets for objects with fixed locations (IE: those saved by libcall) are
450     // simply calculated from the frame index.
451     if (FrameIdx < 0)
452       Offset = FrameIdx * (int64_t) STI.getXLen() / 8;
453     else
454       Offset = MFI.getObjectOffset(Entry.getFrameIdx()) -
455                RVFI->getLibCallStackSize();
456     Register Reg = Entry.getReg();
457     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
458         nullptr, RI->getDwarfRegNum(Reg, true), Offset));
459     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
460         .addCFIIndex(CFIIndex)
461         .setMIFlag(MachineInstr::FrameSetup);
462   }
463 
464   // Generate new FP.
465   if (hasFP(MF)) {
466     if (STI.isRegisterReservedByUser(FPReg))
467       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
468           MF.getFunction(), "Frame pointer required, but has been reserved."});
469 
470     adjustReg(MBB, MBBI, DL, FPReg, SPReg,
471               RealStackSize - RVFI->getVarArgsSaveSize(),
472               MachineInstr::FrameSetup);
473 
474     // Emit ".cfi_def_cfa $fp, RVFI->getVarArgsSaveSize()"
475     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
476         nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
477     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
478         .addCFIIndex(CFIIndex)
479         .setMIFlag(MachineInstr::FrameSetup);
480   }
481 
482   // Emit the second SP adjustment after saving callee saved registers.
483   if (FirstSPAdjustAmount) {
484     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
485     assert(SecondSPAdjustAmount > 0 &&
486            "SecondSPAdjustAmount should be greater than zero");
487     adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount,
488               MachineInstr::FrameSetup);
489 
490     // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
491     // don't emit an sp-based .cfi_def_cfa_offset
492     if (!hasFP(MF)) {
493       // Emit ".cfi_def_cfa_offset StackSize"
494       unsigned CFIIndex = MF.addFrameInst(
495           MCCFIInstruction::cfiDefCfaOffset(nullptr, MFI.getStackSize()));
496       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
497           .addCFIIndex(CFIIndex)
498           .setMIFlag(MachineInstr::FrameSetup);
499     }
500   }
501 
502   if (RVVStackSize)
503     adjustStackForRVV(MF, MBB, MBBI, DL, -RVVStackSize,
504                       MachineInstr::FrameSetup);
505 
506   if (hasFP(MF)) {
507     // Realign Stack
508     const RISCVRegisterInfo *RI = STI.getRegisterInfo();
509     if (RI->hasStackRealignment(MF)) {
510       Align MaxAlignment = MFI.getMaxAlign();
511 
512       const RISCVInstrInfo *TII = STI.getInstrInfo();
513       if (isInt<12>(-(int)MaxAlignment.value())) {
514         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
515             .addReg(SPReg)
516             .addImm(-(int)MaxAlignment.value())
517             .setMIFlag(MachineInstr::FrameSetup);
518       } else {
519         unsigned ShiftAmount = Log2(MaxAlignment);
520         Register VR =
521             MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
522         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
523             .addReg(SPReg)
524             .addImm(ShiftAmount)
525             .setMIFlag(MachineInstr::FrameSetup);
526         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
527             .addReg(VR)
528             .addImm(ShiftAmount)
529             .setMIFlag(MachineInstr::FrameSetup);
530       }
531       // FP will be used to restore the frame in the epilogue, so we need
532       // another base register BP to record SP after re-alignment. SP will
533       // track the current stack after allocating variable sized objects.
534       if (hasBP(MF)) {
535         // move BP, SP
536         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
537             .addReg(SPReg)
538             .addImm(0)
539             .setMIFlag(MachineInstr::FrameSetup);
540       }
541     }
542   }
543 }
544 
545 void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
546                                       MachineBasicBlock &MBB) const {
547   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
548   MachineFrameInfo &MFI = MF.getFrameInfo();
549   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
550   Register FPReg = getFPReg(STI);
551   Register SPReg = getSPReg(STI);
552 
553   // All calls are tail calls in GHC calling conv, and functions have no
554   // prologue/epilogue.
555   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
556     return;
557 
558   // Get the insert location for the epilogue. If there were no terminators in
559   // the block, get the last instruction.
560   MachineBasicBlock::iterator MBBI = MBB.end();
561   DebugLoc DL;
562   if (!MBB.empty()) {
563     MBBI = MBB.getFirstTerminator();
564     if (MBBI == MBB.end())
565       MBBI = MBB.getLastNonDebugInstr();
566     DL = MBBI->getDebugLoc();
567 
568     // If this is not a terminator, the actual insert location should be after the
569     // last instruction.
570     if (!MBBI->isTerminator())
571       MBBI = std::next(MBBI);
572 
573     // If callee-saved registers are saved via libcall, place stack adjustment
574     // before this call.
575     while (MBBI != MBB.begin() &&
576            std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
577       --MBBI;
578   }
579 
580   const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
581 
582   // Skip to before the restores of callee-saved registers
583   // FIXME: assumes exactly one instruction is used to restore each
584   // callee-saved register.
585   auto LastFrameDestroy = MBBI;
586   if (!CSI.empty())
587     LastFrameDestroy = std::prev(MBBI, CSI.size());
588 
589   uint64_t StackSize = MFI.getStackSize() + RVFI->getRVVPadding();
590   uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
591   uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
592   uint64_t RVVStackSize = RVFI->getRVVStackSize();
593 
594   // Restore the stack pointer using the value of the frame pointer. Only
595   // necessary if the stack pointer was modified, meaning the stack size is
596   // unknown.
597   if (RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects()) {
598     assert(hasFP(MF) && "frame pointer should not have been eliminated");
599     adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset,
600               MachineInstr::FrameDestroy);
601   } else {
602     if (RVVStackSize)
603       adjustStackForRVV(MF, MBB, LastFrameDestroy, DL, RVVStackSize,
604                         MachineInstr::FrameDestroy);
605   }
606 
607   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
608   if (FirstSPAdjustAmount) {
609     uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount;
610     assert(SecondSPAdjustAmount > 0 &&
611            "SecondSPAdjustAmount should be greater than zero");
612 
613     adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
614               MachineInstr::FrameDestroy);
615   }
616 
617   if (FirstSPAdjustAmount)
618     StackSize = FirstSPAdjustAmount;
619 
620   // Deallocate stack
621   adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
622 
623   // Emit epilogue for shadow call stack.
624   emitSCSEpilogue(MF, MBB, MBBI, DL);
625 }
626 
627 StackOffset
628 RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
629                                            Register &FrameReg) const {
630   const MachineFrameInfo &MFI = MF.getFrameInfo();
631   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
632   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
633 
634   // Callee-saved registers should be referenced relative to the stack
635   // pointer (positive offset), otherwise use the frame pointer (negative
636   // offset).
637   const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
638   int MinCSFI = 0;
639   int MaxCSFI = -1;
640   StackOffset Offset;
641   auto StackID = MFI.getStackID(FI);
642 
643   assert((StackID == TargetStackID::Default ||
644           StackID == TargetStackID::ScalableVector) &&
645          "Unexpected stack ID for the frame object.");
646   if (StackID == TargetStackID::Default) {
647     Offset =
648         StackOffset::getFixed(MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
649                               MFI.getOffsetAdjustment());
650   } else if (StackID == TargetStackID::ScalableVector) {
651     Offset = StackOffset::getScalable(MFI.getObjectOffset(FI));
652   }
653 
654   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
655 
656   if (CSI.size()) {
657     MinCSFI = CSI[0].getFrameIdx();
658     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
659   }
660 
661   if (FI >= MinCSFI && FI <= MaxCSFI) {
662     FrameReg = RISCV::X2;
663 
664     if (FirstSPAdjustAmount)
665       Offset += StackOffset::getFixed(FirstSPAdjustAmount);
666     else
667       Offset +=
668           StackOffset::getFixed(MFI.getStackSize() + RVFI->getRVVPadding());
669   } else if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
670     // If the stack was realigned, the frame pointer is set in order to allow
671     // SP to be restored, so we need another base register to record the stack
672     // after realignment.
673     if (hasBP(MF)) {
674       FrameReg = RISCVABI::getBPReg();
675       // |--------------------------| -- <-- FP
676       // | callee-saved registers   | | <----.
677       // |--------------------------| --     |
678       // | realignment (the size of | |      |
679       // | this area is not counted | |      |
680       // | in MFI.getStackSize())   | |      |
681       // |--------------------------| --     |
682       // | Padding after RVV        | |      |
683       // | (not counted in          | |      |
684       // | MFI.getStackSize())      | |      |
685       // |--------------------------| --     |-- MFI.getStackSize()
686       // | RVV objects              | |      |
687       // | (not counted in          | |      |
688       // | MFI.getStackSize())      | |      |
689       // |--------------------------| --     |
690       // | Padding before RVV       | |      |
691       // | (not counted in          | |      |
692       // | MFI.getStackSize())      | |      |
693       // |--------------------------| --     |
694       // | scalar local variables   | | <----'
695       // |--------------------------| -- <-- BP
696       // | VarSize objects          | |
697       // |--------------------------| -- <-- SP
698     } else {
699       FrameReg = RISCV::X2;
700       // |--------------------------| -- <-- FP
701       // | callee-saved registers   | | <----.
702       // |--------------------------| --     |
703       // | realignment (the size of | |      |
704       // | this area is not counted | |      |
705       // | in MFI.getStackSize())   | |      |
706       // |--------------------------| --     |
707       // | Padding after RVV        | |      |
708       // | (not counted in          | |      |
709       // | MFI.getStackSize())      | |      |
710       // |--------------------------| --     |-- MFI.getStackSize()
711       // | RVV objects              | |      |
712       // | (not counted in          | |      |
713       // | MFI.getStackSize())      | |      |
714       // |--------------------------| --     |
715       // | Padding before RVV       | |      |
716       // | (not counted in          | |      |
717       // | MFI.getStackSize())      | |      |
718       // |--------------------------| --     |
719       // | scalar local variables   | | <----'
720       // |--------------------------| -- <-- SP
721     }
722     // The total amount of padding surrounding RVV objects is described by
723     // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
724     // objects to 8 bytes.
725     if (MFI.getStackID(FI) == TargetStackID::Default) {
726       Offset += StackOffset::getFixed(MFI.getStackSize());
727       if (FI < 0)
728         Offset += StackOffset::getFixed(RVFI->getLibCallStackSize());
729     } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
730       Offset += StackOffset::get(
731           alignTo(MFI.getStackSize() - RVFI->getCalleeSavedStackSize(), 8),
732           RVFI->getRVVStackSize());
733     }
734   } else {
735     FrameReg = RI->getFrameRegister(MF);
736     if (hasFP(MF)) {
737       Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
738       if (FI >= 0)
739         Offset -= StackOffset::getFixed(RVFI->getLibCallStackSize());
740       // When using FP to access scalable vector objects, we need to minus
741       // the frame size.
742       //
743       // |--------------------------| -- <-- FP
744       // | callee-saved registers   | |
745       // |--------------------------| | MFI.getStackSize()
746       // | scalar local variables   | |
747       // |--------------------------| -- (Offset of RVV objects is from here.)
748       // | RVV objects              |
749       // |--------------------------|
750       // | VarSize objects          |
751       // |--------------------------| <-- SP
752       if (MFI.getStackID(FI) == TargetStackID::ScalableVector)
753         Offset -= StackOffset::getFixed(MFI.getStackSize());
754     } else {
755       // When using SP to access frame objects, we need to add RVV stack size.
756       //
757       // |--------------------------| -- <-- FP
758       // | callee-saved registers   | | <----.
759       // |--------------------------| --     |
760       // | Padding after RVV        | |      |
761       // | (not counted in          | |      |
762       // | MFI.getStackSize())      | |      |
763       // |--------------------------| --     |
764       // | RVV objects              | |      |-- MFI.getStackSize()
765       // | (not counted in          | |      |
766       // | MFI.getStackSize())      | |      |
767       // |--------------------------| --     |
768       // | Padding before RVV       | |      |
769       // | (not counted in          | |      |
770       // | MFI.getStackSize())      | |      |
771       // |--------------------------| --     |
772       // | scalar local variables   | | <----'
773       // |--------------------------| -- <-- SP
774       //
775       // The total amount of padding surrounding RVV objects is described by
776       // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
777       // objects to 8 bytes.
778       if (MFI.getStackID(FI) == TargetStackID::Default) {
779         if (MFI.isFixedObjectIndex(FI)) {
780           Offset +=
781               StackOffset::get(MFI.getStackSize() + RVFI->getRVVPadding() +
782                                    RVFI->getLibCallStackSize(),
783                                RVFI->getRVVStackSize());
784         } else {
785           Offset += StackOffset::getFixed(MFI.getStackSize());
786         }
787       } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
788         Offset += StackOffset::get(
789             alignTo(MFI.getStackSize() - RVFI->getCalleeSavedStackSize(), 8),
790             RVFI->getRVVStackSize());
791       }
792     }
793   }
794 
795   return Offset;
796 }
797 
798 void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
799                                               BitVector &SavedRegs,
800                                               RegScavenger *RS) const {
801   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
802   // Unconditionally spill RA and FP only if the function uses a frame
803   // pointer.
804   if (hasFP(MF)) {
805     SavedRegs.set(RISCV::X1);
806     SavedRegs.set(RISCV::X8);
807   }
808   // Mark BP as used if function has dedicated base pointer.
809   if (hasBP(MF))
810     SavedRegs.set(RISCVABI::getBPReg());
811 
812   // If interrupt is enabled and there are calls in the handler,
813   // unconditionally save all Caller-saved registers and
814   // all FP registers, regardless whether they are used.
815   MachineFrameInfo &MFI = MF.getFrameInfo();
816 
817   if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
818 
819     static const MCPhysReg CSRegs[] = { RISCV::X1,      /* ra */
820       RISCV::X5, RISCV::X6, RISCV::X7,                  /* t0-t2 */
821       RISCV::X10, RISCV::X11,                           /* a0-a1, a2-a7 */
822       RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
823       RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */
824     };
825 
826     for (unsigned i = 0; CSRegs[i]; ++i)
827       SavedRegs.set(CSRegs[i]);
828 
829     if (MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
830 
831       // If interrupt is enabled, this list contains all FP registers.
832       const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
833 
834       for (unsigned i = 0; Regs[i]; ++i)
835         if (RISCV::FPR16RegClass.contains(Regs[i]) ||
836             RISCV::FPR32RegClass.contains(Regs[i]) ||
837             RISCV::FPR64RegClass.contains(Regs[i]))
838           SavedRegs.set(Regs[i]);
839     }
840   }
841 }
842 
843 int64_t
844 RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFrameInfo &MFI) const {
845   int64_t Offset = 0;
846   // Create a buffer of RVV objects to allocate.
847   SmallVector<int, 8> ObjectsToAllocate;
848   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
849     unsigned StackID = MFI.getStackID(I);
850     if (StackID != TargetStackID::ScalableVector)
851       continue;
852     if (MFI.isDeadObjectIndex(I))
853       continue;
854 
855     ObjectsToAllocate.push_back(I);
856   }
857 
858   // Allocate all RVV locals and spills
859   for (int FI : ObjectsToAllocate) {
860     // ObjectSize in bytes.
861     int64_t ObjectSize = MFI.getObjectSize(FI);
862     // If the data type is the fractional vector type, reserve one vector
863     // register for it.
864     if (ObjectSize < 8)
865       ObjectSize = 8;
866     // Currently, all scalable vector types are aligned to 8 bytes.
867     Offset = alignTo(Offset + ObjectSize, 8);
868     MFI.setObjectOffset(FI, -Offset);
869   }
870 
871   return Offset;
872 }
873 
874 static bool hasRVVSpillWithFIs(MachineFunction &MF, const RISCVInstrInfo &TII) {
875   if (!MF.getSubtarget<RISCVSubtarget>().hasVInstructions())
876     return false;
877   return any_of(MF, [&TII](const MachineBasicBlock &MBB) {
878     return any_of(MBB, [&TII](const MachineInstr &MI) {
879       return TII.isRVVSpill(MI, /*CheckFIs*/ true);
880     });
881   });
882 }
883 
884 void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
885     MachineFunction &MF, RegScavenger *RS) const {
886   const RISCVRegisterInfo *RegInfo =
887       MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
888   MachineFrameInfo &MFI = MF.getFrameInfo();
889   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
890   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
891 
892   int64_t RVVStackSize = assignRVVStackObjectOffsets(MFI);
893   RVFI->setRVVStackSize(RVVStackSize);
894   const RISCVInstrInfo &TII = *MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
895 
896   // estimateStackSize has been observed to under-estimate the final stack
897   // size, so give ourselves wiggle-room by checking for stack size
898   // representable an 11-bit signed field rather than 12-bits.
899   // FIXME: It may be possible to craft a function with a small stack that
900   // still needs an emergency spill slot for branch relaxation. This case
901   // would currently be missed.
902   // RVV loads & stores have no capacity to hold the immediate address offsets
903   // so we must always reserve an emergency spill slot if the MachineFunction
904   // contains any RVV spills.
905   if (!isInt<11>(MFI.estimateStackSize(MF)) || hasRVVSpillWithFIs(MF, TII)) {
906     int RegScavFI = MFI.CreateStackObject(RegInfo->getSpillSize(*RC),
907                                           RegInfo->getSpillAlign(*RC), false);
908     RS->addScavengingFrameIndex(RegScavFI);
909     // For RVV, scalable stack offsets require up to two scratch registers to
910     // compute the final offset. Reserve an additional emergency spill slot.
911     if (RVVStackSize != 0) {
912       int RVVRegScavFI = MFI.CreateStackObject(
913           RegInfo->getSpillSize(*RC), RegInfo->getSpillAlign(*RC), false);
914       RS->addScavengingFrameIndex(RVVRegScavFI);
915     }
916   }
917 
918   if (MFI.getCalleeSavedInfo().empty() || RVFI->useSaveRestoreLibCalls(MF)) {
919     RVFI->setCalleeSavedStackSize(0);
920     return;
921   }
922 
923   unsigned Size = 0;
924   for (const auto &Info : MFI.getCalleeSavedInfo()) {
925     int FrameIdx = Info.getFrameIdx();
926     if (MFI.getStackID(FrameIdx) != TargetStackID::Default)
927       continue;
928 
929     Size += MFI.getObjectSize(FrameIdx);
930   }
931   RVFI->setCalleeSavedStackSize(Size);
932 
933   // Padding required to keep the RVV stack aligned to 8 bytes
934   // within the main stack. We only need this when not using FP.
935   if (RVVStackSize && !hasFP(MF) && Size % 8 != 0) {
936     // Because we add the padding to the size of the stack, adding
937     // getStackAlign() will keep it aligned.
938     RVFI->setRVVPadding(getStackAlign().value());
939   }
940 }
941 
942 static bool hasRVVFrameObject(const MachineFunction &MF) {
943   const MachineFrameInfo &MFI = MF.getFrameInfo();
944   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I)
945     if (MFI.getStackID(I) == TargetStackID::ScalableVector)
946       return true;
947   return false;
948 }
949 
950 // Not preserve stack space within prologue for outgoing variables when the
951 // function contains variable size objects or there are vector objects accessed
952 // by the frame pointer.
953 // Let eliminateCallFramePseudoInstr preserve stack space for it.
954 bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
955   return !MF.getFrameInfo().hasVarSizedObjects() &&
956          !(hasFP(MF) && hasRVVFrameObject(MF));
957 }
958 
959 // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
960 MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
961     MachineFunction &MF, MachineBasicBlock &MBB,
962     MachineBasicBlock::iterator MI) const {
963   Register SPReg = RISCV::X2;
964   DebugLoc DL = MI->getDebugLoc();
965 
966   if (!hasReservedCallFrame(MF)) {
967     // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
968     // ADJCALLSTACKUP must be converted to instructions manipulating the stack
969     // pointer. This is necessary when there is a variable length stack
970     // allocation (e.g. alloca), which means it's not possible to allocate
971     // space for outgoing arguments from within the function prologue.
972     int64_t Amount = MI->getOperand(0).getImm();
973 
974     if (Amount != 0) {
975       // Ensure the stack remains aligned after adjustment.
976       Amount = alignSPAdjust(Amount);
977 
978       if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
979         Amount = -Amount;
980 
981       adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
982     }
983   }
984 
985   return MBB.erase(MI);
986 }
987 
988 // We would like to split the SP adjustment to reduce prologue/epilogue
989 // as following instructions. In this way, the offset of the callee saved
990 // register could fit in a single store.
991 //   add     sp,sp,-2032
992 //   sw      ra,2028(sp)
993 //   sw      s0,2024(sp)
994 //   sw      s1,2020(sp)
995 //   sw      s3,2012(sp)
996 //   sw      s4,2008(sp)
997 //   add     sp,sp,-64
998 uint64_t
999 RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
1000   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1001   const MachineFrameInfo &MFI = MF.getFrameInfo();
1002   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
1003   uint64_t StackSize = MFI.getStackSize();
1004 
1005   // Disable SplitSPAdjust if save-restore libcall used. The callee saved
1006   // registers will be pushed by the save-restore libcalls, so we don't have to
1007   // split the SP adjustment in this case.
1008   if (RVFI->getLibCallStackSize())
1009     return 0;
1010 
1011   // Return the FirstSPAdjustAmount if the StackSize can not fit in signed
1012   // 12-bit and there exists a callee saved register need to be pushed.
1013   if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
1014     // FirstSPAdjustAmount is choosed as (2048 - StackAlign)
1015     // because 2048 will cause sp = sp + 2048 in epilogue split into
1016     // multi-instructions. The offset smaller than 2048 can fit in signle
1017     // load/store instruction and we have to stick with the stack alignment.
1018     // 2048 is 16-byte alignment. The stack alignment for RV32 and RV64 is 16,
1019     // for RV32E is 4. So (2048 - StackAlign) will satisfy the stack alignment.
1020     return 2048 - getStackAlign().value();
1021   }
1022   return 0;
1023 }
1024 
1025 bool RISCVFrameLowering::spillCalleeSavedRegisters(
1026     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1027     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1028   if (CSI.empty())
1029     return true;
1030 
1031   MachineFunction *MF = MBB.getParent();
1032   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1033   DebugLoc DL;
1034   if (MI != MBB.end() && !MI->isDebugInstr())
1035     DL = MI->getDebugLoc();
1036 
1037   const char *SpillLibCall = getSpillLibCallName(*MF, CSI);
1038   if (SpillLibCall) {
1039     // Add spill libcall via non-callee-saved register t0.
1040     BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
1041         .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
1042         .setMIFlag(MachineInstr::FrameSetup);
1043 
1044     // Add registers spilled in libcall as liveins.
1045     for (auto &CS : CSI)
1046       MBB.addLiveIn(CS.getReg());
1047   }
1048 
1049   // Manually spill values not spilled by libcall.
1050   const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
1051   for (auto &CS : NonLibcallCSI) {
1052     // Insert the spill to the stack frame.
1053     Register Reg = CS.getReg();
1054     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1055     TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg), CS.getFrameIdx(),
1056                             RC, TRI);
1057   }
1058 
1059   return true;
1060 }
1061 
1062 bool RISCVFrameLowering::restoreCalleeSavedRegisters(
1063     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1064     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1065   if (CSI.empty())
1066     return true;
1067 
1068   MachineFunction *MF = MBB.getParent();
1069   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1070   DebugLoc DL;
1071   if (MI != MBB.end() && !MI->isDebugInstr())
1072     DL = MI->getDebugLoc();
1073 
1074   // Manually restore values not restored by libcall.
1075   // Keep the same order as in the prologue. There is no need to reverse the
1076   // order in the epilogue. In addition, the return address will be restored
1077   // first in the epilogue. It increases the opportunity to avoid the
1078   // load-to-use data hazard between loading RA and return by RA.
1079   // loadRegFromStackSlot can insert multiple instructions.
1080   const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
1081   for (auto &CS : NonLibcallCSI) {
1082     Register Reg = CS.getReg();
1083     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1084     TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI);
1085     assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
1086   }
1087 
1088   const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
1089   if (RestoreLibCall) {
1090     // Add restore libcall via tail call.
1091     MachineBasicBlock::iterator NewMI =
1092         BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
1093             .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
1094             .setMIFlag(MachineInstr::FrameDestroy);
1095 
1096     // Remove trailing returns, since the terminator is now a tail call to the
1097     // restore function.
1098     if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
1099       NewMI->copyImplicitOps(*MF, *MI);
1100       MI->eraseFromParent();
1101     }
1102   }
1103 
1104   return true;
1105 }
1106 
1107 bool RISCVFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
1108   // Keep the conventional code flow when not optimizing.
1109   if (MF.getFunction().hasOptNone())
1110     return false;
1111 
1112   return true;
1113 }
1114 
1115 bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
1116   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1117   const MachineFunction *MF = MBB.getParent();
1118   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1119 
1120   if (!RVFI->useSaveRestoreLibCalls(*MF))
1121     return true;
1122 
1123   // Inserting a call to a __riscv_save libcall requires the use of the register
1124   // t0 (X5) to hold the return address. Therefore if this register is already
1125   // used we can't insert the call.
1126 
1127   RegScavenger RS;
1128   RS.enterBasicBlock(*TmpMBB);
1129   return !RS.isRegUsed(RISCV::X5);
1130 }
1131 
1132 bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1133   const MachineFunction *MF = MBB.getParent();
1134   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1135   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1136 
1137   if (!RVFI->useSaveRestoreLibCalls(*MF))
1138     return true;
1139 
1140   // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
1141   // This means if we still need to continue executing code within this function
1142   // the restore cannot take place in this basic block.
1143 
1144   if (MBB.succ_size() > 1)
1145     return false;
1146 
1147   MachineBasicBlock *SuccMBB =
1148       MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
1149 
1150   // Doing a tail call should be safe if there are no successors, because either
1151   // we have a returning block or the end of the block is unreachable, so the
1152   // restore will be eliminated regardless.
1153   if (!SuccMBB)
1154     return true;
1155 
1156   // The successor can only contain a return, since we would effectively be
1157   // replacing the successor with our own tail return at the end of our block.
1158   return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
1159 }
1160 
1161 bool RISCVFrameLowering::isSupportedStackID(TargetStackID::Value ID) const {
1162   switch (ID) {
1163   case TargetStackID::Default:
1164   case TargetStackID::ScalableVector:
1165     return true;
1166   case TargetStackID::NoAlloc:
1167   case TargetStackID::SGPRSpill:
1168   case TargetStackID::WasmLocal:
1169     return false;
1170   }
1171   llvm_unreachable("Invalid TargetStackID::Value");
1172 }
1173 
1174 TargetStackID::Value RISCVFrameLowering::getStackIDForScalableVectors() const {
1175   return TargetStackID::ScalableVector;
1176 }
1177