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 &STI = MF.getSubtarget<RISCVSubtarget>();
112 // We check Zimop instead of (Zimop || Zcmop) to determine whether HW shadow
113 // stack is available despite the fact that sspush/sspopchk both have a
114 // compressed form, because if only Zcmop is available, we would need to
115 // reserve X5 due to c.sspopchk only takes X5 and we currently do not support
116 // using X5 as the return address register.
117 // However, we can still aggressively use c.sspush x1 if zcmop is available.
118 bool HasHWShadowStack = MF.getFunction().hasFnAttribute("hw-shadow-stack") &&
119 STI.hasStdExtZimop();
120 bool HasSWShadowStack =
121 MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack);
122 if (!HasHWShadowStack && !HasSWShadowStack)
123 return;
124
125 const llvm::RISCVRegisterInfo *TRI = STI.getRegisterInfo();
126
127 // Do not save RA to the SCS if it's not saved to the regular stack,
128 // i.e. RA is not at risk of being overwritten.
129 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
130 if (llvm::none_of(
131 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
132 return;
133
134 const RISCVInstrInfo *TII = STI.getInstrInfo();
135 if (HasHWShadowStack) {
136 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPUSH))
137 .addReg(RAReg)
139 return;
140 }
141
142 Register SCSPReg = RISCVABI::getSCSPReg();
143
144 bool IsRV64 = STI.is64Bit();
145 int64_t SlotSize = STI.getXLen() / 8;
146 // Store return address to shadow call stack
147 // addi gp, gp, [4|8]
148 // s[w|d] ra, -[4|8](gp)
149 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI), SCSPReg)
150 .addReg(SCSPReg)
151 .addImm(SlotSize)
153 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
154 .addReg(RAReg)
155 .addReg(SCSPReg)
156 .addImm(-SlotSize)
158
159 if (!needsDwarfCFI(MF))
160 return;
161
162 // Emit a CFI instruction that causes SlotSize to be subtracted from the value
163 // of the shadow stack pointer when unwinding past this frame.
164 char DwarfSCSReg = TRI->getDwarfRegNum(SCSPReg, /*IsEH*/ true);
165 assert(DwarfSCSReg < 32 && "SCS Register should be < 32 (X3).");
166
167 char Offset = static_cast<char>(-SlotSize) & 0x7f;
168 const char CFIInst[] = {
169 dwarf::DW_CFA_val_expression,
170 DwarfSCSReg, // register
171 2, // length
172 static_cast<char>(unsigned(dwarf::DW_OP_breg0 + DwarfSCSReg)),
173 Offset, // addend (sleb128)
174 };
175
177 .buildEscape(StringRef(CFIInst, sizeof(CFIInst)));
178}
179
182 const DebugLoc &DL) {
183 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
184 bool HasHWShadowStack = MF.getFunction().hasFnAttribute("hw-shadow-stack") &&
185 STI.hasStdExtZimop();
186 bool HasSWShadowStack =
187 MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack);
188 if (!HasHWShadowStack && !HasSWShadowStack)
189 return;
190
191 // See emitSCSPrologue() above.
192 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
193 if (llvm::none_of(
194 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
195 return;
196
197 // The shadow call stack popchk needs to happen after cm.pop that loads ra.
198 if (MI != MBB.end() &&
199 (MI->getOpcode() == RISCV::CM_POP || MI->getOpcode() == RISCV::QC_CM_POP))
200 ++MI;
201 const RISCVInstrInfo *TII = STI.getInstrInfo();
202 if (HasHWShadowStack) {
203 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPOPCHK))
204 .addReg(RAReg)
206 return;
207 }
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 if (getLibCallID(MF, CSI) != -1) {
1435 // tail __riscv_restore_[0-12] instruction is considered as a terminator,
1436 // therefore it is unnecessary to place any CFI instructions after it. Just
1437 // deallocate stack if needed and return.
1438 if (StackSize != 0)
1439 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1440 RVFI->getLibCallStackSize());
1441
1442 // Emit epilogue for shadow call stack.
1443 emitSCSEpilogue(MF, MBB, MBBI, DL);
1444 return;
1445 }
1446
1447 // Recover callee-saved registers.
1448 if (NeedsDwarfCFI) {
1449 for (const CalleeSavedInfo &CS :
1450 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS)) {
1451 MCRegister Reg = CS.getReg();
1452 // Emit CFI for both sub-registers.
1453 if (RISCV::GPRPairRegClass.contains(Reg)) {
1454 MCRegister EvenReg = RI->getSubReg(Reg, RISCV::sub_gpr_even);
1455 MCRegister OddReg = RI->getSubReg(Reg, RISCV::sub_gpr_odd);
1456 CFIBuilder.buildRestore(EvenReg);
1457 CFIBuilder.buildRestore(OddReg);
1458 } else {
1459 CFIBuilder.buildRestore(Reg);
1460 }
1461 }
1462 }
1463
1464 if (RVFI->isPushable(MF) && MBBI != MBB.end() && isPop(MBBI->getOpcode())) {
1465 // Use available stack adjustment in pop instruction to deallocate stack
1466 // space. Align the stack size down to a multiple of 16. This is needed for
1467 // RVE.
1468 // FIXME: Can we increase the stack size to a multiple of 16 instead?
1469 uint64_t StackAdj =
1470 std::min(alignDown(StackSize, 16), static_cast<uint64_t>(48));
1471 MBBI->getOperand(1).setImm(StackAdj);
1472 StackSize -= StackAdj;
1473
1474 if (StackSize != 0)
1475 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1476 /*stack_adj of cm.pop instr*/ RealStackSize - StackSize);
1477
1478 auto NextI = next_nodbg(MBBI, MBB.end());
1479 if (NextI == MBB.end() || NextI->getOpcode() != RISCV::PseudoRET) {
1480 ++MBBI;
1481 if (NeedsDwarfCFI) {
1482 CFIBuilder.setInsertPoint(MBBI);
1483
1484 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1485 CFIBuilder.buildRestore(CS.getReg());
1486
1487 // Update CFA Offset. If this is a QCI interrupt function, there will
1488 // be a leftover offset which is deallocated by `QC.C.MILEAVERET`,
1489 // otherwise getQCIInterruptStackSize() will be 0.
1490 CFIBuilder.buildDefCFAOffset(RVFI->getQCIInterruptStackSize());
1491 }
1492 }
1493 }
1494
1495 // Deallocate stack if StackSize isn't a zero yet. If this is a QCI interrupt
1496 // function, there will be a leftover offset which is deallocated by
1497 // `QC.C.MILEAVERET`, otherwise getQCIInterruptStackSize() will be 0.
1498 if (StackSize != 0)
1499 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1500 RVFI->getQCIInterruptStackSize());
1501
1502 // Emit epilogue for shadow call stack.
1503 emitSCSEpilogue(MF, MBB, MBBI, DL);
1504
1505 // SiFive CLIC needs to swap `sf.mscratchcsw` into `sp`
1507}
1508
1510 MCRegister Reg) {
1511 if (RISCV::GPRRegClass.contains(Reg))
1512 return Reg;
1513
1514 std::array<TargetRegisterClass const *, 2> RegisterClasses = {
1515 &RISCV::GPRF16RegClass, &RISCV::GPRF32RegClass};
1516 std::array<unsigned, 2> SubIdx = {RISCV::sub_16, RISCV::sub_32};
1517
1518 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1519 if (RegClass->contains(Reg)) {
1520 if (MCRegister Super =
1521 TRI.getMatchingSuperReg(Reg, SubReg, &RISCV::GPRRegClass))
1522 return Super;
1523 }
1524 }
1525
1527 "getPhysicalGPR called with unsupported register");
1528}
1529
1531 const TargetRegisterInfo &TRI,
1532 MCRegister Reg) {
1533 if (!STI.hasStdExtF())
1534 return MCRegister();
1535
1536 TargetRegisterClass const *LargestFPRegClass = STI.getLargestFPRegClass();
1537 assert(LargestFPRegClass);
1538
1539 if (LargestFPRegClass->contains(Reg))
1540 return Reg;
1541
1542 std::array<TargetRegisterClass const *, 3> RegisterClasses = {
1543 &RISCV::FPR16RegClass, &RISCV::FPR32RegClass, &RISCV::FPR64RegClass};
1544 std::array<unsigned, 3> SubIdx = {RISCV::sub_16, RISCV::sub_32,
1545 RISCV::sub_64};
1546
1547 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1548 if (RegClass->contains(Reg)) {
1549 if (MCRegister Super =
1550 TRI.getMatchingSuperReg(Reg, SubReg, LargestFPRegClass))
1551 return Super;
1552 }
1553 }
1554
1555 // Reg is bigger than what's currently available for the target, we can ignore
1556 // it.
1557 return MCRegister();
1558}
1559
1560void RISCVFrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
1562 RegScavenger *RS) const {
1563 // Insertion point.
1565
1566 // Fake a debug loc.
1567 DebugLoc DL;
1568 if (MBBI != MBB.end())
1569 DL = MBBI->getDebugLoc();
1570
1571 const MachineFunction &MF = *MBB.getParent();
1572 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
1573 const RISCVInstrInfo &TII = *STI.getInstrInfo();
1574
1575 BitVector FinalRegsToZero(TRI.getNumRegs());
1576
1577 bool HasVRegister = false;
1578
1579 for (MCRegister Reg : RegsToZero.set_bits()) {
1580 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1581 FinalRegsToZero.set(getPhysicalGPR(TRI, Reg).id());
1582 } else if (RISCV::GPRPairRegClass.contains(Reg)) {
1583 FinalRegsToZero.set(
1584 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_even)).id());
1585 FinalRegsToZero.set(
1586 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_odd)).id());
1587 } else if (TRI.isFPRegister(Reg)) {
1588 if (MCRegister MaybeReg = getLargestFPRegisterOrZero(STI, TRI, Reg))
1589 FinalRegsToZero.set(MaybeReg.id());
1591 TRI.getMinimalPhysRegClass(Reg))) {
1592 if (!STI.hasVInstructions())
1593 continue;
1594 HasVRegister = true;
1595
1596 for (MCRegister SubReg : TRI.subregs_inclusive(Reg)) {
1597 if (TRI.subregs(SubReg).empty())
1598 FinalRegsToZero.set(SubReg.id());
1599 }
1600 }
1601 }
1602
1603 if (HasVRegister) {
1604 RISCVVType::VLMUL VLMUL = RISCVVType::encodeLMUL(1, /*Fractional=*/false);
1605 unsigned VTypeImm = RISCVVType::encodeVTYPE(
1606 VLMUL, /*SEW=*/32, /*TailAgnostic=*/true, /*MaskAgnostic=*/true);
1607
1608 MCRegister TemporaryReg = RISCV::NoRegister;
1609 for (MCRegister Reg : FinalRegsToZero.set_bits()) {
1610 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1611 TemporaryReg = Reg;
1612 break;
1613 }
1614 }
1615
1616 if (TemporaryReg == RISCV::NoRegister) {
1617 RS->enterBasicBlockEnd(MBB);
1618 TemporaryReg = RS->scavengeRegisterBackwards(RISCV::GPRRegClass, MBBI,
1619 /*RestoreAfter=*/false,
1620 /*SPAdj=*/0);
1621 }
1622
1623 if (MBB.getParent()
1624 ->getFunction()
1625 .getFnAttribute("zero-call-used-regs")
1626 .getValueAsString() == "used")
1627 FinalRegsToZero.set(TemporaryReg.id());
1628
1629 BuildMI(MBB, MBBI, DL, TII.get(RISCV::VSETVLI), TemporaryReg)
1630 .addReg(RISCV::X0)
1631 .addImm(VTypeImm)
1632 .addReg(RISCV::VL, RegState::ImplicitDefine)
1633 .addReg(RISCV::VTYPE, RegState::ImplicitDefine);
1634 }
1635
1636 for (MCRegister Reg : FinalRegsToZero.set_bits())
1637 TII.buildClearRegister(Reg, MBB, MBBI, DL);
1638}
1639
1642 Register &FrameReg) const {
1643 const MachineFrameInfo &MFI = MF.getFrameInfo();
1645 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1646
1647 // Callee-saved registers should be referenced relative to the stack
1648 // pointer (positive offset), otherwise use the frame pointer (negative
1649 // offset).
1650 const auto &CSI = getUnmanagedCSI(MF, MFI.getCalleeSavedInfo(),
1651 STI.preferAscendingLoadStore());
1652 int MinCSFI = 0;
1653 int MaxCSFI = -1;
1655 auto StackID = MFI.getStackID(FI);
1656
1657 assert((StackID == TargetStackID::Default ||
1658 StackID == TargetStackID::ScalableVector) &&
1659 "Unexpected stack ID for the frame object.");
1660 if (StackID == TargetStackID::Default) {
1661 assert(getOffsetOfLocalArea() == 0 && "LocalAreaOffset is not 0!");
1663 MFI.getOffsetAdjustment());
1664 } else if (StackID == TargetStackID::ScalableVector) {
1666 }
1667
1668 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1669
1670 if (CSI.size()) {
1671 MinCSFI = std::min(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1672 MaxCSFI = std::max(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1673 }
1674
1675 bool IsInterruptCSR = RVFI->isSiFivePreemptibleInterrupt(MF) &&
1676 (FI == RVFI->getInterruptCSRFrameIndex(0) ||
1677 FI == RVFI->getInterruptCSRFrameIndex(1));
1678 if ((FI >= MinCSFI && FI <= MaxCSFI) || IsInterruptCSR) {
1679 FrameReg = SPReg;
1680
1681 if (FirstSPAdjustAmount)
1682 Offset += StackOffset::getFixed(FirstSPAdjustAmount);
1683 else
1685 return Offset;
1686 }
1687
1688 if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
1689 // If the stack was realigned, the frame pointer is set in order to allow
1690 // SP to be restored, so we need another base register to record the stack
1691 // after realignment.
1692 // |--------------------------| --
1693 // | callee-allocated save | | <----|
1694 // | area for register varargs| | |
1695 // |--------------------------| <-- FP |
1696 // | callee-saved registers | | |
1697 // |--------------------------| -- |
1698 // | realignment (the size of | | |
1699 // | this area is not counted | | |
1700 // | in MFI.getStackSize()) | | |
1701 // |--------------------------| -- |-- MFI.getStackSize()
1702 // | RVV alignment padding | | |
1703 // | (not counted in | | |
1704 // | MFI.getStackSize() but | | |
1705 // | counted in | | |
1706 // | RVFI.getRVVStackSize()) | | |
1707 // |--------------------------| -- |
1708 // | RVV objects | | |
1709 // | (not counted in | | |
1710 // | MFI.getStackSize()) | | |
1711 // |--------------------------| -- |
1712 // | padding before RVV | | |
1713 // | (not counted in | | |
1714 // | MFI.getStackSize() or in | | |
1715 // | RVFI.getRVVStackSize()) | | |
1716 // |--------------------------| -- |
1717 // | scalar local variables | | <----'
1718 // |--------------------------| -- <-- BP (if var sized objects present)
1719 // | VarSize objects | |
1720 // |--------------------------| -- <-- SP
1721 if (hasBP(MF)) {
1722 FrameReg = RISCVABI::getBPReg();
1723 } else {
1724 // VarSize objects must be empty in this case!
1725 assert(!MFI.hasVarSizedObjects());
1726 FrameReg = SPReg;
1727 }
1728 } else if (!RI->hasStackRealignment(MF)) {
1729 // Note: Keeping the following as multiple 'if' statements rather than
1730 // merging to a single expression for readability.
1731 if (!hasFP(MF)) {
1732 // No FP available, must use SP.
1733 FrameReg = SPReg;
1734 } else {
1735 FrameReg = FPReg;
1736 // SP-relative addressing is only valid when SP is stable throughout
1737 // the function body: no dynamic SP adjustments for outgoing call args,
1738 // no variable-sized objects, and no RVV scalable stack regions.
1739 // hasReservedCallFrame() conservatively encompasses all these checks.
1740 if (hasReservedCallFrame(MF)) {
1741 // Both FP and SP are candidates.
1742 // Prefer SP when the SP-relative offset fits in the compressed
1743 // instruction immediate range.
1744 int64_t SPOff = Offset.getFixed() + MFI.getStackSize();
1745 int64_t CLWSPMaxOffset = 252;
1746 int64_t CLDSPMaxOffset = 504;
1747 int64_t SPThreshold = STI.is64Bit() ? CLDSPMaxOffset : CLWSPMaxOffset;
1748 if (SPOff >= 0 && SPOff <= SPThreshold)
1749 FrameReg = SPReg;
1750 }
1751 }
1752 } else {
1753 assert(RI->hasStackRealignment(MF) && MFI.isFixedObjectIndex(FI) &&
1754 "Expected fixed object with stack realignment");
1755 assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1756 FrameReg = FPReg;
1757 }
1758
1759 if (FrameReg == FPReg) {
1760 Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
1761 // When using FP to access scalable vector objects, we need to minus
1762 // the frame size.
1763 //
1764 // |--------------------------| --
1765 // | callee-allocated save | |
1766 // | area for register varargs| |
1767 // |--------------------------| | -- <-- FP
1768 // | callee-saved registers | |
1769 // |--------------------------| | MFI.getStackSize()
1770 // | scalar local variables | |
1771 // |--------------------------| -- (Offset of RVV objects is from here.)
1772 // | RVV objects |
1773 // |--------------------------|
1774 // | VarSize objects |
1775 // |--------------------------| <-- SP
1776 if (StackID == TargetStackID::ScalableVector) {
1777 assert(!RI->hasStackRealignment(MF) &&
1778 "Can't index across variable sized realign");
1779 // We don't expect any extra RVV alignment padding, as the stack size
1780 // and RVV object sections should be correct aligned in their own
1781 // right.
1783 "Inconsistent stack layout");
1785 }
1786 return Offset;
1787 }
1788
1789 // This case handles indexing off both SP and BP.
1790 // If indexing off SP, there must not be any var sized objects
1791 assert(FrameReg == RISCVABI::getBPReg() || !MFI.hasVarSizedObjects());
1792
1793 // When using SP to access frame objects, we need to add RVV stack size.
1794 //
1795 // |--------------------------| --
1796 // | callee-allocated save | | <----|
1797 // | area for register varargs| | |
1798 // |--------------------------| | | <-- FP
1799 // | callee-saved registers | | |
1800 // |--------------------------| -- |
1801 // | RVV alignment padding | | |
1802 // | (not counted in | | |
1803 // | MFI.getStackSize() but | | |
1804 // | counted in | | |
1805 // | RVFI.getRVVStackSize()) | | |
1806 // |--------------------------| -- |
1807 // | RVV objects | | |-- MFI.getStackSize()
1808 // | (not counted in | | |
1809 // | MFI.getStackSize()) | | |
1810 // |--------------------------| -- |
1811 // | padding before RVV | | |
1812 // | (not counted in | | |
1813 // | MFI.getStackSize()) | | |
1814 // |--------------------------| -- |
1815 // | scalar local variables | | <----'
1816 // |--------------------------| -- <-- BP (if var sized objects present)
1817 // | VarSize objects | |
1818 // |--------------------------| -- <-- SP
1819 //
1820 // The total amount of padding surrounding RVV objects is described by
1821 // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
1822 // objects to the required alignment.
1823 if (MFI.getStackID(FI) == TargetStackID::Default) {
1824 if (MFI.isFixedObjectIndex(FI)) {
1825 assert(!RI->hasStackRealignment(MF) &&
1826 "Can't index across variable sized realign");
1828 RVFI->getRVVStackSize());
1829 } else {
1831 }
1832 } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
1833 // Ensure the base of the RVV stack is correctly aligned: add on the
1834 // alignment padding.
1835 int64_t ScalarLocalVarSize =
1836 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
1837 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
1838 Offset += StackOffset::get(ScalarLocalVarSize, RVFI->getRVVStackSize());
1839 }
1840 return Offset;
1841}
1842
1844 const Register &Reg) {
1845 MCRegister BaseReg = TRI.getSubReg(Reg, RISCV::sub_vrm1_0);
1846 // If it's not a grouped vector register, it doesn't have subregister, so
1847 // the base register is just itself.
1848 if (!BaseReg.isValid())
1849 BaseReg = Reg;
1850 return BaseReg;
1851}
1852
1854 BitVector &SavedRegs,
1855 RegScavenger *RS) const {
1857
1858 // In TargetFrameLowering::determineCalleeSaves, any vector register is marked
1859 // as saved if any of its subregister is clobbered, this is not correct in
1860 // vector registers. We only want the vector register to be marked as saved
1861 // if all of its subregisters are clobbered.
1862 // For example:
1863 // Original behavior: If v24 is marked, v24m2, v24m4, v24m8 are also marked.
1864 // Correct behavior: v24m2 is marked only if v24 and v25 are marked.
1865 MachineRegisterInfo &MRI = MF.getRegInfo();
1866 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
1867 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
1868 for (unsigned i = 0; CSRegs[i]; ++i) {
1869 unsigned CSReg = CSRegs[i];
1870 // Only vector registers need special care.
1871 if (!RISCV::VRRegClass.contains(getRVVBaseRegister(TRI, CSReg)))
1872 continue;
1873
1874 SavedRegs.reset(CSReg);
1875
1876 auto SubRegs = TRI.subregs(CSReg);
1877 // Set the register and all its subregisters.
1878 if (!MRI.def_empty(CSReg) || MRI.getUsedPhysRegsMask().test(CSReg)) {
1879 SavedRegs.set(CSReg);
1880 for (unsigned Reg : SubRegs)
1881 SavedRegs.set(Reg);
1882 }
1883
1884 }
1885
1886 // Unconditionally spill RA and FP only if the function uses a frame
1887 // pointer.
1888 if (hasFP(MF)) {
1889 SavedRegs.set(RAReg);
1890 SavedRegs.set(FPReg);
1891 }
1892 // Mark BP as used if function has dedicated base pointer.
1893 if (hasBP(MF))
1894 SavedRegs.set(RISCVABI::getBPReg());
1895
1896 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1897 // X5 is used as a temporary for saving and restoring `mcause` and `mepc`.
1898 if (RVFI->isSiFivePreemptibleInterrupt(MF))
1899 SavedRegs.set(RISCV::X5);
1900
1901 // When using cm.push/pop we must save X27 if we save X26.
1902 if (RVFI->isPushable(MF) && SavedRegs.test(RISCV::X26))
1903 SavedRegs.set(RISCV::X27);
1904
1905 // For Zilsd on RV32, append GPRPair registers to the CSR list. This prevents
1906 // the need to create register sets for each abi which is a lot more complex.
1907 // Don't use Zilsd for callee-saved coalescing if the required alignment
1908 // exceeds the stack alignment or when Zcmp/Xqccmp or save/restore libcalls
1909 // are enabled.
1910 bool UseZilsd = !STI.is64Bit() && STI.hasStdExtZilsd() &&
1911 STI.getZilsdAlign() <= getStackAlign() &&
1912 !RVFI->isPushable(MF) && !RVFI->useSaveRestoreLibCalls(MF);
1913 if (UseZilsd) {
1916 for (unsigned i = 0; CSRegs[i]; ++i) {
1917 NewCSRs.push_back(CSRegs[i]);
1918 CSRSet.insert(CSRegs[i]);
1919 }
1920
1921 // Append GPRPair registers for pairs where both sub-registers are in CSR
1922 // list. Iterate through all GPRPairs and check if both sub-regs are CSRs.
1923 for (MCPhysReg Pair : RISCV::GPRPairRegClass) {
1924 // Do not append a pair that's already in the CSR list.
1925 if (CSRSet.contains(Pair))
1926 continue;
1927 MCRegister EvenReg = TRI.getSubReg(Pair, RISCV::sub_gpr_even);
1928 MCRegister OddReg = TRI.getSubReg(Pair, RISCV::sub_gpr_odd);
1929 if (CSRSet.contains(EvenReg.id()) && CSRSet.contains(OddReg.id())) {
1930 NewCSRs.push_back(Pair);
1931 CSRSet.insert(Pair);
1932 }
1933 }
1934
1935 MRI.setCalleeSavedRegs(NewCSRs);
1936 CSRegs = MRI.getCalleeSavedRegs();
1937 }
1938
1939 // Check if all subregisters are marked for saving. If so, set the super
1940 // register bit. For GPRPair, only check sub_gpr_even and sub_gpr_odd, not
1941 // aliases like X8_W or X8_H which are not set in SavedRegs.
1942 for (unsigned i = 0; CSRegs[i]; ++i) {
1943 MCRegister CSReg = CSRegs[i];
1944 bool CombineToSuperReg;
1945 if (RISCV::GPRPairRegClass.contains(CSReg)) {
1946 MCRegister EvenReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_even);
1947 MCRegister OddReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_odd);
1948 CombineToSuperReg =
1949 SavedRegs.test(EvenReg.id()) && SavedRegs.test(OddReg.id());
1950 // If s0(x8) is used as FP we can't generate load/store pair because it
1951 // breaks the frame chain.
1952 if (hasFP(MF) && CSReg == RISCV::X8_X9)
1953 CombineToSuperReg = false;
1954 } else {
1955 auto SubRegs = TRI.subregs(CSReg);
1956 CombineToSuperReg =
1957 !SubRegs.empty() && llvm::all_of(SubRegs, [&](unsigned Reg) {
1958 return SavedRegs.test(Reg);
1959 });
1960 }
1961
1962 if (CombineToSuperReg)
1963 SavedRegs.set(CSReg);
1964 }
1965
1966 // SiFive Preemptible Interrupt Handlers need additional frame entries
1968}
1969
1970std::pair<int64_t, Align>
1971RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFunction &MF) const {
1972 MachineFrameInfo &MFI = MF.getFrameInfo();
1973 // Create a buffer of RVV objects to allocate.
1974 SmallVector<int, 8> ObjectsToAllocate;
1975 auto pushRVVObjects = [&](int FIBegin, int FIEnd) {
1976 for (int I = FIBegin, E = FIEnd; I != E; ++I) {
1977 unsigned StackID = MFI.getStackID(I);
1978 if (StackID != TargetStackID::ScalableVector)
1979 continue;
1980 if (MFI.isDeadObjectIndex(I))
1981 continue;
1982
1983 ObjectsToAllocate.push_back(I);
1984 }
1985 };
1986 // First push RVV Callee Saved object, then push RVV stack object
1987 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
1988 const auto &RVVCSI = getRVVCalleeSavedInfo(MF, CSI);
1989 if (!RVVCSI.empty())
1990 pushRVVObjects(RVVCSI[0].getFrameIdx(),
1991 RVVCSI[RVVCSI.size() - 1].getFrameIdx() + 1);
1992 pushRVVObjects(0, MFI.getObjectIndexEnd() - RVVCSI.size());
1993
1994 // The minimum alignment is 16 bytes.
1995 Align RVVStackAlign(16);
1996 const auto &ST = MF.getSubtarget<RISCVSubtarget>();
1997
1998 if (!ST.hasVInstructions()) {
1999 assert(ObjectsToAllocate.empty() &&
2000 "Can't allocate scalable-vector objects without V instructions");
2001 return std::make_pair(0, RVVStackAlign);
2002 }
2003
2004 // Allocate all RVV locals and spills
2005 int64_t Offset = 0;
2006 for (int FI : ObjectsToAllocate) {
2007 // ObjectSize in bytes.
2008 int64_t ObjectSize = MFI.getObjectSize(FI);
2009 auto ObjectAlign =
2010 std::max(Align(RISCV::RVVBytesPerBlock), MFI.getObjectAlign(FI));
2011 // If the data type is the fractional vector type, reserve one vector
2012 // register for it.
2013 if (ObjectSize < RISCV::RVVBytesPerBlock)
2014 ObjectSize = RISCV::RVVBytesPerBlock;
2015 Offset = alignTo(Offset + ObjectSize, ObjectAlign);
2016 MFI.setObjectOffset(FI, -Offset);
2017 // Update the maximum alignment of the RVV stack section
2018 RVVStackAlign = std::max(RVVStackAlign, ObjectAlign);
2019 }
2020
2021 uint64_t StackSize = Offset;
2022
2023 // Ensure the alignment of the RVV stack. Since we want the most-aligned
2024 // object right at the bottom (i.e., any padding at the top of the frame),
2025 // readjust all RVV objects down by the alignment padding.
2026 // Stack size and offsets are multiples of vscale, stack alignment is in
2027 // bytes, we can divide stack alignment by minimum vscale to get a maximum
2028 // stack alignment multiple of vscale.
2029 auto VScale =
2030 std::max<uint64_t>(ST.getRealMinVLen() / RISCV::RVVBitsPerBlock, 1);
2031 if (auto RVVStackAlignVScale = RVVStackAlign.value() / VScale) {
2032 if (auto AlignmentPadding =
2033 offsetToAlignment(StackSize, Align(RVVStackAlignVScale))) {
2034 StackSize += AlignmentPadding;
2035 for (int FI : ObjectsToAllocate)
2036 MFI.setObjectOffset(FI, MFI.getObjectOffset(FI) - AlignmentPadding);
2037 }
2038 }
2039
2040 return std::make_pair(StackSize, RVVStackAlign);
2041}
2042
2044 // For RVV spill, scalable stack offsets computing requires up to two scratch
2045 // registers
2046 static constexpr unsigned ScavSlotsNumRVVSpillScalableObject = 2;
2047
2048 // For RVV spill, non-scalable stack offsets computing requires up to one
2049 // scratch register.
2050 static constexpr unsigned ScavSlotsNumRVVSpillNonScalableObject = 1;
2051
2052 // ADDI instruction's destination register can be used for computing
2053 // offsets. So Scalable stack offsets require up to one scratch register.
2054 static constexpr unsigned ScavSlotsADDIScalableObject = 1;
2055
2056 static constexpr unsigned MaxScavSlotsNumKnown =
2057 std::max({ScavSlotsADDIScalableObject, ScavSlotsNumRVVSpillScalableObject,
2058 ScavSlotsNumRVVSpillNonScalableObject});
2059
2060 unsigned MaxScavSlotsNum = 0;
2062 return false;
2063 for (const MachineBasicBlock &MBB : MF)
2064 for (const MachineInstr &MI : MBB) {
2065 bool IsRVVSpill = RISCV::isRVVSpill(MI);
2066 for (auto &MO : MI.operands()) {
2067 if (!MO.isFI())
2068 continue;
2069 bool IsScalableVectorID = MF.getFrameInfo().getStackID(MO.getIndex()) ==
2071 if (IsRVVSpill) {
2072 MaxScavSlotsNum = std::max(
2073 MaxScavSlotsNum, IsScalableVectorID
2074 ? ScavSlotsNumRVVSpillScalableObject
2075 : ScavSlotsNumRVVSpillNonScalableObject);
2076 } else if (MI.getOpcode() == RISCV::ADDI && IsScalableVectorID) {
2077 MaxScavSlotsNum =
2078 std::max(MaxScavSlotsNum, ScavSlotsADDIScalableObject);
2079 }
2080 }
2081 if (MaxScavSlotsNum == MaxScavSlotsNumKnown)
2082 return MaxScavSlotsNumKnown;
2083 }
2084 return MaxScavSlotsNum;
2085}
2086
2087static bool hasRVVFrameObject(const MachineFunction &MF) {
2088 // Originally, the function will scan all the stack objects to check whether
2089 // if there is any scalable vector object on the stack or not. However, it
2090 // causes errors in the register allocator. In issue 53016, it returns false
2091 // before RA because there is no RVV stack objects. After RA, it returns true
2092 // because there are spilling slots for RVV values during RA. It will not
2093 // reserve BP during register allocation and generate BP access in the PEI
2094 // pass due to the inconsistent behavior of the function.
2095 //
2096 // The function is changed to use hasVInstructions() as the return value. It
2097 // is not precise, but it can make the register allocation correct.
2098 //
2099 // FIXME: Find a better way to make the decision or revisit the solution in
2100 // D103622.
2101 //
2102 // Refer to https://github.com/llvm/llvm-project/issues/53016.
2103 return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
2104}
2105
2107 const RISCVInstrInfo &TII) {
2108 unsigned FnSize = 0;
2109 for (auto &MBB : MF) {
2110 for (auto &MI : MBB) {
2111 // Far branches over 20-bit offset will be relaxed in branch relaxation
2112 // pass. In the worst case, conditional branches will be relaxed into
2113 // the following instruction sequence. Unconditional branches are
2114 // relaxed in the same way, with the exception that there is no first
2115 // branch instruction.
2116 //
2117 // foo
2118 // bne t5, t6, .rev_cond # `TII->getInstSizeInBytes(MI)` bytes
2119 // sd s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2120 // jump .restore, s11 # 8 bytes
2121 // .rev_cond
2122 // bar
2123 // j .dest_bb # 4 bytes, or 2 bytes with Zca
2124 // .restore:
2125 // ld s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2126 // .dest:
2127 // baz
2128 if (MI.isConditionalBranch())
2129 FnSize += TII.getInstSizeInBytes(MI);
2130 if (MI.isConditionalBranch() || MI.isUnconditionalBranch()) {
2131 if (MF.getSubtarget<RISCVSubtarget>().hasStdExtZca())
2132 FnSize += 2 + 8 + 2 + 2;
2133 else
2134 FnSize += 4 + 8 + 4 + 4;
2135 continue;
2136 }
2137
2138 FnSize += TII.getInstSizeInBytes(MI);
2139 }
2140 }
2141 return FnSize;
2142}
2143
2145 MachineFunction &MF, RegScavenger *RS) const {
2146 const RISCVRegisterInfo *RegInfo =
2147 MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
2148 const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
2149 MachineFrameInfo &MFI = MF.getFrameInfo();
2150 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
2151 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2152
2153 int64_t RVVStackSize;
2154 Align RVVStackAlign;
2155 std::tie(RVVStackSize, RVVStackAlign) = assignRVVStackObjectOffsets(MF);
2156
2157 RVFI->setRVVStackSize(RVVStackSize);
2158 RVFI->setRVVStackAlign(RVVStackAlign);
2159
2160 if (hasRVVFrameObject(MF)) {
2161 // Ensure the entire stack is aligned to at least the RVV requirement: some
2162 // scalable-vector object alignments are not considered by the
2163 // target-independent code.
2164 MFI.ensureMaxAlignment(RVVStackAlign);
2165 }
2166
2167 unsigned ScavSlotsNum = 0;
2168
2169 // estimateStackSize has been observed to under-estimate the final stack
2170 // size, so give ourselves wiggle-room by checking for stack size
2171 // representable an 11-bit signed field rather than 12-bits.
2172 if (!isInt<11>(MFI.estimateStackSize(MF)))
2173 ScavSlotsNum = 1;
2174
2175 // Far branches over 20-bit offset require a spill slot for scratch register.
2176 bool IsLargeFunction = !isInt<20>(estimateFunctionSizeInBytes(MF, *TII));
2177 if (IsLargeFunction)
2178 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
2179
2180 // RVV loads & stores have no capacity to hold the immediate address offsets
2181 // so we must always reserve an emergency spill slot if the MachineFunction
2182 // contains any RVV spills.
2183 ScavSlotsNum = std::max(ScavSlotsNum, getScavSlotsNumForRVV(MF));
2184
2185 for (unsigned I = 0; I < ScavSlotsNum; I++) {
2186 int FI = MFI.CreateSpillStackObject(RegInfo->getSpillSize(*RC),
2187 RegInfo->getSpillAlign(*RC));
2188 RS->addScavengingFrameIndex(FI);
2189
2190 if (IsLargeFunction && RVFI->getBranchRelaxationScratchFrameIndex() == -1)
2191 RVFI->setBranchRelaxationScratchFrameIndex(FI);
2192 }
2193
2194 unsigned Size = RVFI->getReservedSpillsSize();
2195 for (const auto &Info : MFI.getCalleeSavedInfo()) {
2196 int FrameIdx = Info.getFrameIdx();
2197 if (FrameIdx < 0 || MFI.getStackID(FrameIdx) != TargetStackID::Default)
2198 continue;
2199
2200 Size += MFI.getObjectSize(FrameIdx);
2201 }
2202 RVFI->setCalleeSavedStackSize(Size);
2203}
2204
2205// Not preserve stack space within prologue for outgoing variables when the
2206// function contains variable size objects or there are vector objects accessed
2207// by the frame pointer.
2208// Let eliminateCallFramePseudoInstr preserve stack space for it.
2210 return !MF.getFrameInfo().hasVarSizedObjects() &&
2211 !(hasFP(MF) && hasRVVFrameObject(MF));
2212}
2213
2214// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
2218 DebugLoc DL = MI->getDebugLoc();
2219
2220 if (!hasReservedCallFrame(MF)) {
2221 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
2222 // ADJCALLSTACKUP must be converted to instructions manipulating the stack
2223 // pointer. This is necessary when there is a variable length stack
2224 // allocation (e.g. alloca), which means it's not possible to allocate
2225 // space for outgoing arguments from within the function prologue.
2226 int64_t Amount = MI->getOperand(0).getImm();
2227
2228 if (Amount != 0) {
2229 // Ensure the stack remains aligned after adjustment.
2230 Amount = alignSPAdjust(Amount);
2231
2232 if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
2233 Amount = -Amount;
2234
2235 const RISCVTargetLowering *TLI =
2236 MF.getSubtarget<RISCVSubtarget>().getTargetLowering();
2237 int64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
2238 if (TLI->hasInlineStackProbe(MF) && -Amount >= ProbeSize) {
2239 // When stack probing is enabled, the decrement of SP may need to be
2240 // probed. We can handle both the decrement and the probing in
2241 // allocateStack.
2242 bool DynAllocation =
2243 MF.getInfo<RISCVMachineFunctionInfo>()->hasDynamicAllocation();
2244 allocateStack(MBB, MI, MF, -Amount, -Amount,
2245 needsDwarfCFI(MF) && !hasFP(MF),
2246 /*NeedProbe=*/true, ProbeSize, DynAllocation,
2248 inlineStackProbe(MF, MBB);
2249 } else {
2250 const RISCVRegisterInfo &RI = *STI.getRegisterInfo();
2253 }
2254 }
2255 }
2256
2257 return MBB.erase(MI);
2258}
2259
2260// We would like to split the SP adjustment to reduce prologue/epilogue
2261// as following instructions. In this way, the offset of the callee saved
2262// register could fit in a single store. Supposed that the first sp adjust
2263// amount is 2032.
2264// add sp,sp,-2032
2265// sw ra,2028(sp)
2266// sw s0,2024(sp)
2267// sw s1,2020(sp)
2268// sw s3,2012(sp)
2269// sw s4,2008(sp)
2270// add sp,sp,-64
2271uint64_t
2273 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2274 const MachineFrameInfo &MFI = MF.getFrameInfo();
2275 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2276 uint64_t StackSize = getStackSizeWithRVVPadding(MF);
2277
2278 // Disable SplitSPAdjust if save-restore libcall, push/pop or QCI interrupts
2279 // are used. The callee-saved registers will be pushed by the save-restore
2280 // libcalls, so we don't have to split the SP adjustment in this case.
2281 if (RVFI->getReservedSpillsSize())
2282 return 0;
2283
2284 // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
2285 // 12-bit and there exists a callee-saved register needing to be pushed.
2286 if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
2287 // FirstSPAdjustAmount is chosen at most as (2048 - StackAlign) because
2288 // 2048 will cause sp = sp + 2048 in the epilogue to be split into multiple
2289 // instructions. Offsets smaller than 2048 can fit in a single load/store
2290 // instruction, and we have to stick with the stack alignment. 2048 has
2291 // 16-byte alignment. The stack alignment for RV32 and RV64 is 16 and for
2292 // RV32E it is 4. So (2048 - StackAlign) will satisfy the stack alignment.
2293 const uint64_t StackAlign = getStackAlign().value();
2294
2295 // Amount of (2048 - StackAlign) will prevent callee saved and restored
2296 // instructions be compressed, so try to adjust the amount to the largest
2297 // offset that stack compression instructions accept when target supports
2298 // compression instructions.
2299 if (STI.hasStdExtZca()) {
2300 // The compression extensions may support the following instructions:
2301 // riscv32: c.lwsp rd, offset[7:2] => 2^(6 + 2)
2302 // c.swsp rs2, offset[7:2] => 2^(6 + 2)
2303 // c.flwsp rd, offset[7:2] => 2^(6 + 2)
2304 // c.fswsp rs2, offset[7:2] => 2^(6 + 2)
2305 // riscv64: c.ldsp rd, offset[8:3] => 2^(6 + 3)
2306 // c.sdsp rs2, offset[8:3] => 2^(6 + 3)
2307 // c.fldsp rd, offset[8:3] => 2^(6 + 3)
2308 // c.fsdsp rs2, offset[8:3] => 2^(6 + 3)
2309 const uint64_t RVCompressLen = STI.getXLen() * 8;
2310 // Compared with amount (2048 - StackAlign), StackSize needs to
2311 // satisfy the following conditions to avoid using more instructions
2312 // to adjust the sp after adjusting the amount, such as
2313 // StackSize meets the condition (StackSize <= 2048 + RVCompressLen),
2314 // case1: Amount is 2048 - StackAlign: use addi + addi to adjust sp.
2315 // case2: Amount is RVCompressLen: use addi + addi to adjust sp.
2316 auto CanCompress = [&](uint64_t CompressLen) -> bool {
2317 if (StackSize <= 2047 + CompressLen ||
2318 (StackSize > 2048 * 2 - StackAlign &&
2319 StackSize <= 2047 * 2 + CompressLen) ||
2320 StackSize > 2048 * 3 - StackAlign)
2321 return true;
2322
2323 return false;
2324 };
2325 // In the epilogue, addi sp, sp, 496 is used to recover the sp and it
2326 // can be compressed(C.ADDI16SP, offset can be [-512, 496]), but
2327 // addi sp, sp, 512 can not be compressed. So try to use 496 first.
2328 const uint64_t ADDI16SPCompressLen = 496;
2329 if (STI.is64Bit() && CanCompress(ADDI16SPCompressLen))
2330 return ADDI16SPCompressLen;
2331 if (CanCompress(RVCompressLen))
2332 return RVCompressLen;
2333 }
2334 return 2048 - StackAlign;
2335 }
2336 return 0;
2337}
2338
2341 std::vector<CalleeSavedInfo> &CSI) const {
2342 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2343 MachineFrameInfo &MFI = MF.getFrameInfo();
2344 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
2345
2346 // Preemptible Interrupts have two additional Callee-save Frame Indexes,
2347 // not tracked by `CSI`.
2348 if (RVFI->isSiFivePreemptibleInterrupt(MF)) {
2349 for (int I = 0; I < 2; ++I) {
2350 int FI = RVFI->getInterruptCSRFrameIndex(I);
2351 MFI.setIsCalleeSavedObjectIndex(FI, true);
2352 }
2353 }
2354
2355 // Early exit if no callee saved registers are modified!
2356 if (CSI.empty())
2357 return true;
2358
2359 if (RVFI->useQCIInterrupt(MF)) {
2360 RVFI->setQCIInterruptStackSize(QCIInterruptPushAmount);
2361 }
2362
2363 if (RVFI->isPushable(MF)) {
2364 // Determine how many GPRs we need to push and save it to RVFI.
2365 unsigned PushedRegNum = getNumPushPopRegs(CSI);
2366
2367 // `QC.C.MIENTER(.NEST)` will save `ra` and `s0`, so we should only push if
2368 // we want to push more than 2 registers. Otherwise, we should push if we
2369 // want to push more than 0 registers.
2370 unsigned OnlyPushIfMoreThan = RVFI->useQCIInterrupt(MF) ? 2 : 0;
2371 if (PushedRegNum > OnlyPushIfMoreThan) {
2372 RVFI->setRVPushRegs(PushedRegNum);
2373 RVFI->setRVPushStackSize(alignTo((STI.getXLen() / 8) * PushedRegNum, 16));
2374 }
2375 }
2376
2377 for (auto &CS : CSI) {
2378 MCRegister Reg = CS.getReg();
2379 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
2380 unsigned Size = RegInfo->getSpillSize(*RC);
2381
2382 if (RVFI->useQCIInterrupt(MF)) {
2383 const auto *FFI = llvm::find_if(FixedCSRFIQCIInterruptMap, [&](auto P) {
2384 return P.first == CS.getReg();
2385 });
2386 if (FFI != std::end(FixedCSRFIQCIInterruptMap)) {
2387 int64_t Offset = FFI->second * (int64_t)Size;
2388
2389 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2390 assert(FrameIdx < 0);
2391 CS.setFrameIdx(FrameIdx);
2392 continue;
2393 }
2394 }
2395
2396 if (RVFI->useSaveRestoreLibCalls(MF) || RVFI->isPushable(MF)) {
2397 const auto *FII = llvm::find_if(
2398 FixedCSRFIMap, [&](MCPhysReg P) { return P == CS.getReg(); });
2399 unsigned RegNum = std::distance(std::begin(FixedCSRFIMap), FII);
2400
2401 if (FII != std::end(FixedCSRFIMap)) {
2402 int64_t Offset;
2403 if (RVFI->getPushPopKind(MF) ==
2405 Offset = -int64_t(RVFI->getRVPushRegs() - RegNum) * Size;
2406 else
2407 Offset = -int64_t(RegNum + 1) * Size;
2408
2409 if (RVFI->useQCIInterrupt(MF))
2411
2412 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2413 assert(FrameIdx < 0);
2414 CS.setFrameIdx(FrameIdx);
2415 continue;
2416 }
2417 }
2418
2419 // For GPRPair registers, use 8-byte slots with required alignment by zilsd.
2420 if (!STI.is64Bit() && STI.hasStdExtZilsd() &&
2421 RISCV::GPRPairRegClass.contains(Reg)) {
2422 Align PairAlign = STI.getZilsdAlign();
2423 int FrameIdx = MFI.CreateStackObject(8, PairAlign, true);
2424 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2425 CS.setFrameIdx(FrameIdx);
2426 continue;
2427 }
2428
2429 // Not a fixed slot.
2430 Align Alignment = RegInfo->getSpillAlign(*RC);
2431 // We may not be able to satisfy the desired alignment specification of
2432 // the TargetRegisterClass if the stack alignment is smaller. Use the
2433 // min.
2434 Alignment = std::min(Alignment, getStackAlign());
2435 int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
2436 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2437 CS.setFrameIdx(FrameIdx);
2439 MFI.setStackID(FrameIdx, TargetStackID::ScalableVector);
2440 }
2441
2442 if (RVFI->useQCIInterrupt(MF)) {
2443 // Allocate a fixed object that covers the entire QCI stack allocation,
2444 // because there are gaps which are reserved for future use.
2445 MFI.CreateFixedSpillStackObject(
2446 QCIInterruptPushAmount, -static_cast<int64_t>(QCIInterruptPushAmount));
2447 }
2448
2449 if (RVFI->isPushable(MF)) {
2450 int64_t QCIOffset = RVFI->useQCIInterrupt(MF) ? QCIInterruptPushAmount : 0;
2451 // Allocate a fixed object that covers the full push.
2452 if (int64_t PushSize = RVFI->getRVPushStackSize())
2453 MFI.CreateFixedSpillStackObject(PushSize, -PushSize - QCIOffset);
2454 } else if (int LibCallRegs = getLibCallID(MF, CSI) + 1) {
2455 int64_t LibCallFrameSize =
2456 alignTo((STI.getXLen() / 8) * LibCallRegs, getStackAlign());
2457 MFI.CreateFixedSpillStackObject(LibCallFrameSize, -LibCallFrameSize);
2458 }
2459
2460 return true;
2461}
2462
2466 if (CSI.empty())
2467 return true;
2468
2469 MachineFunction *MF = MBB.getParent();
2470 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2471 DebugLoc DL;
2472 if (MI != MBB.end() && !MI->isDebugInstr())
2473 DL = MI->getDebugLoc();
2474
2476 if (RVFI->useQCIInterrupt(*MF)) {
2477 // Emit QC.C.MIENTER(.NEST)
2478 BuildMI(
2479 MBB, MI, DL,
2480 TII.get(RVFI->getInterruptStackKind(*MF) ==
2482 ? RISCV::QC_C_MIENTER_NEST
2483 : RISCV::QC_C_MIENTER))
2485
2486 for (auto [Reg, _Offset] : FixedCSRFIQCIInterruptMap)
2487 MBB.addLiveIn(Reg);
2488 }
2489
2490 if (RVFI->isPushable(*MF)) {
2491 // Emit CM.PUSH with base StackAdj & evaluate Push stack
2492 unsigned PushedRegNum = RVFI->getRVPushRegs();
2493 if (PushedRegNum > 0) {
2494 // Use encoded number to represent registers to spill.
2495 unsigned Opcode = getPushOpcode(
2496 RVFI->getPushPopKind(*MF), hasFP(*MF) && !RVFI->useQCIInterrupt(*MF));
2497 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2498 MachineInstrBuilder PushBuilder =
2499 BuildMI(MBB, MI, DL, TII.get(Opcode))
2501 PushBuilder.addImm(RegEnc);
2502 PushBuilder.addImm(0);
2503
2504 for (unsigned i = 0; i < PushedRegNum; i++)
2505 PushBuilder.addUse(FixedCSRFIMap[i], RegState::Implicit);
2506 }
2507 } else if (const char *SpillLibCall = getSpillLibCallName(*MF, CSI)) {
2508 // Add spill libcall via non-callee-saved register t0.
2509 MachineInstrBuilder NewMI =
2510 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
2511 .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
2513 .addUse(RISCV::X2, RegState::Implicit)
2514 .addDef(RISCV::X2, RegState::ImplicitDefine);
2515
2516 // Add registers spilled as implicit used.
2517 for (auto &CS : CSI)
2518 NewMI.addUse(CS.getReg(), RegState::Implicit);
2519 }
2520
2521 // Manually spill values not spilled by libcall & Push/Pop.
2522 const auto &UnmanagedCSI =
2523 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2524 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2525
2526 auto storeRegsToStackSlots = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2527 for (auto &CS : CSInfo) {
2528 // Insert the spill to the stack frame.
2529 MCRegister Reg = CS.getReg();
2530 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2531 TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg),
2532 CS.getFrameIdx(), RC, Register(),
2534 }
2535 };
2536 storeRegsToStackSlots(UnmanagedCSI);
2537 storeRegsToStackSlots(RVVCSI);
2538
2539 return true;
2540}
2541
2542static unsigned getCalleeSavedRVVNumRegs(const Register &BaseReg) {
2543 return RISCV::VRRegClass.contains(BaseReg) ? 1
2544 : RISCV::VRM2RegClass.contains(BaseReg) ? 2
2545 : RISCV::VRM4RegClass.contains(BaseReg) ? 4
2546 : 8;
2547}
2548
2549void RISCVFrameLowering::emitCalleeSavedRVVPrologCFI(
2552 const MachineFrameInfo &MFI = MF->getFrameInfo();
2553 RISCVMachineFunctionInfo *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2554 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2555
2556 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2557 if (RVVCSI.empty())
2558 return;
2559
2560 uint64_t FixedSize = getStackSizeWithRVVPadding(*MF);
2561 if (!HasFP) {
2562 uint64_t ScalarLocalVarSize =
2563 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
2564 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
2565 FixedSize -= ScalarLocalVarSize;
2566 }
2567
2568 CFIInstBuilder CFIBuilder(MBB, MI, MachineInstr::FrameSetup);
2569 for (auto &CS : RVVCSI) {
2570 // Insert the spill to the stack frame.
2571 int FI = CS.getFrameIdx();
2572 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2573 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2574 for (unsigned i = 0; i < NumRegs; ++i) {
2575 CFIBuilder.insertCFIInst(createDefCFAOffset(
2576 TRI, BaseReg + i,
2577 StackOffset::get(-FixedSize, MFI.getObjectOffset(FI) / 8 + i)));
2578 }
2579 }
2580}
2581
2582void RISCVFrameLowering::emitCalleeSavedRVVEpilogCFI(
2585 const MachineFrameInfo &MFI = MF->getFrameInfo();
2586 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2587
2588 CFIInstBuilder CFIHelper(MBB, MI, MachineInstr::FrameDestroy);
2589 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2590 for (auto &CS : RVVCSI) {
2591 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2592 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2593 for (unsigned i = 0; i < NumRegs; ++i)
2594 CFIHelper.buildRestore(BaseReg + i);
2595 }
2596}
2597
2601 if (CSI.empty())
2602 return true;
2603
2604 MachineFunction *MF = MBB.getParent();
2605 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2606 DebugLoc DL;
2607 if (MI != MBB.end() && !MI->isDebugInstr())
2608 DL = MI->getDebugLoc();
2609
2610 // Manually restore values not restored by libcall & Push/Pop.
2611 // Reverse the restore order in epilog. In addition, the return
2612 // address will be restored first in the epilogue. It increases
2613 // the opportunity to avoid the load-to-use data hazard between
2614 // loading RA and return by RA. loadRegFromStackSlot can insert
2615 // multiple instructions.
2616 const auto &UnmanagedCSI =
2617 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2618 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2619
2620 auto loadRegFromStackSlot = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2621 for (auto &CS : CSInfo) {
2622 MCRegister Reg = CS.getReg();
2623 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2624 TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, Register(),
2625 RISCV::NoSubRegister,
2627 assert(MI != MBB.begin() &&
2628 "loadRegFromStackSlot didn't insert any code!");
2629 }
2630 };
2631 loadRegFromStackSlot(RVVCSI);
2632 loadRegFromStackSlot(UnmanagedCSI);
2633
2635 if (RVFI->useQCIInterrupt(*MF)) {
2636 // Don't emit anything here because restoration is handled by
2637 // QC.C.MILEAVERET which we already inserted to return.
2638 assert(MI->getOpcode() == RISCV::QC_C_MILEAVERET &&
2639 "Unexpected QCI Interrupt Return Instruction");
2640 }
2641
2642 if (RVFI->isPushable(*MF)) {
2643 unsigned PushedRegNum = RVFI->getRVPushRegs();
2644 if (PushedRegNum > 0) {
2645 unsigned Opcode = getPopOpcode(RVFI->getPushPopKind(*MF));
2646 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2647 MachineInstrBuilder PopBuilder =
2648 BuildMI(MBB, MI, DL, TII.get(Opcode))
2650 // Use encoded number to represent registers to restore.
2651 PopBuilder.addImm(RegEnc);
2652 PopBuilder.addImm(0);
2653
2654 for (unsigned i = 0; i < RVFI->getRVPushRegs(); i++)
2656 }
2657 } else if (const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI)) {
2658 // Add restore libcall via tail call.
2659 MachineInstrBuilder NewMI =
2660 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
2661 .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
2663 .addDef(RISCV::X2, RegState::ImplicitDefine);
2664
2665 // Add registers restored as implicit defined.
2666 for (auto &CS : CSI)
2667 NewMI.addDef(CS.getReg(), RegState::ImplicitDefine);
2668
2669 // Remove trailing returns, since the terminator is now a tail call to the
2670 // restore function.
2671 if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
2672 NewMI.getInstr()->copyImplicitOps(*MF, *MI);
2673 MI->eraseFromParent();
2674 }
2675 }
2676 return true;
2677}
2678
2680 // Keep the conventional code flow when not optimizing.
2681 if (MF.getFunction().hasOptNone())
2682 return false;
2683
2684 // QCI and SiFive CLIC interrupt entry sequences must precede all handler
2685 // code.
2686 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2687 if (RVFI->useQCIInterrupt(MF) || RVFI->useSiFiveInterrupt(MF))
2688 return false;
2689
2690 return true;
2691}
2692
2694 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
2695 const MachineFunction *MF = MBB.getParent();
2696 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2697
2698 // Make sure VTYPE and VL are not live-in since we will use vsetvli in the
2699 // prologue to get the VLEN, and that will clobber these registers.
2700 //
2701 // We may do also check the stack contains objects with scalable vector type,
2702 // but this will require iterating over all the stack objects, but this may
2703 // not worth since the situation is rare, we could do further check in future
2704 // if we find it is necessary.
2705 if (STI.preferVsetvliOverReadVLENB() &&
2706 (MBB.isLiveIn(RISCV::VTYPE) || MBB.isLiveIn(RISCV::VL)))
2707 return false;
2708
2709 if (!RVFI->useSaveRestoreLibCalls(*MF))
2710 return true;
2711
2712 // Inserting a call to a __riscv_save libcall requires the use of the register
2713 // t0 (X5) to hold the return address. Therefore if this register is already
2714 // used we can't insert the call.
2715
2716 RegScavenger RS;
2717 RS.enterBasicBlock(*TmpMBB);
2718 return !RS.isRegUsed(RISCV::X5);
2719}
2720
2722 const MachineFunction *MF = MBB.getParent();
2723 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
2724 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2725
2726 if (!RVFI->useSaveRestoreLibCalls(*MF))
2727 return true;
2728
2729 // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
2730 // This means if we still need to continue executing code within this function
2731 // the restore cannot take place in this basic block.
2732
2733 if (MBB.succ_size() > 1)
2734 return false;
2735
2736 MachineBasicBlock *SuccMBB =
2737 MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
2738
2739 // Doing a tail call should be safe if there are no successors, because either
2740 // we have a returning block or the end of the block is unreachable, so the
2741 // restore will be eliminated regardless.
2742 if (!SuccMBB)
2743 return true;
2744
2745 // The successor can only contain a return and debug instructions, since we
2746 // would effectively replace it with our own tail return at the end of this
2747 // block. The debug instructions would not execute on the tail-return path.
2748 return SuccMBB->isReturnBlock() &&
2749 llvm::count_if(SuccMBB->instrs(), [](const MachineInstr &MI) {
2750 return !MI.isDebugInstr();
2751 }) == 1;
2752}
2753
2755 switch (ID) {
2758 return true;
2764 return false;
2765 }
2766 llvm_unreachable("Invalid TargetStackID::Value");
2767}
2768
2772
2773// Synthesize the probe loop.
2775 Register TargetReg, Register ScratchReg,
2776 bool IsRVV) {
2777 assert(TargetReg != RISCV::X2 && "New top of stack cannot already be in SP");
2778 assert(ScratchReg != RISCV::X2 && "Scratch register cannot be SP");
2779 assert(TargetReg != ScratchReg && "Target and scratch must be different");
2780
2781 MachineBasicBlock &MBB = *MBBI->getParent();
2782 MachineFunction &MF = *MBB.getParent();
2783
2784 auto &Subtarget = MF.getSubtarget<RISCVSubtarget>();
2785 const RISCVInstrInfo *TII = Subtarget.getInstrInfo();
2786 bool IsRV64 = Subtarget.is64Bit();
2787 Align StackAlign = Subtarget.getFrameLowering()->getStackAlign();
2788 const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
2789 uint64_t ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
2790
2791 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
2792 MachineBasicBlock *LoopTestMBB =
2793 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
2794 MF.insert(MBBInsertPoint, LoopTestMBB);
2795 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
2796 MF.insert(MBBInsertPoint, ExitMBB);
2798
2799 // ScratchReg = ProbeSize
2800 TII->movImm(MBB, MBBI, DL, ScratchReg, ProbeSize, Flags);
2801
2802 // LoopTest:
2803 // SUB SP, SP, ProbeSize
2804 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB), SPReg)
2805 .addReg(SPReg)
2806 .addReg(ScratchReg)
2807 .setMIFlags(Flags);
2808
2809 // s[d|w] zero, 0(sp)
2810 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
2811 TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
2812 .addReg(RISCV::X0)
2813 .addReg(SPReg)
2814 .addImm(0)
2815 .setMIFlags(Flags);
2816
2817 if (IsRVV) {
2818 // SUB TargetReg, TargetReg, ProbeSize
2819 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB),
2820 TargetReg)
2821 .addReg(TargetReg)
2822 .addReg(ScratchReg)
2823 .setMIFlags(Flags);
2824
2825 // BGE TargetReg, ProbeSize, LoopTest
2826 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BGE))
2827 .addReg(TargetReg)
2828 .addReg(ScratchReg)
2829 .addMBB(LoopTestMBB)
2830 .setMIFlags(Flags);
2831
2832 } else {
2833 // BNE SP, TargetReg, LoopTest
2834 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BNE))
2835 .addReg(SPReg)
2836 .addReg(TargetReg)
2837 .addMBB(LoopTestMBB)
2838 .setMIFlags(Flags);
2839 }
2840
2841 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
2843
2844 LoopTestMBB->addSuccessor(ExitMBB);
2845 LoopTestMBB->addSuccessor(LoopTestMBB);
2846 MBB.addSuccessor(LoopTestMBB);
2847 // Update liveins.
2848 fullyRecomputeLiveIns({ExitMBB, LoopTestMBB});
2849}
2850
2851void RISCVFrameLowering::inlineStackProbe(MachineFunction &MF,
2852 MachineBasicBlock &MBB) const {
2853 // Get the instructions that need to be replaced. We emit at most two of
2854 // these. Remember them in order to avoid complications coming from the need
2855 // to traverse the block while potentially creating more blocks.
2856 SmallVector<MachineInstr *, 4> ToReplace;
2857 for (MachineInstr &MI : MBB) {
2858 unsigned Opc = MI.getOpcode();
2859 if (Opc == RISCV::PROBED_STACKALLOC ||
2860 Opc == RISCV::PROBED_STACKALLOC_RVV) {
2861 ToReplace.push_back(&MI);
2862 }
2863 }
2864
2865 for (MachineInstr *MI : ToReplace) {
2866 if (MI->getOpcode() == RISCV::PROBED_STACKALLOC ||
2867 MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV) {
2870 Register TargetReg = MI->getOperand(0).getReg();
2871
2872 Register ScratchReg =
2873 findScratchNonCalleeSaveRegister(&MBB, RISCV::X7, TargetReg);
2874
2875 assert(ScratchReg.isValid() &&
2876 "No available scratch register for stack probe loop");
2877
2878 emitStackProbeInline(MBBI, DL, TargetReg, ScratchReg,
2879 (MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV));
2881 }
2882 }
2883}
2884
2886 return 0;
2887}
2888
2891 return RISCV::X2;
2892}
2893
2894// On 64-bit systems the fixed stack can hold INT64_MAX bytes, since
2895// stack-offset calculation is done in 2s-complement.
2896// NOTE: In theory a register can hold any 64-bit number, so this constraint
2897// might be relaxed to UINT64_MAX in the future, if anyone actually needs
2898// that.
2900 return STI.is64Bit() ? INT64_MAX : UINT32_MAX;
2901}
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:765
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
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
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 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