1 //===-- RISCVRegisterInfo.cpp - RISCV Register Information ------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the RISCV implementation of the TargetRegisterInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RISCVRegisterInfo.h"
14 #include "RISCV.h"
15 #include "RISCVMachineFunctionInfo.h"
16 #include "RISCVSubtarget.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/RegisterScavenging.h"
22 #include "llvm/CodeGen/TargetFrameLowering.h"
23 #include "llvm/CodeGen/TargetInstrInfo.h"
24 #include "llvm/IR/DebugInfoMetadata.h"
25 #include "llvm/Support/ErrorHandling.h"
26 
27 #define GET_REGINFO_TARGET_DESC
28 #include "RISCVGenRegisterInfo.inc"
29 
30 using namespace llvm;
31 
32 static_assert(RISCV::X1 == RISCV::X0 + 1, "Register list not consecutive");
33 static_assert(RISCV::X31 == RISCV::X0 + 31, "Register list not consecutive");
34 static_assert(RISCV::F1_H == RISCV::F0_H + 1, "Register list not consecutive");
35 static_assert(RISCV::F31_H == RISCV::F0_H + 31,
36               "Register list not consecutive");
37 static_assert(RISCV::F1_F == RISCV::F0_F + 1, "Register list not consecutive");
38 static_assert(RISCV::F31_F == RISCV::F0_F + 31,
39               "Register list not consecutive");
40 static_assert(RISCV::F1_D == RISCV::F0_D + 1, "Register list not consecutive");
41 static_assert(RISCV::F31_D == RISCV::F0_D + 31,
42               "Register list not consecutive");
43 static_assert(RISCV::V1 == RISCV::V0 + 1, "Register list not consecutive");
44 static_assert(RISCV::V31 == RISCV::V0 + 31, "Register list not consecutive");
45 
46 RISCVRegisterInfo::RISCVRegisterInfo(unsigned HwMode)
47     : RISCVGenRegisterInfo(RISCV::X1, /*DwarfFlavour*/0, /*EHFlavor*/0,
48                            /*PC*/0, HwMode) {}
49 
50 const MCPhysReg *
51 RISCVRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
52   auto &Subtarget = MF->getSubtarget<RISCVSubtarget>();
53   if (MF->getFunction().getCallingConv() == CallingConv::GHC)
54     return CSR_NoRegs_SaveList;
55   if (MF->getFunction().hasFnAttribute("interrupt")) {
56     if (Subtarget.hasStdExtD())
57       return CSR_XLEN_F64_Interrupt_SaveList;
58     if (Subtarget.hasStdExtF())
59       return CSR_XLEN_F32_Interrupt_SaveList;
60     return CSR_Interrupt_SaveList;
61   }
62 
63   switch (Subtarget.getTargetABI()) {
64   default:
65     llvm_unreachable("Unrecognized ABI");
66   case RISCVABI::ABI_ILP32:
67   case RISCVABI::ABI_LP64:
68     return CSR_ILP32_LP64_SaveList;
69   case RISCVABI::ABI_ILP32F:
70   case RISCVABI::ABI_LP64F:
71     return CSR_ILP32F_LP64F_SaveList;
72   case RISCVABI::ABI_ILP32D:
73   case RISCVABI::ABI_LP64D:
74     return CSR_ILP32D_LP64D_SaveList;
75   }
76 }
77 
78 BitVector RISCVRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
79   const RISCVFrameLowering *TFI = getFrameLowering(MF);
80   BitVector Reserved(getNumRegs());
81 
82   // Mark any registers requested to be reserved as such
83   for (size_t Reg = 0; Reg < getNumRegs(); Reg++) {
84     if (MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(Reg))
85       markSuperRegs(Reserved, Reg);
86   }
87 
88   // Use markSuperRegs to ensure any register aliases are also reserved
89   markSuperRegs(Reserved, RISCV::X0); // zero
90   markSuperRegs(Reserved, RISCV::X2); // sp
91   markSuperRegs(Reserved, RISCV::X3); // gp
92   markSuperRegs(Reserved, RISCV::X4); // tp
93   if (TFI->hasFP(MF))
94     markSuperRegs(Reserved, RISCV::X8); // fp
95   // Reserve the base register if we need to realign the stack and allocate
96   // variable-sized objects at runtime.
97   if (TFI->hasBP(MF))
98     markSuperRegs(Reserved, RISCVABI::getBPReg()); // bp
99 
100   // V registers for code generation. We handle them manually.
101   markSuperRegs(Reserved, RISCV::VL);
102   markSuperRegs(Reserved, RISCV::VTYPE);
103   markSuperRegs(Reserved, RISCV::VXSAT);
104   markSuperRegs(Reserved, RISCV::VXRM);
105 
106   // Floating point environment registers.
107   markSuperRegs(Reserved, RISCV::FRM);
108   markSuperRegs(Reserved, RISCV::FFLAGS);
109 
110   assert(checkAllSuperRegsMarked(Reserved));
111   return Reserved;
112 }
113 
114 bool RISCVRegisterInfo::isAsmClobberable(const MachineFunction &MF,
115                                          MCRegister PhysReg) const {
116   return !MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(PhysReg);
117 }
118 
119 bool RISCVRegisterInfo::isConstantPhysReg(MCRegister PhysReg) const {
120   return PhysReg == RISCV::X0;
121 }
122 
123 const uint32_t *RISCVRegisterInfo::getNoPreservedMask() const {
124   return CSR_NoRegs_RegMask;
125 }
126 
127 // Frame indexes representing locations of CSRs which are given a fixed location
128 // by save/restore libcalls.
129 static const std::pair<unsigned, int> FixedCSRFIMap[] = {
130   {/*ra*/  RISCV::X1,   -1},
131   {/*s0*/  RISCV::X8,   -2},
132   {/*s1*/  RISCV::X9,   -3},
133   {/*s2*/  RISCV::X18,  -4},
134   {/*s3*/  RISCV::X19,  -5},
135   {/*s4*/  RISCV::X20,  -6},
136   {/*s5*/  RISCV::X21,  -7},
137   {/*s6*/  RISCV::X22,  -8},
138   {/*s7*/  RISCV::X23,  -9},
139   {/*s8*/  RISCV::X24,  -10},
140   {/*s9*/  RISCV::X25,  -11},
141   {/*s10*/ RISCV::X26,  -12},
142   {/*s11*/ RISCV::X27,  -13}
143 };
144 
145 bool RISCVRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
146                                              Register Reg,
147                                              int &FrameIdx) const {
148   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
149   if (!RVFI->useSaveRestoreLibCalls(MF))
150     return false;
151 
152   const auto *FII =
153       llvm::find_if(FixedCSRFIMap, [&](auto P) { return P.first == Reg; });
154   if (FII == std::end(FixedCSRFIMap))
155     return false;
156 
157   FrameIdx = FII->second;
158   return true;
159 }
160 
161 void RISCVRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
162                                             int SPAdj, unsigned FIOperandNum,
163                                             RegScavenger *RS) const {
164   assert(SPAdj == 0 && "Unexpected non-zero SPAdj value");
165 
166   MachineInstr &MI = *II;
167   MachineFunction &MF = *MI.getParent()->getParent();
168   MachineRegisterInfo &MRI = MF.getRegInfo();
169   const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
170   DebugLoc DL = MI.getDebugLoc();
171 
172   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
173   Register FrameReg;
174   StackOffset Offset =
175       getFrameLowering(MF)->getFrameIndexReference(MF, FrameIndex, FrameReg);
176   bool IsRVVSpill = TII->isRVVSpill(MI, /*CheckFIs*/ false);
177   if (!IsRVVSpill)
178     Offset += StackOffset::getFixed(MI.getOperand(FIOperandNum + 1).getImm());
179 
180   if (!isInt<32>(Offset.getFixed())) {
181     report_fatal_error(
182         "Frame offsets outside of the signed 32-bit range not supported");
183   }
184 
185   MachineBasicBlock &MBB = *MI.getParent();
186   bool FrameRegIsKill = false;
187 
188   // If required, pre-compute the scalable factor amount which will be used in
189   // later offset computation. Since this sequence requires up to two scratch
190   // registers -- after which one is made free -- this grants us better
191   // scavenging of scratch registers as only up to two are live at one time,
192   // rather than three.
193   Register ScalableFactorRegister;
194   unsigned ScalableAdjOpc = RISCV::ADD;
195   if (Offset.getScalable()) {
196     int64_t ScalableValue = Offset.getScalable();
197     if (ScalableValue < 0) {
198       ScalableValue = -ScalableValue;
199       ScalableAdjOpc = RISCV::SUB;
200     }
201     // 1. Get vlenb && multiply vlen with the number of vector registers.
202     ScalableFactorRegister =
203         TII->getVLENFactoredAmount(MF, MBB, II, DL, ScalableValue);
204   }
205 
206   if (!isInt<12>(Offset.getFixed())) {
207     // The offset won't fit in an immediate, so use a scratch register instead
208     // Modify Offset and FrameReg appropriately
209     Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
210     TII->movImm(MBB, II, DL, ScratchReg, Offset.getFixed());
211     if (MI.getOpcode() == RISCV::ADDI && !Offset.getScalable()) {
212       BuildMI(MBB, II, DL, TII->get(RISCV::ADD), MI.getOperand(0).getReg())
213         .addReg(FrameReg)
214         .addReg(ScratchReg, RegState::Kill);
215       MI.eraseFromParent();
216       return;
217     }
218     BuildMI(MBB, II, DL, TII->get(RISCV::ADD), ScratchReg)
219         .addReg(FrameReg)
220         .addReg(ScratchReg, RegState::Kill);
221     Offset = StackOffset::get(0, Offset.getScalable());
222     FrameReg = ScratchReg;
223     FrameRegIsKill = true;
224   }
225 
226   if (!Offset.getScalable()) {
227     // Offset = (fixed offset, 0)
228     MI.getOperand(FIOperandNum)
229         .ChangeToRegister(FrameReg, false, false, FrameRegIsKill);
230     if (!IsRVVSpill)
231       MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset.getFixed());
232     else {
233       if (Offset.getFixed()) {
234         Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
235         BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), ScratchReg)
236           .addReg(FrameReg, getKillRegState(FrameRegIsKill))
237           .addImm(Offset.getFixed());
238         MI.getOperand(FIOperandNum)
239           .ChangeToRegister(ScratchReg, false, false, true);
240       }
241     }
242   } else {
243     // Offset = (fixed offset, scalable offset)
244     // Step 1, the scalable offset, has already been computed.
245     assert(ScalableFactorRegister &&
246            "Expected pre-computation of scalable factor in earlier step");
247 
248     // 2. Calculate address: FrameReg + result of multiply
249     if (MI.getOpcode() == RISCV::ADDI && !Offset.getFixed()) {
250       BuildMI(MBB, II, DL, TII->get(ScalableAdjOpc), MI.getOperand(0).getReg())
251           .addReg(FrameReg, getKillRegState(FrameRegIsKill))
252           .addReg(ScalableFactorRegister, RegState::Kill);
253       MI.eraseFromParent();
254       return;
255     }
256     Register VL = MRI.createVirtualRegister(&RISCV::GPRRegClass);
257     BuildMI(MBB, II, DL, TII->get(ScalableAdjOpc), VL)
258         .addReg(FrameReg, getKillRegState(FrameRegIsKill))
259         .addReg(ScalableFactorRegister, RegState::Kill);
260 
261     if (IsRVVSpill && Offset.getFixed()) {
262       // Scalable load/store has no immediate argument. We need to add the
263       // fixed part into the load/store base address.
264       BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), VL)
265           .addReg(VL)
266           .addImm(Offset.getFixed());
267     }
268 
269     // 3. Replace address register with calculated address register
270     MI.getOperand(FIOperandNum).ChangeToRegister(VL, false, false, true);
271     if (!IsRVVSpill)
272       MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset.getFixed());
273   }
274 
275   auto ZvlssegInfo = TII->isRVVSpillForZvlsseg(MI.getOpcode());
276   if (ZvlssegInfo) {
277     Register VL = MRI.createVirtualRegister(&RISCV::GPRRegClass);
278     BuildMI(MBB, II, DL, TII->get(RISCV::PseudoReadVLENB), VL);
279     uint32_t ShiftAmount = Log2_32(ZvlssegInfo->second);
280     if (ShiftAmount != 0)
281       BuildMI(MBB, II, DL, TII->get(RISCV::SLLI), VL)
282           .addReg(VL)
283           .addImm(ShiftAmount);
284     // The last argument of pseudo spilling opcode for zvlsseg is the length of
285     // one element of zvlsseg types. For example, for vint32m2x2_t, it will be
286     // the length of vint32m2_t.
287     MI.getOperand(FIOperandNum + 1).ChangeToRegister(VL, /*isDef=*/false);
288   }
289 }
290 
291 Register RISCVRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
292   const TargetFrameLowering *TFI = getFrameLowering(MF);
293   return TFI->hasFP(MF) ? RISCV::X8 : RISCV::X2;
294 }
295 
296 const uint32_t *
297 RISCVRegisterInfo::getCallPreservedMask(const MachineFunction & MF,
298                                         CallingConv::ID CC) const {
299   auto &Subtarget = MF.getSubtarget<RISCVSubtarget>();
300 
301   if (CC == CallingConv::GHC)
302     return CSR_NoRegs_RegMask;
303   switch (Subtarget.getTargetABI()) {
304   default:
305     llvm_unreachable("Unrecognized ABI");
306   case RISCVABI::ABI_ILP32:
307   case RISCVABI::ABI_LP64:
308     return CSR_ILP32_LP64_RegMask;
309   case RISCVABI::ABI_ILP32F:
310   case RISCVABI::ABI_LP64F:
311     return CSR_ILP32F_LP64F_RegMask;
312   case RISCVABI::ABI_ILP32D:
313   case RISCVABI::ABI_LP64D:
314     return CSR_ILP32D_LP64D_RegMask;
315   }
316 }
317 
318 const TargetRegisterClass *
319 RISCVRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
320                                              const MachineFunction &) const {
321   if (RC == &RISCV::VMV0RegClass)
322     return &RISCV::VRRegClass;
323   return RC;
324 }
325 
326 void RISCVRegisterInfo::getOffsetOpcodes(const StackOffset &Offset,
327                                          SmallVectorImpl<uint64_t> &Ops) const {
328   // VLENB is the length of a vector register in bytes. We use <vscale x 8 x i8>
329   // to represent one vector register. The dwarf offset is
330   // VLENB * scalable_offset / 8.
331   assert(Offset.getScalable() % 8 == 0 && "Invalid frame offset");
332 
333   // Add fixed-sized offset using existing DIExpression interface.
334   DIExpression::appendOffset(Ops, Offset.getFixed());
335 
336   unsigned VLENB = getDwarfRegNum(RISCV::VLENB, true);
337   int64_t VLENBSized = Offset.getScalable() / 8;
338   if (VLENBSized > 0) {
339     Ops.push_back(dwarf::DW_OP_constu);
340     Ops.push_back(VLENBSized);
341     Ops.append({dwarf::DW_OP_bregx, VLENB, 0ULL});
342     Ops.push_back(dwarf::DW_OP_mul);
343     Ops.push_back(dwarf::DW_OP_plus);
344   } else if (VLENBSized < 0) {
345     Ops.push_back(dwarf::DW_OP_constu);
346     Ops.push_back(-VLENBSized);
347     Ops.append({dwarf::DW_OP_bregx, VLENB, 0ULL});
348     Ops.push_back(dwarf::DW_OP_mul);
349     Ops.push_back(dwarf::DW_OP_minus);
350   }
351 }
352 
353 unsigned
354 RISCVRegisterInfo::getRegisterCostTableIndex(const MachineFunction &MF) const {
355   return MF.getSubtarget<RISCVSubtarget>().hasStdExtC() ? 1 : 0;
356 }
357