LLVM 24.0.0git
RISCVFrameLowering.cpp
Go to the documentation of this file.
1//===-- RISCVFrameLowering.cpp - RISC-V 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 RISC-V implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RISCVFrameLowering.h"
17#include "RISCVSubtarget.h"
28#include "llvm/MC/MCDwarf.h"
29#include "llvm/Support/LEB128.h"
30
31#include <algorithm>
32#include <cstdint>
33
34#define DEBUG_TYPE "riscv-frame"
35
36using namespace llvm;
37
40 RISCVABI::getStackAlignment(STI.getTargetABI()),
41 /*LocalAreaOffset=*/0,
42 /*TransientStackAlignment=*/
43 RISCVABI::getStackAlignment(STI.getTargetABI())),
44 STI(STI) {}
45
46// The register used to hold the frame pointer.
47static constexpr MCPhysReg FPReg = RISCV::X8;
48
49// The register used to hold the stack pointer.
50static constexpr MCPhysReg SPReg = RISCV::X2;
51
52// The register used to hold the return address.
53static constexpr MCPhysReg RAReg = RISCV::X1;
54
55// With inline stack probing, the maximum number of bytes above SP that may be
56// left unprobed at an ABI boundary (function entry or a call). It matches the
57// caller guard that GCC assumes for RISC-V (STACK_CLASH_CALLER_GUARD) and that
58// LLVM uses for AArch64 (StackProbeMaxUnprobedStack).
59static constexpr unsigned StackProbeMaxUnprobedStack = 1024;
60
61// LIst of CSRs that are given a fixed location by save/restore libcalls or
62// Zcmp/Xqccmp Push/Pop. The order in this table indicates the order the
63// registers are saved on the stack. Zcmp uses the reverse order of save/restore
64// and Xqccmp on the stack, but this is handled when offsets are calculated.
65static const MCPhysReg FixedCSRFIMap[] = {
66 /*ra*/ RAReg, /*s0*/ FPReg, /*s1*/ RISCV::X9,
67 /*s2*/ RISCV::X18, /*s3*/ RISCV::X19, /*s4*/ RISCV::X20,
68 /*s5*/ RISCV::X21, /*s6*/ RISCV::X22, /*s7*/ RISCV::X23,
69 /*s8*/ RISCV::X24, /*s9*/ RISCV::X25, /*s10*/ RISCV::X26,
70 /*s11*/ RISCV::X27};
71
72// The number of stack bytes allocated by `QC.C.MIENTER(.NEST)` and popped by
73// `QC.C.MILEAVERET`.
74static constexpr uint64_t QCIInterruptPushAmount = 96;
75
76static const std::pair<MCPhysReg, int8_t> FixedCSRFIQCIInterruptMap[] = {
77 /* -1 is a gap for mepc/mnepc */
78 {/*fp*/ FPReg, -2},
79 /* -3 is a gap for qc.mcause */
80 {/*ra*/ RAReg, -4},
81 /* -5 is reserved */
82 {/*t0*/ RISCV::X5, -6},
83 {/*t1*/ RISCV::X6, -7},
84 {/*t2*/ RISCV::X7, -8},
85 {/*a0*/ RISCV::X10, -9},
86 {/*a1*/ RISCV::X11, -10},
87 {/*a2*/ RISCV::X12, -11},
88 {/*a3*/ RISCV::X13, -12},
89 {/*a4*/ RISCV::X14, -13},
90 {/*a5*/ RISCV::X15, -14},
91 {/*a6*/ RISCV::X16, -15},
92 {/*a7*/ RISCV::X17, -16},
93 {/*t3*/ RISCV::X28, -17},
94 {/*t4*/ RISCV::X29, -18},
95 {/*t5*/ RISCV::X30, -19},
96 {/*t6*/ RISCV::X31, -20},
97 /* -21, -22, -23, -24 are reserved */
98};
99
100/// Returns true if DWARF CFI instructions ("frame moves") should be emitted.
101static bool needsDwarfCFI(const MachineFunction &MF) {
102 return MF.needsFrameMoves();
103}
104
105// For now we use x3, a.k.a gp, as pointer to shadow call stack.
106// User should not use x3 in their asm.
109 const DebugLoc &DL) {
110 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
111 RISCVMachineFunctionInfo::ShadowStackKind SSK = RVFI->getShadowStackKind(MF);
113 return;
114
115 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
116 const llvm::RISCVRegisterInfo *TRI = STI.getRegisterInfo();
117
118 // Do not save RA to the SCS if it's not saved to the regular stack,
119 // i.e. RA is not at risk of being overwritten.
120 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
121 if (llvm::none_of(
122 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
123 return;
124
125 const RISCVInstrInfo *TII = STI.getInstrInfo();
127 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPUSH))
128 .addReg(RAReg)
130 return;
131 }
132
134 "Unexpected Shadow Stack Kind");
135
136 Register SCSPReg = RISCVABI::getSCSPReg();
137
138 bool IsRV64 = STI.is64Bit();
139 int64_t SlotSize = STI.getXLen() / 8;
140 // Store return address to shadow call stack
141 // addi gp, gp, [4|8]
142 // s[w|d] ra, -[4|8](gp)
143 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI), SCSPReg)
144 .addReg(SCSPReg)
145 .addImm(SlotSize)
147 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
148 .addReg(RAReg)
149 .addReg(SCSPReg)
150 .addImm(-SlotSize)
152
153 if (!needsDwarfCFI(MF))
154 return;
155
156 // Emit a CFI instruction that causes SlotSize to be subtracted from the value
157 // of the shadow stack pointer when unwinding past this frame.
158 char DwarfSCSReg = TRI->getDwarfRegNum(SCSPReg, /*IsEH*/ true);
159 assert(DwarfSCSReg < 32 && "SCS Register should be < 32 (X3).");
160
161 char Offset = static_cast<char>(-SlotSize) & 0x7f;
162 const char CFIInst[] = {
163 dwarf::DW_CFA_val_expression,
164 DwarfSCSReg, // register
165 2, // length
166 static_cast<char>(unsigned(dwarf::DW_OP_breg0 + DwarfSCSReg)),
167 Offset, // addend (sleb128)
168 };
169
171 .buildEscape(StringRef(CFIInst, sizeof(CFIInst)));
172}
173
176 const DebugLoc &DL) {
177 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
178 RISCVMachineFunctionInfo::ShadowStackKind SSK = RVFI->getShadowStackKind(MF);
180 return;
181
182 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
183
184 // See emitSCSPrologue() above.
185 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
186 if (llvm::none_of(
187 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
188 return;
189
190 // The shadow call stack popchk needs to happen after cm.pop that loads ra.
191 if (MI != MBB.end() &&
192 (MI->getOpcode() == RISCV::CM_POP || MI->getOpcode() == RISCV::QC_CM_POP))
193 ++MI;
194 const RISCVInstrInfo *TII = STI.getInstrInfo();
196 // `sspopchk x5` is the only compressible form, but this would require using
197 // `x5` as the return address everywhere, which would also mean reserving
198 // it. We prefer to just use `x1` to avoid that complexity.
199 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPOPCHK))
200 .addReg(RAReg)
202 return;
203 }
204
206 "Unexpected Shadow Stack Kind");
207
208 Register SCSPReg = RISCVABI::getSCSPReg();
209
210 bool IsRV64 = STI.is64Bit();
211 int64_t SlotSize = STI.getXLen() / 8;
212 // Load return address from shadow call stack
213 // l[w|d] ra, -[4|8](gp)
214 // addi gp, gp, -[4|8]
215 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::LD : RISCV::LW), RAReg)
216 .addReg(SCSPReg)
217 .addImm(-SlotSize)
219 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI), SCSPReg)
220 .addReg(SCSPReg)
221 .addImm(-SlotSize)
223 if (needsDwarfCFI(MF)) {
224 // Restore the SCS pointer
226 }
227}
228
229// Insert instruction to swap mscratchsw with sp
232 const DebugLoc &DL,
233 MachineInstr::MIFlag FrameFlag) {
234 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
235
236 if (!RVFI->isSiFiveStackSwapInterrupt(MF))
237 return;
238
239 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
240 const RISCVInstrInfo *TII = STI.getInstrInfo();
241
242 assert(STI.hasVendorXSfmclic() && "Stack Swapping Requires XSfmclic");
243
244 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), SPReg)
245 .addImm(RISCVSysReg::sf_mscratchcsw)
247 .setMIFlag(FrameFlag);
248
249 // FIXME: CFI Information for this swap.
250}
251
252static void
255 if (!RVFI.isSiFivePreemptibleInterrupt(MF))
256 return;
257
258 const TargetRegisterClass &RC = RISCV::GPRRegClass;
259 const TargetRegisterInfo &TRI =
260 *MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
261 MachineFrameInfo &MFI = MF.getFrameInfo();
262
263 // Create two frame objects for saving `mcause` and `mepc`.
264 for (int I = 0; I < 2; ++I) {
265 int FI = MFI.CreateStackObject(TRI.getSpillSize(RC), TRI.getSpillAlign(RC),
266 true);
268 }
269}
270
271// The scratch register retains an ordinary CSI slot, but its save and restore
272// are emitted explicitly as part of the SiFive CLIC interrupt sequence.
274 const auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
275 auto ScratchCS = llvm::find_if(
276 CSI, [](const CalleeSavedInfo &CS) { return CS.getReg() == RISCV::X5; });
277 assert(ScratchCS != CSI.end() && "Missing SiFive CLIC scratch spill slot");
278 return ScratchCS->getFrameIdx();
279}
280
284 const DebugLoc &DL) {
285 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
286
287 if (!RVFI->isSiFivePreemptibleInterrupt(MF))
288 return;
289
290 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
291 const RISCVInstrInfo *TII = STI.getInstrInfo();
292
293 // FIXME: CFI information for `mcause` and `mepc` is missing.
294
295 // Preserve X5 before using it to save the interrupt CSRs. Other GPRs
296 // are saved by the ordinary spill sequence after preemption is enabled.
297 int ScratchFI = getSiFiveCLICScratchFrameIndex(MF);
298 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /*IsKill=*/true, ScratchFI,
299 &RISCV::GPRRegClass, Register(),
301 if (needsDwarfCFI(MF))
303 .buildOffset(RISCV::X5, MF.getFrameInfo().getObjectOffset(ScratchFI));
304
305 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRS), RISCV::X5)
306 .addImm(RISCVSysReg::mcause)
307 .addReg(RISCV::X0)
309 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /* IsKill=*/true,
310 RVFI->getInterruptCSRFrameIndex(0),
311 &RISCV::GPRRegClass, Register(),
313
314 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRS), RISCV::X5)
315 .addImm(RISCVSysReg::mepc)
316 .addReg(RISCV::X0)
318
319 // Enable interrupts.
320 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRSI), RISCV::X0)
321 .addImm(RISCVSysReg::mstatus)
322 .addImm(8)
324 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /* IsKill=*/true,
325 RVFI->getInterruptCSRFrameIndex(1),
326 &RISCV::GPRRegClass, Register(),
328}
329
333 CFIInstBuilder &CFIBuilder,
334 const DebugLoc &DL) {
335 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
336
337 if (!RVFI->isSiFivePreemptibleInterrupt(MF))
338 return;
339
340 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
341 const RISCVInstrInfo *TII = STI.getInstrInfo();
342
343 // FIXME: CFI information for `mcause` and `mepc` is missing.
344
345 // Load mepc while preemption is still enabled. A nested handler preserves
346 // X5. Interrupts only need to be disabled before writing the CSRs back.
347 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
348 RVFI->getInterruptCSRFrameIndex(1),
349 &RISCV::GPRRegClass, Register(),
350 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
351
352 // Disable interrupts.
353 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRCI), RISCV::X0)
354 .addImm(RISCVSysReg::mstatus)
355 .addImm(8)
357
358 // Restore `mepc` and `mcause` through X5, then restore the value X5 held
359 // on entry to the handler.
360 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), RISCV::X0)
361 .addImm(RISCVSysReg::mepc)
362 .addReg(RISCV::X5, RegState::Kill)
364
365 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
366 RVFI->getInterruptCSRFrameIndex(0),
367 &RISCV::GPRRegClass, Register(),
368 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
369 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), RISCV::X0)
370 .addImm(RISCVSysReg::mcause)
371 .addReg(RISCV::X5, RegState::Kill)
373
374 // The ordinary reloads have finished. Recover the interrupted value of X5
375 // only after it has restored both CSRs.
376 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
378 &RISCV::GPRRegClass, Register(),
379 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
380 if (needsDwarfCFI(MF))
381 CFIBuilder.buildRestore(RISCV::X5);
382}
383
384// Get the ID of the libcall used for spilling and restoring callee saved
385// registers. The ID is representative of the number of registers saved or
386// restored by the libcall, except it is zero-indexed - ID 0 corresponds to a
387// single register.
388static int getLibCallID(const MachineFunction &MF,
389 const std::vector<CalleeSavedInfo> &CSI) {
390 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
391
392 if (CSI.empty() || !RVFI->useSaveRestoreLibCalls(MF))
393 return -1;
394
395 MCRegister MaxReg;
396 for (auto &CS : CSI)
397 // assignCalleeSavedSpillSlots assigns negative frame indexes to
398 // registers which can be saved by libcall.
399 if (CS.getFrameIdx() < 0)
400 MaxReg = std::max(MaxReg.id(), CS.getReg().id());
401
402 if (!MaxReg)
403 return -1;
404
405 switch (MaxReg.id()) {
406 default:
407 llvm_unreachable("Something has gone wrong!");
408 // clang-format off
409 case /*s11*/ RISCV::X27: return 12;
410 case /*s10*/ RISCV::X26: return 11;
411 case /*s9*/ RISCV::X25: return 10;
412 case /*s8*/ RISCV::X24: return 9;
413 case /*s7*/ RISCV::X23: return 8;
414 case /*s6*/ RISCV::X22: return 7;
415 case /*s5*/ RISCV::X21: return 6;
416 case /*s4*/ RISCV::X20: return 5;
417 case /*s3*/ RISCV::X19: return 4;
418 case /*s2*/ RISCV::X18: return 3;
419 case /*s1*/ RISCV::X9: return 2;
420 case /*s0*/ FPReg: return 1;
421 case /*ra*/ RAReg: return 0;
422 // clang-format on
423 }
424}
425
426// Get the name of the libcall used for spilling callee saved registers.
427// If this function will not use save/restore libcalls, then return a nullptr.
428static const char *
430 const std::vector<CalleeSavedInfo> &CSI) {
431 static const char *const SpillLibCalls[] = {
432 "__riscv_save_0",
433 "__riscv_save_1",
434 "__riscv_save_2",
435 "__riscv_save_3",
436 "__riscv_save_4",
437 "__riscv_save_5",
438 "__riscv_save_6",
439 "__riscv_save_7",
440 "__riscv_save_8",
441 "__riscv_save_9",
442 "__riscv_save_10",
443 "__riscv_save_11",
444 "__riscv_save_12"
445 };
446
447 int LibCallID = getLibCallID(MF, CSI);
448 if (LibCallID == -1)
449 return nullptr;
450 return SpillLibCalls[LibCallID];
451}
452
453// Get the name of the libcall used for restoring callee saved registers.
454// If this function will not use save/restore libcalls, then return a nullptr.
455static const char *
457 const std::vector<CalleeSavedInfo> &CSI) {
458 static const char *const RestoreLibCalls[] = {
459 "__riscv_restore_0",
460 "__riscv_restore_1",
461 "__riscv_restore_2",
462 "__riscv_restore_3",
463 "__riscv_restore_4",
464 "__riscv_restore_5",
465 "__riscv_restore_6",
466 "__riscv_restore_7",
467 "__riscv_restore_8",
468 "__riscv_restore_9",
469 "__riscv_restore_10",
470 "__riscv_restore_11",
471 "__riscv_restore_12"
472 };
473
474 int LibCallID = getLibCallID(MF, CSI);
475 if (LibCallID == -1)
476 return nullptr;
477 return RestoreLibCalls[LibCallID];
478}
479
480// Get the max reg of Push/Pop for restoring callee saved registers.
481static unsigned getNumPushPopRegs(const std::vector<CalleeSavedInfo> &CSI) {
482 unsigned NumPushPopRegs = 0;
483 for (auto &CS : CSI) {
484 auto *FII = llvm::find_if(FixedCSRFIMap,
485 [&](MCPhysReg P) { return P == CS.getReg(); });
486 if (FII != std::end(FixedCSRFIMap)) {
487 unsigned RegNum = std::distance(std::begin(FixedCSRFIMap), FII);
488 NumPushPopRegs = std::max(NumPushPopRegs, RegNum + 1);
489 }
490 }
491 assert(NumPushPopRegs != 12 && "x26 requires x27 to also be pushed");
492 return NumPushPopRegs;
493}
494
495// Return true if the specified function should have a dedicated frame
496// pointer register. This is true if frame pointer elimination is
497// disabled, if it needs dynamic stack realignment, if the function has
498// variable sized allocas, or if the frame address is taken.
500 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
501
502 const MachineFrameInfo &MFI = MF.getFrameInfo();
503 if (MF.disableFramePointerElim() || RegInfo->hasStackRealignment(MF) ||
505 return true;
506
507 // With large callframes around we may need to use FP to access the scavenging
508 // emergency spillslot.
509 //
510 // We calculate the MaxCallFrameSize at the end of isel so this value should
511 // be stable for the whole post-isel MIR pipeline.
512 //
513 // NOTE: The idea of forcing a frame pointer is copied from AArch64, but they
514 // conservatively return true when the call frame size hasd not been
515 // computed yet. On RISC-V that caused MachineOutliner tests to fail the
516 // MachineVerifier due to outlined functions not computing max call frame
517 // size thus the frame pointer would always be reserved.
518 if (MFI.isMaxCallFrameSizeComputed() && MFI.getMaxCallFrameSize() > 2047)
519 return true;
520
521 return false;
522}
523
525 const MachineFrameInfo &MFI = MF.getFrameInfo();
526 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
527
528 // If we do not reserve stack space for outgoing arguments in prologue,
529 // we will adjust the stack pointer before call instruction. After the
530 // adjustment, we can not use SP to access the stack objects for the
531 // arguments. Instead, use BP to access these stack objects.
532 return (MFI.hasVarSizedObjects() ||
534 MFI.getMaxCallFrameSize() != 0))) &&
535 TRI->hasStackRealignment(MF);
536}
537
538// Determines the size of the frame and maximum call frame size.
539void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
540 MachineFrameInfo &MFI = MF.getFrameInfo();
541 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
542
543 // Get the number of bytes to allocate from the FrameInfo.
544 uint64_t FrameSize = MFI.getStackSize();
545
546 // QCI Interrupts use at least 96 bytes of stack space
547 if (RVFI->useQCIInterrupt(MF))
548 FrameSize = std::max(FrameSize, QCIInterruptPushAmount);
549
550 // Get the alignment.
551 Align StackAlign = getStackAlign();
552
553 // Make sure the frame is aligned.
554 FrameSize = alignTo(FrameSize, StackAlign);
555
556 // Update frame info.
557 MFI.setStackSize(FrameSize);
558
559 // When using SP or BP to access stack objects, we may require extra padding
560 // to ensure the bottom of the RVV stack is correctly aligned within the main
561 // stack. We calculate this as the amount required to align the scalar local
562 // variable section up to the RVV alignment.
564 if (RVFI->getRVVStackSize() && (!hasFP(MF) || TRI->hasStackRealignment(MF))) {
565 int ScalarLocalVarSize = FrameSize - RVFI->getCalleeSavedStackSize() -
566 RVFI->getVarArgsSaveSize();
567 if (auto RVVPadding =
568 offsetToAlignment(ScalarLocalVarSize, RVFI->getRVVStackAlign()))
569 RVFI->setRVVPadding(RVVPadding);
570 }
571}
572
573// Returns the stack size including RVV padding (when required), rounded back
574// up to the required stack alignment.
576 const MachineFunction &MF) const {
577 const MachineFrameInfo &MFI = MF.getFrameInfo();
578 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
579 return alignTo(MFI.getStackSize() + RVFI->getRVVPadding(), getStackAlign());
580}
581
584 const std::vector<CalleeSavedInfo> &CSI,
585 bool ReverseOrder = false) {
586 const MachineFrameInfo &MFI = MF.getFrameInfo();
588
589 for (auto &CS : CSI) {
590 int FI = CS.getFrameIdx();
591 // Callee saves with negative frame indices have fixed positions on the
592 // stack, usually relating to libcalls or push/pop.
593 bool IsManagedFI = (FI < 0);
594 if (!IsManagedFI && MFI.getStackID(FI) == TargetStackID::Default)
595 NonLibcallCSI.push_back(CS);
596 }
597
598 // Reverse the order so that load/store operations use ascending addresses,
599 // enabling better load/store clustering and fusion.
600 if (ReverseOrder)
601 std::reverse(NonLibcallCSI.begin(), NonLibcallCSI.end());
602
603 return NonLibcallCSI;
604}
605
606// Exclude X5 from ordinary spills and restores for SiFive CLIC preemptible
607// handlers, which save and restore it explicitly.
610 const std::vector<CalleeSavedInfo> &CSI,
611 bool ReverseOrder = false) {
612 auto InterruptCSI = getUnmanagedCSI(MF, CSI, ReverseOrder);
614 llvm::erase_if(InterruptCSI, [](const CalleeSavedInfo &CS) {
615 return CS.getReg() == RISCV::X5;
616 });
617 return InterruptCSI;
618}
619
622 const std::vector<CalleeSavedInfo> &CSI) {
623 const MachineFrameInfo &MFI = MF.getFrameInfo();
625
626 for (auto &CS : CSI) {
627 int FI = CS.getFrameIdx();
628 if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::ScalableVector)
629 RVVCSI.push_back(CS);
630 }
631
632 return RVVCSI;
633}
634
637 const std::vector<CalleeSavedInfo> &CSI) {
638 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
639
640 SmallVector<CalleeSavedInfo, 8> PushOrLibCallsCSI;
641 if (!RVFI->useSaveRestoreLibCalls(MF) && !RVFI->isPushable(MF))
642 return PushOrLibCallsCSI;
643
644 for (const auto &CS : CSI) {
645 if (RVFI->useQCIInterrupt(MF)) {
646 // Some registers are saved by both `QC.C.MIENTER(.NEST)` and
647 // `QC.CM.PUSH(FP)`. In these cases, prioritise the CFI info that points
648 // to the versions saved by `QC.C.MIENTER(.NEST)` which is what FP
649 // unwinding would use.
651 CS.getReg()))
652 continue;
653 }
654
655 if (llvm::is_contained(FixedCSRFIMap, CS.getReg()))
656 PushOrLibCallsCSI.push_back(CS);
657 }
658
659 return PushOrLibCallsCSI;
660}
661
664 const std::vector<CalleeSavedInfo> &CSI) {
665 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
666
667 SmallVector<CalleeSavedInfo, 8> QCIInterruptCSI;
668 if (!RVFI->useQCIInterrupt(MF))
669 return QCIInterruptCSI;
670
671 for (const auto &CS : CSI) {
673 CS.getReg()))
674 QCIInterruptCSI.push_back(CS);
675 }
676
677 return QCIInterruptCSI;
678}
679
681 const MachineBasicBlock &MBB) {
682 const MachineFunction *MF = MBB.getParent();
683 LiveRegs.addLiveIns(MBB);
684 const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
685 for (unsigned i = 0; CSRegs[i]; ++i)
686 LiveRegs.addReg(CSRegs[i]);
687}
688
690 MachineBasicBlock *MBB, Register PreferredReg, Register DontUseReg) const {
691 MachineFunction *MF = MBB->getParent();
692
693 // Stack protection code is being inserted at beginning of function, use
694 // register which has been historically used
695 if (&MF->front() == MBB)
696 return PreferredReg;
697
699 const TargetRegisterInfo &TRI = *Subtarget.getRegisterInfo();
702
703 const MachineRegisterInfo &MRI = MF->getRegInfo();
704 // Prefer the register which has been historically used for stack protector
705 if (LiveRegs.available(MRI, PreferredReg))
706 return PreferredReg;
707
708 static const MCPhysReg CandidateRegs[] = {
709 RISCV::X5, RISCV::X6, RISCV::X7, RISCV::X28,
710 RISCV::X29, RISCV::X30, RISCV::X31,
711 };
712
713 for (unsigned Reg : CandidateRegs) {
714 if (Reg != DontUseReg && LiveRegs.available(MRI, Reg))
715 return Reg;
716 }
717
718 return Register();
719}
720
721void RISCVFrameLowering::allocateAndProbeStackForRVV(
723 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, int64_t Amount,
724 MachineInstr::MIFlag Flag, bool EmitCFI) const {
725 assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
726
727 // Emit a variable-length allocation probing loop.
728
729 // Get VLEN in TargetReg
730 Register TargetReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
731 assert(TargetReg.isValid() &&
732 "No available scratch register for stack probing");
734 uint32_t NumOfVReg = Amount / RISCV::RVVBytesPerBlock;
735 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PseudoReadVLENB), TargetReg)
736 .setMIFlag(Flag);
737 TII->mulImm(MF, MBB, MBBI, DL, TargetReg, NumOfVReg, Flag);
738
740 if (EmitCFI) {
741 // Set the CFA register to TargetReg.
742 CFIBuilder.buildDefCFA(TargetReg, -Amount);
743 }
744
745 // It will be expanded to a probe loop in `inlineStackProbe`.
746 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC_RVV))
747 .addReg(TargetReg);
748
749 if (EmitCFI) {
750 // Set the CFA register back to SP.
751 CFIBuilder.buildDefCFARegister(SPReg);
752 }
753
754 // SUB SP, SP, T1
755 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SUB), SPReg)
756 .addReg(SPReg)
757 .addReg(TargetReg)
758 .setMIFlag(Flag);
759}
760
764 llvm::raw_string_ostream &Comment) {
765 int64_t FixedOffset = Offset.getFixed();
766 int64_t ScalableOffset = Offset.getScalable();
767 unsigned DwarfVLenB = TRI.getDwarfRegNum(RISCV::VLENB, true);
768 if (FixedOffset) {
769 Expr.push_back(dwarf::DW_OP_consts);
770 appendLEB128<LEB128Sign::Signed>(Expr, FixedOffset);
771 Expr.push_back((uint8_t)dwarf::DW_OP_plus);
772 Comment << (FixedOffset < 0 ? " - " : " + ") << std::abs(FixedOffset);
773 }
774
775 Expr.push_back((uint8_t)dwarf::DW_OP_consts);
776 appendLEB128<LEB128Sign::Signed>(Expr, ScalableOffset);
777
778 Expr.push_back((uint8_t)dwarf::DW_OP_bregx);
779 appendLEB128<LEB128Sign::Unsigned>(Expr, DwarfVLenB);
780 Expr.push_back(0);
781
782 Expr.push_back((uint8_t)dwarf::DW_OP_mul);
783 Expr.push_back((uint8_t)dwarf::DW_OP_plus);
784
785 Comment << (ScalableOffset < 0 ? " - " : " + ") << std::abs(ScalableOffset)
786 << " * vlenb";
787}
788
792 assert(Offset.getScalable() != 0 && "Did not need to adjust CFA for RVV");
793 SmallString<64> Expr;
794 std::string CommentBuffer;
795 llvm::raw_string_ostream Comment(CommentBuffer);
796 // Build up the expression (Reg + FixedOffset + ScalableOffset * VLENB).
797 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
798 Expr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
799 Expr.push_back(0);
800 if (Reg == SPReg)
801 Comment << "sp";
802 else
803 Comment << printReg(Reg, &TRI);
804
806
807 SmallString<64> DefCfaExpr;
808 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
809 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
810 DefCfaExpr.append(Expr.str());
811
812 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
813 Comment.str());
814}
815
818 assert(Offset.getScalable() != 0 && "Did not need to adjust CFA for RVV");
819 SmallString<64> Expr;
820 std::string CommentBuffer;
821 llvm::raw_string_ostream Comment(CommentBuffer);
822 Comment << printReg(Reg, &TRI) << " @ cfa";
823
824 // Build up the expression (FixedOffset + ScalableOffset * VLENB).
826
827 SmallString<64> DefCfaExpr;
828 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
829 DefCfaExpr.push_back(dwarf::DW_CFA_expression);
830 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, DwarfReg);
831 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
832 DefCfaExpr.append(Expr.str());
833
834 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
835 Comment.str());
836}
837
838// Allocate stack space and probe it if necessary. When probing, the new SP is
839// probed if the bytes this allocation leaves unprobed, plus FollowupSize (what
840// later code may allocate before it probes), are more than
841// StackProbeMaxUnprobedStack. With SpillsToSP, a register spilled to 0(sp)
842// right after this allocation probes the new SP instead.
845 MachineFunction &MF, uint64_t Offset,
846 uint64_t RealStackSize, bool EmitCFI,
847 bool NeedProbe, uint64_t ProbeSize,
848 uint64_t FollowupSize, bool SpillsToSP,
849 MachineInstr::MIFlag Flag) const {
850 DebugLoc DL;
851 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
852 const RISCVInstrInfo *TII = STI.getInstrInfo();
853 bool IsRV64 = STI.is64Bit();
855 auto NeedsSPProbe = [&](uint64_t Unprobed) {
856 return NeedProbe && !SpillsToSP && Unprobed != 0 &&
857 Unprobed + FollowupSize > StackProbeMaxUnprobedStack;
858 };
859
860 // Simply allocate the stack if it's not big enough to require a probe loop.
861 if (!NeedProbe || Offset <= ProbeSize) {
863 Flag, getStackAlign());
864
865 if (EmitCFI)
866 CFIBuilder.buildDefCFAOffset(RealStackSize);
867
868 if (NeedsSPProbe(Offset)) {
869 // s[d|w] zero, 0(sp)
870 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
871 .addReg(RISCV::X0)
872 .addReg(SPReg)
873 .addImm(0)
874 .setMIFlags(Flag);
875 }
876
877 return;
878 }
879
880 // The amount of stack that was already allocated before this allocation.
881 uint64_t CFAAdjust = RealStackSize - Offset;
882
883 // Unroll the probe loop depending on the number of iterations.
884 if (Offset < ProbeSize * 5) {
885 uint64_t CurrentOffset = 0;
886 while (CurrentOffset + ProbeSize <= Offset) {
887 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
888 StackOffset::getFixed(-ProbeSize), Flag, getStackAlign());
889 // s[d|w] zero, 0(sp)
890 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
891 .addReg(RISCV::X0)
892 .addReg(SPReg)
893 .addImm(0)
894 .setMIFlags(Flag);
895
896 CurrentOffset += ProbeSize;
897 if (EmitCFI)
898 CFIBuilder.buildDefCFAOffset(CurrentOffset + CFAAdjust);
899 }
900
901 uint64_t Residual = Offset - CurrentOffset;
902 if (Residual) {
903 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
904 StackOffset::getFixed(-Residual), Flag, getStackAlign());
905 if (EmitCFI)
906 CFIBuilder.buildDefCFAOffset(RealStackSize);
907
908 if (NeedsSPProbe(Residual)) {
909 // s[d|w] zero, 0(sp)
910 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
911 .addReg(RISCV::X0)
912 .addReg(SPReg)
913 .addImm(0)
914 .setMIFlags(Flag);
915 }
916 }
917
918 return;
919 }
920
921 // Emit a variable-length allocation probing loop.
922 uint64_t RoundedSize = alignDown(Offset, ProbeSize);
923 uint64_t Residual = Offset - RoundedSize;
924
925 Register TargetReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
926 assert(TargetReg.isValid() &&
927 "No available scratch register for stack probing");
928 // SUB TargetReg, SP, RoundedSize
929 RI->adjustReg(MBB, MBBI, DL, TargetReg, SPReg,
930 StackOffset::getFixed(-RoundedSize), Flag, getStackAlign());
931
932 if (EmitCFI) {
933 // Set the CFA register to TargetReg.
934 CFIBuilder.buildDefCFA(TargetReg, RoundedSize + CFAAdjust);
935 }
936
937 // It will be expanded to a probe loop in `inlineStackProbe`.
938 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC)).addReg(TargetReg);
939
940 if (EmitCFI) {
941 // Set the CFA register back to SP.
942 CFIBuilder.buildDefCFARegister(SPReg);
943 }
944
945 if (Residual)
947 Flag, getStackAlign());
948
949 if (EmitCFI)
950 CFIBuilder.buildDefCFAOffset(RealStackSize);
951
952 if (NeedsSPProbe(Residual)) {
953 // s[d|w] zero, 0(sp)
954 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
955 .addReg(RISCV::X0)
956 .addReg(SPReg)
957 .addImm(0)
958 .setMIFlags(Flag);
959 }
960}
961
962static bool isPush(unsigned Opcode) {
963 switch (Opcode) {
964 case RISCV::CM_PUSH:
965 case RISCV::QC_CM_PUSH:
966 case RISCV::QC_CM_PUSHFP:
967 return true;
968 default:
969 return false;
970 }
971}
972
973static bool isPop(unsigned Opcode) {
974 // There are other pops but these are the only ones introduced during this
975 // pass.
976 switch (Opcode) {
977 case RISCV::CM_POP:
978 case RISCV::QC_CM_POP:
979 return true;
980 default:
981 return false;
982 }
983}
984
986 bool UpdateFP) {
987 switch (Kind) {
989 return RISCV::CM_PUSH;
991 return UpdateFP ? RISCV::QC_CM_PUSHFP : RISCV::QC_CM_PUSH;
992 default:
993 llvm_unreachable("Unhandled PushPopKind");
994 }
995}
996
998 // There are other pops but they are introduced later by the Push/Pop
999 // Optimizer.
1000 switch (Kind) {
1002 return RISCV::CM_POP;
1004 return RISCV::QC_CM_POP;
1005 default:
1006 llvm_unreachable("Unhandled PushPopKind");
1007 }
1008}
1009
1011 MachineBasicBlock &MBB) const {
1012 MachineFrameInfo &MFI = MF.getFrameInfo();
1013 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1014 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1016 bool PreferAscendingLS = STI.preferAscendingLoadStore();
1017
1018 Register BPReg = RISCVABI::getBPReg();
1019
1020 // Debug location must be unknown since the first debug location is used
1021 // to determine the end of the prologue.
1022 DebugLoc DL;
1023
1024 // All calls are tail calls in GHC calling conv, and functions have no
1025 // prologue/epilogue.
1027 return;
1028
1029 // SiFive CLIC needs to swap `sp` into `sf.mscratchcsw`
1031
1032 // Emit prologue for shadow call stack.
1033 emitSCSPrologue(MF, MBB, MBBI, DL);
1034
1035 // We keep track of the first instruction because it might be a
1036 // `(QC.)CM.PUSH(FP)`, and we may need to adjust the immediate rather than
1037 // inserting an `addi sp, sp, -N*16`
1038 auto PossiblePush = MBBI;
1039
1040 // Skip past all callee-saved register spill instructions.
1041 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
1042 ++MBBI;
1043
1044 // Determine the correct frame layout
1045 determineFrameLayout(MF);
1046
1047 const auto &CSI = MFI.getCalleeSavedInfo();
1048
1049 // Skip to before the spills of scalar callee-saved registers
1050 // FIXME: assumes exactly one instruction is used to restore each
1051 // callee-saved register.
1052 MBBI = std::prev(
1053 MBBI, getRVVCalleeSavedInfo(MF, CSI).size() +
1054 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1056 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1057
1058 if (unsigned LibCallFrameSize = RVFI->getLibCallStackSize()) {
1059 if (NeedsDwarfCFI) {
1060 CFIBuilder.buildDefCFAOffset(LibCallFrameSize);
1061 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1062 CFIBuilder.buildOffset(CS.getReg(),
1063 MFI.getObjectOffset(CS.getFrameIdx()));
1064 }
1065 }
1066
1067 // FIXME (note copied from Lanai): This appears to be overallocating. Needs
1068 // investigation. Get the number of bytes to allocate from the FrameInfo.
1069 uint64_t RealStackSize = getStackSizeWithRVVPadding(MF);
1070 uint64_t StackSize = RealStackSize - RVFI->getReservedSpillsSize();
1071 uint64_t RVVStackSize = RVFI->getRVVStackSize();
1072
1073 // Early exit if there is no need to allocate on the stack
1074 if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
1075 return;
1076
1077 // If the stack pointer has been marked as reserved, then produce an error if
1078 // the frame requires stack allocation
1079 if (STI.isRegisterReservedByUser(SPReg))
1081 MF.getFunction(), "Stack pointer required, but has been reserved."});
1082
1083 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1084 // Split the SP adjustment to reduce the offsets of callee saved spill.
1085 if (FirstSPAdjustAmount) {
1086 StackSize = FirstSPAdjustAmount;
1087 RealStackSize = FirstSPAdjustAmount;
1088 }
1089
1090 if (RVFI->useQCIInterrupt(MF)) {
1091 // The function starts with `QC.C.MIENTER(.NEST)`, so the `(QC.)CM.PUSH(FP)`
1092 // could only be the next instruction.
1093 ++PossiblePush;
1094
1095 if (NeedsDwarfCFI) {
1096 // Insert the CFI metadata before where we think the `(QC.)CM.PUSH(FP)`
1097 // could be. The PUSH will also get its own CFI metadata for its own
1098 // modifications, which should come after the PUSH.
1099 CFIInstBuilder PushCFIBuilder(MBB, PossiblePush,
1102 for (const CalleeSavedInfo &CS : getQCISavedInfo(MF, CSI))
1103 PushCFIBuilder.buildOffset(CS.getReg(),
1104 MFI.getObjectOffset(CS.getFrameIdx()));
1105 }
1106 }
1107
1108 if (RVFI->isPushable(MF) && PossiblePush != MBB.end() &&
1109 isPush(PossiblePush->getOpcode())) {
1110 // Use available stack adjustment in push instruction to allocate additional
1111 // stack space. Align the stack size down to a multiple of 16. This is
1112 // needed for RVE.
1113 // FIXME: Can we increase the stack size to a multiple of 16 instead?
1114 uint64_t StackAdj =
1115 std::min(alignDown(StackSize, 16), static_cast<uint64_t>(48));
1116 PossiblePush->getOperand(1).setImm(StackAdj);
1117 StackSize -= StackAdj;
1118
1119 if (NeedsDwarfCFI) {
1120 CFIBuilder.buildDefCFAOffset(RealStackSize - StackSize);
1121 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1122 CFIBuilder.buildOffset(CS.getReg(),
1123 MFI.getObjectOffset(CS.getFrameIdx()));
1124 }
1125 }
1126
1127 // Allocate space on the stack if necessary.
1129 const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
1130 bool NeedProbe = TLI->hasInlineStackProbe(MF);
1131 uint64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
1132 // With inline stack probing, at most StackProbeMaxUnprobedStack bytes above
1133 // SP may be left unprobed at a call, and a probing loop starts from a probed
1134 // SP. Each allocation is given what may follow it before the next probe;
1135 // FromProbedSP, over the limit, makes it probe the new SP.
1136 constexpr uint64_t FromProbedSP = StackProbeMaxUnprobedStack + 1;
1137 // Call frames that are not reserved are probed when larger than
1138 // StackProbeMaxUnprobedStack, and dynamic allocations always are.
1139 uint64_t BodyAllocSize = 0;
1140 if (RVFI->hasDynamicAllocation())
1141 BodyAllocSize = FromProbedSP;
1142 else if (!hasReservedCallFrame(MF))
1143 BodyAllocSize = MFI.isMaxCallFrameSizeComputed()
1145 : FromProbedSP;
1146 // Realigning SP moves it down by up to RealignPadding bytes, with a probing
1147 // loop if that may be the probe size or more. The realigned SP is probed
1148 // after a loop, or if RealignPadding + BodyAllocSize is over the limit.
1149 bool RealignStack = RI->hasStackRealignment(MF);
1150 uint64_t RealignPadding =
1151 RealignStack && MFI.getMaxAlign() > getStackAlign()
1152 ? MFI.getMaxAlign().value() - getStackAlign().value()
1153 : 0;
1154 bool ProbeRealignLoop = NeedProbe && RealignPadding >= ProbeSize;
1155 bool ProbeRealignedSP = NeedProbe && RealignStack &&
1156 (ProbeRealignLoop || RealignPadding + BodyAllocSize >
1158 // What follows the fixed-size allocations: the RVV area and a realignment
1159 // loop start from a probed SP; otherwise the realignment, if any, and the
1160 // function body, unless the realigned SP is probed.
1161 uint64_t FollowupSize =
1162 RealignPadding + (ProbeRealignedSP ? 0 : BodyAllocSize);
1163 if (RVVStackSize || ProbeRealignLoop)
1164 FollowupSize = FromProbedSP;
1165 if (StackSize != 0) {
1166 // A callee-saved register spilled to 0(sp) probes the new SP, before any
1167 // later allocation or call.
1168 bool SpillsToSP =
1169 NeedProbe &&
1171 getUnmanagedInterruptCSI(MF, CSI), [&](const CalleeSavedInfo &CS) {
1172 Register FrameReg;
1174 getFrameIndexReference(MF, CS.getFrameIdx(), FrameReg);
1175 return FrameReg == SPReg && !Offset.getScalable() &&
1176 Offset.getFixed() == 0;
1177 });
1178 // A second SP adjustment starts from a probed SP.
1179 allocateStack(MBB, MBBI, MF, StackSize, RealStackSize, NeedsDwarfCFI,
1180 NeedProbe, ProbeSize,
1181 FirstSPAdjustAmount ? FromProbedSP : FollowupSize, SpillsToSP,
1183 }
1184
1185 // Save SiFive CLIC CSRs into Stack
1187
1188 // The frame pointer is callee-saved, and code has been generated for us to
1189 // save it to the stack. We need to skip over the storing of callee-saved
1190 // registers as the frame pointer must be modified after it has been saved
1191 // to the stack, not before.
1192 // FIXME: assumes exactly one instruction is used to save each callee-saved
1193 // register.
1194 std::advance(MBBI,
1195 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1196 CFIBuilder.setInsertPoint(MBBI);
1197
1198 // Iterate over list of callee-saved registers and emit .cfi_offset
1199 // directives.
1200 if (NeedsDwarfCFI) {
1201 for (const CalleeSavedInfo &CS :
1202 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS)) {
1203 MCRegister Reg = CS.getReg();
1204 int64_t Offset = MFI.getObjectOffset(CS.getFrameIdx());
1205 // Emit CFI for both sub-registers. The even register is at the base
1206 // offset and odd at base+4.
1207 if (RISCV::GPRPairRegClass.contains(Reg)) {
1208 MCRegister EvenReg = RI->getSubReg(Reg, RISCV::sub_gpr_even);
1209 MCRegister OddReg = RI->getSubReg(Reg, RISCV::sub_gpr_odd);
1210 CFIBuilder.buildOffset(EvenReg, Offset);
1211 CFIBuilder.buildOffset(OddReg, Offset + 4);
1212 } else {
1213 CFIBuilder.buildOffset(Reg, Offset);
1214 }
1215 }
1216 }
1217
1218 // Generate new FP.
1219 if (hasFP(MF)) {
1220 if (STI.isRegisterReservedByUser(FPReg))
1222 MF.getFunction(), "Frame pointer required, but has been reserved."});
1223 // The frame pointer does need to be reserved from register allocation.
1224 assert(MF.getRegInfo().isReserved(FPReg) && "FP not reserved");
1225
1226 // Some stack management variants automatically keep FP updated, so we don't
1227 // need an instruction to do so.
1228 if (!RVFI->hasImplicitFPUpdates(MF)) {
1229 RI->adjustReg(
1230 MBB, MBBI, DL, FPReg, SPReg,
1231 StackOffset::getFixed(RealStackSize - RVFI->getVarArgsSaveSize()),
1233 }
1234
1235 if (NeedsDwarfCFI)
1236 CFIBuilder.buildDefCFA(FPReg, RVFI->getVarArgsSaveSize());
1237 }
1238
1239 uint64_t SecondSPAdjustAmount = 0;
1240 // Emit the second SP adjustment after saving callee saved registers.
1241 if (FirstSPAdjustAmount) {
1242 SecondSPAdjustAmount = getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
1243 assert(SecondSPAdjustAmount > 0 &&
1244 "SecondSPAdjustAmount should be greater than zero");
1245
1246 // The first SP adjustment left SP probed.
1247 allocateStack(MBB, MBBI, MF, SecondSPAdjustAmount,
1248 getStackSizeWithRVVPadding(MF), NeedsDwarfCFI && !hasFP(MF),
1249 NeedProbe, ProbeSize, FollowupSize, /*SpillsToSP=*/false,
1251 }
1252
1253 if (RVVStackSize) {
1254 if (NeedProbe) {
1255 allocateAndProbeStackForRVV(MF, MBB, MBBI, DL, RVVStackSize,
1257 NeedsDwarfCFI && !hasFP(MF));
1258 } else {
1259 // We must keep the stack pointer aligned through any intermediate
1260 // updates.
1261 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
1262 StackOffset::getScalable(-RVVStackSize),
1264 }
1265
1266 if (NeedsDwarfCFI && !hasFP(MF)) {
1267 // Emit .cfi_def_cfa_expression "sp + StackSize + RVVStackSize * vlenb".
1269 *RI, SPReg,
1270 StackOffset::get(getStackSizeWithRVVPadding(MF), RVVStackSize / 8)));
1271 }
1272
1273 if (NeedProbe) {
1274 // The probing loop leaves a residual of up to ProbeSize - 1 bytes, whose
1275 // size is not known at compile time: probe it.
1276 const RISCVInstrInfo *TII = STI.getInstrInfo();
1277 BuildMI(MBB, MBBI, DL, TII->get(STI.is64Bit() ? RISCV::SD : RISCV::SW))
1278 .addReg(RISCV::X0)
1279 .addReg(SPReg)
1280 .addImm(0)
1282 }
1283
1284 std::advance(MBBI, getRVVCalleeSavedInfo(MF, CSI).size());
1285 if (NeedsDwarfCFI)
1286 emitCalleeSavedRVVPrologCFI(MBB, MBBI, hasFP(MF));
1287 }
1288
1289 if (hasFP(MF)) {
1290 // Realign Stack
1291 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1292 if (RI->hasStackRealignment(MF)) {
1293 Align MaxAlignment = MFI.getMaxAlign();
1294
1295 const RISCVInstrInfo *TII = STI.getInstrInfo();
1296 if (ProbeRealignLoop) {
1297 // Realigning may move SP down by more than the probe size. Compute
1298 // that amount (SP modulo MaxAlignment) and allocate it with the
1299 // probing loop used for the RVV area.
1300 Register AmountReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
1301 assert(AmountReg.isValid() &&
1302 "No available scratch register for stack probing");
1303 unsigned ShiftAmount = STI.getXLen() - Log2(MaxAlignment);
1304 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), AmountReg)
1305 .addReg(SPReg)
1306 .addImm(ShiftAmount)
1308 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), AmountReg)
1309 .addReg(AmountReg)
1310 .addImm(ShiftAmount)
1312 // It will be expanded to a probe loop in `inlineStackProbe`.
1313 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC_RVV))
1314 .addReg(AmountReg);
1315 // SUB SP, SP, AmountReg
1316 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SUB), SPReg)
1317 .addReg(SPReg)
1318 .addReg(AmountReg)
1320 } else if (isInt<12>(-(int64_t)MaxAlignment.value())) {
1321 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
1322 .addReg(SPReg)
1323 .addImm(-(int64_t)MaxAlignment.value())
1325 } else {
1326 unsigned ShiftAmount = Log2(MaxAlignment);
1327 Register VR =
1328 MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
1329 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
1330 .addReg(SPReg)
1331 .addImm(ShiftAmount)
1333 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
1334 .addReg(VR)
1335 .addImm(ShiftAmount)
1337 }
1338 if (ProbeRealignedSP) {
1339 bool IsRV64 = STI.is64Bit();
1340 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
1341 .addReg(RISCV::X0)
1342 .addReg(SPReg)
1343 .addImm(0)
1345 }
1346 // FP will be used to restore the frame in the epilogue, so we need
1347 // another base register BP to record SP after re-alignment. SP will
1348 // track the current stack after allocating variable sized objects.
1349 if (hasBP(MF)) {
1350 // move BP, SP
1351 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
1352 .addReg(SPReg)
1353 .addImm(0)
1355 }
1356 }
1357 }
1358}
1359
1360void RISCVFrameLowering::deallocateStack(MachineFunction &MF,
1363 const DebugLoc &DL,
1364 uint64_t &StackSize,
1365 int64_t CFAOffset) const {
1367
1368 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackOffset::getFixed(StackSize),
1370 StackSize = 0;
1371
1372 if (needsDwarfCFI(MF))
1374 .buildDefCFAOffset(CFAOffset);
1375}
1376
1378 MachineBasicBlock &MBB) const {
1379 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1380 MachineFrameInfo &MFI = MF.getFrameInfo();
1381 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1382 bool PreferAscendingLS = STI.preferAscendingLoadStore();
1383
1384 // All calls are tail calls in GHC calling conv, and functions have no
1385 // prologue/epilogue.
1387 return;
1388
1389 // Get the insert location for the epilogue. If there were no terminators in
1390 // the block, get the last instruction.
1392 DebugLoc DL;
1393 if (!MBB.empty()) {
1394 MBBI = MBB.getLastNonDebugInstr();
1395 if (MBBI != MBB.end())
1396 DL = MBBI->getDebugLoc();
1397
1398 MBBI = MBB.getFirstTerminator();
1399
1400 // Skip to before the restores of all callee-saved registers.
1401 while (MBBI != MBB.begin() &&
1402 std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
1403 --MBBI;
1404 }
1405
1406 const auto &CSI = MFI.getCalleeSavedInfo();
1407
1408 // Skip to before the restores of scalar callee-saved registers
1409 // FIXME: assumes exactly one instruction is used to restore each
1410 // callee-saved register.
1411 auto FirstScalarCSRRestoreInsn =
1412 std::next(MBBI, getRVVCalleeSavedInfo(MF, CSI).size());
1413 CFIInstBuilder CFIBuilder(MBB, FirstScalarCSRRestoreInsn,
1415 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1416
1417 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1418 uint64_t RealStackSize = FirstSPAdjustAmount ? FirstSPAdjustAmount
1420 uint64_t StackSize = FirstSPAdjustAmount ? FirstSPAdjustAmount
1422 RVFI->getReservedSpillsSize();
1423 uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
1424 uint64_t RVVStackSize = RVFI->getRVVStackSize();
1425
1426 // An unreserved call frame moves SP only around calls that pass arguments
1427 // on the stack. Otherwise SP is where the prologue left it, and the FP
1428 // restore is worth keeping only where it replaces the multi-instruction
1429 // undo of an RVV area or a split SP adjustment.
1430 bool CallFrameMovesSP =
1431 !hasReservedCallFrame(MF) &&
1432 (!MFI.isMaxCallFrameSizeComputed() || MFI.getMaxCallFrameSize() != 0);
1433 bool RestoreSPFromFP =
1434 RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
1435 CallFrameMovesSP ||
1436 (!hasReservedCallFrame(MF) && (RVVStackSize || FirstSPAdjustAmount));
1437 if (RVVStackSize) {
1438 // If RestoreSPFromFP the stack pointer will be restored using the frame
1439 // pointer value.
1440 if (!RestoreSPFromFP)
1441 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, SPReg,
1442 StackOffset::getScalable(RVVStackSize),
1444
1445 if (NeedsDwarfCFI) {
1446 if (!hasFP(MF))
1447 CFIBuilder.buildDefCFA(SPReg, RealStackSize);
1448 emitCalleeSavedRVVEpilogCFI(MBB, FirstScalarCSRRestoreInsn);
1449 }
1450 }
1451
1452 if (FirstSPAdjustAmount) {
1453 uint64_t SecondSPAdjustAmount =
1454 getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
1455 assert(SecondSPAdjustAmount > 0 &&
1456 "SecondSPAdjustAmount should be greater than zero");
1457
1458 // If RestoreSPFromFP the stack pointer will be restored using the frame
1459 // pointer value.
1460 if (!RestoreSPFromFP)
1461 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, SPReg,
1462 StackOffset::getFixed(SecondSPAdjustAmount),
1464
1465 if (NeedsDwarfCFI && !hasFP(MF))
1466 CFIBuilder.buildDefCFAOffset(FirstSPAdjustAmount);
1467 }
1468
1469 // Restore the stack pointer using the value of the frame pointer. Only
1470 // necessary if the stack pointer was modified, meaning the stack size is
1471 // unknown.
1472 //
1473 // In order to make sure the stack point is right through the EH region,
1474 // we also need to restore stack pointer from the frame pointer if we
1475 // don't preserve stack space within prologue/epilogue for outgoing variables,
1476 // normally it's just checking the variable sized object is present or not
1477 // is enough, but we also don't preserve that at prologue/epilogue when
1478 // have vector objects in stack.
1479 if (RestoreSPFromFP) {
1480 assert(hasFP(MF) && "frame pointer should not have been eliminated");
1481 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, FPReg,
1483 getStackAlign());
1484 }
1485
1486 if (NeedsDwarfCFI && hasFP(MF))
1487 CFIBuilder.buildDefCFA(SPReg, RealStackSize);
1488
1489 // Skip to after the restores of scalar callee-saved registers
1490 // FIXME: assumes exactly one instruction is used to restore each
1491 // callee-saved register.
1492 MBBI = std::next(FirstScalarCSRRestoreInsn,
1493 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1494 CFIBuilder.setInsertPoint(MBBI);
1495 emitSiFiveCLICPreemptibleRestores(MF, MBB, MBBI, CFIBuilder, DL);
1496
1497 auto emitRestoreCFI = [&](auto CSInfo) {
1498 for (auto &CS : CSInfo) {
1499 MCRegister Reg = CS.getReg();
1500 // Emit CFI for both sub-registers.
1501 if (RISCV::GPRPairRegClass.contains(Reg)) {
1502 MCRegister EvenReg = RI->getSubReg(Reg, RISCV::sub_gpr_even);
1503 MCRegister OddReg = RI->getSubReg(Reg, RISCV::sub_gpr_odd);
1504 CFIBuilder.buildRestore(EvenReg);
1505 CFIBuilder.buildRestore(OddReg);
1506 } else {
1507 CFIBuilder.buildRestore(Reg);
1508 }
1509 }
1510 };
1511
1512 if (RVFI->useSaveRestoreLibCalls(MF)) {
1513 if (RVFI->hasShadowStack(MF)) {
1514 // We don't use `__riscv_restore_<N>` to restore in this case, so we need
1515 // to make sure we're correctly accounting for the stack deallocation we
1516 // need to do, which now must include the allocation made by
1517 // `__riscv_save_<N>`.
1518 StackSize += RVFI->getLibCallStackSize();
1519
1522 MBBI = std::next(MBBI, LibcallCSI.size());
1523 CFIBuilder.setInsertPoint(MBBI);
1524
1525 if (NeedsDwarfCFI)
1526 emitRestoreCFI(LibcallCSI);
1527 } else {
1528 // tail __riscv_restore_[0-12] instruction is considered as a terminator,
1529 // therefore it is unnecessary to place any CFI instructions after it.
1530 // Just deallocate stack if needed and return.
1531 if (StackSize != 0)
1532 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1533 RVFI->getLibCallStackSize());
1534
1535 // Emit epilogue for shadow call stack.
1536 emitSCSEpilogue(MF, MBB, MBBI, DL);
1537 return;
1538 }
1539 }
1540
1541 // Recover callee-saved registers.
1542 if (NeedsDwarfCFI)
1543 emitRestoreCFI(getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS));
1544
1545 if (RVFI->isPushable(MF) && MBBI != MBB.end() && isPop(MBBI->getOpcode())) {
1546 // Use available stack adjustment in pop instruction to deallocate stack
1547 // space. Align the stack size down to a multiple of 16. This is needed for
1548 // RVE.
1549 // FIXME: Can we increase the stack size to a multiple of 16 instead?
1550 uint64_t StackAdj =
1551 std::min(alignDown(StackSize, 16), static_cast<uint64_t>(48));
1552 MBBI->getOperand(1).setImm(StackAdj);
1553 StackSize -= StackAdj;
1554
1555 if (StackSize != 0)
1556 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1557 /*stack_adj of cm.pop instr*/ RealStackSize - StackSize);
1558
1559 auto NextI = next_nodbg(MBBI, MBB.end());
1560 if (NextI == MBB.end() || NextI->getOpcode() != RISCV::PseudoRET) {
1561 ++MBBI;
1562 if (NeedsDwarfCFI) {
1563 CFIBuilder.setInsertPoint(MBBI);
1564
1565 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1566 CFIBuilder.buildRestore(CS.getReg());
1567
1568 // Update CFA Offset. If this is a QCI interrupt function, there will
1569 // be a leftover offset which is deallocated by `QC.C.MILEAVERET`,
1570 // otherwise getQCIInterruptStackSize() will be 0.
1571 CFIBuilder.buildDefCFAOffset(RVFI->getQCIInterruptStackSize());
1572 }
1573 }
1574 }
1575
1576 // Deallocate stack if StackSize isn't a zero yet. If this is a QCI interrupt
1577 // function, there will be a leftover offset which is deallocated by
1578 // `QC.C.MILEAVERET`, otherwise getQCIInterruptStackSize() will be 0.
1579 if (StackSize != 0)
1580 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1581 RVFI->getQCIInterruptStackSize());
1582
1583 // Emit epilogue for shadow call stack.
1584 emitSCSEpilogue(MF, MBB, MBBI, DL);
1585
1586 // SiFive CLIC needs to swap `sf.mscratchcsw` into `sp`
1588}
1589
1591 MCRegister Reg) {
1592 if (RISCV::GPRRegClass.contains(Reg))
1593 return Reg;
1594
1595 std::array<TargetRegisterClass const *, 2> RegisterClasses = {
1596 &RISCV::GPRF16RegClass, &RISCV::GPRF32RegClass};
1597 std::array<unsigned, 2> SubIdx = {RISCV::sub_16, RISCV::sub_32};
1598
1599 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1600 if (RegClass->contains(Reg)) {
1601 if (MCRegister Super =
1602 TRI.getMatchingSuperReg(Reg, SubReg, &RISCV::GPRRegClass))
1603 return Super;
1604 }
1605 }
1606
1608 "getPhysicalGPR called with unsupported register");
1609}
1610
1612 const TargetRegisterInfo &TRI,
1613 MCRegister Reg) {
1614 if (!STI.hasStdExtF())
1615 return MCRegister();
1616
1617 TargetRegisterClass const *LargestFPRegClass = STI.getLargestFPRegClass();
1618 assert(LargestFPRegClass);
1619
1620 if (LargestFPRegClass->contains(Reg))
1621 return Reg;
1622
1623 std::array<TargetRegisterClass const *, 3> RegisterClasses = {
1624 &RISCV::FPR16RegClass, &RISCV::FPR32RegClass, &RISCV::FPR64RegClass};
1625 std::array<unsigned, 3> SubIdx = {RISCV::sub_16, RISCV::sub_32,
1626 RISCV::sub_64};
1627
1628 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1629 if (RegClass->contains(Reg)) {
1630 if (MCRegister Super =
1631 TRI.getMatchingSuperReg(Reg, SubReg, LargestFPRegClass))
1632 return Super;
1633 }
1634 }
1635
1636 // Reg is bigger than what's currently available for the target, we can ignore
1637 // it.
1638 return MCRegister();
1639}
1640
1641void RISCVFrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
1643 RegScavenger *RS) const {
1644 // Insertion point.
1646
1647 // Fake a debug loc.
1648 DebugLoc DL;
1649 if (MBBI != MBB.end())
1650 DL = MBBI->getDebugLoc();
1651
1652 const MachineFunction &MF = *MBB.getParent();
1653 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
1654 const RISCVInstrInfo &TII = *STI.getInstrInfo();
1655
1656 BitVector FinalRegsToZero(TRI.getNumRegs());
1657
1658 bool HasVRegister = false;
1659
1660 for (MCRegister Reg : RegsToZero.set_bits()) {
1661 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1662 FinalRegsToZero.set(getPhysicalGPR(TRI, Reg).id());
1663 } else if (RISCV::GPRPairRegClass.contains(Reg)) {
1664 FinalRegsToZero.set(
1665 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_even)).id());
1666 FinalRegsToZero.set(
1667 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_odd)).id());
1668 } else if (TRI.isFPRegister(Reg)) {
1669 if (MCRegister MaybeReg = getLargestFPRegisterOrZero(STI, TRI, Reg))
1670 FinalRegsToZero.set(MaybeReg.id());
1672 TRI.getMinimalPhysRegClass(Reg))) {
1673 if (!STI.hasVInstructions())
1674 continue;
1675 HasVRegister = true;
1676
1677 for (MCRegister SubReg : TRI.subregs_inclusive(Reg)) {
1678 if (TRI.subregs(SubReg).empty())
1679 FinalRegsToZero.set(SubReg.id());
1680 }
1681 }
1682 }
1683
1684 if (HasVRegister) {
1685 RISCVVType::VLMUL VLMUL = RISCVVType::encodeLMUL(1, /*Fractional=*/false);
1686 unsigned VTypeImm = RISCVVType::encodeVTYPE(
1687 VLMUL, /*SEW=*/32, /*TailAgnostic=*/true, /*MaskAgnostic=*/true);
1688
1689 MCRegister TemporaryReg = RISCV::NoRegister;
1690 for (MCRegister Reg : FinalRegsToZero.set_bits()) {
1691 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1692 TemporaryReg = Reg;
1693 break;
1694 }
1695 }
1696
1697 if (TemporaryReg == RISCV::NoRegister) {
1698 RS->enterBasicBlockEnd(MBB);
1699 TemporaryReg = RS->scavengeRegisterBackwards(RISCV::GPRRegClass, MBBI,
1700 /*RestoreAfter=*/false,
1701 /*SPAdj=*/0);
1702 }
1703
1704 if (MBB.getParent()
1705 ->getFunction()
1706 .getFnAttribute("zero-call-used-regs")
1707 .getValueAsString() == "used")
1708 FinalRegsToZero.set(TemporaryReg.id());
1709
1710 BuildMI(MBB, MBBI, DL, TII.get(RISCV::VSETVLI), TemporaryReg)
1711 .addReg(RISCV::X0)
1712 .addImm(VTypeImm)
1713 .addReg(RISCV::VL, RegState::ImplicitDefine)
1714 .addReg(RISCV::VTYPE, RegState::ImplicitDefine);
1715 }
1716
1717 for (MCRegister Reg : FinalRegsToZero.set_bits())
1718 TII.buildClearRegister(Reg, MBB, MBBI, DL);
1719}
1720
1723 Register &FrameReg) const {
1724 const MachineFrameInfo &MFI = MF.getFrameInfo();
1726 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1727
1728 // Callee-saved registers should be referenced relative to the stack
1729 // pointer (positive offset), otherwise use the frame pointer (negative
1730 // offset).
1731 const auto &CSI = getUnmanagedCSI(MF, MFI.getCalleeSavedInfo(),
1732 STI.preferAscendingLoadStore());
1733 int MinCSFI = 0;
1734 int MaxCSFI = -1;
1736 auto StackID = MFI.getStackID(FI);
1737
1738 assert((StackID == TargetStackID::Default ||
1739 StackID == TargetStackID::ScalableVector) &&
1740 "Unexpected stack ID for the frame object.");
1741 if (StackID == TargetStackID::Default) {
1742 assert(getOffsetOfLocalArea() == 0 && "LocalAreaOffset is not 0!");
1744 MFI.getOffsetAdjustment());
1745 } else if (StackID == TargetStackID::ScalableVector) {
1747 }
1748
1749 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1750
1751 if (CSI.size()) {
1752 MinCSFI = std::min(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1753 MaxCSFI = std::max(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1754 }
1755
1756 auto FIIsCalleeSave = [&](const CalleeSavedInfo &CS) -> bool {
1757 return FI == CS.getFrameIdx();
1758 };
1759
1760 bool IsInterruptCSR = RVFI->isSiFivePreemptibleInterrupt(MF) &&
1761 (FI == RVFI->getInterruptCSRFrameIndex(0) ||
1762 FI == RVFI->getInterruptCSRFrameIndex(1));
1763 bool IsInlineRestoredLibcallCSR = llvm::any_of(
1764 getPushOrLibCallsSavedInfo(MF, MFI.getCalleeSavedInfo()), FIIsCalleeSave);
1765 if ((FI >= MinCSFI && FI <= MaxCSFI) || IsInterruptCSR ||
1766 IsInlineRestoredLibcallCSR) {
1767 FrameReg = SPReg;
1768
1769 if (FirstSPAdjustAmount)
1770 Offset += StackOffset::getFixed(FirstSPAdjustAmount);
1771 else
1773 return Offset;
1774 }
1775
1776 if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
1777 // If the stack was realigned, the frame pointer is set in order to allow
1778 // SP to be restored, so we need another base register to record the stack
1779 // after realignment.
1780 // |--------------------------| --
1781 // | callee-allocated save | | <----|
1782 // | area for register varargs| | |
1783 // |--------------------------| <-- FP |
1784 // | callee-saved registers | | |
1785 // |--------------------------| -- |
1786 // | realignment (the size of | | |
1787 // | this area is not counted | | |
1788 // | in MFI.getStackSize()) | | |
1789 // |--------------------------| -- |-- MFI.getStackSize()
1790 // | RVV alignment padding | | |
1791 // | (not counted in | | |
1792 // | MFI.getStackSize() but | | |
1793 // | counted in | | |
1794 // | RVFI.getRVVStackSize()) | | |
1795 // |--------------------------| -- |
1796 // | RVV objects | | |
1797 // | (not counted in | | |
1798 // | MFI.getStackSize()) | | |
1799 // |--------------------------| -- |
1800 // | padding before RVV | | |
1801 // | (not counted in | | |
1802 // | MFI.getStackSize() or in | | |
1803 // | RVFI.getRVVStackSize()) | | |
1804 // |--------------------------| -- |
1805 // | scalar local variables | | <----'
1806 // |--------------------------| -- <-- BP (if var sized objects present)
1807 // | VarSize objects | |
1808 // |--------------------------| -- <-- SP
1809 if (hasBP(MF)) {
1810 FrameReg = RISCVABI::getBPReg();
1811 } else {
1812 // VarSize objects must be empty in this case!
1813 assert(!MFI.hasVarSizedObjects());
1814 FrameReg = SPReg;
1815 }
1816 } else if (!RI->hasStackRealignment(MF)) {
1817 // Note: Keeping the following as multiple 'if' statements rather than
1818 // merging to a single expression for readability.
1819 if (!hasFP(MF)) {
1820 // No FP available, must use SP.
1821 FrameReg = SPReg;
1822 } else {
1823 FrameReg = FPReg;
1824 // SP-relative addressing is only valid when SP is stable throughout
1825 // the function body: no dynamic SP adjustments for outgoing call args,
1826 // no variable-sized objects, and no RVV scalable stack regions.
1827 // hasReservedCallFrame() conservatively encompasses all these checks.
1828 if (hasReservedCallFrame(MF)) {
1829 // Both FP and SP are candidates.
1830 // Prefer SP when the SP-relative offset fits in the compressed
1831 // instruction immediate range.
1832 int64_t SPOff = Offset.getFixed() + MFI.getStackSize();
1833 int64_t CLWSPMaxOffset = 252;
1834 int64_t CLDSPMaxOffset = 504;
1835 int64_t SPThreshold = STI.is64Bit() ? CLDSPMaxOffset : CLWSPMaxOffset;
1836 if (SPOff >= 0 && SPOff <= SPThreshold)
1837 FrameReg = SPReg;
1838 }
1839 }
1840 } else {
1841 assert(RI->hasStackRealignment(MF) && MFI.isFixedObjectIndex(FI) &&
1842 "Expected fixed object with stack realignment");
1843 assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1844 FrameReg = FPReg;
1845 }
1846
1847 if (FrameReg == FPReg) {
1848 Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
1849 // When using FP to access scalable vector objects, we need to minus
1850 // the frame size.
1851 //
1852 // |--------------------------| --
1853 // | callee-allocated save | |
1854 // | area for register varargs| |
1855 // |--------------------------| | -- <-- FP
1856 // | callee-saved registers | |
1857 // |--------------------------| | MFI.getStackSize()
1858 // | scalar local variables | |
1859 // |--------------------------| -- (Offset of RVV objects is from here.)
1860 // | RVV objects |
1861 // |--------------------------|
1862 // | VarSize objects |
1863 // |--------------------------| <-- SP
1864 if (StackID == TargetStackID::ScalableVector) {
1865 assert(!RI->hasStackRealignment(MF) &&
1866 "Can't index across variable sized realign");
1867 // We don't expect any extra RVV alignment padding, as the stack size
1868 // and RVV object sections should be correct aligned in their own
1869 // right.
1871 "Inconsistent stack layout");
1873 }
1874 return Offset;
1875 }
1876
1877 // This case handles indexing off both SP and BP.
1878 // If indexing off SP, there must not be any var sized objects
1879 assert(FrameReg == RISCVABI::getBPReg() || !MFI.hasVarSizedObjects());
1880
1881 // When using SP to access frame objects, we need to add RVV stack size.
1882 //
1883 // |--------------------------| --
1884 // | callee-allocated save | | <----|
1885 // | area for register varargs| | |
1886 // |--------------------------| | | <-- FP
1887 // | callee-saved registers | | |
1888 // |--------------------------| -- |
1889 // | RVV alignment padding | | |
1890 // | (not counted in | | |
1891 // | MFI.getStackSize() but | | |
1892 // | counted in | | |
1893 // | RVFI.getRVVStackSize()) | | |
1894 // |--------------------------| -- |
1895 // | RVV objects | | |-- MFI.getStackSize()
1896 // | (not counted in | | |
1897 // | MFI.getStackSize()) | | |
1898 // |--------------------------| -- |
1899 // | padding before RVV | | |
1900 // | (not counted in | | |
1901 // | MFI.getStackSize()) | | |
1902 // |--------------------------| -- |
1903 // | scalar local variables | | <----'
1904 // |--------------------------| -- <-- BP (if var sized objects present)
1905 // | VarSize objects | |
1906 // |--------------------------| -- <-- SP
1907 //
1908 // The total amount of padding surrounding RVV objects is described by
1909 // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
1910 // objects to the required alignment.
1911 if (MFI.getStackID(FI) == TargetStackID::Default) {
1912 if (MFI.isFixedObjectIndex(FI)) {
1913 assert(!RI->hasStackRealignment(MF) &&
1914 "Can't index across variable sized realign");
1916 RVFI->getRVVStackSize());
1917 } else {
1919 }
1920 } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
1921 // Ensure the base of the RVV stack is correctly aligned: add on the
1922 // alignment padding.
1923 int64_t ScalarLocalVarSize =
1924 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
1925 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
1926 Offset += StackOffset::get(ScalarLocalVarSize, RVFI->getRVVStackSize());
1927 }
1928 return Offset;
1929}
1930
1932 const Register &Reg) {
1933 MCRegister BaseReg = TRI.getSubReg(Reg, RISCV::sub_vrm1_0);
1934 // If it's not a grouped vector register, it doesn't have subregister, so
1935 // the base register is just itself.
1936 if (!BaseReg.isValid())
1937 BaseReg = Reg;
1938 return BaseReg;
1939}
1940
1942 BitVector &SavedRegs,
1943 RegScavenger *RS) const {
1945
1946 // In TargetFrameLowering::determineCalleeSaves, any vector register is marked
1947 // as saved if any of its subregister is clobbered, this is not correct in
1948 // vector registers. We only want the vector register to be marked as saved
1949 // if all of its subregisters are clobbered.
1950 // For example:
1951 // Original behavior: If v24 is marked, v24m2, v24m4, v24m8 are also marked.
1952 // Correct behavior: v24m2 is marked only if v24 and v25 are marked.
1954 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
1955 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
1956 for (unsigned i = 0; CSRegs[i]; ++i) {
1957 unsigned CSReg = CSRegs[i];
1958 // Only vector registers need special care.
1959 if (!RISCV::VRRegClass.contains(getRVVBaseRegister(TRI, CSReg)))
1960 continue;
1961
1962 SavedRegs.reset(CSReg);
1963
1964 auto SubRegs = TRI.subregs(CSReg);
1965 // Set the register and all its subregisters.
1966 if (!MRI.def_empty(CSReg) || MRI.getUsedPhysRegsMask().test(CSReg)) {
1967 SavedRegs.set(CSReg);
1968 for (unsigned Reg : SubRegs)
1969 SavedRegs.set(Reg);
1970 }
1971
1972 }
1973
1974 // Unconditionally spill RA and FP only if the function uses a frame
1975 // pointer.
1976 if (hasFP(MF)) {
1977 SavedRegs.set(RAReg);
1978 SavedRegs.set(FPReg);
1979 }
1980 // Mark BP as used if function has dedicated base pointer.
1981 if (hasBP(MF))
1982 SavedRegs.set(RISCVABI::getBPReg());
1983
1984 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1985 // X5 is used as a temporary for saving and restoring `mcause` and `mepc`.
1986 if (RVFI->isSiFivePreemptibleInterrupt(MF))
1987 SavedRegs.set(RISCV::X5);
1988
1989 // When using cm.push/pop we must save X27 if we save X26.
1990 if (RVFI->isPushable(MF) && SavedRegs.test(RISCV::X26))
1991 SavedRegs.set(RISCV::X27);
1992
1993 // For Zilsd on RV32, append GPRPair registers to the CSR list. This prevents
1994 // the need to create register sets for each abi which is a lot more complex.
1995 // Don't use Zilsd for callee-saved coalescing if the required alignment
1996 // exceeds the stack alignment or when Zcmp/Xqccmp or save/restore libcalls
1997 // are enabled.
1998 bool UseZilsd = !STI.is64Bit() && STI.hasStdExtZilsd() &&
1999 STI.getZilsdAlign() <= getStackAlign() &&
2000 !RVFI->isPushable(MF) && !RVFI->useSaveRestoreLibCalls(MF);
2001 if (UseZilsd) {
2004 for (unsigned i = 0; CSRegs[i]; ++i) {
2005 NewCSRs.push_back(CSRegs[i]);
2006 CSRSet.insert(CSRegs[i]);
2007 }
2008
2009 // Append GPRPair registers for pairs where both sub-registers are in CSR
2010 // list. Iterate through all GPRPairs and check if both sub-regs are CSRs.
2011 for (MCPhysReg Pair : RISCV::GPRPairRegClass) {
2012 // Do not append a pair that's already in the CSR list.
2013 if (CSRSet.contains(Pair))
2014 continue;
2015 MCRegister EvenReg = TRI.getSubReg(Pair, RISCV::sub_gpr_even);
2016 MCRegister OddReg = TRI.getSubReg(Pair, RISCV::sub_gpr_odd);
2017 if (CSRSet.contains(EvenReg.id()) && CSRSet.contains(OddReg.id())) {
2018 NewCSRs.push_back(Pair);
2019 CSRSet.insert(Pair);
2020 }
2021 }
2022
2023 MRI.setCalleeSavedRegs(NewCSRs);
2024 CSRegs = MRI.getCalleeSavedRegs();
2025 }
2026
2027 // Check if all subregisters are marked for saving. If so, set the super
2028 // register bit. For GPRPair, only check sub_gpr_even and sub_gpr_odd, not
2029 // aliases like X8_W or X8_H which are not set in SavedRegs.
2030 for (unsigned i = 0; CSRegs[i]; ++i) {
2031 MCRegister CSReg = CSRegs[i];
2032 bool CombineToSuperReg;
2033 if (RISCV::GPRPairRegClass.contains(CSReg)) {
2034 MCRegister EvenReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_even);
2035 MCRegister OddReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_odd);
2036 CombineToSuperReg =
2037 SavedRegs.test(EvenReg.id()) && SavedRegs.test(OddReg.id());
2038 // If s0(x8) is used as FP we can't generate load/store pair because it
2039 // breaks the frame chain.
2040 if (hasFP(MF) && CSReg == RISCV::X8_X9)
2041 CombineToSuperReg = false;
2042 } else {
2043 auto SubRegs = TRI.subregs(CSReg);
2044 CombineToSuperReg =
2045 !SubRegs.empty() && llvm::all_of(SubRegs, [&](unsigned Reg) {
2046 return SavedRegs.test(Reg);
2047 });
2048 }
2049
2050 if (CombineToSuperReg)
2051 SavedRegs.set(CSReg);
2052 }
2053
2054 // SiFive Preemptible Interrupt Handlers need additional frame entries
2056}
2057
2058std::pair<int64_t, Align>
2059RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFunction &MF) const {
2060 MachineFrameInfo &MFI = MF.getFrameInfo();
2061 // Create a buffer of RVV objects to allocate.
2062 SmallVector<int, 8> ObjectsToAllocate;
2063 auto pushRVVObjects = [&](int FIBegin, int FIEnd) {
2064 for (int I = FIBegin, E = FIEnd; I != E; ++I) {
2065 unsigned StackID = MFI.getStackID(I);
2066 if (StackID != TargetStackID::ScalableVector)
2067 continue;
2068 if (MFI.isDeadObjectIndex(I))
2069 continue;
2070
2071 ObjectsToAllocate.push_back(I);
2072 }
2073 };
2074 // First push RVV Callee Saved object, then push RVV stack object
2075 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
2076 const auto &RVVCSI = getRVVCalleeSavedInfo(MF, CSI);
2077 if (!RVVCSI.empty())
2078 pushRVVObjects(RVVCSI[0].getFrameIdx(),
2079 RVVCSI[RVVCSI.size() - 1].getFrameIdx() + 1);
2080 pushRVVObjects(0, MFI.getObjectIndexEnd() - RVVCSI.size());
2081
2082 // The minimum alignment is 16 bytes.
2083 Align RVVStackAlign(16);
2084 const auto &ST = MF.getSubtarget<RISCVSubtarget>();
2085
2086 if (!ST.hasVInstructions()) {
2087 assert(ObjectsToAllocate.empty() &&
2088 "Can't allocate scalable-vector objects without V instructions");
2089 return std::make_pair(0, RVVStackAlign);
2090 }
2091
2092 // Allocate all RVV locals and spills
2093 int64_t Offset = 0;
2094 for (int FI : ObjectsToAllocate) {
2095 // ObjectSize in bytes.
2096 int64_t ObjectSize = MFI.getObjectSize(FI);
2097 auto ObjectAlign =
2098 std::max(Align(RISCV::RVVBytesPerBlock), MFI.getObjectAlign(FI));
2099 // If the data type is the fractional vector type, reserve one vector
2100 // register for it.
2101 if (ObjectSize < RISCV::RVVBytesPerBlock)
2102 ObjectSize = RISCV::RVVBytesPerBlock;
2103 Offset = alignTo(Offset + ObjectSize, ObjectAlign);
2104 MFI.setObjectOffset(FI, -Offset);
2105 // Update the maximum alignment of the RVV stack section
2106 RVVStackAlign = std::max(RVVStackAlign, ObjectAlign);
2107 }
2108
2109 uint64_t StackSize = Offset;
2110
2111 // Ensure the alignment of the RVV stack. Since we want the most-aligned
2112 // object right at the bottom (i.e., any padding at the top of the frame),
2113 // readjust all RVV objects down by the alignment padding.
2114 // Stack size and offsets are multiples of vscale, stack alignment is in
2115 // bytes, we can divide stack alignment by minimum vscale to get a maximum
2116 // stack alignment multiple of vscale.
2117 auto VScale =
2118 std::max<uint64_t>(ST.getRealMinVLen() / RISCV::RVVBitsPerBlock, 1);
2119 if (auto RVVStackAlignVScale = RVVStackAlign.value() / VScale) {
2120 if (auto AlignmentPadding =
2121 offsetToAlignment(StackSize, Align(RVVStackAlignVScale))) {
2122 StackSize += AlignmentPadding;
2123 for (int FI : ObjectsToAllocate)
2124 MFI.setObjectOffset(FI, MFI.getObjectOffset(FI) - AlignmentPadding);
2125 }
2126 }
2127
2128 return std::make_pair(StackSize, RVVStackAlign);
2129}
2130
2132 // For RVV spill, scalable stack offsets computing requires up to two scratch
2133 // registers
2134 static constexpr unsigned ScavSlotsNumRVVSpillScalableObject = 2;
2135
2136 // For RVV spill, non-scalable stack offsets computing requires up to one
2137 // scratch register.
2138 static constexpr unsigned ScavSlotsNumRVVSpillNonScalableObject = 1;
2139
2140 // ADDI instruction's destination register can be used for computing
2141 // offsets. So Scalable stack offsets require up to one scratch register.
2142 static constexpr unsigned ScavSlotsADDIScalableObject = 1;
2143
2144 static constexpr unsigned MaxScavSlotsNumKnown =
2145 std::max({ScavSlotsADDIScalableObject, ScavSlotsNumRVVSpillScalableObject,
2146 ScavSlotsNumRVVSpillNonScalableObject});
2147
2148 unsigned MaxScavSlotsNum = 0;
2150 return false;
2151 for (const MachineBasicBlock &MBB : MF)
2152 for (const MachineInstr &MI : MBB) {
2153 bool IsRVVSpill = RISCV::isRVVSpill(MI);
2154 for (auto &MO : MI.operands()) {
2155 if (!MO.isFI())
2156 continue;
2157 bool IsScalableVectorID = MF.getFrameInfo().getStackID(MO.getIndex()) ==
2159 if (IsRVVSpill) {
2160 MaxScavSlotsNum = std::max(
2161 MaxScavSlotsNum, IsScalableVectorID
2162 ? ScavSlotsNumRVVSpillScalableObject
2163 : ScavSlotsNumRVVSpillNonScalableObject);
2164 } else if (MI.getOpcode() == RISCV::ADDI && IsScalableVectorID) {
2165 MaxScavSlotsNum =
2166 std::max(MaxScavSlotsNum, ScavSlotsADDIScalableObject);
2167 }
2168 }
2169 if (MaxScavSlotsNum == MaxScavSlotsNumKnown)
2170 return MaxScavSlotsNumKnown;
2171 }
2172 return MaxScavSlotsNum;
2173}
2174
2175static bool hasRVVFrameObject(const MachineFunction &MF) {
2176 // Originally, the function will scan all the stack objects to check whether
2177 // if there is any scalable vector object on the stack or not. However, it
2178 // causes errors in the register allocator. In issue 53016, it returns false
2179 // before RA because there is no RVV stack objects. After RA, it returns true
2180 // because there are spilling slots for RVV values during RA. It will not
2181 // reserve BP during register allocation and generate BP access in the PEI
2182 // pass due to the inconsistent behavior of the function.
2183 //
2184 // The function is changed to use hasVInstructions() as the return value. It
2185 // is not precise, but it can make the register allocation correct.
2186 //
2187 // FIXME: Find a better way to make the decision or revisit the solution in
2188 // D103622.
2189 //
2190 // Refer to https://github.com/llvm/llvm-project/issues/53016.
2191 return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
2192}
2193
2195 const RISCVInstrInfo &TII) {
2196 unsigned FnSize = 0;
2197 for (auto &MBB : MF) {
2198 for (auto &MI : MBB) {
2199 // Far branches over 20-bit offset will be relaxed in branch relaxation
2200 // pass. In the worst case, conditional branches will be relaxed into
2201 // the following instruction sequence. Unconditional branches are
2202 // relaxed in the same way, with the exception that there is no first
2203 // branch instruction.
2204 //
2205 // foo
2206 // bne t5, t6, .rev_cond # `TII->getInstSizeInBytes(MI)` bytes
2207 // sd s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2208 // jump .restore, s11 # 8 bytes
2209 // .rev_cond
2210 // bar
2211 // j .dest_bb # 4 bytes, or 2 bytes with Zca
2212 // .restore:
2213 // ld s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2214 // .dest:
2215 // baz
2216 if (MI.isConditionalBranch())
2217 FnSize += TII.getInstSizeInBytes(MI);
2218 if (MI.isConditionalBranch() || MI.isUnconditionalBranch()) {
2219 if (MF.getSubtarget<RISCVSubtarget>().hasStdExtZca())
2220 FnSize += 2 + 8 + 2 + 2;
2221 else
2222 FnSize += 4 + 8 + 4 + 4;
2223 continue;
2224 }
2225
2226 FnSize += TII.getInstSizeInBytes(MI);
2227 }
2228 }
2229 return FnSize;
2230}
2231
2233 MachineFunction &MF, RegScavenger *RS) const {
2234 const RISCVRegisterInfo *RegInfo =
2235 MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
2236 const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
2237 MachineFrameInfo &MFI = MF.getFrameInfo();
2238 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
2239 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2240
2241 int64_t RVVStackSize;
2242 Align RVVStackAlign;
2243 std::tie(RVVStackSize, RVVStackAlign) = assignRVVStackObjectOffsets(MF);
2244
2245 RVFI->setRVVStackSize(RVVStackSize);
2246 RVFI->setRVVStackAlign(RVVStackAlign);
2247
2248 if (hasRVVFrameObject(MF)) {
2249 // Ensure the entire stack is aligned to at least the RVV requirement: some
2250 // scalable-vector object alignments are not considered by the
2251 // target-independent code.
2252 MFI.ensureMaxAlignment(RVVStackAlign);
2253 }
2254
2255 unsigned ScavSlotsNum = 0;
2256
2257 // estimateStackSize has been observed to under-estimate the final stack
2258 // size, so give ourselves wiggle-room by checking for stack size
2259 // representable an 11-bit signed field rather than 12-bits.
2260 if (!isInt<11>(MFI.estimateStackSize(MF)))
2261 ScavSlotsNum = 1;
2262
2263 // Far branches over 20-bit offset require a spill slot for scratch register.
2264 bool IsLargeFunction = !isInt<20>(estimateFunctionSizeInBytes(MF, *TII));
2265 if (IsLargeFunction)
2266 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
2267
2268 // RVV loads & stores have no capacity to hold the immediate address offsets
2269 // so we must always reserve an emergency spill slot if the MachineFunction
2270 // contains any RVV spills.
2271 ScavSlotsNum = std::max(ScavSlotsNum, getScavSlotsNumForRVV(MF));
2272
2273 for (unsigned I = 0; I < ScavSlotsNum; I++) {
2274 int FI = MFI.CreateSpillStackObject(RegInfo->getSpillSize(*RC),
2275 RegInfo->getSpillAlign(*RC));
2276 RS->addScavengingFrameIndex(FI);
2277
2278 if (IsLargeFunction && RVFI->getBranchRelaxationScratchFrameIndex() == -1)
2279 RVFI->setBranchRelaxationScratchFrameIndex(FI);
2280 }
2281
2282 unsigned Size = RVFI->getReservedSpillsSize();
2283 for (const auto &Info : MFI.getCalleeSavedInfo()) {
2284 int FrameIdx = Info.getFrameIdx();
2285 if (FrameIdx < 0 || MFI.getStackID(FrameIdx) != TargetStackID::Default)
2286 continue;
2287
2288 Size += MFI.getObjectSize(FrameIdx);
2289 }
2290 RVFI->setCalleeSavedStackSize(Size);
2291}
2292
2293// Not preserve stack space within prologue for outgoing variables when the
2294// function contains variable size objects or there are vector objects accessed
2295// by the frame pointer.
2296// Let eliminateCallFramePseudoInstr preserve stack space for it.
2298 return !MF.getFrameInfo().hasVarSizedObjects() &&
2299 !(hasFP(MF) && hasRVVFrameObject(MF));
2300}
2301
2302// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
2306 DebugLoc DL = MI->getDebugLoc();
2307
2308 if (!hasReservedCallFrame(MF)) {
2309 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
2310 // ADJCALLSTACKUP must be converted to instructions manipulating the stack
2311 // pointer. This is necessary when there is a variable length stack
2312 // allocation (e.g. alloca), which means it's not possible to allocate
2313 // space for outgoing arguments from within the function prologue.
2314 int64_t Amount = MI->getOperand(0).getImm();
2315
2316 if (Amount != 0) {
2317 // Ensure the stack remains aligned after adjustment.
2318 Amount = alignSPAdjust(Amount);
2319
2320 if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
2321 Amount = -Amount;
2322
2323 const RISCVTargetLowering *TLI =
2324 MF.getSubtarget<RISCVSubtarget>().getTargetLowering();
2325 int64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
2326 if (TLI->hasInlineStackProbe(MF) &&
2327 -Amount > StackProbeMaxUnprobedStack) {
2328 // When stack probing is enabled, the decrement of SP may need to be
2329 // probed. We only need to do this if the call frame is larger than
2330 // what may be left unprobed at the call, as SP has been probed at
2331 // this point, either by the prologue or by the most recent dynamic
2332 // allocation. We can handle both the decrement and the probing in
2333 // allocateStack.
2334 allocateStack(MBB, MI, MF, -Amount, -Amount,
2335 needsDwarfCFI(MF) && !hasFP(MF),
2336 /*NeedProbe=*/true, ProbeSize, /*FollowupSize=*/0,
2337 /*SpillsToSP=*/false, MachineInstr::NoFlags);
2338 inlineStackProbe(MF, MBB);
2339 } else {
2340 const RISCVRegisterInfo &RI = *STI.getRegisterInfo();
2343 }
2344 }
2345 }
2346
2347 return MBB.erase(MI);
2348}
2349
2350// We would like to split the SP adjustment to reduce prologue/epilogue
2351// as following instructions. In this way, the offset of the callee saved
2352// register could fit in a single store. Supposed that the first sp adjust
2353// amount is 2032.
2354// add sp,sp,-2032
2355// sw ra,2028(sp)
2356// sw s0,2024(sp)
2357// sw s1,2020(sp)
2358// sw s3,2012(sp)
2359// sw s4,2008(sp)
2360// add sp,sp,-64
2361uint64_t
2363 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2364 const MachineFrameInfo &MFI = MF.getFrameInfo();
2365 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2366 uint64_t StackSize = getStackSizeWithRVVPadding(MF);
2367
2368 // Disable SplitSPAdjust if save-restore libcall, push/pop or QCI interrupts
2369 // are used. The callee-saved registers will be pushed by the save-restore
2370 // libcalls, so we don't have to split the SP adjustment in this case.
2371 if (RVFI->getReservedSpillsSize())
2372 return 0;
2373
2374 // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
2375 // 12-bit and there exists a callee-saved register needing to be pushed.
2376 if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
2377 // FirstSPAdjustAmount is chosen at most as (2048 - StackAlign) because
2378 // 2048 will cause sp = sp + 2048 in the epilogue to be split into multiple
2379 // instructions. Offsets smaller than 2048 can fit in a single load/store
2380 // instruction, and we have to stick with the stack alignment. 2048 has
2381 // 16-byte alignment. The stack alignment for RV32 and RV64 is 16 and for
2382 // RV32E it is 4. So (2048 - StackAlign) will satisfy the stack alignment.
2383 const uint64_t StackAlign = getStackAlign().value();
2384
2385 // Amount of (2048 - StackAlign) will prevent callee saved and restored
2386 // instructions be compressed, so try to adjust the amount to the largest
2387 // offset that stack compression instructions accept when target supports
2388 // compression instructions.
2389 if (STI.hasStdExtZca()) {
2390 // The compression extensions may support the following instructions:
2391 // riscv32: c.lwsp rd, offset[7:2] => 2^(6 + 2)
2392 // c.swsp rs2, offset[7:2] => 2^(6 + 2)
2393 // c.flwsp rd, offset[7:2] => 2^(6 + 2)
2394 // c.fswsp rs2, offset[7:2] => 2^(6 + 2)
2395 // riscv64: c.ldsp rd, offset[8:3] => 2^(6 + 3)
2396 // c.sdsp rs2, offset[8:3] => 2^(6 + 3)
2397 // c.fldsp rd, offset[8:3] => 2^(6 + 3)
2398 // c.fsdsp rs2, offset[8:3] => 2^(6 + 3)
2399 const uint64_t RVCompressLen = STI.getXLen() * 8;
2400 // Compared with amount (2048 - StackAlign), StackSize needs to
2401 // satisfy the following conditions to avoid using more instructions
2402 // to adjust the sp after adjusting the amount, such as
2403 // StackSize meets the condition (StackSize <= 2048 + RVCompressLen),
2404 // case1: Amount is 2048 - StackAlign: use addi + addi to adjust sp.
2405 // case2: Amount is RVCompressLen: use addi + addi to adjust sp.
2406 auto CanCompress = [&](uint64_t CompressLen) -> bool {
2407 if (StackSize <= 2047 + CompressLen ||
2408 (StackSize > 2048 * 2 - StackAlign &&
2409 StackSize <= 2047 * 2 + CompressLen) ||
2410 StackSize > 2048 * 3 - StackAlign)
2411 return true;
2412
2413 return false;
2414 };
2415 // In the epilogue, addi sp, sp, 496 is used to recover the sp and it
2416 // can be compressed(C.ADDI16SP, offset can be [-512, 496]), but
2417 // addi sp, sp, 512 can not be compressed. So try to use 496 first.
2418 const uint64_t ADDI16SPCompressLen = 496;
2419 if (STI.is64Bit() && CanCompress(ADDI16SPCompressLen))
2420 return ADDI16SPCompressLen;
2421 if (CanCompress(RVCompressLen))
2422 return RVCompressLen;
2423 }
2424 return 2048 - StackAlign;
2425 }
2426 return 0;
2427}
2428
2431 std::vector<CalleeSavedInfo> &CSI) const {
2432 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2433 MachineFrameInfo &MFI = MF.getFrameInfo();
2434 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
2435
2436 // Preemptible Interrupts have two additional Callee-save Frame Indexes,
2437 // not tracked by `CSI`.
2438 if (RVFI->isSiFivePreemptibleInterrupt(MF)) {
2439 for (int I = 0; I < 2; ++I) {
2440 int FI = RVFI->getInterruptCSRFrameIndex(I);
2441 MFI.setIsCalleeSavedObjectIndex(FI, true);
2442 }
2443 }
2444
2445 // Early exit if no callee saved registers are modified!
2446 if (CSI.empty())
2447 return true;
2448
2449 if (RVFI->useQCIInterrupt(MF)) {
2450 RVFI->setQCIInterruptStackSize(QCIInterruptPushAmount);
2451 }
2452
2453 if (RVFI->isPushable(MF)) {
2454 // Determine how many GPRs we need to push and save it to RVFI.
2455 unsigned PushedRegNum = getNumPushPopRegs(CSI);
2456
2457 // `QC.C.MIENTER(.NEST)` will save `ra` and `s0`, so we should only push if
2458 // we want to push more than 2 registers. Otherwise, we should push if we
2459 // want to push more than 0 registers.
2460 unsigned OnlyPushIfMoreThan = RVFI->useQCIInterrupt(MF) ? 2 : 0;
2461 if (PushedRegNum > OnlyPushIfMoreThan) {
2462 RVFI->setRVPushRegs(PushedRegNum);
2463 RVFI->setRVPushStackSize(alignTo((STI.getXLen() / 8) * PushedRegNum, 16));
2464 }
2465 }
2466
2467 for (auto &CS : CSI) {
2468 MCRegister Reg = CS.getReg();
2469 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
2470 unsigned Size = RegInfo->getSpillSize(*RC);
2471
2472 if (RVFI->useQCIInterrupt(MF)) {
2473 const auto *FFI = llvm::find_if(FixedCSRFIQCIInterruptMap, [&](auto P) {
2474 return P.first == CS.getReg();
2475 });
2476 if (FFI != std::end(FixedCSRFIQCIInterruptMap)) {
2477 int64_t Offset = FFI->second * (int64_t)Size;
2478
2479 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2480 assert(FrameIdx < 0);
2481 CS.setFrameIdx(FrameIdx);
2482 continue;
2483 }
2484 }
2485
2486 if (RVFI->useSaveRestoreLibCalls(MF) || RVFI->isPushable(MF)) {
2487 const auto *FII = llvm::find_if(
2488 FixedCSRFIMap, [&](MCPhysReg P) { return P == CS.getReg(); });
2489 unsigned RegNum = std::distance(std::begin(FixedCSRFIMap), FII);
2490
2491 if (FII != std::end(FixedCSRFIMap)) {
2492 int64_t Offset;
2493 if (RVFI->getPushPopKind(MF) ==
2495 Offset = -int64_t(RVFI->getRVPushRegs() - RegNum) * Size;
2496 else
2497 Offset = -int64_t(RegNum + 1) * Size;
2498
2499 if (RVFI->useQCIInterrupt(MF))
2501
2502 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2503 assert(FrameIdx < 0);
2504 CS.setFrameIdx(FrameIdx);
2505 continue;
2506 }
2507 }
2508
2509 // For GPRPair registers, use 8-byte slots with required alignment by zilsd.
2510 if (!STI.is64Bit() && STI.hasStdExtZilsd() &&
2511 RISCV::GPRPairRegClass.contains(Reg)) {
2512 Align PairAlign = STI.getZilsdAlign();
2513 int FrameIdx = MFI.CreateStackObject(8, PairAlign, true);
2514 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2515 CS.setFrameIdx(FrameIdx);
2516 continue;
2517 }
2518
2519 // Not a fixed slot.
2520 Align Alignment = RegInfo->getSpillAlign(*RC);
2521 // We may not be able to satisfy the desired alignment specification of
2522 // the TargetRegisterClass if the stack alignment is smaller. Use the
2523 // min.
2524 Alignment = std::min(Alignment, getStackAlign());
2525 int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
2526 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2527 CS.setFrameIdx(FrameIdx);
2529 MFI.setStackID(FrameIdx, TargetStackID::ScalableVector);
2530 }
2531
2532 if (RVFI->useQCIInterrupt(MF)) {
2533 // Allocate a fixed object that covers the entire QCI stack allocation,
2534 // because there are gaps which are reserved for future use.
2535 MFI.CreateFixedSpillStackObject(
2536 QCIInterruptPushAmount, -static_cast<int64_t>(QCIInterruptPushAmount));
2537 }
2538
2539 if (RVFI->isPushable(MF)) {
2540 int64_t QCIOffset = RVFI->useQCIInterrupt(MF) ? QCIInterruptPushAmount : 0;
2541 // Allocate a fixed object that covers the full push.
2542 if (int64_t PushSize = RVFI->getRVPushStackSize())
2543 MFI.CreateFixedSpillStackObject(PushSize, -PushSize - QCIOffset);
2544 } else if (int LibCallRegs = getLibCallID(MF, CSI) + 1) {
2545 // If libcalls are used to spill and restore callee-saved registers, the
2546 // frame has two sections; the opaque section managed by the libcalls, and
2547 // the section managed by MachineFrameInfo which can also hold callee saved
2548 // registers in fixed stack slots, both of which have negative frame
2549 // indices. This gets even more complicated when incoming arguments are
2550 // passed via the stack, as these too have negative frame indices. An
2551 // example is detailed below:
2552 //
2553 // | incoming arg | <- FI[-3]
2554 // | libcallspill |
2555 // | calleespill | <- FI[-2]
2556 // | calleespill | <- FI[-1]
2557 // | this_frame | <- FI[0]
2558 //
2559 // For negative frame indices, the offset from the frame pointer will differ
2560 // depending on which of these groups the frame index applies to.
2561 // The following calculates the correct offset knowing the number of callee
2562 // saved registers spilt by the two methods.
2563 unsigned LibCallFrameSize =
2564 alignTo((STI.getXLen() / 8) * LibCallRegs, getStackAlign());
2565 RVFI->setLibCallStackSize(LibCallFrameSize);
2566 // Allocate a fixed object that covers the entire libcall area.
2567 MFI.CreateFixedSpillStackObject(LibCallFrameSize,
2568 -static_cast<int64_t>(LibCallFrameSize));
2569 }
2570
2571 return true;
2572}
2573
2577 if (CSI.empty())
2578 return true;
2579
2580 MachineFunction *MF = MBB.getParent();
2581 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2582 DebugLoc DL;
2583 if (MI != MBB.end() && !MI->isDebugInstr())
2584 DL = MI->getDebugLoc();
2585
2587 if (RVFI->useQCIInterrupt(*MF)) {
2588 // Emit QC.C.MIENTER(.NEST)
2589 BuildMI(
2590 MBB, MI, DL,
2591 TII.get(RVFI->getInterruptStackKind(*MF) ==
2593 ? RISCV::QC_C_MIENTER_NEST
2594 : RISCV::QC_C_MIENTER))
2596
2597 for (auto [Reg, _Offset] : FixedCSRFIQCIInterruptMap)
2598 MBB.addLiveIn(Reg);
2599 }
2600
2601 if (RVFI->isPushable(*MF)) {
2602 // Emit CM.PUSH with base StackAdj & evaluate Push stack
2603 unsigned PushedRegNum = RVFI->getRVPushRegs();
2604 if (PushedRegNum > 0) {
2605 // Use encoded number to represent registers to spill.
2606 unsigned Opcode = getPushOpcode(
2607 RVFI->getPushPopKind(*MF), hasFP(*MF) && !RVFI->useQCIInterrupt(*MF));
2608 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2609 MachineInstrBuilder PushBuilder =
2610 BuildMI(MBB, MI, DL, TII.get(Opcode))
2612 PushBuilder.addImm(RegEnc);
2613 PushBuilder.addImm(0);
2614
2615 for (unsigned i = 0; i < PushedRegNum; i++)
2616 PushBuilder.addUse(FixedCSRFIMap[i], RegState::Implicit);
2617 }
2618 } else if (const char *SpillLibCall = getSpillLibCallName(*MF, CSI)) {
2619 // Add spill libcall via non-callee-saved register t0.
2620 MachineInstrBuilder NewMI =
2621 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
2622 .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
2624 .addUse(RISCV::X2, RegState::Implicit)
2625 .addDef(RISCV::X2, RegState::ImplicitDefine)
2626 // The libcall may use t1 as a scratch register.
2628 // libgcc may emit an lui t2, 0 to set a landing pad label.
2630
2631 // Add registers spilled as implicit used.
2632 for (auto &CS : CSI)
2633 NewMI.addUse(CS.getReg(), RegState::Implicit);
2634 }
2635
2636 // Manually spill values not spilled by libcall & Push/Pop.
2637 const auto &UnmanagedCSI =
2638 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2639 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2640
2641 auto storeRegsToStackSlots = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2642 for (auto &CS : CSInfo) {
2643 // Insert the spill to the stack frame.
2644 MCRegister Reg = CS.getReg();
2645 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2646 TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg),
2647 CS.getFrameIdx(), RC, Register(),
2649 }
2650 };
2651 storeRegsToStackSlots(UnmanagedCSI);
2652 storeRegsToStackSlots(RVVCSI);
2653
2654 return true;
2655}
2656
2657static unsigned getCalleeSavedRVVNumRegs(const Register &BaseReg) {
2658 return RISCV::VRRegClass.contains(BaseReg) ? 1
2659 : RISCV::VRM2RegClass.contains(BaseReg) ? 2
2660 : RISCV::VRM4RegClass.contains(BaseReg) ? 4
2661 : 8;
2662}
2663
2664void RISCVFrameLowering::emitCalleeSavedRVVPrologCFI(
2667 const MachineFrameInfo &MFI = MF->getFrameInfo();
2668 RISCVMachineFunctionInfo *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2669 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2670
2671 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2672 if (RVVCSI.empty())
2673 return;
2674
2675 uint64_t FixedSize = getStackSizeWithRVVPadding(*MF);
2676 if (!HasFP) {
2677 uint64_t ScalarLocalVarSize =
2678 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
2679 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
2680 FixedSize -= ScalarLocalVarSize;
2681 }
2682
2683 CFIInstBuilder CFIBuilder(MBB, MI, MachineInstr::FrameSetup);
2684 for (auto &CS : RVVCSI) {
2685 // Insert the spill to the stack frame.
2686 int FI = CS.getFrameIdx();
2687 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2688 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2689 for (unsigned i = 0; i < NumRegs; ++i) {
2690 CFIBuilder.insertCFIInst(createDefCFAOffset(
2691 TRI, BaseReg + i,
2692 StackOffset::get(-FixedSize, MFI.getObjectOffset(FI) / 8 + i)));
2693 }
2694 }
2695}
2696
2697void RISCVFrameLowering::emitCalleeSavedRVVEpilogCFI(
2700 const MachineFrameInfo &MFI = MF->getFrameInfo();
2701 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2702
2703 CFIInstBuilder CFIHelper(MBB, MI, MachineInstr::FrameDestroy);
2704 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2705 for (auto &CS : RVVCSI) {
2706 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2707 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2708 for (unsigned i = 0; i < NumRegs; ++i)
2709 CFIHelper.buildRestore(BaseReg + i);
2710 }
2711}
2712
2716 if (CSI.empty())
2717 return true;
2718
2719 MachineFunction *MF = MBB.getParent();
2720 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2721 DebugLoc DL;
2722 if (MI != MBB.end() && !MI->isDebugInstr())
2723 DL = MI->getDebugLoc();
2724
2725 // Manually restore values not restored by libcall & Push/Pop.
2726 // Reverse the restore order in epilog. In addition, the return
2727 // address will be restored first in the epilogue. It increases
2728 // the opportunity to avoid the load-to-use data hazard between
2729 // loading RA and return by RA. loadRegFromStackSlot can insert
2730 // multiple instructions.
2731 const auto &UnmanagedCSI =
2732 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2733 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2734
2735 auto loadRegFromStackSlot = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2736 for (auto &CS : CSInfo) {
2737 MCRegister Reg = CS.getReg();
2738 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2739 TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, Register(),
2740 RISCV::NoSubRegister,
2742 assert(MI != MBB.begin() &&
2743 "loadRegFromStackSlot didn't insert any code!");
2744 }
2745 };
2746 loadRegFromStackSlot(RVVCSI);
2747 loadRegFromStackSlot(UnmanagedCSI);
2748
2750 if (RVFI->useQCIInterrupt(*MF)) {
2751 // Don't emit anything here because restoration is handled by
2752 // QC.C.MILEAVERET which we already inserted to return.
2753 assert(MI->getOpcode() == RISCV::QC_C_MILEAVERET &&
2754 "Unexpected QCI Interrupt Return Instruction");
2755 }
2756
2757 if (RVFI->isPushable(*MF)) {
2758 unsigned PushedRegNum = RVFI->getRVPushRegs();
2759 if (PushedRegNum > 0) {
2760 unsigned Opcode = getPopOpcode(RVFI->getPushPopKind(*MF));
2761 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2762 MachineInstrBuilder PopBuilder =
2763 BuildMI(MBB, MI, DL, TII.get(Opcode))
2765 // Use encoded number to represent registers to restore.
2766 PopBuilder.addImm(RegEnc);
2767 PopBuilder.addImm(0);
2768
2769 for (unsigned i = 0; i < RVFI->getRVPushRegs(); i++)
2771 }
2772 } else if (const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI)) {
2773 assert(RVFI->useSaveRestoreLibCalls(*MF) &&
2774 "Expected restore with libcall to use save restore libcalls");
2775
2776 // Restore is not compatible with shadow stacks, so do the restore manually.
2777 // This ensures we still get the code size saving of `__riscv_save_<N>`.
2778 if (RVFI->hasShadowStack(*MF)) {
2779 loadRegFromStackSlot(getPushOrLibCallsSavedInfo(*MF, CSI));
2780 return true;
2781 }
2782
2783 // Add restore libcall via tail call. Use the software guarded variant when
2784 // cf-protection-branch is enabled because the restore function does not
2785 // contain an lpad.
2786 unsigned TailOpc =
2787 RVFI->hasCFProtectionBranch() ? RISCV::PseudoTAILX7 : RISCV::PseudoTAIL;
2788 MachineInstrBuilder NewMI =
2789 BuildMI(MBB, MI, DL, TII.get(TailOpc))
2790 .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
2792 .addDef(RISCV::X2, RegState::ImplicitDefine);
2793
2794 // Add registers restored as implicit defined.
2795 for (auto &CS : CSI)
2796 NewMI.addDef(CS.getReg(), RegState::ImplicitDefine);
2797
2798 // Remove trailing returns, since the terminator is now a tail call to the
2799 // restore function.
2800 if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
2801 NewMI.getInstr()->copyImplicitOps(*MF, *MI);
2802 MI->eraseFromParent();
2803 }
2804 }
2805 return true;
2806}
2807
2809 // Keep the conventional code flow when not optimizing.
2810 if (MF.getFunction().hasOptNone())
2811 return false;
2812
2813 // QCI and SiFive CLIC interrupt entry sequences must precede all handler
2814 // code.
2815 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2816 if (RVFI->useQCIInterrupt(MF) || RVFI->useSiFiveInterrupt(MF))
2817 return false;
2818
2819 return true;
2820}
2821
2823 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
2824 const MachineFunction *MF = MBB.getParent();
2825 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2826
2827 // Make sure VTYPE and VL are not live-in since we will use vsetvli in the
2828 // prologue to get the VLEN, and that will clobber these registers.
2829 //
2830 // We may do also check the stack contains objects with scalable vector type,
2831 // but this will require iterating over all the stack objects, but this may
2832 // not worth since the situation is rare, we could do further check in future
2833 // if we find it is necessary.
2834 if (STI.preferVsetvliOverReadVLENB() &&
2835 (MBB.isLiveIn(RISCV::VTYPE) || MBB.isLiveIn(RISCV::VL)))
2836 return false;
2837
2838 if (!RVFI->useSaveRestoreLibCalls(*MF))
2839 return true;
2840
2841 // Inserting a call to a __riscv_save libcall requires the use of the register
2842 // t0 (X5) to hold the return address. Therefore if this register is already
2843 // used we can't insert the call.
2844
2845 RegScavenger RS;
2846 RS.enterBasicBlock(*TmpMBB);
2847 return !RS.isRegUsed(RISCV::X5);
2848}
2849
2851 const MachineFunction *MF = MBB.getParent();
2852 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
2853 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2854
2855 // If we have a shadow stack, we don't use `__riscv_restore` libcalls.
2856 if (RVFI->hasShadowStack(*MF))
2857 return true;
2858
2859 if (!RVFI->useSaveRestoreLibCalls(*MF))
2860 return true;
2861
2862 // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
2863 // This means if we still need to continue executing code within this function
2864 // the restore cannot take place in this basic block.
2865
2866 if (MBB.succ_size() > 1)
2867 return false;
2868
2869 MachineBasicBlock *SuccMBB =
2870 MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
2871
2872 // Doing a tail call should be safe if there are no successors, because either
2873 // we have a returning block or the end of the block is unreachable, so the
2874 // restore will be eliminated regardless.
2875 if (!SuccMBB)
2876 return true;
2877
2878 // The successor can only contain a return and debug instructions, since we
2879 // would effectively replace it with our own tail return at the end of this
2880 // block. The debug instructions would not execute on the tail-return path.
2881 return SuccMBB->isReturnBlock() &&
2882 llvm::count_if(SuccMBB->instrs(), [](const MachineInstr &MI) {
2883 return !MI.isDebugInstr();
2884 }) == 1;
2885}
2886
2890
2894
2895// Synthesize the probe loop.
2897 Register TargetReg, Register ScratchReg,
2898 bool IsRVV) {
2899 assert(TargetReg != RISCV::X2 && "New top of stack cannot already be in SP");
2900 assert(ScratchReg != RISCV::X2 && "Scratch register cannot be SP");
2901 assert(TargetReg != ScratchReg && "Target and scratch must be different");
2902
2903 MachineBasicBlock &MBB = *MBBI->getParent();
2904 MachineFunction &MF = *MBB.getParent();
2905
2907 const RISCVInstrInfo *TII = Subtarget.getInstrInfo();
2908 bool IsRV64 = Subtarget.is64Bit();
2909 Align StackAlign = Subtarget.getFrameLowering()->getStackAlign();
2910 const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
2911 uint64_t ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
2912
2913 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
2914 MachineBasicBlock *LoopTestMBB =
2915 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
2916 MF.insert(MBBInsertPoint, LoopTestMBB);
2917 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
2918 MF.insert(MBBInsertPoint, ExitMBB);
2920
2921 // ScratchReg = ProbeSize
2922 TII->movImm(MBB, MBBI, DL, ScratchReg, ProbeSize, Flags);
2923
2924 // LoopTest:
2925 // SUB SP, SP, ProbeSize
2926 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB), SPReg)
2927 .addReg(SPReg)
2928 .addReg(ScratchReg)
2929 .setMIFlags(Flags);
2930
2931 // s[d|w] zero, 0(sp)
2932 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
2933 TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
2934 .addReg(RISCV::X0)
2935 .addReg(SPReg)
2936 .addImm(0)
2937 .setMIFlags(Flags);
2938
2939 if (IsRVV) {
2940 // SUB TargetReg, TargetReg, ProbeSize
2941 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB),
2942 TargetReg)
2943 .addReg(TargetReg)
2944 .addReg(ScratchReg)
2945 .setMIFlags(Flags);
2946
2947 // BGE TargetReg, ProbeSize, LoopTest
2948 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BGE))
2949 .addReg(TargetReg)
2950 .addReg(ScratchReg)
2951 .addMBB(LoopTestMBB)
2952 .setMIFlags(Flags);
2953
2954 } else {
2955 // BNE SP, TargetReg, LoopTest
2956 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BNE))
2957 .addReg(SPReg)
2958 .addReg(TargetReg)
2959 .addMBB(LoopTestMBB)
2960 .setMIFlags(Flags);
2961 }
2962
2963 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
2965
2966 LoopTestMBB->addSuccessor(ExitMBB);
2967 LoopTestMBB->addSuccessor(LoopTestMBB);
2968 MBB.addSuccessor(LoopTestMBB);
2969 // Update liveins.
2970 fullyRecomputeLiveIns({ExitMBB, LoopTestMBB});
2971}
2972
2973void RISCVFrameLowering::inlineStackProbe(MachineFunction &MF,
2974 MachineBasicBlock &MBB) const {
2975 // Get the instructions that need to be replaced. We emit at most three of
2976 // these. Remember them in order to avoid complications coming from the need
2977 // to traverse the block while potentially creating more blocks.
2978 SmallVector<MachineInstr *, 4> ToReplace;
2979 for (MachineInstr &MI : MBB) {
2980 unsigned Opc = MI.getOpcode();
2981 if (Opc == RISCV::PROBED_STACKALLOC ||
2982 Opc == RISCV::PROBED_STACKALLOC_RVV) {
2983 ToReplace.push_back(&MI);
2984 }
2985 }
2986
2987 for (MachineInstr *MI : ToReplace) {
2988 if (MI->getOpcode() == RISCV::PROBED_STACKALLOC ||
2989 MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV) {
2992 Register TargetReg = MI->getOperand(0).getReg();
2993
2994 Register ScratchReg =
2995 findScratchNonCalleeSaveRegister(&MBB, RISCV::X7, TargetReg);
2996
2997 assert(ScratchReg.isValid() &&
2998 "No available scratch register for stack probe loop");
2999
3000 emitStackProbeInline(MBBI, DL, TargetReg, ScratchReg,
3001 (MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV));
3003 }
3004 }
3005}
3006
3008 return 0;
3009}
3010
3013 return RISCV::X2;
3014}
3015
3016// On 64-bit systems the fixed stack can hold INT64_MAX bytes, since
3017// stack-offset calculation is done in 2s-complement.
3018// NOTE: In theory a register can hold any 64-bit number, so this constraint
3019// might be relaxed to UINT64_MAX in the future, if anyone actually needs
3020// that.
3022 return STI.is64Bit() ? INT64_MAX : UINT32_MAX;
3023}
static void getLiveRegsForEntryMBB(LivePhysRegs &LiveRegs, const MachineBasicBlock &MBB)
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
static MCCFIInstruction createDefCFAExpression(const TargetRegisterInfo &TRI, unsigned Reg, const StackOffset &Offset)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains constants used for implementing Dwarf debug support.
const HexagonInstrInfo * TII
static void emitSCSPrologue(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL)
static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL)
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
static uint64_t estimateFunctionSizeInBytes(const LoongArchInstrInfo *TII, const MachineFunction &MF)
static void emitStackProbeInline(MachineBasicBlock::iterator MBBI, DebugLoc DL, Register TargetReg)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
static constexpr uint64_t QCIInterruptPushAmount
static void emitSiFiveCLICStackSwap(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MachineInstr::MIFlag FrameFlag)
static unsigned getPushOpcode(RISCVMachineFunctionInfo::PushPopKind Kind, bool UpdateFP)
static void emitSiFiveCLICPreemptibleSaves(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL)
static MCRegister getRVVBaseRegister(const RISCVRegisterInfo &TRI, const Register &Reg)
static void createSiFivePreemptibleInterruptFrameEntries(MachineFunction &MF, RISCVMachineFunctionInfo &RVFI)
static constexpr MCPhysReg FPReg
static const char * getRestoreLibCallName(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static bool needsDwarfCFI(const MachineFunction &MF)
Returns true if DWARF CFI instructions ("frame moves") should be emitted.
static constexpr MCPhysReg SPReg
static const char * getSpillLibCallName(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static bool hasRVVFrameObject(const MachineFunction &MF)
static constexpr unsigned StackProbeMaxUnprobedStack
static SmallVector< CalleeSavedInfo, 8 > getUnmanagedInterruptCSI(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI, bool ReverseOrder=false)
static void appendScalableVectorExpression(const TargetRegisterInfo &TRI, SmallVectorImpl< char > &Expr, StackOffset Offset, llvm::raw_string_ostream &Comment)
static SmallVector< CalleeSavedInfo, 8 > getQCISavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static SmallVector< CalleeSavedInfo, 8 > getRVVCalleeSavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static SmallVector< CalleeSavedInfo, 8 > getUnmanagedCSI(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI, bool ReverseOrder=false)
static void emitSiFiveCLICPreemptibleRestores(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, CFIInstBuilder &CFIBuilder, const DebugLoc &DL)
static bool isPop(unsigned Opcode)
static unsigned getCalleeSavedRVVNumRegs(const Register &BaseReg)
static MCCFIInstruction createDefCFAOffset(const TargetRegisterInfo &TRI, Register Reg, StackOffset Offset)
static unsigned getPopOpcode(RISCVMachineFunctionInfo::PushPopKind Kind)
static SmallVector< CalleeSavedInfo, 8 > getPushOrLibCallsSavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static int getLibCallID(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static const std::pair< MCPhysReg, int8_t > FixedCSRFIQCIInterruptMap[]
static bool isPush(unsigned Opcode)
static constexpr MCPhysReg RAReg
static MCRegister getLargestFPRegisterOrZero(const RISCVSubtarget &STI, const TargetRegisterInfo &TRI, MCRegister Reg)
static const MCPhysReg FixedCSRFIMap[]
static int getSiFiveCLICScratchFrameIndex(const MachineFunction &MF)
static unsigned getNumPushPopRegs(const std::vector< CalleeSavedInfo > &CSI)
static MCRegister getPhysicalGPR(const TargetRegisterInfo &TRI, MCRegister Reg)
static unsigned getScavSlotsNumForRVV(MachineFunction &MF)
MachineRegisterInfo & MRI
This file declares the machine register scavenger class.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:160
Helper class for creating CFI instructions and inserting them into MIR.
void buildEscape(StringRef Bytes, StringRef Comment="") const
void buildDefCFAOffset(int64_t Offset, MCSymbol *Label=nullptr) const
void buildRestore(MCRegister Reg) const
void buildDefCFARegister(MCRegister Reg) const
void buildOffset(MCRegister Reg, int64_t Offset) const
void insertCFIInst(const MCCFIInstruction &CFIInst) const
void buildDefCFA(MCRegister Reg, int64_t Offset) const
void setInsertPoint(MachineBasicBlock::iterator IP)
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
MCRegister getReg() const
A debug info location.
Definition DebugLoc.h:127
Diagnostic information for unsupported feature in backend.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
A set of physical registers with utility functions to track liveness when walking backward/forward th...
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:759
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr unsigned id() const
Definition MCRegister.h:82
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
LLVM_ABI void ensureMaxAlignment(Align Alignment)
Make sure the function's frame is at least Align bytes aligned.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return alignment of this function's frame.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
LLVM_ABI uint64_t estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool isMaxCallFrameSizeComputed() const
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
uint8_t getStackID(int ObjectIdx) const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
LLVM_ABI void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI)
Copy implicit register operands from specified instruction to this instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
uint64_t getFirstSPAdjustAmount(const MachineFunction &MF) const
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
uint64_t getStackThreshold() const override
getStackThreshold - Return the maximum stack size
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
bool hasBP(const MachineFunction &MF) const
bool canUseAsEpilogue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a epilogue for the target.
bool hasFPImpl(const MachineFunction &MF) const override
Register findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB, Register PreferredReg, Register DontUseReg=Register()) const
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
Register getInitialCFARegister(const MachineFunction &MF) const override
Return initial CFA register value i.e.
const RISCVSubtarget & STI
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
bool isSupportedStackID(TargetStackID::Value ID) const override
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
TargetStackID::Value getStackIDForScalableVectors() const override
Returns the StackID that scalable vectors should be associated with.
void allocateStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, MachineFunction &MF, uint64_t Offset, uint64_t RealStackSize, bool EmitCFI, bool NeedProbe, uint64_t ProbeSize, uint64_t FollowupSize, bool SpillsToSP, MachineInstr::MIFlag Flag) const
int getInitialCFAOffset(const MachineFunction &MF) const override
Return initial CFA offset value i.e.
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
bool canUseAsPrologue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a prologue for the target.
RISCVFrameLowering(const RISCVSubtarget &STI)
uint64_t getStackSizeWithRVVPadding(const MachineFunction &MF) const
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
bool isPushable(const MachineFunction &MF) const
InterruptStackKind getInterruptStackKind(const MachineFunction &MF) const
bool useSiFiveInterrupt(const MachineFunction &MF) const
bool isSiFivePreemptibleInterrupt(const MachineFunction &MF) const
PushPopKind getPushPopKind(const MachineFunction &MF) const
bool hasShadowStack(const MachineFunction &MF) const
bool useSaveRestoreLibCalls(const MachineFunction &MF) const
bool useQCIInterrupt(const MachineFunction &MF) const
TargetRegisterClass const * getLargestFPRegClass() const
bool hasVInstructions() const
const RISCVRegisterInfo * getRegisterInfo() const override
const RISCVInstrInfo * getInstrInfo() const override
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
Represents a location in source code.
Definition SMLoc.h:22
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:50
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition TypeSize.h:42
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
TargetFrameLowering(StackDirection D, Align StackAl, int LAO, Align TransAl=Align(1), bool StackReal=true)
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
MCRegister getBPReg()
MCRegister getSCSPReg()
static VLMUL encodeLMUL(unsigned LMUL, bool Fractional)
LLVM_ABI unsigned encodeVTYPE(VLMUL VLMUL, unsigned SEW, bool TailAgnostic, bool MaskAgnostic, bool AltFmt=false)
static unsigned encodeRegListNumRegs(unsigned NumRegs)
static constexpr unsigned RVVBitsPerBlock
bool isRVVSpill(const MachineInstr &MI)
static constexpr unsigned RVVBytesPerBlock
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:191
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
void appendLEB128(SmallVectorImpl< U > &Buffer, T Value)
Definition LEB128.h:280
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
static bool isRVVRegClass(const TargetRegisterClass *RC)
void adjustReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator II, const DebugLoc &DL, Register DestReg, Register SrcReg, StackOffset Offset, MachineInstr::MIFlag Flag, MaybeAlign RequiredAlign) const