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