1//===-- RISCVSubtarget.cpp - RISC-V Subtarget 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 implements the RISC-V specific subclass of TargetSubtargetInfo.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RISCVSubtarget.h"
14#include "GISel/RISCVCallLowering.h"
15#include "GISel/RISCVLegalizerInfo.h"
16#include "RISCV.h"
17#include "RISCVFrameLowering.h"
18#include "RISCVSelectionDAGInfo.h"
19#include "RISCVTargetMachine.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/MC/TargetRegistry.h"
22#include "llvm/Support/ErrorHandling.h"
23
24using namespace llvm;
25
26#define DEBUG_TYPE "riscv-subtarget"
27
28#define GET_SUBTARGETINFO_TARGET_DESC
29#define GET_SUBTARGETINFO_CTOR
30#include "RISCVGenSubtargetInfo.inc"
31
32#define GET_RISCV_MACRO_FUSION_PRED_IMPL
33#include "RISCVGenMacroFusion.inc"
34
35namespace llvm::RISCVTuneInfoTable {
36
37#define GET_RISCVTuneInfoTable_IMPL
38#include "RISCVGenSearchableTables.inc"
39} // namespace llvm::RISCVTuneInfoTable
40
41static cl::opt<unsigned> RVVVectorLMULMax(
42 "riscv-v-fixed-length-vector-lmul-max",
43 cl::desc("The maximum LMUL value to use for fixed length vectors. "
44 "Fractional LMUL values are not supported."),
45 cl::init(Val: 8), cl::Hidden);
46
47static cl::opt<bool> RISCVDisableUsingConstantPoolForLargeInts(
48 "riscv-disable-using-constant-pool-for-large-ints",
49 cl::desc("Disable using constant pool for large integers."),
50 cl::init(Val: false), cl::Hidden);
51
52static cl::opt<unsigned> RISCVMaxBuildIntsCost(
53 "riscv-max-build-ints-cost",
54 cl::desc("The maximum cost used for building integers."), cl::init(Val: 0),
55 cl::Hidden);
56
57static cl::opt<bool> UseAA("riscv-use-aa", cl::init(Val: true),
58 cl::desc("Enable the use of AA during codegen."));
59
60static cl::opt<unsigned> RISCVMinimumJumpTableEntries(
61 "riscv-min-jump-table-entries", cl::Hidden,
62 cl::desc("Set minimum number of entries to use a jump table on RISCV"));
63
64static cl::opt<bool> UseMIPSLoadStorePairsOpt(
65 "use-riscv-mips-load-store-pairs",
66 cl::desc("Enable the load/store pair optimization pass"), cl::init(Val: false),
67 cl::Hidden);
68
69static cl::opt<bool> UseMIPSCCMovInsn("use-riscv-mips-ccmov",
70 cl::desc("Use 'mips.ccmov' instruction"),
71 cl::init(Val: true), cl::Hidden);
72
73void RISCVSubtarget::anchor() {}
74
75RISCVSubtarget &
76RISCVSubtarget::initializeSubtargetDependencies(const Triple &TT, StringRef CPU,
77 StringRef TuneCPU, StringRef FS,
78 StringRef ABIName) {
79 // Determine default and user-specified characteristics
80 bool Is64Bit = TT.isArch64Bit();
81 if (CPU.empty() || CPU == "generic")
82 CPU = Is64Bit ? "generic-rv64" : "generic-rv32";
83
84 if (TuneCPU.empty())
85 TuneCPU = CPU;
86 if (TuneCPU == "generic")
87 TuneCPU = Is64Bit ? "generic-rv64" : "generic-rv32";
88
89 TuneInfo = RISCVTuneInfoTable::getRISCVTuneInfo(Name: TuneCPU);
90 // If there is no TuneInfo for this CPU, we fail back to generic.
91 if (!TuneInfo)
92 TuneInfo = RISCVTuneInfoTable::getRISCVTuneInfo(Name: "generic");
93 assert(TuneInfo && "TuneInfo shouldn't be nullptr!");
94
95 ParseSubtargetFeatures(CPU, TuneCPU, FS);
96
97 RISCV::updateCZceFeatureImplications(STI&: *this);
98
99 // Re-sync the flags.
100 HasStdExtZcd = hasFeature(Feature: RISCV::FeatureStdExtZcd);
101 HasStdExtZcf = hasFeature(Feature: RISCV::FeatureStdExtZcf);
102 HasStdExtC = hasFeature(Feature: RISCV::FeatureStdExtC);
103 HasStdExtZce = hasFeature(Feature: RISCV::FeatureStdExtZce);
104
105 TargetABI = RISCVABI::computeTargetABI(TT, FeatureBits: getFeatureBits(), ABIName);
106 RISCVFeatures::validate(TT, FeatureBits: getFeatureBits());
107 return *this;
108}
109
110RISCVSubtarget::RISCVSubtarget(const Triple &TT, StringRef CPU,
111 StringRef TuneCPU, StringRef FS,
112 StringRef ABIName, unsigned RVVVectorBitsMin,
113 unsigned RVVVectorBitsMax,
114 const TargetMachine &TM)
115 : RISCVGenSubtargetInfo(TT, CPU, TuneCPU, FS),
116 IsLittleEndian(TT.isLittleEndian()), RVVVectorBitsMin(RVVVectorBitsMin),
117 RVVVectorBitsMax(RVVVectorBitsMax),
118 FrameLowering(
119 initializeSubtargetDependencies(TT, CPU, TuneCPU, FS, ABIName)),
120 InstrInfo(*this), TLInfo(TM, *this) {
121 TSInfo = std::make_unique<RISCVSelectionDAGInfo>();
122}
123
124RISCVSubtarget::~RISCVSubtarget() = default;
125
126const SelectionDAGTargetInfo *RISCVSubtarget::getSelectionDAGInfo() const {
127 return TSInfo.get();
128}
129
130const CallLowering *RISCVSubtarget::getCallLowering() const {
131 if (!CallLoweringInfo)
132 CallLoweringInfo.reset(p: new RISCVCallLowering(*getTargetLowering()));
133 return CallLoweringInfo.get();
134}
135
136InstructionSelector *RISCVSubtarget::getInstructionSelector() const {
137 if (!InstSelector) {
138 InstSelector.reset(p: createRISCVInstructionSelector(
139 *static_cast<const RISCVTargetMachine *>(&TLInfo.getTargetMachine()),
140 *this, *getRegBankInfo()));
141 }
142 return InstSelector.get();
143}
144
145const LegalizerInfo *RISCVSubtarget::getLegalizerInfo() const {
146 if (!Legalizer)
147 Legalizer.reset(p: new RISCVLegalizerInfo(*this));
148 return Legalizer.get();
149}
150
151const RISCVRegisterBankInfo *RISCVSubtarget::getRegBankInfo() const {
152 if (!RegBankInfo)
153 RegBankInfo.reset(p: new RISCVRegisterBankInfo(getHwMode()));
154 return RegBankInfo.get();
155}
156
157bool RISCVSubtarget::useConstantPoolForLargeInts() const {
158 return !RISCVDisableUsingConstantPoolForLargeInts;
159}
160
161// Returns true if VT is a P extension packed SIMD type that fits in XLen.
162bool RISCVSubtarget::isPExtPackedType(MVT VT) const {
163 if (!HasStdExtP)
164 return false;
165
166 if (is64Bit())
167 return VT == MVT::v8i8 || VT == MVT::v4i16 || VT == MVT::v2i32;
168 return VT == MVT::v4i8 || VT == MVT::v2i16;
169}
170
171unsigned RISCVSubtarget::getMaxBuildIntsCost() const {
172 // Loading integer from constant pool needs two instructions (the reason why
173 // the minimum cost is 2): an address calculation instruction and a load
174 // instruction. Usually, address calculation and instructions used for
175 // building integers (addi, slli, etc.) can be done in one cycle, so here we
176 // set the default cost to (LoadLatency + 1) if no threshold is provided.
177 return RISCVMaxBuildIntsCost == 0
178 ? getSchedModel().LoadLatency + 1
179 : std::max<unsigned>(a: 2, b: RISCVMaxBuildIntsCost);
180}
181
182unsigned RISCVSubtarget::getMaxRVVVectorSizeInBits() const {
183 assert(hasVInstructions() &&
184 "Tried to get vector length without Zve or V extension support!");
185
186 // ZvlLen specifies the minimum required vlen. The upper bound provided by
187 // riscv-v-vector-bits-max should be no less than it.
188 if (RVVVectorBitsMax != 0 && RVVVectorBitsMax < ZvlLen)
189 report_fatal_error(reason: "riscv-v-vector-bits-max specified is lower "
190 "than the Zvl*b limitation");
191
192 return RVVVectorBitsMax;
193}
194
195unsigned RISCVSubtarget::getMinRVVVectorSizeInBits() const {
196 assert(hasVInstructions() &&
197 "Tried to get vector length without Zve or V extension support!");
198
199 if (RVVVectorBitsMin == -1U)
200 return ZvlLen;
201
202 // ZvlLen specifies the minimum required vlen. The lower bound provided by
203 // riscv-v-vector-bits-min should be no less than it.
204 if (RVVVectorBitsMin != 0 && RVVVectorBitsMin < ZvlLen)
205 report_fatal_error(reason: "riscv-v-vector-bits-min specified is lower "
206 "than the Zvl*b limitation");
207
208 return RVVVectorBitsMin;
209}
210
211unsigned RISCVSubtarget::getMaxLMULForFixedLengthVectors() const {
212 assert(hasVInstructions() &&
213 "Tried to get vector length without Zve or V extension support!");
214 assert(RVVVectorLMULMax <= 8 &&
215 llvm::has_single_bit<uint32_t>(RVVVectorLMULMax) &&
216 "V extension requires a LMUL to be at most 8 and a power of 2!");
217 return llvm::bit_floor(Value: std::clamp<unsigned>(val: RVVVectorLMULMax, lo: 1, hi: 8));
218}
219
220bool RISCVSubtarget::useRVVForFixedLengthVectors() const {
221 return hasVInstructions() &&
222 getMinRVVVectorSizeInBits() >= RISCV::RVVBitsPerBlock;
223}
224
225bool RISCVSubtarget::enableSubRegLiveness() const { return true; }
226
227bool RISCVSubtarget::enableMachinePipeliner() const {
228 return getSchedModel().hasInstrSchedModel();
229}
230
231void RISCVSubtarget::mirFileLoaded(MachineFunction &MF) const {
232 // We usually compute max call frame size after ISel. Do the computation now
233 // if the .mir file didn't specify it. Note that this will probably give you
234 // bogus values after PEI has eliminated the callframe setup/destroy pseudo
235 // instructions, specify explicitly if you need it to be correct.
236 MachineFrameInfo &MFI = MF.getFrameInfo();
237 if (!MFI.isMaxCallFrameSizeComputed())
238 MFI.computeMaxCallFrameSize(MF);
239}
240
241 /// Enable use of alias analysis during code generation (during MI
242 /// scheduling, DAGCombine, etc.).
243bool RISCVSubtarget::useAA() const { return UseAA; }
244
245unsigned RISCVSubtarget::getMinimumJumpTableEntries() const {
246 return RISCVMinimumJumpTableEntries.getNumOccurrences() > 0
247 ? RISCVMinimumJumpTableEntries
248 : TuneInfo->MinimumJumpTableEntries;
249}
250
251void RISCVSubtarget::overrideSchedPolicy(MachineSchedPolicy &Policy,
252 const SchedRegion &Region) const {
253 // Do bidirectional scheduling since it provides a more balanced scheduling
254 // leading to better performance. This will increase compile time.
255 Policy.OnlyTopDown = false;
256 Policy.OnlyBottomUp = false;
257
258 // Disabling the latency heuristic can reduce the number of spills/reloads but
259 // will cause some regressions on some cores.
260 Policy.DisableLatencyHeuristic = DisableLatencySchedHeuristic;
261
262 // Spilling is generally expensive on all RISC-V cores, so always enable
263 // register-pressure tracking. This will increase compile time.
264 Policy.ShouldTrackPressure = true;
265}
266
267void RISCVSubtarget::overridePostRASchedPolicy(
268 MachineSchedPolicy &Policy, const SchedRegion &Region) const {
269 MISched::Direction PostRASchedDirection = getPostRASchedDirection();
270 if (PostRASchedDirection == MISched::TopDown) {
271 Policy.OnlyTopDown = true;
272 Policy.OnlyBottomUp = false;
273 } else if (PostRASchedDirection == MISched::BottomUp) {
274 Policy.OnlyTopDown = false;
275 Policy.OnlyBottomUp = true;
276 } else if (PostRASchedDirection == MISched::Bidirectional) {
277 Policy.OnlyTopDown = false;
278 Policy.OnlyBottomUp = false;
279 }
280}
281
282bool RISCVSubtarget::useMIPSLoadStorePairs() const {
283 return UseMIPSLoadStorePairsOpt && HasVendorXMIPSLSP;
284}
285
286bool RISCVSubtarget::useMIPSCCMovInsn() const {
287 return UseMIPSCCMovInsn && HasVendorXMIPSCMov;
288}
289