LLVM 24.0.0git
RISCVRegisterInfo.cpp
Go to the documentation of this file.
1//===-- RISCVRegisterInfo.cpp - RISC-V 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 RISC-V implementation of the TargetRegisterInfo class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RISCVRegisterInfo.h"
14#include "RISCV.h"
15#include "RISCVSubtarget.h"
16#include "llvm/ADT/SmallSet.h"
26
27#define GET_REGINFO_TARGET_DESC
28#include "RISCVGenRegisterInfo.inc"
29
30using namespace llvm;
31
32static_assert(RISCV::X1 == RISCV::X0 + 1, "Register list not consecutive");
33static_assert(RISCV::X31 == RISCV::X0 + 31, "Register list not consecutive");
34static_assert(RISCV::F1_H == RISCV::F0_H + 1, "Register list not consecutive");
35static_assert(RISCV::F31_H == RISCV::F0_H + 31,
36 "Register list not consecutive");
37static_assert(RISCV::F1_F == RISCV::F0_F + 1, "Register list not consecutive");
38static_assert(RISCV::F31_F == RISCV::F0_F + 31,
39 "Register list not consecutive");
40static_assert(RISCV::F1_D == RISCV::F0_D + 1, "Register list not consecutive");
41static_assert(RISCV::F31_D == RISCV::F0_D + 31,
42 "Register list not consecutive");
43static_assert(RISCV::F1_Q == RISCV::F0_Q + 1, "Register list not consecutive");
44static_assert(RISCV::F31_Q == RISCV::F0_Q + 31,
45 "Register list not consecutive");
46static_assert(RISCV::V1 == RISCV::V0 + 1, "Register list not consecutive");
47static_assert(RISCV::V31 == RISCV::V0 + 31, "Register list not consecutive");
48
50 const std::bitset<32> &UserReservedXRegs)
51 : RISCVGenRegisterInfo(RISCV::X1, /*DwarfFlavour*/ 0, /*EHFlavor*/ 0,
52 /*PC*/ 0, HwMode),
53 UserReservedRegs(getNumRegs()) {
54 // Expand the reserve-xN features to include aliases.
55 for (unsigned I = 1; I != 32; ++I) {
56 if (!UserReservedXRegs[I])
57 continue;
58 for (MCRegAliasIterator AI(RISCV::X0 + I, this, /*IncludeSelf=*/true);
59 AI.isValid(); ++AI)
60 UserReservedRegs.set((*AI).id());
61 }
62}
63
64const MCPhysReg *
66 return CSR_IPRA_SaveList;
67}
68
69const MCPhysReg *
73 return CSR_NoRegs_SaveList;
75 return Subtarget.hasStdExtE() ? CSR_RT_MostRegs_RVE_SaveList
76 : CSR_RT_MostRegs_SaveList;
77 if (MF->getFunction().hasFnAttribute("interrupt")) {
78 if (Subtarget.hasVInstructions()) {
79 if (Subtarget.hasStdExtD())
80 return Subtarget.hasStdExtE() ? CSR_XLEN_F64_V_Interrupt_RVE_SaveList
81 : CSR_XLEN_F64_V_Interrupt_SaveList;
82 if (Subtarget.hasStdExtF())
83 return Subtarget.hasStdExtE() ? CSR_XLEN_F32_V_Interrupt_RVE_SaveList
84 : CSR_XLEN_F32_V_Interrupt_SaveList;
85 return Subtarget.hasStdExtE() ? CSR_XLEN_V_Interrupt_RVE_SaveList
86 : CSR_XLEN_V_Interrupt_SaveList;
87 }
88 if (Subtarget.hasStdExtD())
89 return Subtarget.hasStdExtE() ? CSR_XLEN_F64_Interrupt_RVE_SaveList
90 : CSR_XLEN_F64_Interrupt_SaveList;
91 if (Subtarget.hasStdExtF())
92 return Subtarget.hasStdExtE() ? CSR_XLEN_F32_Interrupt_RVE_SaveList
93 : CSR_XLEN_F32_Interrupt_SaveList;
94 return Subtarget.hasStdExtE() ? CSR_Interrupt_RVE_SaveList
95 : CSR_Interrupt_SaveList;
96 }
97
98 bool HasVectorCSR =
100 Subtarget.hasVInstructions();
101
102 RISCVABI::ABI ABI = Subtarget.getTargetABI();
104 "Unrecognized ABI");
105 if (RISCVABI::isRVE(ABI))
106 return CSR_ILP32E_LP64E_SaveList;
107 if (RISCVABI::isSoftFP(ABI))
108 return HasVectorCSR ? CSR_ILP32_LP64_V_SaveList : CSR_ILP32_LP64_SaveList;
109 if (RISCVABI::isSingleFP(ABI))
110 return HasVectorCSR ? CSR_ILP32F_LP64F_V_SaveList
111 : CSR_ILP32F_LP64F_SaveList;
112 assert(RISCVABI::isDoubleFP(ABI) && "Unrecognized ABI");
113 return HasVectorCSR ? CSR_ILP32D_LP64D_V_SaveList : CSR_ILP32D_LP64D_SaveList;
114}
115
117 Register Reg, const MachineRegisterInfo &MRI) const {
118 const RISCVSubtarget &STI = MRI.getMF().getSubtarget<RISCVSubtarget>();
119
120 const RegClassOrRegBank &RCOrRB = MRI.getRegClassOrRegBank(Reg);
121 if (const RegisterBank *RB = dyn_cast<const RegisterBank *>(RCOrRB))
122 return getRegClassForTypeOnBank(MRI.getType(Reg), *RB, STI.is64Bit());
123
124 if (const auto *RC = dyn_cast<const TargetRegisterClass *>(RCOrRB)) {
125 return getAllocatableClass(RC);
126 }
127
128 return nullptr;
129}
130
133 bool Is64Bit) const {
134 if (RB.getID() == RISCV::GPRBRegBankID) {
135 if (Ty.getSizeInBits() <= 32 || (Is64Bit && Ty.getSizeInBits() == 64))
136 return &RISCV::GPRRegClass;
137 }
138
139 if (RB.getID() == RISCV::FPRBRegBankID) {
140 if (Ty.getSizeInBits() == 16)
141 return &RISCV::FPR16RegClass;
142 if (Ty.getSizeInBits() == 32)
143 return &RISCV::FPR32RegClass;
144 if (Ty.getSizeInBits() == 64)
145 return &RISCV::FPR64RegClass;
146 }
147
148 if (RB.getID() == RISCV::VRBRegBankID) {
149 if (Ty.getSizeInBits().getKnownMinValue() <= 64)
150 return &RISCV::VRRegClass;
151
152 if (Ty.getSizeInBits().getKnownMinValue() == 128)
153 return &RISCV::VRM2RegClass;
154
155 if (Ty.getSizeInBits().getKnownMinValue() == 256)
156 return &RISCV::VRM4RegClass;
157
158 if (Ty.getSizeInBits().getKnownMinValue() == 512)
159 return &RISCV::VRM8RegClass;
160 }
161
162 return nullptr;
163}
164
166 const RISCVFrameLowering *TFI = getFrameLowering(MF);
167 BitVector Reserved(getNumRegs());
169
170 // Mark any GPRs requested to be reserved as such.
171 const std::bitset<32> &UserReservedXRegs = Subtarget.getUserReservedXRegs();
172 for (unsigned I = 1; I != 32; ++I) {
173 if (!UserReservedXRegs[I])
174 continue;
175 markSuperRegs(Reserved, RISCV::X0 + I);
176 }
177
178 // Use markSuperRegs to ensure any register aliases are also reserved
179 markSuperRegs(Reserved, RISCV::X0_H); // x0
180 markSuperRegs(Reserved, RISCV::X2_H); // sp
181 markSuperRegs(Reserved, RISCV::X3_H); // gp
182 markSuperRegs(Reserved, RISCV::X4_H); // tp
183 if (TFI->hasFP(MF))
184 markSuperRegs(Reserved, RISCV::X8_H); // fp
185 // Reserve the base register if we need to realign the stack and allocate
186 // variable-sized objects at runtime.
187 if (TFI->hasBP(MF))
188 markSuperRegs(Reserved, RISCVABI::getBPReg()); // bp
189
190 // There are only 16 GPRs for RVE.
191 if (Subtarget.hasStdExtE())
192 for (MCPhysReg Reg = RISCV::X16_H; Reg <= RISCV::X31_H; Reg++)
193 markSuperRegs(Reserved, Reg);
194
195 // V registers for code generation. We handle them manually.
196 markSuperRegs(Reserved, RISCV::VL);
197 markSuperRegs(Reserved, RISCV::VTYPE);
198 markSuperRegs(Reserved, RISCV::VXSAT);
199 markSuperRegs(Reserved, RISCV::VXRM);
200 markSuperRegs(Reserved, RISCV::VLENB);
201
202 // Floating point environment registers.
203 markSuperRegs(Reserved, RISCV::FRM);
204 markSuperRegs(Reserved, RISCV::FFLAGS);
205
206 // SiFive VCIX state registers.
207 markSuperRegs(Reserved, RISCV::SF_VCIX_STATE);
208
210 if (Subtarget.hasStdExtE())
211 reportFatalUsageError("Graal reserved registers do not exist in RVE");
212 markSuperRegs(Reserved, RISCV::X23_H);
213 markSuperRegs(Reserved, RISCV::X27_H);
214 }
215
216 // Shadow stack pointer.
217 markSuperRegs(Reserved, RISCV::SSP);
218
219 // XSfmmbase
220 for (MCPhysReg Reg = RISCV::T0; Reg <= RISCV::T15; Reg++)
221 markSuperRegs(Reserved, Reg);
222
223 assert(checkAllSuperRegsMarked(Reserved));
224 return Reserved;
225}
226
228 MCRegister PhysReg) const {
229 return !MF.getSubtarget().isRegisterReservedByUser(PhysReg);
230}
231
233 return CSR_NoRegs_RegMask;
234}
235
238 const DebugLoc &DL, Register DestReg,
241 MaybeAlign RequiredAlign) const {
242
243 if (DestReg == SrcReg && !Offset.getFixed() && !Offset.getScalable())
244 return;
245
246 MachineFunction &MF = *MBB.getParent();
249 const RISCVInstrInfo *TII = ST.getInstrInfo();
250
251 // Optimize compile time offset case
252 if (Offset.getScalable()) {
253 if (auto VLEN = ST.getRealVLen()) {
254 // 1. Multiply the number of v-slots by the (constant) length of register
255 const int64_t VLENB = *VLEN / 8;
256 assert(Offset.getScalable() % RISCV::RVVBytesPerBlock == 0 &&
257 "Reserve the stack by the multiple of one vector size.");
258 const int64_t NumOfVReg = Offset.getScalable() / 8;
259 const int64_t FixedOffset = NumOfVReg * VLENB;
260 if (!isInt<32>(FixedOffset)) {
261 // This check might also need to be updated to 64bit.
262 // However mulImm() still assumes 32bit. For now only support fixed
263 // 64bit frame offsets, since scalable offsets would require the number
264 // of spilled registers to exceed 2^31, which is unlikely.
265 reportFatalUsageError("Scalable frame size outside of the signed "
266 "32-bit range not supported");
267 }
268 Offset = StackOffset::getFixed(FixedOffset + Offset.getFixed());
269 }
270 }
271
272 bool KillSrcReg = false;
273
274 if (Offset.getScalable()) {
275 unsigned ScalableAdjOpc = RISCV::ADD;
276 int64_t ScalableValue = Offset.getScalable();
277 if (ScalableValue < 0) {
278 ScalableValue = -ScalableValue;
279 ScalableAdjOpc = RISCV::SUB;
280 }
281 // Get vlenb and multiply vlen with the number of vector registers.
282 Register ScratchReg = DestReg;
283 if (DestReg == SrcReg)
284 ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
285
286 assert(ScalableValue > 0 && "There is no need to get VLEN scaled value.");
287 assert(ScalableValue % RISCV::RVVBytesPerBlock == 0 &&
288 "Reserve the stack by the multiple of one vector size.");
289 assert(isInt<32>(ScalableValue / RISCV::RVVBytesPerBlock) &&
290 "Expect the number of vector registers within 32-bits.");
291 uint32_t NumOfVReg = ScalableValue / RISCV::RVVBytesPerBlock;
292 // Only use vsetvli rather than vlenb if adjusting in the prologue or
293 // epilogue, otherwise it may disturb the VTYPE and VL status.
294 bool IsPrologueOrEpilogue =
296 bool UseVsetvliRatherThanVlenb =
297 IsPrologueOrEpilogue && ST.preferVsetvliOverReadVLENB();
298 if (UseVsetvliRatherThanVlenb && (NumOfVReg == 1 || NumOfVReg == 2 ||
299 NumOfVReg == 4 || NumOfVReg == 8)) {
300 BuildMI(MBB, II, DL, TII->get(RISCV::PseudoReadVLENBViaVSETVLIX0),
301 ScratchReg)
302 .addImm(NumOfVReg)
303 .setMIFlag(Flag);
304 BuildMI(MBB, II, DL, TII->get(ScalableAdjOpc), DestReg)
305 .addReg(SrcReg)
306 .addReg(ScratchReg, RegState::Kill)
307 .setMIFlag(Flag);
308 } else {
309 if (UseVsetvliRatherThanVlenb)
310 BuildMI(MBB, II, DL, TII->get(RISCV::PseudoReadVLENBViaVSETVLIX0),
311 ScratchReg)
312 .addImm(1)
313 .setMIFlag(Flag);
314 else
315 BuildMI(MBB, II, DL, TII->get(RISCV::PseudoReadVLENB), ScratchReg)
316 .setMIFlag(Flag);
317
318 if (ScalableAdjOpc == RISCV::ADD && ST.hasStdExtZba() &&
319 (NumOfVReg == 2 || NumOfVReg == 4 || NumOfVReg == 8)) {
320 unsigned Opc = NumOfVReg == 2
321 ? RISCV::SH1ADD
322 : (NumOfVReg == 4 ? RISCV::SH2ADD : RISCV::SH3ADD);
323 BuildMI(MBB, II, DL, TII->get(Opc), DestReg)
324 .addReg(ScratchReg, RegState::Kill)
325 .addReg(SrcReg)
326 .setMIFlag(Flag);
327 } else {
328 TII->mulImm(MF, MBB, II, DL, ScratchReg, NumOfVReg, Flag);
329 BuildMI(MBB, II, DL, TII->get(ScalableAdjOpc), DestReg)
330 .addReg(SrcReg)
331 .addReg(ScratchReg, RegState::Kill)
332 .setMIFlag(Flag);
333 }
334 }
335 SrcReg = DestReg;
336 KillSrcReg = true;
337 }
338
339 int64_t Val = Offset.getFixed();
340 if (DestReg == SrcReg && Val == 0)
341 return;
342
343 const uint64_t Align = RequiredAlign.valueOrOne().value();
344
345 if (isInt<12>(Val)) {
346 BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), DestReg)
347 .addReg(SrcReg, getKillRegState(KillSrcReg))
348 .addImm(Val)
349 .setMIFlag(Flag);
350 return;
351 }
352
353 // Use the QC_E_ADDI instruction from the Xqcilia extension that can take a
354 // signed 26-bit immediate.
355 if (ST.hasVendorXqcilia() && isInt<26>(Val)) {
356 // The one case where using this instruction is sub-optimal is if Val can be
357 // materialized with a single compressible LUI and following add/sub is also
358 // compressible. Avoid doing this if that is the case.
359 int Hi20 = (Val & 0xFFFFF000) >> 12;
360 bool IsCompressLUI =
361 ((Val & 0xFFF) == 0) && (Hi20 != 0) &&
362 (isUInt<5>(Hi20) || (Hi20 >= 0xfffe0 && Hi20 <= 0xfffff));
363 bool IsCompressAddSub =
364 (SrcReg == DestReg) &&
365 ((Val > 0 && RISCV::GPRNoX0RegClass.contains(SrcReg)) ||
366 (Val < 0 && RISCV::GPRCRegClass.contains(SrcReg)));
367
368 if (!(IsCompressLUI && IsCompressAddSub)) {
369 BuildMI(MBB, II, DL, TII->get(RISCV::QC_E_ADDI), DestReg)
370 .addReg(SrcReg, getKillRegState(KillSrcReg))
371 .addImm(Val)
372 .setMIFlag(Flag);
373 return;
374 }
375 }
376
377 // Try to split the offset across two ADDIs. We need to keep the intermediate
378 // result aligned after each ADDI. We need to determine the maximum value we
379 // can put in each ADDI. In the negative direction, we can use -2048 which is
380 // always sufficiently aligned. In the positive direction, we need to find the
381 // largest 12-bit immediate that is aligned. Exclude -4096 since it can be
382 // created with LUI.
383 assert(Align < 2048 && "Required alignment too large");
384 int64_t MaxPosAdjStep = 2048 - Align;
385 if (Val > -4096 && Val <= (2 * MaxPosAdjStep)) {
386 int64_t FirstAdj = Val < 0 ? -2048 : MaxPosAdjStep;
387 Val -= FirstAdj;
388 BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), DestReg)
389 .addReg(SrcReg, getKillRegState(KillSrcReg))
390 .addImm(FirstAdj)
391 .setMIFlag(Flag);
392 BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), DestReg)
393 .addReg(DestReg, RegState::Kill)
394 .addImm(Val)
395 .setMIFlag(Flag);
396 return;
397 }
398
399 // Use shNadd if doing so lets us materialize a 12 bit immediate with a single
400 // instruction. This saves 1 instruction over the full lui/addi+add fallback
401 // path. We avoid anything which can be done with a single lui as it might
402 // be compressible. Note that the sh1add case is fully covered by the 2x addi
403 // case just above and is thus omitted.
404 if (ST.hasStdExtZba() && (Val & 0xFFF) != 0) {
405 unsigned Opc = 0;
406 if (isShiftedInt<12, 3>(Val)) {
407 Opc = RISCV::SH3ADD;
408 Val = Val >> 3;
409 } else if (isShiftedInt<12, 2>(Val)) {
410 Opc = RISCV::SH2ADD;
411 Val = Val >> 2;
412 }
413 if (Opc) {
414 Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
415 TII->movImm(MBB, II, DL, ScratchReg, Val, Flag);
416 BuildMI(MBB, II, DL, TII->get(Opc), DestReg)
417 .addReg(ScratchReg, RegState::Kill)
418 .addReg(SrcReg, getKillRegState(KillSrcReg))
419 .setMIFlag(Flag);
420 return;
421 }
422 }
423
424 // Emit a PseudoAddUpperImm instead of LUI+ADD when the offset is a multiple
425 // of 4096 and the source is the frame register. The frame register is
426 // invariant after PEI, so MachineLateInstrsCleanup can CSE identical pseudos.
427 // The pseudo is later expanded back to LUI+ADD.
428 if (Flag == MachineInstr::NoFlags && !KillSrcReg && DestReg != SrcReg &&
429 SrcReg == getFrameRegister(MF) && isShiftedInt<20, 12>(Val)) {
430 BuildMI(MBB, II, DL, TII->get(RISCV::PseudoAddUpperImm), DestReg)
431 .addReg(SrcReg)
432 .addImm(static_cast<uint32_t>(Val) >> 12);
433 return;
434 }
435
436 unsigned Opc = RISCV::ADD;
437 if (Val < 0) {
438 Val = -Val;
439 Opc = RISCV::SUB;
440 }
441
442 Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
443 TII->movImm(MBB, II, DL, ScratchReg, Val, Flag);
444 BuildMI(MBB, II, DL, TII->get(Opc), DestReg)
445 .addReg(SrcReg, getKillRegState(KillSrcReg))
446 .addReg(ScratchReg, RegState::Kill)
447 .setMIFlag(Flag);
448}
449
450static std::tuple<RISCVVType::VLMUL, const TargetRegisterClass &, unsigned>
451getSpillReloadInfo(unsigned NumRemaining, uint16_t RegEncoding, bool IsSpill) {
452 if (NumRemaining >= 8 && RegEncoding % 8 == 0)
453 return {RISCVVType::LMUL_8, RISCV::VRM8RegClass,
454 IsSpill ? RISCV::VS8R_V : RISCV::VL8RE8_V};
455 if (NumRemaining >= 4 && RegEncoding % 4 == 0)
456 return {RISCVVType::LMUL_4, RISCV::VRM4RegClass,
457 IsSpill ? RISCV::VS4R_V : RISCV::VL4RE8_V};
458 if (NumRemaining >= 2 && RegEncoding % 2 == 0)
459 return {RISCVVType::LMUL_2, RISCV::VRM2RegClass,
460 IsSpill ? RISCV::VS2R_V : RISCV::VL2RE8_V};
461 return {RISCVVType::LMUL_1, RISCV::VRRegClass,
462 IsSpill ? RISCV::VS1R_V : RISCV::VL1RE8_V};
463}
464
465// Split a VSPILLx_Mx/VSPILLx_Mx pseudo into multiple whole register stores
466// separated by LMUL*VLENB bytes.
468 bool IsSpill) const {
469 DebugLoc DL = II->getDebugLoc();
470 MachineBasicBlock &MBB = *II->getParent();
471 MachineFunction &MF = *MBB.getParent();
473 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
474 const TargetInstrInfo *TII = STI.getInstrInfo();
476
477 auto ZvlssegInfo = RISCV::isRVVSpillForZvlsseg(II->getOpcode());
478 unsigned NF = ZvlssegInfo->first;
479 unsigned LMUL = ZvlssegInfo->second;
480 unsigned NumRegs = NF * LMUL;
481 assert(NumRegs <= 8 && "Invalid NF/LMUL combinations.");
482
483 Register Reg = II->getOperand(0).getReg();
484 uint16_t RegEncoding = TRI->getEncodingValue(Reg);
485 Register Base = II->getOperand(1).getReg();
486 bool IsBaseKill = II->getOperand(1).isKill();
487 Register NewBase = MRI.createVirtualRegister(&RISCV::GPRRegClass);
488
489 auto *OldMMO = *(II->memoperands_begin());
490 LocationSize OldLoc = OldMMO->getSize();
491 assert(OldLoc.isPrecise() && OldLoc.getValue().isKnownMultipleOf(NF));
492 TypeSize VRegSize = OldLoc.getValue().divideCoefficientBy(NumRegs);
493
494 Register VLENB = 0;
495 unsigned VLENBShift = 0;
496 unsigned PrevHandledNum = 0;
497 unsigned I = 0;
498 while (I != NumRegs) {
499 auto [LMulHandled, RegClass, Opcode] =
500 getSpillReloadInfo(NumRegs - I, RegEncoding, IsSpill);
501 auto [RegNumHandled, _] = RISCVVType::decodeVLMUL(LMulHandled);
502 bool IsLast = I + RegNumHandled == NumRegs;
503 if (PrevHandledNum) {
504 Register Step;
505 // Optimize for constant VLEN.
506 if (auto VLEN = STI.getRealVLen()) {
507 int64_t Offset = *VLEN / 8 * PrevHandledNum;
508 Step = MRI.createVirtualRegister(&RISCV::GPRRegClass);
509 STI.getInstrInfo()->movImm(MBB, II, DL, Step, Offset);
510 } else {
511 if (!VLENB) {
512 VLENB = MRI.createVirtualRegister(&RISCV::GPRRegClass);
513 BuildMI(MBB, II, DL, TII->get(RISCV::PseudoReadVLENB), VLENB);
514 }
515 uint32_t ShiftAmount = Log2_32(PrevHandledNum);
516 // To avoid using an extra register, we shift the VLENB register and
517 // remember how much it has been shifted. We can then use relative
518 // shifts to adjust to the desired shift amount.
519 if (VLENBShift > ShiftAmount) {
520 BuildMI(MBB, II, DL, TII->get(RISCV::SRLI), VLENB)
521 .addReg(VLENB, RegState::Kill)
522 .addImm(VLENBShift - ShiftAmount);
523 } else if (VLENBShift < ShiftAmount) {
524 BuildMI(MBB, II, DL, TII->get(RISCV::SLLI), VLENB)
525 .addReg(VLENB, RegState::Kill)
526 .addImm(ShiftAmount - VLENBShift);
527 }
528 VLENBShift = ShiftAmount;
529 Step = VLENB;
530 }
531
532 BuildMI(MBB, II, DL, TII->get(RISCV::ADD), NewBase)
533 .addReg(Base, getKillRegState(I != 0 || IsBaseKill))
534 .addReg(Step, getKillRegState(Step != VLENB || IsLast));
535 Base = NewBase;
536 }
537
538 MCRegister ActualReg = findVRegWithEncoding(RegClass, RegEncoding);
540 BuildMI(MBB, II, DL, TII->get(Opcode))
541 .addReg(ActualReg, getDefRegState(!IsSpill))
542 .addReg(Base, getKillRegState(IsLast))
543 .addMemOperand(MF.getMachineMemOperand(OldMMO, OldMMO->getOffset(),
544 VRegSize * RegNumHandled));
545
546 // Adding implicit-use of super register to describe we are using part of
547 // super register, that prevents machine verifier complaining when part of
548 // subreg is undef, see comment in MachineVerifier::checkLiveness for more
549 // detail.
550 if (IsSpill)
551 MIB.addReg(Reg, RegState::Implicit);
552
553 PrevHandledNum = RegNumHandled;
554 RegEncoding += RegNumHandled;
555 I += RegNumHandled;
556 }
557 II->eraseFromParent();
558}
559
560static unsigned getXqciloWideOpcode(unsigned Opc) {
561 switch (Opc) {
562 case RISCV::LW:
563 return RISCV::QC_E_LW;
564 case RISCV::SW:
565 return RISCV::QC_E_SW;
566 case RISCV::LB:
567 return RISCV::QC_E_LB;
568 case RISCV::LBU:
569 return RISCV::QC_E_LBU;
570 case RISCV::LH:
571 return RISCV::QC_E_LH;
572 case RISCV::LHU:
573 return RISCV::QC_E_LHU;
574 case RISCV::SB:
575 return RISCV::QC_E_SB;
576 case RISCV::SH:
577 return RISCV::QC_E_SH;
578 default:
579 return 0;
580 }
581}
582
584 int SPAdj, unsigned FIOperandNum,
585 RegScavenger *RS) const {
586 assert(SPAdj == 0 && "Unexpected non-zero SPAdj value");
587
588 MachineInstr &MI = *II;
589 MachineFunction &MF = *MI.getParent()->getParent();
592 const RISCVInstrInfo *TII = ST.getInstrInfo();
593 bool Is64Bit = ST.is64Bit();
594 DebugLoc DL = MI.getDebugLoc();
595
596 int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
597 Register FrameReg;
599 getFrameLowering(MF)->getFrameIndexReference(MF, FrameIndex, FrameReg);
600 bool IsRVVSpill = RISCV::isRVVSpill(MI);
601 if (!IsRVVSpill)
602 Offset += StackOffset::getFixed(MI.getOperand(FIOperandNum + 1).getImm());
603
604 if (!Is64Bit && !isInt<32>(Offset.getFixed())) {
605 reportFatalUsageError("Frame offsets outside of the signed 32-bit range "
606 "not supported on RV32");
607 }
608
609 if (!IsRVVSpill) {
610 int64_t Val = Offset.getFixed();
611 int64_t Lo12 = SignExtend64<12>(Val);
612 int64_t Lo26 = SignExtend64<26>(Val);
613 unsigned Opc = MI.getOpcode();
614
615 if (Opc == RISCV::ADDI && !isInt<12>(Val)) {
616 // We chose to emit the canonical immediate sequence rather than folding
617 // the offset into the using add under the theory that doing so doesn't
618 // save dynamic instruction count and some target may fuse the canonical
619 // 32 bit immediate sequence. We still need to clear the portion of the
620 // offset encoded in the immediate.
621 MI.getOperand(FIOperandNum + 1).ChangeToImmediate(0);
622 } else if ((Opc == RISCV::PREFETCH_I || Opc == RISCV::PREFETCH_R ||
623 Opc == RISCV::PREFETCH_W) &&
624 (Lo12 & 0b11111) != 0) {
625 // Prefetch instructions require the offset to be 32 byte aligned.
626 MI.getOperand(FIOperandNum + 1).ChangeToImmediate(0);
627 } else if (Opc == RISCV::MIPS_PREF && !isUInt<9>(Val)) {
628 // MIPS Prefetch instructions require the offset to be 9 bits encoded.
629 MI.getOperand(FIOperandNum + 1).ChangeToImmediate(0);
630 } else if ((Opc == RISCV::PseudoRV32ZdinxLD ||
631 Opc == RISCV::PseudoRV32ZdinxSD ||
632 Opc == RISCV::PseudoLD_RV32_OPT ||
633 Opc == RISCV::PseudoSD_RV32_OPT) &&
634 Lo12 >= 2044) {
635 // This instruction will/might be split into 2 instructions. The second
636 // instruction will add 4 to the immediate. If that would overflow 12
637 // bits, we can't fold the offset.
638 MI.getOperand(FIOperandNum + 1).ChangeToImmediate(0);
639 } else if (unsigned WideOpc = getXqciloWideOpcode(Opc);
640 !isInt<12>(Val) && ST.hasVendorXqcilo() && WideOpc) {
641 // The resolved frame offset exceeds simm12 but the instruction is a
642 // standard load/store (LW/SW/etc). Promote to the wide Xqcilo equivalent
643 // so the full 26-bit offset folds directly, avoiding a separate
644 // base-adjust instruction. This runs post-RA and does not affect
645 // register allocation decisions.
646 MI.setDesc(TII->get(WideOpc));
647 MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Lo26);
648 Offset = StackOffset::get((uint64_t)Val - (uint64_t)Lo26,
649 Offset.getScalable());
650 } else if (Opc == RISCV::QC_E_ADDI || RISCVInstrInfo::isBaseQCLoad(MI) ||
651 RISCVInstrInfo::isBaseQCStore(MI)) {
652 MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Lo26);
653 Offset = StackOffset::get((uint64_t)Val - (uint64_t)Lo26,
654 Offset.getScalable());
655 } else {
656 // We can encode an add with 12 bit signed immediate in the immediate
657 // operand of our user instruction. As a result, the remaining
658 // offset can by construction, at worst, a LUI and a ADD.
659 MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Lo12);
660 Offset = StackOffset::get((uint64_t)Val - (uint64_t)Lo12,
661 Offset.getScalable());
662 }
663 }
664
665 if (Offset.getScalable() || Offset.getFixed()) {
666 Register DestReg;
667 if (MI.getOpcode() == RISCV::ADDI)
668 DestReg = MI.getOperand(0).getReg();
669 else
670 DestReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
671 adjustReg(*II->getParent(), II, DL, DestReg, FrameReg, Offset,
672 MachineInstr::NoFlags, std::nullopt);
673 MI.getOperand(FIOperandNum).ChangeToRegister(DestReg, /*IsDef*/false,
674 /*IsImp*/false,
675 /*IsKill*/true);
676 } else {
677 MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, /*IsDef*/false,
678 /*IsImp*/false,
679 /*IsKill*/false);
680 }
681
682 // If after materializing the adjustment, we have a pointless ADDI, remove it
683 if (MI.getOpcode() == RISCV::ADDI &&
684 MI.getOperand(0).getReg() == MI.getOperand(1).getReg() &&
685 MI.getOperand(2).getImm() == 0) {
686 MI.eraseFromParent();
687 return true;
688 }
689
690 // Handle spill/fill of synthetic register classes for segment operations to
691 // ensure correctness in the edge case one gets spilled.
692 switch (MI.getOpcode()) {
693 case RISCV::PseudoVSPILL2_M1:
694 case RISCV::PseudoVSPILL2_M2:
695 case RISCV::PseudoVSPILL2_M4:
696 case RISCV::PseudoVSPILL3_M1:
697 case RISCV::PseudoVSPILL3_M2:
698 case RISCV::PseudoVSPILL4_M1:
699 case RISCV::PseudoVSPILL4_M2:
700 case RISCV::PseudoVSPILL5_M1:
701 case RISCV::PseudoVSPILL6_M1:
702 case RISCV::PseudoVSPILL7_M1:
703 case RISCV::PseudoVSPILL8_M1:
704 lowerSegmentSpillReload(II, /*IsSpill=*/true);
705 return true;
706 case RISCV::PseudoVRELOAD2_M1:
707 case RISCV::PseudoVRELOAD2_M2:
708 case RISCV::PseudoVRELOAD2_M4:
709 case RISCV::PseudoVRELOAD3_M1:
710 case RISCV::PseudoVRELOAD3_M2:
711 case RISCV::PseudoVRELOAD4_M1:
712 case RISCV::PseudoVRELOAD4_M2:
713 case RISCV::PseudoVRELOAD5_M1:
714 case RISCV::PseudoVRELOAD6_M1:
715 case RISCV::PseudoVRELOAD7_M1:
716 case RISCV::PseudoVRELOAD8_M1:
717 lowerSegmentSpillReload(II, /*IsSpill=*/false);
718 return true;
719 }
720
721 return false;
722}
723
725 const MachineFunction &MF) const {
726 return true;
727}
728
729// Returns true if the instruction's frame index reference would be better
730// served by a base register other than FP or SP.
731// Used by LocalStackSlotAllocation pass to determine which frame index
732// references it should create new base registers for.
734 int64_t Offset) const {
735 unsigned FIOperandNum = 0;
736 for (; !MI->getOperand(FIOperandNum).isFI(); FIOperandNum++)
737 assert(FIOperandNum < MI->getNumOperands() &&
738 "Instr doesn't have FrameIndex operand");
739
740 // For RISC-V, The machine instructions that include a FrameIndex operand
741 // are load/store, ADDI instructions.
742 unsigned MIFrm = RISCVII::getFormat(MI->getDesc().TSFlags);
743 if (MIFrm != RISCVII::InstFormatI && MIFrm != RISCVII::InstFormatS)
744 return false;
745 // We only generate virtual base registers for loads and stores, so
746 // return false for everything else.
747 if (!MI->mayLoad() && !MI->mayStore())
748 return false;
749
750 const MachineFunction &MF = *MI->getMF();
751 const MachineFrameInfo &MFI = MF.getFrameInfo();
752 const RISCVFrameLowering *TFI = getFrameLowering(MF);
753 const MachineRegisterInfo &MRI = MF.getRegInfo();
754
755 if (TFI->hasFP(MF) && !shouldRealignStack(MF)) {
757 // Estimate the stack size used to store callee saved registers(
758 // excludes reserved registers).
759 unsigned CalleeSavedSize = 0;
760 for (const MCPhysReg *R = MRI.getCalleeSavedRegs(); MCPhysReg Reg = *R;
761 ++R) {
762 if (Subtarget.isRegisterReservedByUser(Reg))
763 continue;
764
765 if (RISCV::GPRRegClass.contains(Reg))
766 CalleeSavedSize += getSpillSize(RISCV::GPRRegClass);
767 else if (RISCV::FPR64RegClass.contains(Reg))
768 CalleeSavedSize += getSpillSize(RISCV::FPR64RegClass);
769 else if (RISCV::FPR32RegClass.contains(Reg))
770 CalleeSavedSize += getSpillSize(RISCV::FPR32RegClass);
771 // Ignore vector registers.
772 }
773
774 int64_t MaxFPOffset = Offset - CalleeSavedSize;
775 if (isFrameOffsetLegal(MI, RISCV::X8, MaxFPOffset))
776 return false;
777
778 // If the FP-relative offset doesn't fit, fall through to check the
779 // SP-relative offset. getFrameIndexReference may select SP over FP when
780 // the SP offset fits in the compressed instruction immediate range, so a
781 // base register might not be needed.
782 }
783
784 // Assume 128 bytes spill slots size to estimate the maximum possible
785 // offset relative to the stack pointer.
786 // FIXME: The 128 is copied from ARM. We should run some statistics and pick a
787 // real one for RISC-V.
788 int64_t MaxSPOffset = Offset + 128;
789 MaxSPOffset += MFI.getLocalFrameSize();
790 return !isFrameOffsetLegal(MI, RISCV::X2, MaxSPOffset);
791}
792
793// Determine whether a given base register plus offset immediate is
794// encodable to resolve a frame index.
796 Register BaseReg,
797 int64_t Offset) const {
798 unsigned FIOperandNum = 0;
799 while (!MI->getOperand(FIOperandNum).isFI()) {
800 FIOperandNum++;
801 assert(FIOperandNum < MI->getNumOperands() &&
802 "Instr does not have a FrameIndex operand!");
803 }
804
805 Offset += getFrameIndexInstrOffset(MI, FIOperandNum);
806 return isInt<12>(Offset);
807}
808
809// Insert defining instruction(s) for a pointer to FrameIdx before
810// insertion point I.
811// Return materialized frame pointer.
813 int FrameIdx,
814 int64_t Offset) const {
816 DebugLoc DL;
817 if (MBBI != MBB->end())
818 DL = MBBI->getDebugLoc();
819 MachineFunction *MF = MBB->getParent();
820 MachineRegisterInfo &MFI = MF->getRegInfo();
822
823 Register BaseReg = MFI.createVirtualRegister(&RISCV::GPRRegClass);
824 BuildMI(*MBB, MBBI, DL, TII->get(RISCV::ADDI), BaseReg)
825 .addFrameIndex(FrameIdx)
826 .addImm(Offset);
827 return BaseReg;
828}
829
830// Resolve a frame index operand of an instruction to reference the
831// indicated base register plus offset instead.
833 int64_t Offset) const {
834 unsigned FIOperandNum = 0;
835 while (!MI.getOperand(FIOperandNum).isFI()) {
836 FIOperandNum++;
837 assert(FIOperandNum < MI.getNumOperands() &&
838 "Instr does not have a FrameIndex operand!");
839 }
840
841 Offset += getFrameIndexInstrOffset(&MI, FIOperandNum);
842 // FrameIndex Operands are always represented as a
843 // register followed by an immediate.
844 MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
845 MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset);
846}
847
848// Get the offset from the referenced frame index in the instruction,
849// if there is one.
851 int Idx) const {
852 assert((RISCVII::getFormat(MI->getDesc().TSFlags) == RISCVII::InstFormatI ||
853 RISCVII::getFormat(MI->getDesc().TSFlags) == RISCVII::InstFormatS) &&
854 "The MI must be I or S format.");
855 assert(MI->getOperand(Idx).isFI() && "The Idx'th operand of MI is not a "
856 "FrameIndex operand");
857 return MI->getOperand(Idx + 1).getImm();
858}
859
861 const TargetFrameLowering *TFI = getFrameLowering(MF);
862 return TFI->hasFP(MF) ? RISCV::X8 : RISCV::X2;
863}
864
866 MCRegister Reg) const {
867 auto const &STI = MF.getSubtarget<RISCVSubtarget>();
868 const RISCVRegisterInfo *TRI = STI.getRegisterInfo();
869
870 if (TRI->isGeneralPurposeRegister(MF, Reg))
871 return llvm::is_contained(RISCV::getArgGPRs(STI), Reg);
872
873 if (TRI->isFPRegister(Reg))
874 return llvm::is_contained(RISCV::getArgFPRs(STI), Reg);
875
876 if (RISCV::VRRegClass.contains(Reg))
877 return llvm::is_contained(RISCV::getArgVRs(STI), Reg);
878
879 return false;
880}
881
883 if (Reg == RISCV::SF_VCIX_STATE)
884 return "sf.vcix_state";
886}
887
888const uint32_t *
890 CallingConv::ID CC) const {
892
893 if (CC == CallingConv::GHC)
894 return CSR_NoRegs_RegMask;
895 RISCVABI::ABI ABI = Subtarget.getTargetABI();
897 "Unrecognized ABI");
899 if (RISCVABI::isRVE(ABI))
900 return CSR_RT_MostRegs_RVE_RegMask;
901 return CSR_RT_MostRegs_RegMask;
902 }
903 if (RISCVABI::isRVE(ABI))
904 return CSR_ILP32E_LP64E_RegMask;
905 bool IsVectorCall = CC == CallingConv::RISCV_VectorCall;
906 if (RISCVABI::isSoftFP(ABI))
907 return IsVectorCall ? CSR_ILP32_LP64_V_RegMask : CSR_ILP32_LP64_RegMask;
908 if (RISCVABI::isSingleFP(ABI))
909 return IsVectorCall ? CSR_ILP32F_LP64F_V_RegMask : CSR_ILP32F_LP64F_RegMask;
910 assert(RISCVABI::isDoubleFP(ABI) && "Unrecognized ABI");
911 return IsVectorCall ? CSR_ILP32D_LP64D_V_RegMask : CSR_ILP32D_LP64D_RegMask;
912}
913
916 const MachineFunction &) const {
917 if (RC == &RISCV::VMV0RegClass)
918 return &RISCV::VRRegClass;
919 if (RC == &RISCV::VRNoV0RegClass)
920 return &RISCV::VRRegClass;
921 if (RC == &RISCV::VRM2NoV0RegClass)
922 return &RISCV::VRM2RegClass;
923 if (RC == &RISCV::VRM4NoV0RegClass)
924 return &RISCV::VRM4RegClass;
925 if (RC == &RISCV::VRM8NoV0RegClass)
926 return &RISCV::VRM8RegClass;
927 return RC;
928}
929
932 // VLENB is the length of a vector register in bytes. We use <vscale x 8 x i8>
933 // to represent one vector register. The dwarf offset is
934 // VLENB * scalable_offset / 8.
935 assert(Offset.getScalable() % 8 == 0 && "Invalid frame offset");
936
937 // Add fixed-sized offset using existing DIExpression interface.
939
940 unsigned VLENB = getDwarfRegNum(RISCV::VLENB, true);
941 int64_t VLENBSized = Offset.getScalable() / 8;
942 if (VLENBSized > 0) {
943 Ops.push_back(dwarf::DW_OP_constu);
944 Ops.push_back(VLENBSized);
945 Ops.append({dwarf::DW_OP_bregx, VLENB, 0ULL});
946 Ops.push_back(dwarf::DW_OP_mul);
947 Ops.push_back(dwarf::DW_OP_plus);
948 } else if (VLENBSized < 0) {
949 Ops.push_back(dwarf::DW_OP_constu);
950 Ops.push_back(-VLENBSized);
951 Ops.append({dwarf::DW_OP_bregx, VLENB, 0ULL});
952 Ops.push_back(dwarf::DW_OP_mul);
953 Ops.push_back(dwarf::DW_OP_minus);
954 }
955}
956
957std::pair<Register, Register>
959 if (Pair == RISCV::X0_Pair)
960 return {RISCV::X0, RISCV::X0};
961 return {getSubReg(Pair, RISCV::sub_gpr_even),
962 getSubReg(Pair, RISCV::sub_gpr_odd)};
963}
964
965unsigned
967 // Set CostPerUse to 1 only when optimizing for size and RVC exists.
968 const auto &ST = MF.getSubtarget<RISCVSubtarget>();
969 return MF.getFunction().hasOptSize() && ST.hasStdExtZca() &&
970 ST.getCLOpts().cost_per_use
971 ? 1
972 : 0;
973}
974
976 const TargetRegisterClass *RC) const {
977 return getRegClassWeight(RC).RegWeight;
978}
979
980// Add two address hints to improve chances of being able to use a compressed
981// instruction.
983 Register VirtReg, ArrayRef<MCPhysReg> Order,
985 const VirtRegMap *VRM, const LiveRegMatrix *Matrix) const {
986 const MachineRegisterInfo *MRI = &MF.getRegInfo();
988
989 // Handle RegPairEven/RegPairOdd hints for Zilsd register pairs
990 std::pair<unsigned, Register> Hint = MRI->getRegAllocationHint(VirtReg);
991 unsigned HintType = Hint.first;
992 Register Partner = Hint.second;
993
994 MCRegister TargetReg;
995 if (HintType == RISCVRI::RegPairEven || HintType == RISCVRI::RegPairOdd) {
996 // Check if we want the even or odd register of a consecutive pair
997 bool WantOdd = (HintType == RISCVRI::RegPairOdd);
998
999 // First priority: Check if partner is already allocated
1000 if (Partner.isVirtual() && VRM && VRM->hasPhys(Partner)) {
1001 MCRegister PartnerPhys = VRM->getPhys(Partner);
1002 // Calculate the exact register we need for consecutive pairing
1003 TargetReg = PartnerPhys.id() + (WantOdd ? 1 : -1);
1004
1005 // Verify it's valid and available
1006 if (RISCV::GPRRegClass.contains(TargetReg) &&
1007 is_contained(Order, TargetReg))
1008 Hints.insert(TargetReg.id());
1009 }
1010
1011 // Second priority: Try to find consecutive register pairs in the allocation
1012 // order
1013 for (MCPhysReg PhysReg : Order) {
1014 // Don't add the hint if we already added above.
1015 if (TargetReg == PhysReg)
1016 continue;
1017
1018 unsigned RegNum = getEncodingValue(PhysReg);
1019 // Check if this register matches the even/odd requirement
1020 bool IsOdd = (RegNum % 2 != 0);
1021
1022 // Don't provide hints that are paired to a reserved register.
1023 MCRegister Paired = PhysReg + (IsOdd ? -1 : 1);
1024 if (WantOdd == IsOdd && !MRI->isReserved(Paired))
1025 Hints.insert(PhysReg);
1026 }
1027 }
1028
1029 bool BaseImplRetVal = TargetRegisterInfo::getRegAllocationHints(
1030 VirtReg, Order, Hints, MF, VRM, Matrix);
1031
1032 if (!VRM || !MF.getSubtarget<RISCVSubtarget>().getCLOpts().regalloc_hints)
1033 return BaseImplRetVal;
1034
1035 // Add any two address hints after any copy hints.
1036 SmallSet<Register, 4> TwoAddrHints;
1037
1038 auto tryAddHint = [&](const MachineOperand &VRRegMO, const MachineOperand &MO,
1039 bool NeedGPRC) -> void {
1040 Register Reg = MO.getReg();
1041 Register PhysReg = Reg.isPhysical() ? Reg : Register(VRM->getPhys(Reg));
1042 // TODO: Support GPRPair subregisters? Need to be careful with even/odd
1043 // registers. If the virtual register is an odd register of a pair and the
1044 // physical register is even (or vice versa), we should not add the hint.
1045 if (PhysReg && (!NeedGPRC || RISCV::GPRCRegClass.contains(PhysReg)) &&
1046 !MO.getSubReg() && !VRRegMO.getSubReg()) {
1047 if (!MRI->isReserved(PhysReg) && !Hints.contains(PhysReg))
1048 TwoAddrHints.insert(PhysReg);
1049 }
1050 };
1051
1052 // This is all of the compressible binary instructions. If an instruction
1053 // needs GPRC register class operands \p NeedGPRC will be set to true.
1054 auto isCompressible = [&Subtarget](const MachineInstr &MI, bool &NeedGPRC) {
1055 NeedGPRC = false;
1056 switch (MI.getOpcode()) {
1057 default:
1058 return false;
1059 case RISCV::AND:
1060 case RISCV::OR:
1061 case RISCV::XOR:
1062 case RISCV::SUB:
1063 case RISCV::ADDW:
1064 case RISCV::SUBW:
1065 NeedGPRC = true;
1066 return true;
1067 case RISCV::ANDI: {
1068 NeedGPRC = true;
1069 if (!MI.getOperand(2).isImm())
1070 return false;
1071 int64_t Imm = MI.getOperand(2).getImm();
1072 if (isInt<6>(Imm))
1073 return true;
1074 // c.zext.b
1075 return Subtarget.hasStdExtZcb() && Imm == 255;
1076 }
1077 case RISCV::SRAI:
1078 case RISCV::SRLI:
1079 NeedGPRC = true;
1080 return true;
1081 case RISCV::ADD:
1082 case RISCV::SLLI:
1083 return true;
1084 case RISCV::ADDI:
1085 case RISCV::ADDIW:
1086 return MI.getOperand(2).isImm() && isInt<6>(MI.getOperand(2).getImm());
1087 case RISCV::MUL:
1088 // c.mul
1089 NeedGPRC = true;
1090 return Subtarget.hasStdExtZcb();
1091 case RISCV::SEXT_B:
1092 case RISCV::SEXT_H:
1093 case RISCV::ZEXT_H_RV32:
1094 case RISCV::ZEXT_H_RV64:
1095 // c.sext.b, c.sext.h, c.zext.h
1096 NeedGPRC = true;
1097 return Subtarget.hasStdExtZcb() && Subtarget.hasStdExtZbb();
1098 case RISCV::ADD_UW:
1099 // c.zext.w
1100 NeedGPRC = true;
1101 return Subtarget.hasStdExtZcb() && MI.getOperand(2).isReg() &&
1102 MI.getOperand(2).getReg() == RISCV::X0;
1103 case RISCV::XORI:
1104 // c.not
1105 NeedGPRC = true;
1106 return Subtarget.hasStdExtZcb() && MI.getOperand(2).isImm() &&
1107 MI.getOperand(2).getImm() == -1;
1108 case RISCV::QC_EXTU:
1109 return MI.getOperand(2).getImm() >= 6 && MI.getOperand(3).getImm() == 0;
1110 case RISCV::BSETI:
1111 case RISCV::BEXTI:
1112 // qc.c.bseti, qc.c.bexti
1113 NeedGPRC = true;
1114 return Subtarget.hasVendorXqcibm() && MI.getOperand(2).getImm() != 0;
1115 }
1116 };
1117
1118 // Returns true if this operand is compressible. For non-registers it always
1119 // returns true. Immediate range was already checked in isCompressible.
1120 // For registers, it checks if the register is a GPRC register. reg-reg
1121 // instructions that require GPRC need all register operands to be GPRC.
1122 auto isCompressibleOpnd = [&](const MachineOperand &MO) {
1123 if (!MO.isReg())
1124 return true;
1125 Register Reg = MO.getReg();
1126 Register PhysReg = Reg.isPhysical() ? Reg : Register(VRM->getPhys(Reg));
1127 return PhysReg && RISCV::GPRCRegClass.contains(PhysReg);
1128 };
1129
1130 for (auto &MO : MRI->reg_nodbg_operands(VirtReg)) {
1131 const MachineInstr &MI = *MO.getParent();
1132 unsigned OpIdx = MO.getOperandNo();
1133 bool NeedGPRC;
1134 if (isCompressible(MI, NeedGPRC)) {
1135 if (OpIdx == 0 && MI.getOperand(1).isReg()) {
1136 if (!NeedGPRC || MI.getNumExplicitOperands() < 3 ||
1137 MI.getOpcode() == RISCV::ADD_UW ||
1138 isCompressibleOpnd(MI.getOperand(2)))
1139 tryAddHint(MO, MI.getOperand(1), NeedGPRC);
1140 if (MI.isCommutable() && MI.getOperand(2).isReg() &&
1141 (!NeedGPRC || isCompressibleOpnd(MI.getOperand(1))))
1142 tryAddHint(MO, MI.getOperand(2), NeedGPRC);
1143 } else if (OpIdx == 1 && (!NeedGPRC || MI.getNumExplicitOperands() < 3 ||
1144 isCompressibleOpnd(MI.getOperand(2)))) {
1145 tryAddHint(MO, MI.getOperand(0), NeedGPRC);
1146 } else if (MI.isCommutable() && OpIdx == 2 &&
1147 (!NeedGPRC || isCompressibleOpnd(MI.getOperand(1)))) {
1148 tryAddHint(MO, MI.getOperand(0), NeedGPRC);
1149 }
1150 }
1151
1152 // Add a hint if it would allow auipc/lui+addi(w) fusion. We do this even
1153 // without the fusions explicitly enabled as the impact is rarely negative
1154 // and some cores do implement this fusion.
1155 if ((MI.getOpcode() == RISCV::ADDIW || MI.getOpcode() == RISCV::ADDI) &&
1156 MI.getOperand(1).isReg()) {
1157 const MachineBasicBlock &MBB = *MI.getParent();
1158 MachineBasicBlock::const_iterator I = MI.getIterator();
1159 // Is the previous instruction a LUI or AUIPC that can be fused?
1160 if (I != MBB.begin()) {
1161 I = skipDebugInstructionsBackward(std::prev(I), MBB.begin());
1162 if ((I->getOpcode() == RISCV::LUI || I->getOpcode() == RISCV::AUIPC) &&
1163 I->getOperand(0).getReg() == MI.getOperand(1).getReg()) {
1164 if (OpIdx == 0)
1165 tryAddHint(MO, MI.getOperand(1), /*NeedGPRC=*/false);
1166 else
1167 tryAddHint(MO, MI.getOperand(0), /*NeedGPRC=*/false);
1168 }
1169 }
1170 }
1171 }
1172
1173 for (MCPhysReg OrderReg : Order)
1174 if (TwoAddrHints.count(OrderReg))
1175 Hints.insert(OrderReg);
1176
1177 return BaseImplRetVal;
1178}
1179
1181 MachineFunction &MF) const {
1183 std::pair<unsigned, Register> Hint = MRI->getRegAllocationHint(Reg);
1184
1185 // Handle RegPairEven/RegPairOdd hints for Zilsd register pairs
1186 if ((Hint.first == RISCVRI::RegPairOdd ||
1187 Hint.first == RISCVRI::RegPairEven) &&
1188 Hint.second.isVirtual()) {
1189 // If 'Reg' is one of the even/odd register pair and it's now changed
1190 // (e.g. coalesced) into a different register, the other register of the
1191 // pair allocation hint must be updated to reflect the relationship change.
1192 Register Partner = Hint.second;
1193 std::pair<unsigned, Register> PartnerHint =
1194 MRI->getRegAllocationHint(Partner);
1195
1196 // Make sure partner still points to us
1197 if (PartnerHint.second == Reg) {
1198 // Update partner to point to NewReg instead of Reg
1199 MRI->setRegAllocationHint(Partner, PartnerHint.first, NewReg);
1200
1201 // If NewReg is virtual, set up the reciprocal hint
1202 // NewReg takes over Reg's role, so it gets the SAME hint type as Reg
1203 if (NewReg.isVirtual())
1204 MRI->setRegAllocationHint(NewReg, Hint.first, Partner);
1205 }
1206 }
1207}
1208
1211 uint16_t Encoding) const {
1212 MCRegister Reg = RISCV::V0 + Encoding;
1214 return Reg;
1215 return getMatchingSuperReg(Reg, RISCV::sub_vrm1_0, &RegClass);
1216}
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t Imm
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains constants used for implementing Dwarf debug support.
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Live Register Matrix
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
static unsigned getXqciloWideOpcode(unsigned Opc)
static std::tuple< RISCVVType::VLMUL, const TargetRegisterClass &, unsigned > getSpillReloadInfo(unsigned NumRemaining, uint16_t RegEncoding, bool IsSpill)
This file declares the machine register scavenger class.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the SmallSet class.
static unsigned getDwarfRegNum(MCRegister Reg, const TargetRegisterInfo *TRI)
Go up the super-register chain until we hit a valid dwarf register number.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
A debug info location.
Definition DebugLoc.h:126
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:699
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
TypeSize getValue() const
bool isPrecise() const
MCRegAliasIterator enumerates all registers aliasing Reg.
const uint8_t TSFlags
Configurable target specific flags.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr unsigned id() const
Definition MCRegister.h:82
MachineInstrBundleIterator< const MachineInstr > const_iterator
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int64_t getLocalFrameSize() const
Get the size of the local object blob.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
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.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
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 & addFrameIndex(int Idx) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
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 hasBP(const MachineFunction &MF) const
void movImm(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, Register DstReg, uint64_t Val, MachineInstr::MIFlag Flag=MachineInstr::NoFlags, bool DstRenamable=false, bool DstIsDead=false) const
const RISCVOptions & getCLOpts() const
std::optional< unsigned > getRealVLen() const
const RISCVRegisterInfo * getRegisterInfo() const override
const RISCVInstrInfo * getInstrInfo() const override
This class implements the register bank concept.
unsigned getID() const
Get the identifier of this register bank.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
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
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition TypeSize.h:42
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Information about stack frame layout on the target.
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual bool getRegAllocationHints(Register VirtReg, ArrayRef< MCPhysReg > Order, SmallSetVector< MCPhysReg, 16 > &Hints, const MachineFunction &MF, const VirtRegMap *VRM=nullptr, const LiveRegMatrix *Matrix=nullptr) const
Get a list of 'hint' registers that the register allocator should try first when allocating a physica...
virtual StringRef getRegAsmName(MCRegister Reg) const
Return the assembly name for Reg.
virtual bool isRegisterReservedByUser(Register R) const
virtual const TargetInstrInfo * getInstrInfo() const
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
Definition VirtRegMap.h:91
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
Definition VirtRegMap.h:87
constexpr bool isKnownMultipleOf(ScalarTy RHS) const
This function tells the caller whether the element count is known at compile time to be a multiple of...
Definition TypeSize.h:181
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:253
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
bool isRVE(ABI TargetABI)
MCRegister getBPReg()
bool isSingleFP(ABI TargetABI)
bool isDoubleFP(ABI TargetABI)
bool isPurecap(ABI TargetABI)
bool isSoftFP(ABI TargetABI)
static unsigned getFormat(uint64_t TSFlags)
static RISCVVType::VLMUL getLMul(uint8_t TSFlags)
LLVM_ABI std::pair< unsigned, bool > decodeVLMUL(VLMUL VLMul)
ArrayRef< MCPhysReg > getArgFPRs(const RISCVSubtarget &STI)
ArrayRef< MCPhysReg > getArgGPRs(const RISCVSubtarget &STI)
ArrayRef< MCPhysReg > getArgVRs(const RISCVSubtarget &STI)
std::optional< std::pair< unsigned, unsigned > > isRVVSpillForZvlsseg(unsigned Opcode)
bool isRVVSpill(const MachineInstr &MI)
static constexpr unsigned RVVBytesPerBlock
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
PointerUnion< const TargetRegisterClass *, const RegisterBank * > RegClassOrRegBank
Convenient type to represent either a register class or a register bank.
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 RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
constexpr RegState getDefRegState(bool B)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
IterT skipDebugInstructionsBackward(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It until it points to a non-debug instruction or to Begin and return the resulting iterator...
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition MathExtras.h:183
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135
bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const override
bool requiresVirtualBaseRegisters(const MachineFunction &MF) const override
const TargetRegisterClass * getLargestLegalSuperClass(const TargetRegisterClass *RC, const MachineFunction &) const override
std::pair< Register, Register > getGPRPairSubRegs(MCRegister Pair) const
bool isArgumentRegister(const MachineFunction &MF, MCRegister Reg) const override
const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const override
BitVector getReservedRegs(const MachineFunction &MF) const override
bool getRegAllocationHints(Register VirtReg, ArrayRef< MCPhysReg > Order, SmallSetVector< MCPhysReg, 16 > &Hints, const MachineFunction &MF, const VirtRegMap *VRM, const LiveRegMatrix *Matrix) const override
const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const override
MCRegister findVRegWithEncoding(const TargetRegisterClass &RegClass, uint16_t Encoding) const
Register materializeFrameBaseRegister(MachineBasicBlock *MBB, int FrameIdx, int64_t Offset) const override
void getOffsetOpcodes(const StackOffset &Offset, SmallVectorImpl< uint64_t > &Ops) const override
RISCVRegisterInfo(unsigned HwMode, const std::bitset< 32 > &UserReservedXRegs)
UserReservedXRegs is the set of X registers reserved by the reserve-xN features, indexed by N.
bool isFrameOffsetLegal(const MachineInstr *MI, Register BaseReg, int64_t Offset) const override
Register getFrameRegister(const MachineFunction &MF) const override
const MCPhysReg * getIPRACSRegs(const MachineFunction *MF) const override
void lowerSegmentSpillReload(MachineBasicBlock::iterator II, bool IsSpill) const
const TargetRegisterClass * getRegClassForTypeOnBank(LLT Ty, const RegisterBank &RB, bool Is64Bit) const
void adjustReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator II, const DebugLoc &DL, Register DestReg, Register SrcReg, StackOffset Offset, MachineInstr::MIFlag Flag, MaybeAlign RequiredAlign) const
void updateRegAllocHint(Register Reg, Register NewReg, MachineFunction &MF) const override
bool isAsmClobberable(const MachineFunction &MF, MCRegister PhysReg) const override
const uint32_t * getNoPreservedMask() const override
float getSpillWeightScaleFactor(const TargetRegisterClass *RC) const override
const TargetRegisterClass * getConstrainedRegClassForReg(Register Reg, const MachineRegisterInfo &MRI) const override
void resolveFrameIndex(MachineInstr &MI, Register BaseReg, int64_t Offset) const override
int64_t getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const override
unsigned getRegisterCostTableIndex(const MachineFunction &MF) const override
StringRef getRegAsmName(MCRegister Reg) const override
bool eliminateFrameIndex(MachineBasicBlock::iterator MI, int SPAdj, unsigned FIOperandNum, RegScavenger *RS=nullptr) const override