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