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
76// Smip/Ssip push six registers. ACLIC specifies a 24-byte frame for RV32E,
77// a 32-byte frame for RV32I, and a 48-byte frame for RV64I/E.
79 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
80 if (STI.is64Bit())
81 return 48;
82 return STI.hasStdExtE() ? 24 : 32;
83}
84
85// FIXME: These offsets are placeholders. ACLIC does not yet define where
86// Smip/Ssip store a0-a5 within the hardware-pushed frame. Update them
87// to agree with the architecture once the frame layout is specified.
88static const std::pair<MCPhysReg, int8_t> FixedCSRFIACLICInterruptMap[] = {
89 {/*a0*/ RISCV::X10, -1}, {/*a1*/ RISCV::X11, -2}, {/*a2*/ RISCV::X12, -3},
90 {/*a3*/ RISCV::X13, -4}, {/*a4*/ RISCV::X14, -5}, {/*a5*/ RISCV::X15, -6},
91};
92
93static const std::pair<MCPhysReg, int8_t> FixedCSRFIQCIInterruptMap[] = {
94 /* -1 is a gap for mepc/mnepc */
95 {/*fp*/ FPReg, -2},
96 /* -3 is a gap for qc.mcause */
97 {/*ra*/ RAReg, -4},
98 /* -5 is reserved */
99 {/*t0*/ RISCV::X5, -6},
100 {/*t1*/ RISCV::X6, -7},
101 {/*t2*/ RISCV::X7, -8},
102 {/*a0*/ RISCV::X10, -9},
103 {/*a1*/ RISCV::X11, -10},
104 {/*a2*/ RISCV::X12, -11},
105 {/*a3*/ RISCV::X13, -12},
106 {/*a4*/ RISCV::X14, -13},
107 {/*a5*/ RISCV::X15, -14},
108 {/*a6*/ RISCV::X16, -15},
109 {/*a7*/ RISCV::X17, -16},
110 {/*t3*/ RISCV::X28, -17},
111 {/*t4*/ RISCV::X29, -18},
112 {/*t5*/ RISCV::X30, -19},
113 {/*t6*/ RISCV::X31, -20},
114 /* -21, -22, -23, -24 are reserved */
115};
116
117/// Returns true if DWARF CFI instructions ("frame moves") should be emitted.
118static bool needsDwarfCFI(const MachineFunction &MF) {
119 return MF.needsFrameMoves();
120}
121
122// For now we use x3, a.k.a gp, as pointer to shadow call stack.
123// User should not use x3 in their asm.
126 const DebugLoc &DL) {
127 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
128 RISCVMachineFunctionInfo::ShadowStackKind SSK = RVFI->getShadowStackKind(MF);
130 return;
131
132 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
133 const llvm::RISCVRegisterInfo *TRI = STI.getRegisterInfo();
134
135 // Do not save RA to the SCS if it's not saved to the regular stack,
136 // i.e. RA is not at risk of being overwritten.
137 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
138 if (llvm::none_of(
139 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
140 return;
141
142 const RISCVInstrInfo *TII = STI.getInstrInfo();
144 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPUSH))
145 .addReg(RAReg)
147 return;
148 }
149
151 "Unexpected Shadow Stack Kind");
152
153 Register SCSPReg = RISCVABI::getSCSPReg();
154
155 bool IsRV64 = STI.is64Bit();
156 int64_t SlotSize = STI.getXLen() / 8;
157 // Store return address to shadow call stack
158 // addi gp, gp, [4|8]
159 // s[w|d] ra, -[4|8](gp)
160 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI), SCSPReg)
161 .addReg(SCSPReg)
162 .addImm(SlotSize)
164 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
165 .addReg(RAReg)
166 .addReg(SCSPReg)
167 .addImm(-SlotSize)
169
170 if (!needsDwarfCFI(MF))
171 return;
172
173 // Emit a CFI instruction that causes SlotSize to be subtracted from the value
174 // of the shadow stack pointer when unwinding past this frame.
175 char DwarfSCSReg = TRI->getDwarfRegNum(SCSPReg, /*IsEH*/ true);
176 assert(DwarfSCSReg < 32 && "SCS Register should be < 32 (X3).");
177
178 char Offset = static_cast<char>(-SlotSize) & 0x7f;
179 const char CFIInst[] = {
180 dwarf::DW_CFA_val_expression,
181 DwarfSCSReg, // register
182 2, // length
183 static_cast<char>(unsigned(dwarf::DW_OP_breg0 + DwarfSCSReg)),
184 Offset, // addend (sleb128)
185 };
186
188 .buildEscape(StringRef(CFIInst, sizeof(CFIInst)));
189}
190
193 const DebugLoc &DL) {
194 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
195 RISCVMachineFunctionInfo::ShadowStackKind SSK = RVFI->getShadowStackKind(MF);
197 return;
198
199 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
200
201 // See emitSCSPrologue() above.
202 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
203 if (llvm::none_of(
204 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
205 return;
206
207 // The shadow call stack popchk needs to happen after cm.pop that loads ra.
208 if (MI != MBB.end() &&
209 (MI->getOpcode() == RISCV::CM_POP || MI->getOpcode() == RISCV::QC_CM_POP))
210 ++MI;
211 const RISCVInstrInfo *TII = STI.getInstrInfo();
213 // `sspopchk x5` is the only compressible form, but this would require using
214 // `x5` as the return address everywhere, which would also mean reserving
215 // it. We prefer to just use `x1` to avoid that complexity.
216 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPOPCHK))
217 .addReg(RAReg)
219 return;
220 }
221
223 "Unexpected Shadow Stack Kind");
224
225 Register SCSPReg = RISCVABI::getSCSPReg();
226
227 bool IsRV64 = STI.is64Bit();
228 int64_t SlotSize = STI.getXLen() / 8;
229 // Load return address from shadow call stack
230 // l[w|d] ra, -[4|8](gp)
231 // addi gp, gp, -[4|8]
232 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::LD : RISCV::LW), RAReg)
233 .addReg(SCSPReg)
234 .addImm(-SlotSize)
236 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI), SCSPReg)
237 .addReg(SCSPReg)
238 .addImm(-SlotSize)
240 if (needsDwarfCFI(MF)) {
241 // Restore the SCS pointer
243 }
244}
245
246// Insert instruction to swap mscratchsw with sp
249 const DebugLoc &DL,
250 MachineInstr::MIFlag FrameFlag) {
251 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
252
253 if (!RVFI->isSiFiveStackSwapInterrupt(MF))
254 return;
255
256 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
257 const RISCVInstrInfo *TII = STI.getInstrInfo();
258
259 assert(STI.hasVendorXSfmclic() && "Stack Swapping Requires XSfmclic");
260
261 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), SPReg)
262 .addImm(RISCVSysReg::sf_mscratchcsw)
264 .setMIFlag(FrameFlag);
265
266 // FIXME: CFI Information for this swap.
267}
268
269static void
272 if (!RVFI.isSiFivePreemptibleInterrupt(MF) &&
274 return;
275
276 const TargetRegisterClass &RC = RISCV::GPRRegClass;
277 const TargetRegisterInfo &TRI =
278 *MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
279 MachineFrameInfo &MFI = MF.getFrameInfo();
280
281 // Each preemptible interrupt kind saves two CSRs in dedicated frame objects.
282 for (int I = 0; I < 2; ++I) {
283 int FI = MFI.CreateStackObject(TRI.getSpillSize(RC), TRI.getSpillAlign(RC),
284 true);
286 }
287}
288
289// X5 retains an ordinary CSI slot, but preemptible interrupt handlers save
290// and restore it explicitly around their CSR sequences.
292 const auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
293 auto ScratchCS = llvm::find_if(
294 CSI, [](const CalleeSavedInfo &CS) { return CS.getReg() == RISCV::X5; });
295 assert(ScratchCS != CSI.end() && "Missing interrupt scratch spill slot");
296 return ScratchCS->getFrameIdx();
297}
298
302 const DebugLoc &DL) {
303 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
304
305 if (!RVFI->isSiFivePreemptibleInterrupt(MF))
306 return;
307
308 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
309 const RISCVInstrInfo *TII = STI.getInstrInfo();
310
311 // FIXME: CFI information for `mcause` and `mepc` is missing.
312
313 // Preserve X5 before using it to save the interrupt CSRs. Other GPRs
314 // are saved by the ordinary spill sequence after preemption is enabled.
316 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /*IsKill=*/true, ScratchFI,
317 &RISCV::GPRRegClass, Register(),
319 if (needsDwarfCFI(MF))
321 .buildOffset(RISCV::X5, MF.getFrameInfo().getObjectOffset(ScratchFI));
322
323 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRS), RISCV::X5)
324 .addImm(RISCVSysReg::mcause)
325 .addReg(RISCV::X0)
327 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /* IsKill=*/true,
328 RVFI->getInterruptCSRFrameIndex(0),
329 &RISCV::GPRRegClass, Register(),
331
332 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRS), RISCV::X5)
333 .addImm(RISCVSysReg::mepc)
334 .addReg(RISCV::X0)
336
337 // Enable interrupts.
338 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRSI), RISCV::X0)
339 .addImm(RISCVSysReg::mstatus)
340 .addImm(8)
342 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /* IsKill=*/true,
343 RVFI->getInterruptCSRFrameIndex(1),
344 &RISCV::GPRRegClass, Register(),
346}
347
351 CFIInstBuilder &CFIBuilder,
352 const DebugLoc &DL) {
353 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
354
355 if (!RVFI->isSiFivePreemptibleInterrupt(MF))
356 return;
357
358 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
359 const RISCVInstrInfo *TII = STI.getInstrInfo();
360
361 // FIXME: CFI information for `mcause` and `mepc` is missing.
362
363 // Load mepc while preemption is still enabled. A nested handler preserves
364 // X5. Interrupts only need to be disabled before writing the CSRs back.
365 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
366 RVFI->getInterruptCSRFrameIndex(1),
367 &RISCV::GPRRegClass, Register(),
368 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
369
370 // Disable interrupts.
371 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRCI), RISCV::X0)
372 .addImm(RISCVSysReg::mstatus)
373 .addImm(8)
375
376 // Restore `mepc` and `mcause` through X5, then restore the value X5 held
377 // on entry to the handler.
378 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), RISCV::X0)
379 .addImm(RISCVSysReg::mepc)
380 .addReg(RISCV::X5, RegState::Kill)
382
383 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
384 RVFI->getInterruptCSRFrameIndex(0),
385 &RISCV::GPRRegClass, Register(),
386 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
387 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), RISCV::X0)
388 .addImm(RISCVSysReg::mcause)
389 .addReg(RISCV::X5, RegState::Kill)
391
392 // The ordinary reloads have finished. Recover the interrupted value of X5
393 // only after it has restored both CSRs.
394 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
396 &RISCV::GPRRegClass, Register(),
397 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
398 if (needsDwarfCFI(MF))
399 CFIBuilder.buildRestore(RISCV::X5);
400}
401
405 const DebugLoc &DL) {
406 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
407 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
408 if (!RVFI->isACLICPreemptibleInterrupt(MF))
409 return;
410
411 const RISCVInstrInfo *TII = STI.getInstrInfo();
412 const bool IsSupervisor = RVFI->isACLICSupervisorInterrupt(MF);
413 const unsigned StatusCSR =
414 IsSupervisor ? RISCVSysReg::sistatus : RISCVSysReg::mistatus;
415 const unsigned EpcCSR = IsSupervisor ? RISCVSysReg::sepc : RISCVSysReg::mepc;
416
417 // Preserve X5 before using it to save the interrupt CSRs. The ordinary
418 // GPR spills follow after preemption is enabled.
420 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /*IsKill=*/true, ScratchFI,
421 &RISCV::GPRRegClass, Register(),
423 if (needsDwarfCFI(MF))
425 .buildOffset(RISCV::X5, MF.getFrameInfo().getObjectOffset(ScratchFI));
426
427 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRS), RISCV::X5)
428 .addImm(EpcCSR)
429 .addReg(RISCV::X0)
431 TII->storeRegToStackSlot(
432 MBB, MBBI, RISCV::X5, /*IsKill=*/true, RVFI->getInterruptCSRFrameIndex(0),
433 &RISCV::GPRRegClass, Register(), MachineInstr::FrameSetup);
434
435 // xistatus.xie is bit zero. CSRRSI returns the old status in X5 and enables
436 // interrupts after that value has been captured.
437 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRSI), RISCV::X5)
438 .addImm(StatusCSR)
439 .addImm(1)
441 TII->storeRegToStackSlot(
442 MBB, MBBI, RISCV::X5, /*IsKill=*/true, RVFI->getInterruptCSRFrameIndex(1),
443 &RISCV::GPRRegClass, Register(), MachineInstr::FrameSetup);
444}
445
449 CFIInstBuilder &CFIBuilder,
450 const DebugLoc &DL) {
451 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
452 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
453 if (!RVFI->isACLICPreemptibleInterrupt(MF))
454 return;
455
456 const RISCVInstrInfo *TII = STI.getInstrInfo();
457 const bool IsSupervisor = RVFI->isACLICSupervisorInterrupt(MF);
458 const unsigned StatusCSR =
459 IsSupervisor ? RISCVSysReg::sistatus : RISCVSysReg::mistatus;
460 const unsigned EpcCSR = IsSupervisor ? RISCVSysReg::sepc : RISCVSysReg::mepc;
461
462 // Loading xistatus while preemption is enabled is safe because nested
463 // handlers preserve X5. Restoring the entry value disables preemption.
464 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
465 RVFI->getInterruptCSRFrameIndex(1),
466 &RISCV::GPRRegClass, Register(),
467 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
468 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), RISCV::X0)
469 .addImm(StatusCSR)
470 .addReg(RISCV::X5, RegState::Kill)
472
473 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
474 RVFI->getInterruptCSRFrameIndex(0),
475 &RISCV::GPRRegClass, Register(),
476 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
477 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), RISCV::X0)
478 .addImm(EpcCSR)
479 .addReg(RISCV::X5, RegState::Kill)
481
482 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
484 &RISCV::GPRRegClass, Register(),
485 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
486 if (needsDwarfCFI(MF))
487 CFIBuilder.buildRestore(RISCV::X5);
488}
489
490// Get the ID of the libcall used for spilling and restoring callee saved
491// registers. The ID is representative of the number of registers saved or
492// restored by the libcall, except it is zero-indexed - ID 0 corresponds to a
493// single register.
494static int getLibCallID(const MachineFunction &MF,
495 const std::vector<CalleeSavedInfo> &CSI) {
496 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
497
498 if (CSI.empty() || !RVFI->useSaveRestoreLibCalls(MF))
499 return -1;
500
501 MCRegister MaxReg;
502 for (auto &CS : CSI)
503 // assignCalleeSavedSpillSlots assigns negative frame indexes to
504 // registers which can be saved by libcall.
505 if (CS.getFrameIdx() < 0)
506 MaxReg = std::max(MaxReg.id(), CS.getReg().id());
507
508 if (!MaxReg)
509 return -1;
510
511 switch (MaxReg.id()) {
512 default:
513 llvm_unreachable("Something has gone wrong!");
514 // clang-format off
515 case /*s11*/ RISCV::X27: return 12;
516 case /*s10*/ RISCV::X26: return 11;
517 case /*s9*/ RISCV::X25: return 10;
518 case /*s8*/ RISCV::X24: return 9;
519 case /*s7*/ RISCV::X23: return 8;
520 case /*s6*/ RISCV::X22: return 7;
521 case /*s5*/ RISCV::X21: return 6;
522 case /*s4*/ RISCV::X20: return 5;
523 case /*s3*/ RISCV::X19: return 4;
524 case /*s2*/ RISCV::X18: return 3;
525 case /*s1*/ RISCV::X9: return 2;
526 case /*s0*/ FPReg: return 1;
527 case /*ra*/ RAReg: return 0;
528 // clang-format on
529 }
530}
531
532// Get the name of the libcall used for spilling callee saved registers.
533// If this function will not use save/restore libcalls, then return a nullptr.
534static const char *
536 const std::vector<CalleeSavedInfo> &CSI) {
537 static const char *const SpillLibCalls[] = {
538 "__riscv_save_0",
539 "__riscv_save_1",
540 "__riscv_save_2",
541 "__riscv_save_3",
542 "__riscv_save_4",
543 "__riscv_save_5",
544 "__riscv_save_6",
545 "__riscv_save_7",
546 "__riscv_save_8",
547 "__riscv_save_9",
548 "__riscv_save_10",
549 "__riscv_save_11",
550 "__riscv_save_12"
551 };
552
553 int LibCallID = getLibCallID(MF, CSI);
554 if (LibCallID == -1)
555 return nullptr;
556 return SpillLibCalls[LibCallID];
557}
558
559// Get the name of the libcall used for restoring callee saved registers.
560// If this function will not use save/restore libcalls, then return a nullptr.
561static const char *
563 const std::vector<CalleeSavedInfo> &CSI) {
564 static const char *const RestoreLibCalls[] = {
565 "__riscv_restore_0",
566 "__riscv_restore_1",
567 "__riscv_restore_2",
568 "__riscv_restore_3",
569 "__riscv_restore_4",
570 "__riscv_restore_5",
571 "__riscv_restore_6",
572 "__riscv_restore_7",
573 "__riscv_restore_8",
574 "__riscv_restore_9",
575 "__riscv_restore_10",
576 "__riscv_restore_11",
577 "__riscv_restore_12"
578 };
579
580 int LibCallID = getLibCallID(MF, CSI);
581 if (LibCallID == -1)
582 return nullptr;
583 return RestoreLibCalls[LibCallID];
584}
585
586// Get the max reg of Push/Pop for restoring callee saved registers.
587static unsigned getNumPushPopRegs(const std::vector<CalleeSavedInfo> &CSI) {
588 unsigned NumPushPopRegs = 0;
589 for (auto &CS : CSI) {
590 auto *FII = llvm::find_if(FixedCSRFIMap,
591 [&](MCPhysReg P) { return P == CS.getReg(); });
592 if (FII != std::end(FixedCSRFIMap)) {
593 unsigned RegNum = std::distance(std::begin(FixedCSRFIMap), FII);
594 NumPushPopRegs = std::max(NumPushPopRegs, RegNum + 1);
595 }
596 }
597 assert(NumPushPopRegs != 12 && "x26 requires x27 to also be pushed");
598 return NumPushPopRegs;
599}
600
602 const MachineFunction &MF = *MBB.getParent();
603 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
604 const auto *TRI = STI.getRegisterInfo();
605
606 CFIInstBuilder CFIBuilder(MBB, MBB.begin(), MachineInstr::NoFlags);
607 CFIBuilder.buildDefCFA(SPReg, 0);
608
609 if (RVFI->getShadowStackKind(MF) ==
613 [&](const CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; })) {
615 }
616
617 for (const CalleeSavedInfo &Info : MF.getFrameInfo().getCalleeSavedInfo()) {
618 MCRegister Reg = Info.getReg();
619 if (RISCV::GPRPairRegClass.contains(Reg)) {
620 MCRegister EvenReg = TRI->getSubReg(Reg, RISCV::sub_gpr_even);
621 MCRegister OddReg = TRI->getSubReg(Reg, RISCV::sub_gpr_odd);
622 CFIBuilder.buildSameValue(EvenReg);
623 CFIBuilder.buildSameValue(OddReg);
624 } else {
625 CFIBuilder.buildSameValue(Reg);
626 }
627 }
628}
629
630// Return true if the specified function should have a dedicated frame
631// pointer register. This is true if frame pointer elimination is
632// disabled, if it needs dynamic stack realignment, if the function has
633// variable sized allocas, or if the frame address is taken.
635 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
636
637 const MachineFrameInfo &MFI = MF.getFrameInfo();
638 if (MF.disableFramePointerElim() || RegInfo->hasStackRealignment(MF) ||
640 return true;
641
642 // With large callframes around we may need to use FP to access the scavenging
643 // emergency spillslot.
644 //
645 // We calculate the MaxCallFrameSize at the end of isel so this value should
646 // be stable for the whole post-isel MIR pipeline.
647 //
648 // NOTE: The idea of forcing a frame pointer is copied from AArch64, but they
649 // conservatively return true when the call frame size hasd not been
650 // computed yet. On RISC-V that caused MachineOutliner tests to fail the
651 // MachineVerifier due to outlined functions not computing max call frame
652 // size thus the frame pointer would always be reserved.
653 if (MFI.isMaxCallFrameSizeComputed() && MFI.getMaxCallFrameSize() > 2047)
654 return true;
655
656 return false;
657}
658
660 const MachineFrameInfo &MFI = MF.getFrameInfo();
661 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
662
663 // If we do not reserve stack space for outgoing arguments in prologue,
664 // we will adjust the stack pointer before call instruction. After the
665 // adjustment, we can not use SP to access the stack objects for the
666 // arguments. Instead, use BP to access these stack objects.
667 return (MFI.hasVarSizedObjects() ||
669 MFI.getMaxCallFrameSize() != 0))) &&
670 TRI->hasStackRealignment(MF);
671}
672
673// Determines the size of the frame and maximum call frame size.
674void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
675 MachineFrameInfo &MFI = MF.getFrameInfo();
676 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
677
678 // Get the number of bytes to allocate from the FrameInfo.
679 uint64_t FrameSize = MFI.getStackSize();
680
681 // QCI Interrupts use at least 96 bytes of stack space
682 if (RVFI->useQCIInterrupt(MF))
683 FrameSize = std::max(FrameSize, QCIInterruptPushAmount);
684
685 // Get the alignment.
686 Align StackAlign = getStackAlign();
687
688 // Make sure the frame is aligned.
689 FrameSize = alignTo(FrameSize, StackAlign);
690
691 // Update frame info.
692 MFI.setStackSize(FrameSize);
693
694 // When using SP or BP to access stack objects, we may require extra padding
695 // to ensure the bottom of the RVV stack is correctly aligned within the main
696 // stack. We calculate this as the amount required to align the scalar local
697 // variable section up to the RVV alignment.
699 if (RVFI->getRVVStackSize() && (!hasFP(MF) || TRI->hasStackRealignment(MF))) {
700 int ScalarLocalVarSize = FrameSize - RVFI->getCalleeSavedStackSize() -
701 RVFI->getVarArgsSaveSize();
702 if (auto RVVPadding =
703 offsetToAlignment(ScalarLocalVarSize, RVFI->getRVVStackAlign()))
704 RVFI->setRVVPadding(RVVPadding);
705 }
706}
707
708// Returns the stack size including RVV padding (when required), rounded back
709// up to the required stack alignment.
711 const MachineFunction &MF) const {
712 const MachineFrameInfo &MFI = MF.getFrameInfo();
713 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
714 return alignTo(MFI.getStackSize() + RVFI->getRVVPadding(), getStackAlign());
715}
716
719 const std::vector<CalleeSavedInfo> &CSI,
720 bool ReverseOrder = false) {
721 const MachineFrameInfo &MFI = MF.getFrameInfo();
723
724 for (auto &CS : CSI) {
725 int FI = CS.getFrameIdx();
726 // Callee saves with negative frame indices have fixed positions on the
727 // stack, usually relating to libcalls or push/pop.
728 bool IsManagedFI = (FI < 0);
729 if (!IsManagedFI && MFI.getStackID(FI) == TargetStackID::Default)
730 NonLibcallCSI.push_back(CS);
731 }
732
733 // Reverse the order so that load/store operations use ascending addresses,
734 // enabling better load/store clustering and fusion.
735 if (ReverseOrder)
736 std::reverse(NonLibcallCSI.begin(), NonLibcallCSI.end());
737
738 return NonLibcallCSI;
739}
740
741// Exclude X5 from ordinary spills and restores for preemptible interrupt
742// handlers, which save and restore it explicitly before the other GPRs.
745 const std::vector<CalleeSavedInfo> &CSI,
746 bool ReverseOrder = false) {
747 auto InterruptCSI = getUnmanagedCSI(MF, CSI, ReverseOrder);
748 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
749 if (RVFI->isSiFivePreemptibleInterrupt(MF) ||
750 RVFI->isACLICPreemptibleInterrupt(MF))
751 llvm::erase_if(InterruptCSI, [](const CalleeSavedInfo &CS) {
752 return CS.getReg() == RISCV::X5;
753 });
754 return InterruptCSI;
755}
756
759 const std::vector<CalleeSavedInfo> &CSI) {
760 const MachineFrameInfo &MFI = MF.getFrameInfo();
762
763 for (auto &CS : CSI) {
764 int FI = CS.getFrameIdx();
765 if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::ScalableVector)
766 RVVCSI.push_back(CS);
767 }
768
769 return RVVCSI;
770}
771
774 const std::vector<CalleeSavedInfo> &CSI) {
775 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
776
777 SmallVector<CalleeSavedInfo, 8> PushOrLibCallsCSI;
778 if (!RVFI->useSaveRestoreLibCalls(MF) && !RVFI->isPushable(MF))
779 return PushOrLibCallsCSI;
780
781 for (const auto &CS : CSI) {
782 if (RVFI->useQCIInterrupt(MF)) {
783 // Some registers are saved by both `QC.C.MIENTER(.NEST)` and
784 // `QC.CM.PUSH(FP)`. In these cases, prioritise the CFI info that points
785 // to the versions saved by `QC.C.MIENTER(.NEST)` which is what FP
786 // unwinding would use.
788 CS.getReg()))
789 continue;
790 }
791
792 if (llvm::is_contained(FixedCSRFIMap, CS.getReg()))
793 PushOrLibCallsCSI.push_back(CS);
794 }
795
796 return PushOrLibCallsCSI;
797}
798
801 const std::vector<CalleeSavedInfo> &CSI) {
802 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
803
804 SmallVector<CalleeSavedInfo, 8> QCIInterruptCSI;
805 if (!RVFI->useQCIInterrupt(MF))
806 return QCIInterruptCSI;
807
808 for (const auto &CS : CSI) {
810 CS.getReg()))
811 QCIInterruptCSI.push_back(CS);
812 }
813
814 return QCIInterruptCSI;
815}
816
819 const std::vector<CalleeSavedInfo> &CSI) {
820 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
821
822 SmallVector<CalleeSavedInfo, 8> ACLICInterruptCSI;
823 if (!RVFI->isACLICPushPopInterrupt(MF))
824 return ACLICInterruptCSI;
825
826 for (const auto &CS : CSI) {
828 CS.getReg()))
829 ACLICInterruptCSI.push_back(CS);
830 }
831
832 return ACLICInterruptCSI;
833}
834
836 const MachineBasicBlock &MBB) {
837 const MachineFunction *MF = MBB.getParent();
838 LiveRegs.addLiveIns(MBB);
839 const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
840 for (unsigned i = 0; CSRegs[i]; ++i)
841 LiveRegs.addReg(CSRegs[i]);
842}
843
845 MachineBasicBlock *MBB, Register PreferredReg, Register DontUseReg) const {
846 MachineFunction *MF = MBB->getParent();
847
848 // Stack protection code is being inserted at beginning of function, use
849 // register which has been historically used
850 if (&MF->front() == MBB)
851 return PreferredReg;
852
854 const TargetRegisterInfo &TRI = *Subtarget.getRegisterInfo();
857
858 const MachineRegisterInfo &MRI = MF->getRegInfo();
859 // Prefer the register which has been historically used for stack protector
860 if (LiveRegs.available(MRI, PreferredReg))
861 return PreferredReg;
862
863 static const MCPhysReg CandidateRegs[] = {
864 RISCV::X5, RISCV::X6, RISCV::X7, RISCV::X28,
865 RISCV::X29, RISCV::X30, RISCV::X31,
866 };
867
868 for (unsigned Reg : CandidateRegs) {
869 if (Reg != DontUseReg && LiveRegs.available(MRI, Reg))
870 return Reg;
871 }
872
873 return Register();
874}
875
876void RISCVFrameLowering::allocateAndProbeStackForRVV(
878 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, int64_t Amount,
879 MachineInstr::MIFlag Flag, bool EmitCFI) const {
880 assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
881
882 // Emit a variable-length allocation probing loop.
883
884 // Get VLEN in TargetReg
885 Register TargetReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
886 assert(TargetReg.isValid() &&
887 "No available scratch register for stack probing");
889 uint32_t NumOfVReg = Amount / RISCV::RVVBytesPerBlock;
890 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PseudoReadVLENB), TargetReg)
891 .setMIFlag(Flag);
892 TII->mulImm(MF, MBB, MBBI, DL, TargetReg, NumOfVReg, Flag);
893
895 if (EmitCFI) {
896 // Set the CFA register to TargetReg.
897 CFIBuilder.buildDefCFA(TargetReg, -Amount);
898 }
899
900 // It will be expanded to a probe loop in `inlineStackProbe`.
901 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC_RVV))
902 .addReg(TargetReg);
903
904 if (EmitCFI) {
905 // Set the CFA register back to SP.
906 CFIBuilder.buildDefCFARegister(SPReg);
907 }
908
909 // SUB SP, SP, T1
910 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SUB), SPReg)
911 .addReg(SPReg)
912 .addReg(TargetReg)
913 .setMIFlag(Flag);
914}
915
919 llvm::raw_string_ostream &Comment) {
920 int64_t FixedOffset = Offset.getFixed();
921 int64_t ScalableOffset = Offset.getScalable();
922 unsigned DwarfVLenB = TRI.getDwarfRegNum(RISCV::VLENB, true);
923 if (FixedOffset) {
924 Expr.push_back(dwarf::DW_OP_consts);
925 appendLEB128<LEB128Sign::Signed>(Expr, FixedOffset);
926 Expr.push_back((uint8_t)dwarf::DW_OP_plus);
927 Comment << (FixedOffset < 0 ? " - " : " + ") << std::abs(FixedOffset);
928 }
929
930 Expr.push_back((uint8_t)dwarf::DW_OP_consts);
931 appendLEB128<LEB128Sign::Signed>(Expr, ScalableOffset);
932
933 Expr.push_back((uint8_t)dwarf::DW_OP_bregx);
934 appendLEB128<LEB128Sign::Unsigned>(Expr, DwarfVLenB);
935 Expr.push_back(0);
936
937 Expr.push_back((uint8_t)dwarf::DW_OP_mul);
938 Expr.push_back((uint8_t)dwarf::DW_OP_plus);
939
940 Comment << (ScalableOffset < 0 ? " - " : " + ") << std::abs(ScalableOffset)
941 << " * vlenb";
942}
943
947 assert(Offset.getScalable() != 0 && "Did not need to adjust CFA for RVV");
948 SmallString<64> Expr;
949 std::string CommentBuffer;
950 llvm::raw_string_ostream Comment(CommentBuffer);
951 // Build up the expression (Reg + FixedOffset + ScalableOffset * VLENB).
952 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
953 Expr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
954 Expr.push_back(0);
955 if (Reg == SPReg)
956 Comment << "sp";
957 else
958 Comment << printReg(Reg, &TRI);
959
961
962 SmallString<64> DefCfaExpr;
963 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
964 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
965 DefCfaExpr.append(Expr.str());
966
967 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
968 Comment.str());
969}
970
973 assert(Offset.getScalable() != 0 && "Did not need to adjust CFA for RVV");
974 SmallString<64> Expr;
975 std::string CommentBuffer;
976 llvm::raw_string_ostream Comment(CommentBuffer);
977 Comment << printReg(Reg, &TRI) << " @ cfa";
978
979 // Build up the expression (FixedOffset + ScalableOffset * VLENB).
981
982 SmallString<64> DefCfaExpr;
983 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
984 DefCfaExpr.push_back(dwarf::DW_CFA_expression);
985 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, DwarfReg);
986 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
987 DefCfaExpr.append(Expr.str());
988
989 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
990 Comment.str());
991}
992
993// Allocate stack space and probe it if necessary. When probing, the new SP is
994// probed if the bytes this allocation leaves unprobed, plus FollowupSize (what
995// later code may allocate before it probes), are more than
996// StackProbeMaxUnprobedStack. With SpillsToSP, a register spilled to 0(sp)
997// right after this allocation probes the new SP instead.
1000 MachineFunction &MF, uint64_t Offset,
1001 uint64_t RealStackSize, bool EmitCFI,
1002 bool NeedProbe, uint64_t ProbeSize,
1003 uint64_t FollowupSize, bool SpillsToSP,
1004 MachineInstr::MIFlag Flag) const {
1005 DebugLoc DL;
1006 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1007 const RISCVInstrInfo *TII = STI.getInstrInfo();
1008 bool IsRV64 = STI.is64Bit();
1010 auto NeedsSPProbe = [&](uint64_t Unprobed) {
1011 return NeedProbe && !SpillsToSP && Unprobed != 0 &&
1012 Unprobed + FollowupSize > StackProbeMaxUnprobedStack;
1013 };
1014
1015 // Simply allocate the stack if it's not big enough to require a probe loop.
1016 if (!NeedProbe || Offset <= ProbeSize) {
1018 Flag, getStackAlign());
1019
1020 if (EmitCFI)
1021 CFIBuilder.buildDefCFAOffset(RealStackSize);
1022
1023 if (NeedsSPProbe(Offset)) {
1024 // s[d|w] zero, 0(sp)
1025 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
1026 .addReg(RISCV::X0)
1027 .addReg(SPReg)
1028 .addImm(0)
1029 .setMIFlags(Flag);
1030 }
1031
1032 return;
1033 }
1034
1035 // The amount of stack that was already allocated before this allocation.
1036 uint64_t CFAAdjust = RealStackSize - Offset;
1037
1038 // Unroll the probe loop depending on the number of iterations.
1039 if (Offset < ProbeSize * 5) {
1040 uint64_t CurrentOffset = 0;
1041 while (CurrentOffset + ProbeSize <= Offset) {
1042 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
1043 StackOffset::getFixed(-ProbeSize), Flag, getStackAlign());
1044 // s[d|w] zero, 0(sp)
1045 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
1046 .addReg(RISCV::X0)
1047 .addReg(SPReg)
1048 .addImm(0)
1049 .setMIFlags(Flag);
1050
1051 CurrentOffset += ProbeSize;
1052 if (EmitCFI)
1053 CFIBuilder.buildDefCFAOffset(CurrentOffset + CFAAdjust);
1054 }
1055
1056 uint64_t Residual = Offset - CurrentOffset;
1057 if (Residual) {
1058 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
1059 StackOffset::getFixed(-Residual), Flag, getStackAlign());
1060 if (EmitCFI)
1061 CFIBuilder.buildDefCFAOffset(RealStackSize);
1062
1063 if (NeedsSPProbe(Residual)) {
1064 // s[d|w] zero, 0(sp)
1065 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
1066 .addReg(RISCV::X0)
1067 .addReg(SPReg)
1068 .addImm(0)
1069 .setMIFlags(Flag);
1070 }
1071 }
1072
1073 return;
1074 }
1075
1076 // Emit a variable-length allocation probing loop.
1077 uint64_t RoundedSize = alignDown(Offset, ProbeSize);
1078 uint64_t Residual = Offset - RoundedSize;
1079
1080 Register TargetReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
1081 assert(TargetReg.isValid() &&
1082 "No available scratch register for stack probing");
1083 // SUB TargetReg, SP, RoundedSize
1084 RI->adjustReg(MBB, MBBI, DL, TargetReg, SPReg,
1085 StackOffset::getFixed(-RoundedSize), Flag, getStackAlign());
1086
1087 if (EmitCFI) {
1088 // Set the CFA register to TargetReg.
1089 CFIBuilder.buildDefCFA(TargetReg, RoundedSize + CFAAdjust);
1090 }
1091
1092 // It will be expanded to a probe loop in `inlineStackProbe`.
1093 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC)).addReg(TargetReg);
1094
1095 if (EmitCFI) {
1096 // Set the CFA register back to SP.
1097 CFIBuilder.buildDefCFARegister(SPReg);
1098 }
1099
1100 if (Residual)
1101 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackOffset::getFixed(-Residual),
1102 Flag, getStackAlign());
1103
1104 if (EmitCFI)
1105 CFIBuilder.buildDefCFAOffset(RealStackSize);
1106
1107 if (NeedsSPProbe(Residual)) {
1108 // s[d|w] zero, 0(sp)
1109 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
1110 .addReg(RISCV::X0)
1111 .addReg(SPReg)
1112 .addImm(0)
1113 .setMIFlags(Flag);
1114 }
1115}
1116
1117static bool isPush(unsigned Opcode) {
1118 switch (Opcode) {
1119 case RISCV::CM_PUSH:
1120 case RISCV::QC_CM_PUSH:
1121 case RISCV::QC_CM_PUSHFP:
1122 return true;
1123 default:
1124 return false;
1125 }
1126}
1127
1128static bool isPop(unsigned Opcode) {
1129 // There are other pops but these are the only ones introduced during this
1130 // pass.
1131 switch (Opcode) {
1132 case RISCV::CM_POP:
1133 case RISCV::QC_CM_POP:
1134 return true;
1135 default:
1136 return false;
1137 }
1138}
1139
1141 bool UpdateFP) {
1142 switch (Kind) {
1144 return RISCV::CM_PUSH;
1146 return UpdateFP ? RISCV::QC_CM_PUSHFP : RISCV::QC_CM_PUSH;
1147 default:
1148 llvm_unreachable("Unhandled PushPopKind");
1149 }
1150}
1151
1153 // There are other pops but they are introduced later by the Push/Pop
1154 // Optimizer.
1155 switch (Kind) {
1157 return RISCV::CM_POP;
1159 return RISCV::QC_CM_POP;
1160 default:
1161 llvm_unreachable("Unhandled PushPopKind");
1162 }
1163}
1164
1166 MachineBasicBlock &MBB) const {
1167 MachineFrameInfo &MFI = MF.getFrameInfo();
1168 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1169 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1171 bool PreferAscendingLS = STI.preferAscendingLoadStore();
1172
1173 Register BPReg = RISCVABI::getBPReg();
1174
1175 // Debug location must be unknown since the first debug location is used
1176 // to determine the end of the prologue.
1177 DebugLoc DL;
1178
1179 // All calls are tail calls in GHC calling conv, and functions have no
1180 // prologue/epilogue.
1182 return;
1183
1184 // The CFA is the SP before the Smip/Ssip hardware push, so describe it
1185 // before any other prologue code.
1186 if (needsDwarfCFI(MF) && RVFI->isACLICPushPopInterrupt(MF)) {
1188 CFIBuilder.buildDefCFAOffset(RVFI->getACLICInterruptStackSize());
1189 for (const CalleeSavedInfo &CS :
1191 CFIBuilder.buildOffset(CS.getReg(),
1192 MFI.getObjectOffset(CS.getFrameIdx()));
1193 }
1194
1195 // SiFive CLIC needs to swap `sp` into `sf.mscratchcsw`
1197
1198 // Emit prologue for shadow call stack.
1199 emitSCSPrologue(MF, MBB, MBBI, DL);
1200
1201 // We keep track of the first instruction because it might be a
1202 // `(QC.)CM.PUSH(FP)`, and we may need to adjust the immediate rather than
1203 // inserting an `addi sp, sp, -N*16`
1204 auto PossiblePush = MBBI;
1205
1206 // Skip past all callee-saved register spill instructions.
1207 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
1208 ++MBBI;
1209
1210 // Determine the correct frame layout
1211 determineFrameLayout(MF);
1212
1213 const auto &CSI = MFI.getCalleeSavedInfo();
1214
1215 // Skip to before the spills of scalar callee-saved registers
1216 // FIXME: assumes exactly one instruction is used to restore each
1217 // callee-saved register.
1218 MBBI = std::prev(
1219 MBBI, getRVVCalleeSavedInfo(MF, CSI).size() +
1220 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1222 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1223
1224 if (unsigned LibCallFrameSize = RVFI->getLibCallStackSize()) {
1225 if (NeedsDwarfCFI) {
1226 CFIBuilder.buildDefCFAOffset(LibCallFrameSize);
1227 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1228 CFIBuilder.buildOffset(CS.getReg(),
1229 MFI.getObjectOffset(CS.getFrameIdx()));
1230 }
1231 }
1232
1233 // FIXME (note copied from Lanai): This appears to be overallocating. Needs
1234 // investigation. Get the number of bytes to allocate from the FrameInfo.
1235 uint64_t RealStackSize = getStackSizeWithRVVPadding(MF);
1236 uint64_t StackSize = RealStackSize - RVFI->getReservedSpillsSize();
1237 uint64_t RVVStackSize = RVFI->getRVVStackSize();
1238
1239 // Early exit if there is no need to allocate on the stack
1240 if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
1241 return;
1242
1243 // If the stack pointer has been marked as reserved, then produce an error if
1244 // the frame requires stack allocation
1245 if (STI.isRegisterReservedByUser(SPReg))
1247 MF.getFunction(), "Stack pointer required, but has been reserved."});
1248
1249 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1250 // Split the SP adjustment to reduce the offsets of callee saved spill.
1251 if (FirstSPAdjustAmount) {
1252 StackSize = FirstSPAdjustAmount - RVFI->getACLICInterruptStackSize();
1253 RealStackSize = FirstSPAdjustAmount;
1254 }
1255
1256 if (RVFI->useQCIInterrupt(MF)) {
1257 // The function starts with `QC.C.MIENTER(.NEST)`, so the `(QC.)CM.PUSH(FP)`
1258 // could only be the next instruction.
1259 ++PossiblePush;
1260
1261 if (NeedsDwarfCFI) {
1262 // Insert the CFI metadata before where we think the `(QC.)CM.PUSH(FP)`
1263 // could be. The PUSH will also get its own CFI metadata for its own
1264 // modifications, which should come after the PUSH.
1265 CFIInstBuilder PushCFIBuilder(MBB, PossiblePush,
1268 for (const CalleeSavedInfo &CS : getQCISavedInfo(MF, CSI))
1269 PushCFIBuilder.buildOffset(CS.getReg(),
1270 MFI.getObjectOffset(CS.getFrameIdx()));
1271 }
1272 }
1273
1274 if (RVFI->isPushable(MF) && PossiblePush != MBB.end() &&
1275 isPush(PossiblePush->getOpcode())) {
1276 // Use available stack adjustment in push instruction to allocate additional
1277 // stack space. Align the stack size down to a multiple of 16. This is
1278 // needed for RVE.
1279 // FIXME: Can we increase the stack size to a multiple of 16 instead?
1280 uint64_t StackAdj =
1281 std::min(alignDown(StackSize, 16), static_cast<uint64_t>(48));
1282 PossiblePush->getOperand(1).setImm(StackAdj);
1283 StackSize -= StackAdj;
1284
1285 if (NeedsDwarfCFI) {
1286 CFIBuilder.buildDefCFAOffset(RealStackSize - StackSize);
1287 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1288 CFIBuilder.buildOffset(CS.getReg(),
1289 MFI.getObjectOffset(CS.getFrameIdx()));
1290 }
1291 }
1292
1293 // Allocate space on the stack if necessary.
1295 const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
1296 bool NeedProbe = TLI->hasInlineStackProbe(MF);
1297 uint64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
1298 // With inline stack probing, at most StackProbeMaxUnprobedStack bytes above
1299 // SP may be left unprobed at a call, and a probing loop starts from a probed
1300 // SP. Each allocation is given what may follow it before the next probe;
1301 // FromProbedSP, over the limit, makes it probe the new SP.
1302 constexpr uint64_t FromProbedSP = StackProbeMaxUnprobedStack + 1;
1303 // Call frames that are not reserved are probed when larger than
1304 // StackProbeMaxUnprobedStack, and dynamic allocations always are.
1305 uint64_t BodyAllocSize = 0;
1306 if (RVFI->hasDynamicAllocation())
1307 BodyAllocSize = FromProbedSP;
1308 else if (!hasReservedCallFrame(MF))
1309 BodyAllocSize = MFI.isMaxCallFrameSizeComputed()
1311 : FromProbedSP;
1312 // Realigning SP moves it down by up to RealignPadding bytes, with a probing
1313 // loop if that may be the probe size or more. The realigned SP is probed
1314 // after a loop, or if RealignPadding + BodyAllocSize is over the limit.
1315 bool RealignStack = RI->hasStackRealignment(MF);
1316 uint64_t RealignPadding =
1317 RealignStack && MFI.getMaxAlign() > getStackAlign()
1318 ? MFI.getMaxAlign().value() - getStackAlign().value()
1319 : 0;
1320 bool ProbeRealignLoop = NeedProbe && RealignPadding >= ProbeSize;
1321 bool ProbeRealignedSP = NeedProbe && RealignStack &&
1322 (ProbeRealignLoop || RealignPadding + BodyAllocSize >
1324 // What follows the fixed-size allocations: the RVV area and a realignment
1325 // loop start from a probed SP; otherwise the realignment, if any, and the
1326 // function body, unless the realigned SP is probed.
1327 uint64_t FollowupSize =
1328 RealignPadding + (ProbeRealignedSP ? 0 : BodyAllocSize);
1329 if (RVVStackSize || ProbeRealignLoop)
1330 FollowupSize = FromProbedSP;
1331 if (StackSize != 0) {
1332 // A callee-saved register spilled to 0(sp) probes the new SP, before any
1333 // later allocation or call.
1334 bool SpillsToSP =
1335 NeedProbe &&
1337 getUnmanagedInterruptCSI(MF, CSI), [&](const CalleeSavedInfo &CS) {
1338 Register FrameReg;
1340 getFrameIndexReference(MF, CS.getFrameIdx(), FrameReg);
1341 return FrameReg == SPReg && !Offset.getScalable() &&
1342 Offset.getFixed() == 0;
1343 });
1344 // A second SP adjustment starts from a probed SP.
1345 allocateStack(MBB, MBBI, MF, StackSize, RealStackSize, NeedsDwarfCFI,
1346 NeedProbe, ProbeSize,
1347 FirstSPAdjustAmount ? FromProbedSP : FollowupSize, SpillsToSP,
1349 }
1350
1352
1353 // Save SiFive CLIC CSRs into Stack
1355
1356 // The frame pointer is callee-saved, and code has been generated for us to
1357 // save it to the stack. We need to skip over the storing of callee-saved
1358 // registers as the frame pointer must be modified after it has been saved
1359 // to the stack, not before.
1360 // FIXME: assumes exactly one instruction is used to save each callee-saved
1361 // register.
1362 std::advance(MBBI,
1363 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1364 CFIBuilder.setInsertPoint(MBBI);
1365
1366 // Iterate over list of callee-saved registers and emit .cfi_offset
1367 // directives.
1368 if (NeedsDwarfCFI) {
1369 for (const CalleeSavedInfo &CS :
1370 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS)) {
1371 MCRegister Reg = CS.getReg();
1372 int64_t Offset = MFI.getObjectOffset(CS.getFrameIdx());
1373 // Emit CFI for both sub-registers. The even register is at the base
1374 // offset and odd at base+4.
1375 if (RISCV::GPRPairRegClass.contains(Reg)) {
1376 MCRegister EvenReg = RI->getSubReg(Reg, RISCV::sub_gpr_even);
1377 MCRegister OddReg = RI->getSubReg(Reg, RISCV::sub_gpr_odd);
1378 CFIBuilder.buildOffset(EvenReg, Offset);
1379 CFIBuilder.buildOffset(OddReg, Offset + 4);
1380 } else {
1381 CFIBuilder.buildOffset(Reg, Offset);
1382 }
1383 }
1384 }
1385
1386 // Generate new FP.
1387 if (hasFP(MF)) {
1388 if (STI.isRegisterReservedByUser(FPReg))
1390 MF.getFunction(), "Frame pointer required, but has been reserved."});
1391 // The frame pointer does need to be reserved from register allocation.
1392 assert(MF.getRegInfo().isReserved(FPReg) && "FP not reserved");
1393
1394 // Some stack management variants automatically keep FP updated, so we don't
1395 // need an instruction to do so.
1396 if (!RVFI->hasImplicitFPUpdates(MF)) {
1397 RI->adjustReg(
1398 MBB, MBBI, DL, FPReg, SPReg,
1399 StackOffset::getFixed(RealStackSize - RVFI->getVarArgsSaveSize()),
1401 }
1402
1403 if (NeedsDwarfCFI)
1404 CFIBuilder.buildDefCFA(FPReg, RVFI->getVarArgsSaveSize());
1405 }
1406
1407 uint64_t SecondSPAdjustAmount = 0;
1408 // Emit the second SP adjustment after saving callee saved registers.
1409 if (FirstSPAdjustAmount) {
1410 SecondSPAdjustAmount = getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
1411 assert(SecondSPAdjustAmount > 0 &&
1412 "SecondSPAdjustAmount should be greater than zero");
1413
1414 // The first SP adjustment left SP probed.
1415 allocateStack(MBB, MBBI, MF, SecondSPAdjustAmount,
1416 getStackSizeWithRVVPadding(MF), NeedsDwarfCFI && !hasFP(MF),
1417 NeedProbe, ProbeSize, FollowupSize, /*SpillsToSP=*/false,
1419 }
1420
1421 if (RVVStackSize) {
1422 if (NeedProbe) {
1423 allocateAndProbeStackForRVV(MF, MBB, MBBI, DL, RVVStackSize,
1425 NeedsDwarfCFI && !hasFP(MF));
1426 } else {
1427 // We must keep the stack pointer aligned through any intermediate
1428 // updates.
1429 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
1430 StackOffset::getScalable(-RVVStackSize),
1432 }
1433
1434 if (NeedsDwarfCFI && !hasFP(MF)) {
1435 // Emit .cfi_def_cfa_expression "sp + StackSize + RVVStackSize * vlenb".
1437 *RI, SPReg,
1438 StackOffset::get(getStackSizeWithRVVPadding(MF), RVVStackSize / 8)));
1439 }
1440
1441 if (NeedProbe) {
1442 // The probing loop leaves a residual of up to ProbeSize - 1 bytes, whose
1443 // size is not known at compile time: probe it.
1444 const RISCVInstrInfo *TII = STI.getInstrInfo();
1445 BuildMI(MBB, MBBI, DL, TII->get(STI.is64Bit() ? RISCV::SD : RISCV::SW))
1446 .addReg(RISCV::X0)
1447 .addReg(SPReg)
1448 .addImm(0)
1450 }
1451
1452 std::advance(MBBI, getRVVCalleeSavedInfo(MF, CSI).size());
1453 if (NeedsDwarfCFI)
1454 emitCalleeSavedRVVPrologCFI(MBB, MBBI, hasFP(MF));
1455 }
1456
1457 if (hasFP(MF)) {
1458 // Realign Stack
1459 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1460 if (RI->hasStackRealignment(MF)) {
1461 Align MaxAlignment = MFI.getMaxAlign();
1462
1463 const RISCVInstrInfo *TII = STI.getInstrInfo();
1464 if (ProbeRealignLoop) {
1465 // Realigning may move SP down by more than the probe size. Compute
1466 // that amount (SP modulo MaxAlignment) and allocate it with the
1467 // probing loop used for the RVV area.
1468 Register AmountReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
1469 assert(AmountReg.isValid() &&
1470 "No available scratch register for stack probing");
1471 unsigned ShiftAmount = STI.getXLen() - Log2(MaxAlignment);
1472 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), AmountReg)
1473 .addReg(SPReg)
1474 .addImm(ShiftAmount)
1476 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), AmountReg)
1477 .addReg(AmountReg)
1478 .addImm(ShiftAmount)
1480 // It will be expanded to a probe loop in `inlineStackProbe`.
1481 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC_RVV))
1482 .addReg(AmountReg);
1483 // SUB SP, SP, AmountReg
1484 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SUB), SPReg)
1485 .addReg(SPReg)
1486 .addReg(AmountReg)
1488 } else if (isInt<12>(-(int64_t)MaxAlignment.value())) {
1489 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
1490 .addReg(SPReg)
1491 .addImm(-(int64_t)MaxAlignment.value())
1493 } else {
1494 unsigned ShiftAmount = Log2(MaxAlignment);
1495 Register VR =
1496 MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
1497 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
1498 .addReg(SPReg)
1499 .addImm(ShiftAmount)
1501 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
1502 .addReg(VR)
1503 .addImm(ShiftAmount)
1505 }
1506 if (ProbeRealignedSP) {
1507 bool IsRV64 = STI.is64Bit();
1508 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
1509 .addReg(RISCV::X0)
1510 .addReg(SPReg)
1511 .addImm(0)
1513 }
1514 // FP will be used to restore the frame in the epilogue, so we need
1515 // another base register BP to record SP after re-alignment. SP will
1516 // track the current stack after allocating variable sized objects.
1517 if (hasBP(MF)) {
1518 // move BP, SP
1519 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
1520 .addReg(SPReg)
1521 .addImm(0)
1523 }
1524 }
1525 }
1526}
1527
1528void RISCVFrameLowering::deallocateStack(MachineFunction &MF,
1531 const DebugLoc &DL,
1532 uint64_t &StackSize,
1533 int64_t CFAOffset) const {
1535
1536 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackOffset::getFixed(StackSize),
1538 StackSize = 0;
1539
1540 if (needsDwarfCFI(MF))
1542 .buildDefCFAOffset(CFAOffset);
1543}
1544
1546 MachineBasicBlock &MBB) const {
1547 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1548 MachineFrameInfo &MFI = MF.getFrameInfo();
1549 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1550 bool PreferAscendingLS = STI.preferAscendingLoadStore();
1551
1552 // All calls are tail calls in GHC calling conv, and functions have no
1553 // prologue/epilogue.
1555 return;
1556
1557 // Get the insert location for the epilogue. If there were no terminators in
1558 // the block, get the last instruction.
1560 DebugLoc DL;
1561 if (!MBB.empty()) {
1562 MBBI = MBB.getLastNonDebugInstr();
1563 if (MBBI != MBB.end())
1564 DL = MBBI->getDebugLoc();
1565
1566 MBBI = MBB.getFirstTerminator();
1567
1568 // Skip to before the restores of all callee-saved registers.
1569 while (MBBI != MBB.begin() &&
1570 std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
1571 --MBBI;
1572 }
1573
1574 const auto &CSI = MFI.getCalleeSavedInfo();
1575
1576 // Skip to before the restores of scalar callee-saved registers
1577 // FIXME: assumes exactly one instruction is used to restore each
1578 // callee-saved register.
1579 auto FirstScalarCSRRestoreInsn =
1580 std::next(MBBI, getRVVCalleeSavedInfo(MF, CSI).size());
1581 CFIInstBuilder CFIBuilder(MBB, FirstScalarCSRRestoreInsn,
1583 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1584
1585 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1586 uint64_t RealStackSize = FirstSPAdjustAmount ? FirstSPAdjustAmount
1588 uint64_t StackSize =
1589 FirstSPAdjustAmount
1590 ? FirstSPAdjustAmount - RVFI->getACLICInterruptStackSize()
1591 : getStackSizeWithRVVPadding(MF) - RVFI->getReservedSpillsSize();
1592 uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
1593 uint64_t RVVStackSize = RVFI->getRVVStackSize();
1594
1595 // An unreserved call frame moves SP only around calls that pass arguments
1596 // on the stack. Otherwise SP is where the prologue left it, and the FP
1597 // restore is worth keeping only where it replaces the multi-instruction
1598 // undo of an RVV area or a split SP adjustment.
1599 bool CallFrameMovesSP =
1600 !hasReservedCallFrame(MF) &&
1601 (!MFI.isMaxCallFrameSizeComputed() || MFI.getMaxCallFrameSize() != 0);
1602 bool RestoreSPFromFP =
1603 RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
1604 CallFrameMovesSP ||
1605 (!hasReservedCallFrame(MF) && (RVVStackSize || FirstSPAdjustAmount));
1606 if (RVVStackSize) {
1607 // If RestoreSPFromFP the stack pointer will be restored using the frame
1608 // pointer value.
1609 if (!RestoreSPFromFP)
1610 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, SPReg,
1611 StackOffset::getScalable(RVVStackSize),
1613
1614 if (NeedsDwarfCFI) {
1615 if (!hasFP(MF))
1616 CFIBuilder.buildDefCFA(SPReg, RealStackSize);
1617 emitCalleeSavedRVVEpilogCFI(MBB, FirstScalarCSRRestoreInsn);
1618 }
1619 }
1620
1621 if (FirstSPAdjustAmount) {
1622 uint64_t SecondSPAdjustAmount =
1623 getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
1624 assert(SecondSPAdjustAmount > 0 &&
1625 "SecondSPAdjustAmount should be greater than zero");
1626
1627 // If RestoreSPFromFP the stack pointer will be restored using the frame
1628 // pointer value.
1629 if (!RestoreSPFromFP)
1630 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, SPReg,
1631 StackOffset::getFixed(SecondSPAdjustAmount),
1633
1634 if (NeedsDwarfCFI && !hasFP(MF))
1635 CFIBuilder.buildDefCFAOffset(FirstSPAdjustAmount);
1636 }
1637
1638 // Restore the stack pointer using the value of the frame pointer. Only
1639 // necessary if the stack pointer was modified, meaning the stack size is
1640 // unknown.
1641 //
1642 // In order to make sure the stack point is right through the EH region,
1643 // we also need to restore stack pointer from the frame pointer if we
1644 // don't preserve stack space within prologue/epilogue for outgoing variables,
1645 // normally it's just checking the variable sized object is present or not
1646 // is enough, but we also don't preserve that at prologue/epilogue when
1647 // have vector objects in stack.
1648 if (RestoreSPFromFP) {
1649 assert(hasFP(MF) && "frame pointer should not have been eliminated");
1650 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, FPReg,
1652 getStackAlign());
1653 }
1654
1655 if (NeedsDwarfCFI && hasFP(MF))
1656 CFIBuilder.buildDefCFA(SPReg, RealStackSize);
1657
1658 // Skip to after the restores of scalar callee-saved registers
1659 // FIXME: assumes exactly one instruction is used to restore each
1660 // callee-saved register.
1661 MBBI = std::next(FirstScalarCSRRestoreInsn,
1662 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1663 CFIBuilder.setInsertPoint(MBBI);
1664 emitSiFiveCLICPreemptibleRestores(MF, MBB, MBBI, CFIBuilder, DL);
1665 emitACLICPreemptibleRestores(MF, MBB, MBBI, CFIBuilder, DL);
1666
1667 auto emitRestoreCFI = [&](auto CSInfo) {
1668 for (auto &CS : CSInfo) {
1669 MCRegister Reg = CS.getReg();
1670 // Emit CFI for both sub-registers.
1671 if (RISCV::GPRPairRegClass.contains(Reg)) {
1672 MCRegister EvenReg = RI->getSubReg(Reg, RISCV::sub_gpr_even);
1673 MCRegister OddReg = RI->getSubReg(Reg, RISCV::sub_gpr_odd);
1674 CFIBuilder.buildRestore(EvenReg);
1675 CFIBuilder.buildRestore(OddReg);
1676 } else {
1677 CFIBuilder.buildRestore(Reg);
1678 }
1679 }
1680 };
1681
1682 if (RVFI->useSaveRestoreLibCalls(MF)) {
1683 if (RVFI->hasShadowStack(MF)) {
1684 // We don't use `__riscv_restore_<N>` to restore in this case, so we need
1685 // to make sure we're correctly accounting for the stack deallocation we
1686 // need to do, which now must include the allocation made by
1687 // `__riscv_save_<N>`.
1688 StackSize += RVFI->getLibCallStackSize();
1689
1692 MBBI = std::next(MBBI, LibcallCSI.size());
1693 CFIBuilder.setInsertPoint(MBBI);
1694
1695 if (NeedsDwarfCFI)
1696 emitRestoreCFI(LibcallCSI);
1697 } else {
1698 // tail __riscv_restore_[0-12] instruction is considered as a terminator,
1699 // therefore it is unnecessary to place any CFI instructions after it.
1700 // Just deallocate stack if needed and return.
1701 if (StackSize != 0)
1702 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1703 RVFI->getLibCallStackSize());
1704
1705 // Emit epilogue for shadow call stack.
1706 emitSCSEpilogue(MF, MBB, MBBI, DL);
1707 return;
1708 }
1709 }
1710
1711 // Recover callee-saved registers.
1712 if (NeedsDwarfCFI)
1713 emitRestoreCFI(getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS));
1714
1715 if (RVFI->isPushable(MF) && MBBI != MBB.end() && isPop(MBBI->getOpcode())) {
1716 // Use available stack adjustment in pop instruction to deallocate stack
1717 // space. Align the stack size down to a multiple of 16. This is needed for
1718 // RVE.
1719 // FIXME: Can we increase the stack size to a multiple of 16 instead?
1720 uint64_t StackAdj =
1721 std::min(alignDown(StackSize, 16), static_cast<uint64_t>(48));
1722 MBBI->getOperand(1).setImm(StackAdj);
1723 StackSize -= StackAdj;
1724
1725 if (StackSize != 0)
1726 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1727 /*stack_adj of cm.pop instr*/ RealStackSize - StackSize);
1728
1729 if (NeedsDwarfCFI) {
1730 CFIBuilder.setInsertPoint(++MBBI);
1731 emitRestoreCFI(getPushOrLibCallsSavedInfo(MF, CSI));
1732 // Update CFA Offset. If this is a QCI interrupt function, there will
1733 // be a leftover offset which is deallocated by `QC.C.MILEAVERET`,
1734 // otherwise getQCIInterruptStackSize() will be 0.
1735 CFIBuilder.buildDefCFAOffset(RVFI->getQCIInterruptStackSize());
1736 }
1737 }
1738
1739 // Deallocate the software-managed stack. Hardware interrupt return
1740 // instructions deallocate any remaining interrupt entry frame.
1741 if (StackSize != 0)
1742 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1743 RVFI->getQCIInterruptStackSize() +
1744 RVFI->getACLICInterruptStackSize());
1745
1746 // Emit epilogue for shadow call stack.
1747 emitSCSEpilogue(MF, MBB, MBBI, DL);
1748
1749 // SiFive CLIC needs to swap `sf.mscratchcsw` into `sp`
1751}
1752
1754 MCRegister Reg) {
1755 if (RISCV::GPRRegClass.contains(Reg))
1756 return Reg;
1757
1758 std::array<TargetRegisterClass const *, 2> RegisterClasses = {
1759 &RISCV::GPRF16RegClass, &RISCV::GPRF32RegClass};
1760 std::array<unsigned, 2> SubIdx = {RISCV::sub_16, RISCV::sub_32};
1761
1762 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1763 if (RegClass->contains(Reg)) {
1764 if (MCRegister Super =
1765 TRI.getMatchingSuperReg(Reg, SubReg, &RISCV::GPRRegClass))
1766 return Super;
1767 }
1768 }
1769
1771 "getPhysicalGPR called with unsupported register");
1772}
1773
1775 const TargetRegisterInfo &TRI,
1776 MCRegister Reg) {
1777 if (!STI.hasStdExtF())
1778 return MCRegister();
1779
1780 TargetRegisterClass const *LargestFPRegClass = STI.getLargestFPRegClass();
1781 assert(LargestFPRegClass);
1782
1783 if (LargestFPRegClass->contains(Reg))
1784 return Reg;
1785
1786 std::array<TargetRegisterClass const *, 3> RegisterClasses = {
1787 &RISCV::FPR16RegClass, &RISCV::FPR32RegClass, &RISCV::FPR64RegClass};
1788 std::array<unsigned, 3> SubIdx = {RISCV::sub_16, RISCV::sub_32,
1789 RISCV::sub_64};
1790
1791 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1792 if (RegClass->contains(Reg)) {
1793 if (MCRegister Super =
1794 TRI.getMatchingSuperReg(Reg, SubReg, LargestFPRegClass))
1795 return Super;
1796 }
1797 }
1798
1799 // Reg is bigger than what's currently available for the target, we can ignore
1800 // it.
1801 return MCRegister();
1802}
1803
1804void RISCVFrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
1806 RegScavenger *RS) const {
1807 // Insertion point.
1809
1810 // Fake a debug loc.
1811 DebugLoc DL;
1812 if (MBBI != MBB.end())
1813 DL = MBBI->getDebugLoc();
1814
1815 const MachineFunction &MF = *MBB.getParent();
1816 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
1817 const RISCVInstrInfo &TII = *STI.getInstrInfo();
1818
1819 BitVector FinalRegsToZero(TRI.getNumRegs());
1820
1821 bool HasVRegister = false;
1822
1823 for (MCRegister Reg : RegsToZero.set_bits()) {
1824 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1825 FinalRegsToZero.set(getPhysicalGPR(TRI, Reg).id());
1826 } else if (RISCV::GPRPairRegClass.contains(Reg)) {
1827 FinalRegsToZero.set(
1828 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_even)).id());
1829 FinalRegsToZero.set(
1830 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_odd)).id());
1831 } else if (TRI.isFPRegister(Reg)) {
1832 if (MCRegister MaybeReg = getLargestFPRegisterOrZero(STI, TRI, Reg))
1833 FinalRegsToZero.set(MaybeReg.id());
1835 TRI.getMinimalPhysRegClass(Reg))) {
1836 if (!STI.hasVInstructions())
1837 continue;
1838 HasVRegister = true;
1839
1840 for (MCRegister SubReg : TRI.subregs_inclusive(Reg)) {
1841 if (TRI.subregs(SubReg).empty())
1842 FinalRegsToZero.set(SubReg.id());
1843 }
1844 }
1845 }
1846
1847 if (HasVRegister) {
1848 RISCVVType::VLMUL VLMUL = RISCVVType::encodeLMUL(1, /*Fractional=*/false);
1849 unsigned VTypeImm = RISCVVType::encodeVTYPE(
1850 VLMUL, /*SEW=*/32, /*TailAgnostic=*/true, /*MaskAgnostic=*/true);
1851
1852 MCRegister TemporaryReg = RISCV::NoRegister;
1853 for (MCRegister Reg : FinalRegsToZero.set_bits()) {
1854 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1855 TemporaryReg = Reg;
1856 break;
1857 }
1858 }
1859
1860 if (TemporaryReg == RISCV::NoRegister) {
1861 RS->enterBasicBlockEnd(MBB);
1862 TemporaryReg = RS->scavengeRegisterBackwards(RISCV::GPRRegClass, MBBI,
1863 /*RestoreAfter=*/false,
1864 /*SPAdj=*/0);
1865 }
1866
1867 if (MBB.getParent()
1868 ->getFunction()
1869 .getFnAttribute("zero-call-used-regs")
1870 .getValueAsString() == "used")
1871 FinalRegsToZero.set(TemporaryReg.id());
1872
1873 BuildMI(MBB, MBBI, DL, TII.get(RISCV::VSETVLI), TemporaryReg)
1874 .addReg(RISCV::X0)
1875 .addImm(VTypeImm)
1876 .addReg(RISCV::VL, RegState::ImplicitDefine)
1877 .addReg(RISCV::VTYPE, RegState::ImplicitDefine);
1878 }
1879
1880 for (MCRegister Reg : FinalRegsToZero.set_bits())
1881 TII.buildClearRegister(Reg, MBB, MBBI, DL);
1882}
1883
1886 Register &FrameReg) const {
1887 const MachineFrameInfo &MFI = MF.getFrameInfo();
1889 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1890
1891 // Callee-saved registers should be referenced relative to the stack
1892 // pointer (positive offset), otherwise use the frame pointer (negative
1893 // offset).
1894 const auto &CSI = getUnmanagedCSI(MF, MFI.getCalleeSavedInfo(),
1895 STI.preferAscendingLoadStore());
1896 int MinCSFI = 0;
1897 int MaxCSFI = -1;
1899 auto StackID = MFI.getStackID(FI);
1900
1901 assert((StackID == TargetStackID::Default ||
1902 StackID == TargetStackID::ScalableVector) &&
1903 "Unexpected stack ID for the frame object.");
1904 if (StackID == TargetStackID::Default) {
1905 assert(getOffsetOfLocalArea() == 0 && "LocalAreaOffset is not 0!");
1907 MFI.getOffsetAdjustment());
1908 } else if (StackID == TargetStackID::ScalableVector) {
1910 }
1911
1912 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1913
1914 if (CSI.size()) {
1915 MinCSFI = std::min(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1916 MaxCSFI = std::max(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1917 }
1918
1919 auto FIIsCalleeSave = [&](const CalleeSavedInfo &CS) -> bool {
1920 return FI == CS.getFrameIdx();
1921 };
1922
1923 bool IsInterruptCSR = RVFI->isInterruptCSRFrameIndex(FI);
1924 bool IsInlineRestoredLibcallCSR = llvm::any_of(
1925 getPushOrLibCallsSavedInfo(MF, MFI.getCalleeSavedInfo()), FIIsCalleeSave);
1926 if ((FI >= MinCSFI && FI <= MaxCSFI) || IsInterruptCSR ||
1927 IsInlineRestoredLibcallCSR) {
1928 FrameReg = SPReg;
1929
1930 if (FirstSPAdjustAmount)
1931 Offset += StackOffset::getFixed(FirstSPAdjustAmount);
1932 else
1934 return Offset;
1935 }
1936
1937 if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
1938 // If the stack was realigned, the frame pointer is set in order to allow
1939 // SP to be restored, so we need another base register to record the stack
1940 // after realignment.
1941 // |--------------------------| --
1942 // | callee-allocated save | | <----|
1943 // | area for register varargs| | |
1944 // |--------------------------| <-- FP |
1945 // | callee-saved registers | | |
1946 // |--------------------------| -- |
1947 // | realignment (the size of | | |
1948 // | this area is not counted | | |
1949 // | in MFI.getStackSize()) | | |
1950 // |--------------------------| -- |-- MFI.getStackSize()
1951 // | RVV alignment padding | | |
1952 // | (not counted in | | |
1953 // | MFI.getStackSize() but | | |
1954 // | counted in | | |
1955 // | RVFI.getRVVStackSize()) | | |
1956 // |--------------------------| -- |
1957 // | RVV objects | | |
1958 // | (not counted in | | |
1959 // | MFI.getStackSize()) | | |
1960 // |--------------------------| -- |
1961 // | padding before RVV | | |
1962 // | (not counted in | | |
1963 // | MFI.getStackSize() or in | | |
1964 // | RVFI.getRVVStackSize()) | | |
1965 // |--------------------------| -- |
1966 // | scalar local variables | | <----'
1967 // |--------------------------| -- <-- BP (if var sized objects present)
1968 // | VarSize objects | |
1969 // |--------------------------| -- <-- SP
1970 if (hasBP(MF)) {
1971 FrameReg = RISCVABI::getBPReg();
1972 } else {
1973 // VarSize objects must be empty in this case!
1974 assert(!MFI.hasVarSizedObjects());
1975 FrameReg = SPReg;
1976 }
1977 } else if (!RI->hasStackRealignment(MF)) {
1978 // Note: Keeping the following as multiple 'if' statements rather than
1979 // merging to a single expression for readability.
1980 if (!hasFP(MF)) {
1981 // No FP available, must use SP.
1982 FrameReg = SPReg;
1983 } else {
1984 FrameReg = FPReg;
1985 // SP-relative addressing is only valid when SP is stable throughout
1986 // the function body: no dynamic SP adjustments for outgoing call args,
1987 // no variable-sized objects, and no RVV scalable stack regions.
1988 // hasReservedCallFrame() conservatively encompasses all these checks.
1989 if (hasReservedCallFrame(MF)) {
1990 // Both FP and SP are candidates.
1991 // Prefer SP when the SP-relative offset fits in the compressed
1992 // instruction immediate range.
1993 int64_t SPOff = Offset.getFixed() + MFI.getStackSize();
1994 int64_t CLWSPMaxOffset = 252;
1995 int64_t CLDSPMaxOffset = 504;
1996 int64_t SPThreshold = STI.is64Bit() ? CLDSPMaxOffset : CLWSPMaxOffset;
1997 if (SPOff >= 0 && SPOff <= SPThreshold)
1998 FrameReg = SPReg;
1999 }
2000 }
2001 } else {
2002 assert(RI->hasStackRealignment(MF) && MFI.isFixedObjectIndex(FI) &&
2003 "Expected fixed object with stack realignment");
2004 assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
2005 FrameReg = FPReg;
2006 }
2007
2008 if (FrameReg == FPReg) {
2009 Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
2010 // When using FP to access scalable vector objects, we need to minus
2011 // the frame size.
2012 //
2013 // |--------------------------| --
2014 // | callee-allocated save | |
2015 // | area for register varargs| |
2016 // |--------------------------| | -- <-- FP
2017 // | callee-saved registers | |
2018 // |--------------------------| | MFI.getStackSize()
2019 // | scalar local variables | |
2020 // |--------------------------| -- (Offset of RVV objects is from here.)
2021 // | RVV objects |
2022 // |--------------------------|
2023 // | VarSize objects |
2024 // |--------------------------| <-- SP
2025 if (StackID == TargetStackID::ScalableVector) {
2026 assert(!RI->hasStackRealignment(MF) &&
2027 "Can't index across variable sized realign");
2028 // We don't expect any extra RVV alignment padding, as the stack size
2029 // and RVV object sections should be correct aligned in their own
2030 // right.
2032 "Inconsistent stack layout");
2034 }
2035 return Offset;
2036 }
2037
2038 // This case handles indexing off both SP and BP.
2039 // If indexing off SP, there must not be any var sized objects
2040 assert(FrameReg == RISCVABI::getBPReg() || !MFI.hasVarSizedObjects());
2041
2042 // When using SP to access frame objects, we need to add RVV stack size.
2043 //
2044 // |--------------------------| --
2045 // | callee-allocated save | | <----|
2046 // | area for register varargs| | |
2047 // |--------------------------| | | <-- FP
2048 // | callee-saved registers | | |
2049 // |--------------------------| -- |
2050 // | RVV alignment padding | | |
2051 // | (not counted in | | |
2052 // | MFI.getStackSize() but | | |
2053 // | counted in | | |
2054 // | RVFI.getRVVStackSize()) | | |
2055 // |--------------------------| -- |
2056 // | RVV objects | | |-- MFI.getStackSize()
2057 // | (not counted in | | |
2058 // | MFI.getStackSize()) | | |
2059 // |--------------------------| -- |
2060 // | padding before RVV | | |
2061 // | (not counted in | | |
2062 // | MFI.getStackSize()) | | |
2063 // |--------------------------| -- |
2064 // | scalar local variables | | <----'
2065 // |--------------------------| -- <-- BP (if var sized objects present)
2066 // | VarSize objects | |
2067 // |--------------------------| -- <-- SP
2068 //
2069 // The total amount of padding surrounding RVV objects is described by
2070 // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
2071 // objects to the required alignment.
2072 if (MFI.getStackID(FI) == TargetStackID::Default) {
2073 if (MFI.isFixedObjectIndex(FI)) {
2074 assert(!RI->hasStackRealignment(MF) &&
2075 "Can't index across variable sized realign");
2077 RVFI->getRVVStackSize());
2078 } else {
2080 }
2081 } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
2082 // Ensure the base of the RVV stack is correctly aligned: add on the
2083 // alignment padding.
2084 int64_t ScalarLocalVarSize =
2085 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
2086 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
2087 Offset += StackOffset::get(ScalarLocalVarSize, RVFI->getRVVStackSize());
2088 }
2089 return Offset;
2090}
2091
2093 const Register &Reg) {
2094 MCRegister BaseReg = TRI.getSubReg(Reg, RISCV::sub_vrm1_0);
2095 // If it's not a grouped vector register, it doesn't have subregister, so
2096 // the base register is just itself.
2097 if (!BaseReg.isValid())
2098 BaseReg = Reg;
2099 return BaseReg;
2100}
2101
2103 BitVector &SavedRegs,
2104 RegScavenger *RS) const {
2106
2107 // In TargetFrameLowering::determineCalleeSaves, any vector register is marked
2108 // as saved if any of its subregister is clobbered, this is not correct in
2109 // vector registers. We only want the vector register to be marked as saved
2110 // if all of its subregisters are clobbered.
2111 // For example:
2112 // Original behavior: If v24 is marked, v24m2, v24m4, v24m8 are also marked.
2113 // Correct behavior: v24m2 is marked only if v24 and v25 are marked.
2115 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
2116 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2117 for (unsigned i = 0; CSRegs[i]; ++i) {
2118 unsigned CSReg = CSRegs[i];
2119 // Only vector registers need special care.
2120 if (!RISCV::VRRegClass.contains(getRVVBaseRegister(TRI, CSReg)))
2121 continue;
2122
2123 SavedRegs.reset(CSReg);
2124
2125 auto SubRegs = TRI.subregs(CSReg);
2126 // Set the register and all its subregisters.
2127 if (!MRI.def_empty(CSReg) || MRI.getUsedPhysRegsMask().test(CSReg)) {
2128 SavedRegs.set(CSReg);
2129 for (unsigned Reg : SubRegs)
2130 SavedRegs.set(Reg);
2131 }
2132
2133 }
2134
2135 // Unconditionally spill RA and FP only if the function uses a frame
2136 // pointer.
2137 if (hasFP(MF)) {
2138 SavedRegs.set(RAReg);
2139 SavedRegs.set(FPReg);
2140 }
2141 // Mark BP as used if function has dedicated base pointer.
2142 if (hasBP(MF))
2143 SavedRegs.set(RISCVABI::getBPReg());
2144
2145 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2146 // X5 is used as a temporary for saving and restoring interrupt CSRs.
2147 if (RVFI->isSiFivePreemptibleInterrupt(MF) ||
2148 RVFI->isACLICPreemptibleInterrupt(MF))
2149 SavedRegs.set(RISCV::X5);
2150
2151 // When using cm.push/pop we must save X27 if we save X26.
2152 if (RVFI->isPushable(MF) && SavedRegs.test(RISCV::X26))
2153 SavedRegs.set(RISCV::X27);
2154
2155 // For Zilsd on RV32, append GPRPair registers to the CSR list. This prevents
2156 // the need to create register sets for each abi which is a lot more complex.
2157 // Don't use Zilsd for callee-saved coalescing if the required alignment
2158 // exceeds the stack alignment or when Zcmp/Xqccmp or save/restore libcalls
2159 // are enabled.
2160 bool UseZilsd = !STI.is64Bit() && STI.hasStdExtZilsd() &&
2161 STI.getZilsdAlign() <= getStackAlign() &&
2162 !RVFI->isPushable(MF) && !RVFI->useSaveRestoreLibCalls(MF);
2163 if (UseZilsd) {
2166 for (unsigned i = 0; CSRegs[i]; ++i) {
2167 NewCSRs.push_back(CSRegs[i]);
2168 CSRSet.insert(CSRegs[i]);
2169 }
2170
2171 // Append GPRPair registers for pairs where both sub-registers are in CSR
2172 // list. Iterate through all GPRPairs and check if both sub-regs are CSRs.
2173 for (MCPhysReg Pair : RISCV::GPRPairRegClass) {
2174 // Do not append a pair that's already in the CSR list.
2175 if (CSRSet.contains(Pair))
2176 continue;
2177 MCRegister EvenReg = TRI.getSubReg(Pair, RISCV::sub_gpr_even);
2178 MCRegister OddReg = TRI.getSubReg(Pair, RISCV::sub_gpr_odd);
2179 if (CSRSet.contains(EvenReg.id()) && CSRSet.contains(OddReg.id())) {
2180 NewCSRs.push_back(Pair);
2181 CSRSet.insert(Pair);
2182 }
2183 }
2184
2185 MRI.setCalleeSavedRegs(NewCSRs);
2186 CSRegs = MRI.getCalleeSavedRegs();
2187 }
2188
2189 // Check if all subregisters are marked for saving. If so, set the super
2190 // register bit. For GPRPair, only check sub_gpr_even and sub_gpr_odd, not
2191 // aliases like X8_W or X8_H which are not set in SavedRegs.
2192 for (unsigned i = 0; CSRegs[i]; ++i) {
2193 MCRegister CSReg = CSRegs[i];
2194 bool CombineToSuperReg;
2195 if (RISCV::GPRPairRegClass.contains(CSReg)) {
2196 MCRegister EvenReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_even);
2197 MCRegister OddReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_odd);
2198 CombineToSuperReg =
2199 SavedRegs.test(EvenReg.id()) && SavedRegs.test(OddReg.id());
2200 // If s0(x8) is used as FP we can't generate load/store pair because it
2201 // breaks the frame chain.
2202 if (hasFP(MF) && CSReg == RISCV::X8_X9)
2203 CombineToSuperReg = false;
2204 if (RVFI->useQCIInterrupt(MF) &&
2206 EvenReg))
2207 CombineToSuperReg = false;
2208 // a0-a5 are saved by the ACLIC hardware push.
2209 if (RVFI->isACLICPushPopInterrupt(MF) &&
2212 CombineToSuperReg = false;
2213 } else {
2214 auto SubRegs = TRI.subregs(CSReg);
2215 CombineToSuperReg =
2216 !SubRegs.empty() && llvm::all_of(SubRegs, [&](unsigned Reg) {
2217 return SavedRegs.test(Reg);
2218 });
2219 }
2220
2221 if (CombineToSuperReg)
2222 SavedRegs.set(CSReg);
2223 }
2224
2225 // Preemptible interrupt handlers need additional frame entries.
2227}
2228
2229std::pair<int64_t, Align>
2230RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFunction &MF) const {
2231 MachineFrameInfo &MFI = MF.getFrameInfo();
2232 // Create a buffer of RVV objects to allocate.
2233 SmallVector<int, 8> ObjectsToAllocate;
2234 auto pushRVVObjects = [&](int FIBegin, int FIEnd) {
2235 for (int I = FIBegin, E = FIEnd; I != E; ++I) {
2236 unsigned StackID = MFI.getStackID(I);
2237 if (StackID != TargetStackID::ScalableVector)
2238 continue;
2239 if (MFI.isDeadObjectIndex(I))
2240 continue;
2241
2242 ObjectsToAllocate.push_back(I);
2243 }
2244 };
2245 // First push RVV Callee Saved object, then push RVV stack object
2246 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
2247 const auto &RVVCSI = getRVVCalleeSavedInfo(MF, CSI);
2248 if (!RVVCSI.empty())
2249 pushRVVObjects(RVVCSI[0].getFrameIdx(),
2250 RVVCSI[RVVCSI.size() - 1].getFrameIdx() + 1);
2251 pushRVVObjects(0, MFI.getObjectIndexEnd() - RVVCSI.size());
2252
2253 // The minimum alignment is 16 bytes.
2254 Align RVVStackAlign(16);
2255 const auto &ST = MF.getSubtarget<RISCVSubtarget>();
2256
2257 if (!ST.hasVInstructions()) {
2258 assert(ObjectsToAllocate.empty() &&
2259 "Can't allocate scalable-vector objects without V instructions");
2260 return std::make_pair(0, RVVStackAlign);
2261 }
2262
2263 // Allocate all RVV locals and spills
2264 int64_t Offset = 0;
2265 for (int FI : ObjectsToAllocate) {
2266 // ObjectSize in bytes.
2267 int64_t ObjectSize = MFI.getObjectSize(FI);
2268 auto ObjectAlign =
2269 std::max(Align(RISCV::RVVBytesPerBlock), MFI.getObjectAlign(FI));
2270 // If the data type is the fractional vector type, reserve one vector
2271 // register for it.
2272 if (ObjectSize < RISCV::RVVBytesPerBlock)
2273 ObjectSize = RISCV::RVVBytesPerBlock;
2274 Offset = alignTo(Offset + ObjectSize, ObjectAlign);
2275 MFI.setObjectOffset(FI, -Offset);
2276 // Update the maximum alignment of the RVV stack section
2277 RVVStackAlign = std::max(RVVStackAlign, ObjectAlign);
2278 }
2279
2280 uint64_t StackSize = Offset;
2281
2282 // Ensure the alignment of the RVV stack. Since we want the most-aligned
2283 // object right at the bottom (i.e., any padding at the top of the frame),
2284 // readjust all RVV objects down by the alignment padding.
2285 // Stack size and offsets are multiples of vscale, stack alignment is in
2286 // bytes, we can divide stack alignment by minimum vscale to get a maximum
2287 // stack alignment multiple of vscale.
2288 auto VScale =
2289 std::max<uint64_t>(ST.getRealMinVLen() / RISCV::RVVBitsPerBlock, 1);
2290 if (auto RVVStackAlignVScale = RVVStackAlign.value() / VScale) {
2291 if (auto AlignmentPadding =
2292 offsetToAlignment(StackSize, Align(RVVStackAlignVScale))) {
2293 StackSize += AlignmentPadding;
2294 for (int FI : ObjectsToAllocate)
2295 MFI.setObjectOffset(FI, MFI.getObjectOffset(FI) - AlignmentPadding);
2296 }
2297 }
2298
2299 return std::make_pair(StackSize, RVVStackAlign);
2300}
2301
2303 // For RVV spill, scalable stack offsets computing requires up to two scratch
2304 // registers
2305 static constexpr unsigned ScavSlotsNumRVVSpillScalableObject = 2;
2306
2307 // For RVV spill, non-scalable stack offsets computing requires up to one
2308 // scratch register.
2309 static constexpr unsigned ScavSlotsNumRVVSpillNonScalableObject = 1;
2310
2311 // ADDI instruction's destination register can be used for computing
2312 // offsets. So Scalable stack offsets require up to one scratch register.
2313 static constexpr unsigned ScavSlotsADDIScalableObject = 1;
2314
2315 static constexpr unsigned MaxScavSlotsNumKnown =
2316 std::max({ScavSlotsADDIScalableObject, ScavSlotsNumRVVSpillScalableObject,
2317 ScavSlotsNumRVVSpillNonScalableObject});
2318
2319 unsigned MaxScavSlotsNum = 0;
2321 return false;
2322 for (const MachineBasicBlock &MBB : MF)
2323 for (const MachineInstr &MI : MBB) {
2324 bool IsRVVSpill = RISCV::isRVVSpill(MI);
2325 for (auto &MO : MI.operands()) {
2326 if (!MO.isFI())
2327 continue;
2328 bool IsScalableVectorID = MF.getFrameInfo().getStackID(MO.getIndex()) ==
2330 if (IsRVVSpill) {
2331 MaxScavSlotsNum = std::max(
2332 MaxScavSlotsNum, IsScalableVectorID
2333 ? ScavSlotsNumRVVSpillScalableObject
2334 : ScavSlotsNumRVVSpillNonScalableObject);
2335 } else if (MI.getOpcode() == RISCV::ADDI && IsScalableVectorID) {
2336 MaxScavSlotsNum =
2337 std::max(MaxScavSlotsNum, ScavSlotsADDIScalableObject);
2338 }
2339 }
2340 if (MaxScavSlotsNum == MaxScavSlotsNumKnown)
2341 return MaxScavSlotsNumKnown;
2342 }
2343 return MaxScavSlotsNum;
2344}
2345
2346static bool hasRVVFrameObject(const MachineFunction &MF) {
2347 // Originally, the function will scan all the stack objects to check whether
2348 // if there is any scalable vector object on the stack or not. However, it
2349 // causes errors in the register allocator. In issue 53016, it returns false
2350 // before RA because there is no RVV stack objects. After RA, it returns true
2351 // because there are spilling slots for RVV values during RA. It will not
2352 // reserve BP during register allocation and generate BP access in the PEI
2353 // pass due to the inconsistent behavior of the function.
2354 //
2355 // The function is changed to use hasVInstructions() as the return value. It
2356 // is not precise, but it can make the register allocation correct.
2357 //
2358 // FIXME: Find a better way to make the decision or revisit the solution in
2359 // D103622.
2360 //
2361 // Refer to https://github.com/llvm/llvm-project/issues/53016.
2362 return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
2363}
2364
2366 const RISCVInstrInfo &TII) {
2367 unsigned FnSize = 0;
2368 for (auto &MBB : MF) {
2369 for (auto &MI : MBB) {
2370 // Far branches over 20-bit offset will be relaxed in branch relaxation
2371 // pass. In the worst case, conditional branches will be relaxed into
2372 // the following instruction sequence. Unconditional branches are
2373 // relaxed in the same way, with the exception that there is no first
2374 // branch instruction.
2375 //
2376 // foo
2377 // bne t5, t6, .rev_cond # `TII->getInstSizeInBytes(MI)` bytes
2378 // sd s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2379 // jump .restore, s11 # 8 bytes
2380 // .rev_cond
2381 // bar
2382 // j .dest_bb # 4 bytes, or 2 bytes with Zca
2383 // .restore:
2384 // ld s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2385 // .dest:
2386 // baz
2387 if (MI.isConditionalBranch())
2388 FnSize += TII.getInstSizeInBytes(MI);
2389 if (MI.isConditionalBranch() || MI.isUnconditionalBranch()) {
2390 if (MF.getSubtarget<RISCVSubtarget>().hasStdExtZca())
2391 FnSize += 2 + 8 + 2 + 2;
2392 else
2393 FnSize += 4 + 8 + 4 + 4;
2394 continue;
2395 }
2396
2397 FnSize += TII.getInstSizeInBytes(MI);
2398 }
2399 }
2400 return FnSize;
2401}
2402
2404 MachineFunction &MF, RegScavenger *RS) const {
2405 const RISCVRegisterInfo *RegInfo =
2406 MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
2407 const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
2408 MachineFrameInfo &MFI = MF.getFrameInfo();
2409 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
2410 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2411
2412 int64_t RVVStackSize;
2413 Align RVVStackAlign;
2414 std::tie(RVVStackSize, RVVStackAlign) = assignRVVStackObjectOffsets(MF);
2415
2416 RVFI->setRVVStackSize(RVVStackSize);
2417 RVFI->setRVVStackAlign(RVVStackAlign);
2418
2419 if (hasRVVFrameObject(MF)) {
2420 // Ensure the entire stack is aligned to at least the RVV requirement: some
2421 // scalable-vector object alignments are not considered by the
2422 // target-independent code.
2423 MFI.ensureMaxAlignment(RVVStackAlign);
2424 }
2425
2426 unsigned ScavSlotsNum = 0;
2427
2428 // estimateStackSize has been observed to under-estimate the final stack
2429 // size, so give ourselves wiggle-room by checking for stack size
2430 // representable an 11-bit signed field rather than 12-bits.
2431 if (!isInt<11>(MFI.estimateStackSize(MF)))
2432 ScavSlotsNum = 1;
2433
2434 // Far branches over 20-bit offset require a spill slot for scratch register.
2435 bool IsLargeFunction = !isInt<20>(estimateFunctionSizeInBytes(MF, *TII));
2436 if (IsLargeFunction)
2437 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
2438
2439 // RVV loads & stores have no capacity to hold the immediate address offsets
2440 // so we must always reserve an emergency spill slot if the MachineFunction
2441 // contains any RVV spills.
2442 ScavSlotsNum = std::max(ScavSlotsNum, getScavSlotsNumForRVV(MF));
2443
2444 for (unsigned I = 0; I < ScavSlotsNum; I++) {
2445 int FI = MFI.CreateSpillStackObject(RegInfo->getSpillSize(*RC),
2446 RegInfo->getSpillAlign(*RC));
2447 RS->addScavengingFrameIndex(FI);
2448
2449 if (IsLargeFunction && RVFI->getBranchRelaxationScratchFrameIndex() == -1)
2450 RVFI->setBranchRelaxationScratchFrameIndex(FI);
2451 }
2452
2453 unsigned Size = RVFI->getReservedSpillsSize();
2454 for (const auto &Info : MFI.getCalleeSavedInfo()) {
2455 int FrameIdx = Info.getFrameIdx();
2456 if (FrameIdx < 0 || MFI.getStackID(FrameIdx) != TargetStackID::Default)
2457 continue;
2458
2459 Size += MFI.getObjectSize(FrameIdx);
2460 }
2461 RVFI->setCalleeSavedStackSize(Size);
2462}
2463
2464// Not preserve stack space within prologue for outgoing variables when the
2465// function contains variable size objects or there are vector objects accessed
2466// by the frame pointer.
2467// Let eliminateCallFramePseudoInstr preserve stack space for it.
2469 return !MF.getFrameInfo().hasVarSizedObjects() &&
2470 !(hasFP(MF) && hasRVVFrameObject(MF));
2471}
2472
2473// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
2477 DebugLoc DL = MI->getDebugLoc();
2478
2479 if (!hasReservedCallFrame(MF)) {
2480 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
2481 // ADJCALLSTACKUP must be converted to instructions manipulating the stack
2482 // pointer. This is necessary when there is a variable length stack
2483 // allocation (e.g. alloca), which means it's not possible to allocate
2484 // space for outgoing arguments from within the function prologue.
2485 int64_t Amount = MI->getOperand(0).getImm();
2486
2487 if (Amount != 0) {
2488 // Ensure the stack remains aligned after adjustment.
2489 Amount = alignSPAdjust(Amount);
2490
2491 if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
2492 Amount = -Amount;
2493
2494 const RISCVTargetLowering *TLI =
2495 MF.getSubtarget<RISCVSubtarget>().getTargetLowering();
2496 int64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
2497 if (TLI->hasInlineStackProbe(MF) &&
2498 -Amount > StackProbeMaxUnprobedStack) {
2499 // When stack probing is enabled, the decrement of SP may need to be
2500 // probed. We only need to do this if the call frame is larger than
2501 // what may be left unprobed at the call, as SP has been probed at
2502 // this point, either by the prologue or by the most recent dynamic
2503 // allocation. We can handle both the decrement and the probing in
2504 // allocateStack.
2505 allocateStack(MBB, MI, MF, -Amount, -Amount,
2506 needsDwarfCFI(MF) && !hasFP(MF),
2507 /*NeedProbe=*/true, ProbeSize, /*FollowupSize=*/0,
2508 /*SpillsToSP=*/false, MachineInstr::NoFlags);
2509 inlineStackProbe(MF, MBB);
2510 } else {
2511 const RISCVRegisterInfo &RI = *STI.getRegisterInfo();
2514 }
2515 }
2516 }
2517
2518 return MBB.erase(MI);
2519}
2520
2521// We would like to split the SP adjustment to reduce prologue/epilogue
2522// as following instructions. In this way, the offset of the callee saved
2523// register could fit in a single store. Supposed that the first sp adjust
2524// amount is 2032.
2525// add sp,sp,-2032
2526// sw ra,2028(sp)
2527// sw s0,2024(sp)
2528// sw s1,2020(sp)
2529// sw s3,2012(sp)
2530// sw s4,2008(sp)
2531// add sp,sp,-64
2532uint64_t
2534 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2535 const MachineFrameInfo &MFI = MF.getFrameInfo();
2536 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2537 uint64_t StackSize = getStackSizeWithRVVPadding(MF);
2538
2539 // Disable SplitSPAdjust if save-restore libcall, push/pop or QCI interrupts
2540 // are used. The callee-saved registers will be pushed by the save-restore
2541 // libcalls, so we don't have to split the SP adjustment in this case.
2542 //
2543 // ACLIC push-pop interrupts deliberately allow the split: Smip/Ssip
2544 // only save a0-a5, so the remaining callee-saved registers are spilled in
2545 // software.
2546 if (RVFI->getLibCallStackSize() || RVFI->getRVPushStackSize() ||
2547 RVFI->getQCIInterruptStackSize())
2548 return 0;
2549
2550 // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
2551 // 12-bit and there exists a callee-saved register needing to be pushed.
2552 if (!isInt<12>(StackSize) &&
2553 (CSI.size() > getACLICSavedInfo(MF, CSI).size())) {
2554 // FirstSPAdjustAmount is chosen at most as (2048 - StackAlign) because
2555 // 2048 will cause sp = sp + 2048 in the epilogue to be split into multiple
2556 // instructions. Offsets smaller than 2048 can fit in a single load/store
2557 // instruction, and we have to stick with the stack alignment. 2048 has
2558 // 16-byte alignment. The stack alignment for RV32 and RV64 is 16 and for
2559 // RV32E it is 4. So (2048 - StackAlign) will satisfy the stack alignment.
2560 const uint64_t StackAlign = getStackAlign().value();
2561
2562 // Amount of (2048 - StackAlign) will prevent callee saved and restored
2563 // instructions be compressed, so try to adjust the amount to the largest
2564 // offset that stack compression instructions accept when target supports
2565 // compression instructions.
2566 if (STI.hasStdExtZca()) {
2567 // The compression extensions may support the following instructions:
2568 // riscv32: c.lwsp rd, offset[7:2] => 2^(6 + 2)
2569 // c.swsp rs2, offset[7:2] => 2^(6 + 2)
2570 // c.flwsp rd, offset[7:2] => 2^(6 + 2)
2571 // c.fswsp rs2, offset[7:2] => 2^(6 + 2)
2572 // riscv64: c.ldsp rd, offset[8:3] => 2^(6 + 3)
2573 // c.sdsp rs2, offset[8:3] => 2^(6 + 3)
2574 // c.fldsp rd, offset[8:3] => 2^(6 + 3)
2575 // c.fsdsp rs2, offset[8:3] => 2^(6 + 3)
2576 const uint64_t RVCompressLen = STI.getXLen() * 8;
2577 // Compared with amount (2048 - StackAlign), StackSize needs to
2578 // satisfy the following conditions to avoid using more instructions
2579 // to adjust the sp after adjusting the amount, such as
2580 // StackSize meets the condition (StackSize <= 2048 + RVCompressLen),
2581 // case1: Amount is 2048 - StackAlign: use addi + addi to adjust sp.
2582 // case2: Amount is RVCompressLen: use addi + addi to adjust sp.
2583 auto CanCompress = [&](uint64_t CompressLen) -> bool {
2584 if (StackSize <= 2047 + CompressLen ||
2585 (StackSize > 2048 * 2 - StackAlign &&
2586 StackSize <= 2047 * 2 + CompressLen) ||
2587 StackSize > 2048 * 3 - StackAlign)
2588 return true;
2589
2590 return false;
2591 };
2592 // In the epilogue, addi sp, sp, 496 is used to recover the sp and it
2593 // can be compressed(C.ADDI16SP, offset can be [-512, 496]), but
2594 // addi sp, sp, 512 can not be compressed. So try to use 496 first.
2595 const uint64_t ADDI16SPCompressLen = 496;
2596 if (STI.is64Bit() && CanCompress(ADDI16SPCompressLen))
2597 return ADDI16SPCompressLen;
2598 if (CanCompress(RVCompressLen))
2599 return RVCompressLen;
2600 }
2601 return 2048 - StackAlign;
2602 }
2603 return 0;
2604}
2605
2608 std::vector<CalleeSavedInfo> &CSI) const {
2609 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2610 MachineFrameInfo &MFI = MF.getFrameInfo();
2611 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
2612
2613 if (RVFI->isACLICPushPopInterrupt(MF)) {
2614 uint64_t PushAmount = getACLICInterruptPushAmount(MF);
2615 RVFI->setACLICInterruptStackSize(PushAmount);
2616 MFI.CreateFixedSpillStackObject(PushAmount,
2617 -static_cast<int64_t>(PushAmount));
2618 }
2619
2620 // Preemptible Interrupts have two additional Callee-save Frame Indexes,
2621 // not tracked by `CSI`.
2622 if (RVFI->isSiFivePreemptibleInterrupt(MF) ||
2623 RVFI->isACLICPreemptibleInterrupt(MF)) {
2624 for (int I = 0; I < 2; ++I)
2625 MFI.setIsCalleeSavedObjectIndex(RVFI->getInterruptCSRFrameIndex(I), true);
2626 }
2627
2628 // Early exit if no callee saved registers are modified!
2629 if (CSI.empty())
2630 return true;
2631
2632 if (RVFI->useQCIInterrupt(MF)) {
2633 RVFI->setQCIInterruptStackSize(QCIInterruptPushAmount);
2634 }
2635
2636 if (RVFI->isPushable(MF)) {
2637 // Determine how many GPRs we need to push and save it to RVFI.
2638 unsigned PushedRegNum = getNumPushPopRegs(CSI);
2639
2640 // `QC.C.MIENTER(.NEST)` will save `ra` and `s0`, so we should only push if
2641 // we want to push more than 2 registers. Otherwise, we should push if we
2642 // want to push more than 0 registers.
2643 unsigned OnlyPushIfMoreThan = RVFI->useQCIInterrupt(MF) ? 2 : 0;
2644 if (PushedRegNum > OnlyPushIfMoreThan) {
2645 RVFI->setRVPushRegs(PushedRegNum);
2646 RVFI->setRVPushStackSize(alignTo((STI.getXLen() / 8) * PushedRegNum, 16));
2647 }
2648 }
2649
2650 for (auto &CS : CSI) {
2651 MCRegister Reg = CS.getReg();
2652 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
2653 unsigned Size = RegInfo->getSpillSize(*RC);
2654
2655 if (RVFI->useQCIInterrupt(MF)) {
2656 const auto *FFI = llvm::find_if(FixedCSRFIQCIInterruptMap, [&](auto P) {
2657 return P.first == CS.getReg();
2658 });
2659 if (FFI != std::end(FixedCSRFIQCIInterruptMap)) {
2660 int64_t Offset = FFI->second * (int64_t)Size;
2661
2662 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2663 assert(FrameIdx < 0);
2664 CS.setFrameIdx(FrameIdx);
2665 continue;
2666 }
2667 }
2668
2669 if (RVFI->isACLICPushPopInterrupt(MF)) {
2670 const auto *FFI = llvm::find_if(FixedCSRFIACLICInterruptMap, [&](auto P) {
2671 return P.first == CS.getReg();
2672 });
2673 if (FFI != std::end(FixedCSRFIACLICInterruptMap)) {
2674 int64_t Offset = FFI->second * (int64_t)Size;
2675
2676 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2677 assert(FrameIdx < 0);
2678 CS.setFrameIdx(FrameIdx);
2679 continue;
2680 }
2681 }
2682
2683 if (RVFI->useSaveRestoreLibCalls(MF) || RVFI->isPushable(MF)) {
2684 const auto *FII = llvm::find_if(
2685 FixedCSRFIMap, [&](MCPhysReg P) { return P == CS.getReg(); });
2686 unsigned RegNum = std::distance(std::begin(FixedCSRFIMap), FII);
2687
2688 if (FII != std::end(FixedCSRFIMap)) {
2689 int64_t Offset;
2690 if (RVFI->getPushPopKind(MF) ==
2692 Offset = -int64_t(RVFI->getRVPushRegs() - RegNum) * Size;
2693 else
2694 Offset = -int64_t(RegNum + 1) * Size;
2695
2696 if (RVFI->useQCIInterrupt(MF))
2698
2699 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2700 assert(FrameIdx < 0);
2701 CS.setFrameIdx(FrameIdx);
2702 continue;
2703 }
2704 }
2705
2706 // For GPRPair registers, use 8-byte slots with required alignment by zilsd.
2707 if (!STI.is64Bit() && STI.hasStdExtZilsd() &&
2708 RISCV::GPRPairRegClass.contains(Reg)) {
2709 Align PairAlign = STI.getZilsdAlign();
2710 int FrameIdx = MFI.CreateStackObject(8, PairAlign, true);
2711 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2712 CS.setFrameIdx(FrameIdx);
2713 continue;
2714 }
2715
2716 // Not a fixed slot.
2717 Align Alignment = RegInfo->getSpillAlign(*RC);
2718 // We may not be able to satisfy the desired alignment specification of
2719 // the TargetRegisterClass if the stack alignment is smaller. Use the
2720 // min.
2721 Alignment = std::min(Alignment, getStackAlign());
2722 int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
2723 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2724 CS.setFrameIdx(FrameIdx);
2726 MFI.setStackID(FrameIdx, TargetStackID::ScalableVector);
2727 }
2728
2729 if (RVFI->useQCIInterrupt(MF)) {
2730 // Allocate a fixed object that covers the entire QCI stack allocation,
2731 // because there are gaps which are reserved for future use.
2732 MFI.CreateFixedSpillStackObject(
2733 QCIInterruptPushAmount, -static_cast<int64_t>(QCIInterruptPushAmount));
2734 }
2735
2736 if (RVFI->isPushable(MF)) {
2737 int64_t QCIOffset = RVFI->useQCIInterrupt(MF) ? QCIInterruptPushAmount : 0;
2738 // Allocate a fixed object that covers the full push.
2739 if (int64_t PushSize = RVFI->getRVPushStackSize())
2740 MFI.CreateFixedSpillStackObject(PushSize, -PushSize - QCIOffset);
2741 } else if (int LibCallRegs = getLibCallID(MF, CSI) + 1) {
2742 // If libcalls are used to spill and restore callee-saved registers, the
2743 // frame has two sections; the opaque section managed by the libcalls, and
2744 // the section managed by MachineFrameInfo which can also hold callee saved
2745 // registers in fixed stack slots, both of which have negative frame
2746 // indices. This gets even more complicated when incoming arguments are
2747 // passed via the stack, as these too have negative frame indices. An
2748 // example is detailed below:
2749 //
2750 // | incoming arg | <- FI[-3]
2751 // | libcallspill |
2752 // | calleespill | <- FI[-2]
2753 // | calleespill | <- FI[-1]
2754 // | this_frame | <- FI[0]
2755 //
2756 // For negative frame indices, the offset from the frame pointer will differ
2757 // depending on which of these groups the frame index applies to.
2758 // The following calculates the correct offset knowing the number of callee
2759 // saved registers spilt by the two methods.
2760 unsigned LibCallFrameSize =
2761 alignTo((STI.getXLen() / 8) * LibCallRegs, getStackAlign());
2762 RVFI->setLibCallStackSize(LibCallFrameSize);
2763 // Allocate a fixed object that covers the entire libcall area.
2764 MFI.CreateFixedSpillStackObject(LibCallFrameSize,
2765 -static_cast<int64_t>(LibCallFrameSize));
2766 }
2767
2768 return true;
2769}
2770
2774 if (CSI.empty())
2775 return true;
2776
2777 MachineFunction *MF = MBB.getParent();
2778 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2779 DebugLoc DL;
2780 if (MI != MBB.end() && !MI->isDebugInstr())
2781 DL = MI->getDebugLoc();
2782
2784 if (RVFI->useQCIInterrupt(*MF)) {
2785 // Emit QC.C.MIENTER(.NEST)
2786 BuildMI(
2787 MBB, MI, DL,
2788 TII.get(RVFI->getInterruptStackKind(*MF) ==
2790 ? RISCV::QC_C_MIENTER_NEST
2791 : RISCV::QC_C_MIENTER))
2793
2794 for (auto [Reg, _Offset] : FixedCSRFIQCIInterruptMap)
2795 MBB.addLiveIn(Reg);
2796 }
2797
2798 if (RVFI->isPushable(*MF)) {
2799 // Emit CM.PUSH with base StackAdj & evaluate Push stack
2800 unsigned PushedRegNum = RVFI->getRVPushRegs();
2801 if (PushedRegNum > 0) {
2802 // Use encoded number to represent registers to spill.
2803 unsigned Opcode = getPushOpcode(
2804 RVFI->getPushPopKind(*MF), hasFP(*MF) && !RVFI->useQCIInterrupt(*MF));
2805 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2806 MachineInstrBuilder PushBuilder =
2807 BuildMI(MBB, MI, DL, TII.get(Opcode))
2809 PushBuilder.addImm(RegEnc);
2810 PushBuilder.addImm(0);
2811
2812 for (unsigned i = 0; i < PushedRegNum; i++)
2813 PushBuilder.addUse(FixedCSRFIMap[i], RegState::Implicit);
2814 }
2815 } else if (const char *SpillLibCall = getSpillLibCallName(*MF, CSI)) {
2816 // Add spill libcall via non-callee-saved register t0.
2817 MachineInstrBuilder NewMI =
2818 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
2819 .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
2821 .addUse(RISCV::X2, RegState::Implicit)
2822 .addDef(RISCV::X2, RegState::ImplicitDefine)
2823 // The libcall may use t1 as a scratch register.
2825 // libgcc may emit an lui t2, 0 to set a landing pad label.
2827
2828 // Add registers spilled as implicit used.
2829 for (auto &CS : CSI)
2830 NewMI.addUse(CS.getReg(), RegState::Implicit);
2831 }
2832
2833 // Manually spill values not spilled by libcall & Push/Pop.
2834 const auto &UnmanagedCSI =
2835 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2836 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2837
2838 auto storeRegsToStackSlots = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2839 for (auto &CS : CSInfo) {
2840 // Insert the spill to the stack frame.
2841 MCRegister Reg = CS.getReg();
2842 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2843 TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg),
2844 CS.getFrameIdx(), RC, Register(),
2846 }
2847 };
2848 storeRegsToStackSlots(UnmanagedCSI);
2849 storeRegsToStackSlots(RVVCSI);
2850
2851 return true;
2852}
2853
2854static unsigned getCalleeSavedRVVNumRegs(const Register &BaseReg) {
2855 return RISCV::VRRegClass.contains(BaseReg) ? 1
2856 : RISCV::VRM2RegClass.contains(BaseReg) ? 2
2857 : RISCV::VRM4RegClass.contains(BaseReg) ? 4
2858 : 8;
2859}
2860
2861void RISCVFrameLowering::emitCalleeSavedRVVPrologCFI(
2864 const MachineFrameInfo &MFI = MF->getFrameInfo();
2865 RISCVMachineFunctionInfo *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2866 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2867
2868 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2869 if (RVVCSI.empty())
2870 return;
2871
2872 uint64_t FixedSize = getStackSizeWithRVVPadding(*MF);
2873 if (!HasFP) {
2874 uint64_t ScalarLocalVarSize =
2875 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
2876 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
2877 FixedSize -= ScalarLocalVarSize;
2878 }
2879
2880 CFIInstBuilder CFIBuilder(MBB, MI, MachineInstr::FrameSetup);
2881 for (auto &CS : RVVCSI) {
2882 // Insert the spill to the stack frame.
2883 int FI = CS.getFrameIdx();
2884 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2885 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2886 for (unsigned i = 0; i < NumRegs; ++i) {
2887 CFIBuilder.insertCFIInst(createDefCFAOffset(
2888 TRI, BaseReg + i,
2889 StackOffset::get(-FixedSize, MFI.getObjectOffset(FI) / 8 + i)));
2890 }
2891 }
2892}
2893
2894void RISCVFrameLowering::emitCalleeSavedRVVEpilogCFI(
2897 const MachineFrameInfo &MFI = MF->getFrameInfo();
2898 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2899
2900 CFIInstBuilder CFIHelper(MBB, MI, MachineInstr::FrameDestroy);
2901 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2902 for (auto &CS : RVVCSI) {
2903 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2904 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2905 for (unsigned i = 0; i < NumRegs; ++i)
2906 CFIHelper.buildRestore(BaseReg + i);
2907 }
2908}
2909
2913 if (CSI.empty())
2914 return true;
2915
2916 MachineFunction *MF = MBB.getParent();
2917 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2918 DebugLoc DL;
2919 if (MI != MBB.end() && !MI->isDebugInstr())
2920 DL = MI->getDebugLoc();
2921
2922 // Manually restore values not restored by libcall & Push/Pop.
2923 // Reverse the restore order in epilog. In addition, the return
2924 // address will be restored first in the epilogue. It increases
2925 // the opportunity to avoid the load-to-use data hazard between
2926 // loading RA and return by RA. loadRegFromStackSlot can insert
2927 // multiple instructions.
2928 const auto &UnmanagedCSI =
2929 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2930 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2931
2932 auto loadRegFromStackSlot = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2933 for (auto &CS : CSInfo) {
2934 MCRegister Reg = CS.getReg();
2935 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2936 TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, Register(),
2937 RISCV::NoSubRegister,
2939 assert(MI != MBB.begin() &&
2940 "loadRegFromStackSlot didn't insert any code!");
2941 }
2942 };
2943 loadRegFromStackSlot(RVVCSI);
2944 loadRegFromStackSlot(UnmanagedCSI);
2945
2947 if (RVFI->useQCIInterrupt(*MF)) {
2948 // Don't emit anything here because restoration is handled by
2949 // QC.C.MILEAVERET which we already inserted to return.
2950 assert(MI->getOpcode() == RISCV::QC_C_MILEAVERET &&
2951 "Unexpected QCI Interrupt Return Instruction");
2952 }
2953
2954 if (RVFI->isPushable(*MF)) {
2955 unsigned PushedRegNum = RVFI->getRVPushRegs();
2956 if (PushedRegNum > 0) {
2957 unsigned Opcode = getPopOpcode(RVFI->getPushPopKind(*MF));
2958 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2959 MachineInstrBuilder PopBuilder =
2960 BuildMI(MBB, MI, DL, TII.get(Opcode))
2962 // Use encoded number to represent registers to restore.
2963 PopBuilder.addImm(RegEnc);
2964 PopBuilder.addImm(0);
2965
2966 for (unsigned i = 0; i < RVFI->getRVPushRegs(); i++)
2968 }
2969 } else if (const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI)) {
2970 assert(RVFI->useSaveRestoreLibCalls(*MF) &&
2971 "Expected restore with libcall to use save restore libcalls");
2972
2973 // Restore is not compatible with shadow stacks, so do the restore manually.
2974 // This ensures we still get the code size saving of `__riscv_save_<N>`.
2975 if (RVFI->hasShadowStack(*MF)) {
2976 loadRegFromStackSlot(getPushOrLibCallsSavedInfo(*MF, CSI));
2977 return true;
2978 }
2979
2980 // Add restore libcall via tail call. Use the software guarded variant when
2981 // cf-protection-branch is enabled because the restore function does not
2982 // contain an lpad.
2983 unsigned TailOpc =
2984 RVFI->hasCFProtectionBranch() ? RISCV::PseudoTAILX7 : RISCV::PseudoTAIL;
2985 MachineInstrBuilder NewMI =
2986 BuildMI(MBB, MI, DL, TII.get(TailOpc))
2987 .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
2989 .addDef(RISCV::X2, RegState::ImplicitDefine);
2990
2991 // Add registers restored as implicit defined.
2992 for (auto &CS : CSI)
2993 NewMI.addDef(CS.getReg(), RegState::ImplicitDefine);
2994
2995 // Remove trailing returns, since the terminator is now a tail call to the
2996 // restore function.
2997 if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
2998 NewMI.getInstr()->copyImplicitOps(*MF, *MI);
2999 MI->eraseFromParent();
3000 }
3001 }
3002 return true;
3003}
3004
3006 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
3007 if (RVFI->isACLICPreemptibleInterrupt(MF) ||
3008 RVFI->isACLICPushPopInterrupt(MF))
3009 return false;
3010
3011 // QCI and SiFive CLIC interrupt entry sequences must precede all handler
3012 // code.
3013 if (RVFI->useQCIInterrupt(MF) || RVFI->useSiFiveInterrupt(MF))
3014 return false;
3015
3016 // Keep the conventional code flow when not optimizing.
3017 if (MF.getFunction().hasOptNone())
3018 return false;
3019
3020 return true;
3021}
3022
3024 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
3025 const MachineFunction *MF = MBB.getParent();
3026 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
3027
3028 // Make sure VTYPE and VL are not live-in since we will use vsetvli in the
3029 // prologue to get the VLEN, and that will clobber these registers.
3030 //
3031 // We may do also check the stack contains objects with scalable vector type,
3032 // but this will require iterating over all the stack objects, but this may
3033 // not worth since the situation is rare, we could do further check in future
3034 // if we find it is necessary.
3035 if (STI.preferVsetvliOverReadVLENB() &&
3036 (MBB.isLiveIn(RISCV::VTYPE) || MBB.isLiveIn(RISCV::VL)))
3037 return false;
3038
3039 if (!RVFI->useSaveRestoreLibCalls(*MF))
3040 return true;
3041
3042 // Inserting a call to a __riscv_save libcall requires the use of the register
3043 // t0 (X5) to hold the return address. Therefore if this register is already
3044 // used we can't insert the call.
3045 // The libcall also clobbers t1 (X6) and t2 (X7), see emitPrologue.
3046
3047 RegScavenger RS;
3048 RS.enterBasicBlock(*TmpMBB);
3049 return !RS.isRegUsed(RISCV::X5) && !RS.isRegUsed(RISCV::X6) &&
3050 !RS.isRegUsed(RISCV::X7);
3051}
3052
3054 const MachineFunction *MF = MBB.getParent();
3055 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
3056 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
3057
3058 // If we have a shadow stack, we don't use `__riscv_restore` libcalls.
3059 if (RVFI->hasShadowStack(*MF))
3060 return true;
3061
3062 if (!RVFI->useSaveRestoreLibCalls(*MF))
3063 return true;
3064
3065 // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
3066 // This means if we still need to continue executing code within this function
3067 // the restore cannot take place in this basic block.
3068
3069 if (MBB.succ_size() > 1)
3070 return false;
3071
3072 MachineBasicBlock *SuccMBB =
3073 MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
3074
3075 // Doing a tail call should be safe if there are no successors, because either
3076 // we have a returning block or the end of the block is unreachable, so the
3077 // restore will be eliminated regardless.
3078 if (!SuccMBB)
3079 return true;
3080
3081 // The successor can only contain a return and debug instructions, since we
3082 // would effectively replace it with our own tail return at the end of this
3083 // block. The debug instructions would not execute on the tail-return path.
3084 return SuccMBB->isReturnBlock() &&
3085 llvm::count_if(SuccMBB->instrs(), [](const MachineInstr &MI) {
3086 return !MI.isDebugInstr();
3087 }) == 1;
3088}
3089
3093
3097
3098// Synthesize the probe loop.
3100 Register TargetReg, Register ScratchReg,
3101 bool IsRVV) {
3102 assert(TargetReg != RISCV::X2 && "New top of stack cannot already be in SP");
3103 assert(ScratchReg != RISCV::X2 && "Scratch register cannot be SP");
3104 assert(TargetReg != ScratchReg && "Target and scratch must be different");
3105
3106 MachineBasicBlock &MBB = *MBBI->getParent();
3107 MachineFunction &MF = *MBB.getParent();
3108
3110 const RISCVInstrInfo *TII = Subtarget.getInstrInfo();
3111 bool IsRV64 = Subtarget.is64Bit();
3112 Align StackAlign = Subtarget.getFrameLowering()->getStackAlign();
3113 const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
3114 uint64_t ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
3115
3116 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
3117 MachineBasicBlock *LoopTestMBB =
3118 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
3119 MF.insert(MBBInsertPoint, LoopTestMBB);
3120 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
3121 MF.insert(MBBInsertPoint, ExitMBB);
3123
3124 // ScratchReg = ProbeSize
3125 TII->movImm(MBB, MBBI, DL, ScratchReg, ProbeSize, Flags);
3126
3127 // LoopTest:
3128 // SUB SP, SP, ProbeSize
3129 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB), SPReg)
3130 .addReg(SPReg)
3131 .addReg(ScratchReg)
3132 .setMIFlags(Flags);
3133
3134 // s[d|w] zero, 0(sp)
3135 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
3136 TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
3137 .addReg(RISCV::X0)
3138 .addReg(SPReg)
3139 .addImm(0)
3140 .setMIFlags(Flags);
3141
3142 if (IsRVV) {
3143 // SUB TargetReg, TargetReg, ProbeSize
3144 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB),
3145 TargetReg)
3146 .addReg(TargetReg)
3147 .addReg(ScratchReg)
3148 .setMIFlags(Flags);
3149
3150 // BGE TargetReg, ProbeSize, LoopTest
3151 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BGE))
3152 .addReg(TargetReg)
3153 .addReg(ScratchReg)
3154 .addMBB(LoopTestMBB)
3155 .setMIFlags(Flags);
3156
3157 } else {
3158 // BNE SP, TargetReg, LoopTest
3159 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BNE))
3160 .addReg(SPReg)
3161 .addReg(TargetReg)
3162 .addMBB(LoopTestMBB)
3163 .setMIFlags(Flags);
3164 }
3165
3166 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
3168
3169 LoopTestMBB->addSuccessor(ExitMBB);
3170 LoopTestMBB->addSuccessor(LoopTestMBB);
3171 MBB.addSuccessor(LoopTestMBB);
3172 // Update liveins.
3173 fullyRecomputeLiveIns({ExitMBB, LoopTestMBB});
3174}
3175
3176void RISCVFrameLowering::inlineStackProbe(MachineFunction &MF,
3177 MachineBasicBlock &MBB) const {
3178 // Get the instructions that need to be replaced. We emit at most three of
3179 // these. Remember them in order to avoid complications coming from the need
3180 // to traverse the block while potentially creating more blocks.
3181 SmallVector<MachineInstr *, 4> ToReplace;
3182 for (MachineInstr &MI : MBB) {
3183 unsigned Opc = MI.getOpcode();
3184 if (Opc == RISCV::PROBED_STACKALLOC ||
3185 Opc == RISCV::PROBED_STACKALLOC_RVV) {
3186 ToReplace.push_back(&MI);
3187 }
3188 }
3189
3190 for (MachineInstr *MI : ToReplace) {
3191 if (MI->getOpcode() == RISCV::PROBED_STACKALLOC ||
3192 MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV) {
3195 Register TargetReg = MI->getOperand(0).getReg();
3196
3197 Register ScratchReg =
3198 findScratchNonCalleeSaveRegister(&MBB, RISCV::X7, TargetReg);
3199
3200 assert(ScratchReg.isValid() &&
3201 "No available scratch register for stack probe loop");
3202
3203 emitStackProbeInline(MBBI, DL, TargetReg, ScratchReg,
3204 (MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV));
3206 }
3207 }
3208}
3209
3211 return 0;
3212}
3213
3216 return RISCV::X2;
3217}
3218
3219// On 64-bit systems the fixed stack can hold INT64_MAX bytes, since
3220// stack-offset calculation is done in 2s-complement.
3221// NOTE: In theory a register can hold any 64-bit number, so this constraint
3222// might be relaxed to UINT64_MAX in the future, if anyone actually needs
3223// that.
3225 return STI.is64Bit() ? INT64_MAX : UINT32_MAX;
3226}
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)
unsigned Opc
#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 uint64_t getACLICInterruptPushAmount(const MachineFunction &MF)
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 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 void emitACLICPreemptibleRestores(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, CFIInstBuilder &CFIBuilder, const DebugLoc &DL)
static SmallVector< CalleeSavedInfo, 8 > getUnmanagedInterruptCSI(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI, bool ReverseOrder=false)
static SmallVector< CalleeSavedInfo, 8 > getACLICSavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static void appendScalableVectorExpression(const TargetRegisterInfo &TRI, SmallVectorImpl< char > &Expr, StackOffset Offset, llvm::raw_string_ostream &Comment)
static void emitACLICPreemptibleSaves(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL)
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 const std::pair< MCPhysReg, int8_t > FixedCSRFIACLICInterruptMap[]
static void createPreemptibleInterruptFrameEntries(MachineFunction &MF, RISCVMachineFunctionInfo &RVFI)
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 int getPreemptibleInterruptScratchFrameIndex(const MachineFunction &MF)
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 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 buildSameValue(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:126
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:758
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
constexpr unsigned id() const
Definition MCRegister.h:85
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.
void resetCFIToInitialState(MachineBasicBlock &MBB) const override
Emit CFI instructions that recreate the state of the unwind information upon function entry.
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
bool isACLICPushPopInterrupt(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 isACLICPreemptibleInterrupt(const MachineFunction &MF) const
bool useSaveRestoreLibCalls(const MachineFunction &MF) const
bool isACLICSupervisorInterrupt(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:109
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.
@ 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