1 //===--- RISCV.cpp - RISC-V Helpers for Tools -------------------*- 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 #include "RISCV.h"
10 #include "../Clang.h"
11 #include "clang/Driver/CommonArgs.h"
12 #include "clang/Driver/Driver.h"
13 #include "clang/Driver/Options.h"
14 #include "llvm/Option/ArgList.h"
15 #include "llvm/Support/Error.h"
16 #include "llvm/TargetParser/Host.h"
17 #include "llvm/TargetParser/RISCVISAInfo.h"
18 #include "llvm/TargetParser/RISCVTargetParser.h"
19
20 using namespace clang::driver;
21 using namespace clang::driver::tools;
22 using namespace clang;
23 using namespace llvm::opt;
24
25 // Returns false if an error is diagnosed.
getArchFeatures(const Driver & D,StringRef Arch,std::vector<StringRef> & Features,const ArgList & Args)26 static bool getArchFeatures(const Driver &D, StringRef Arch,
27 std::vector<StringRef> &Features,
28 const ArgList &Args) {
29 bool EnableExperimentalExtensions =
30 Args.hasArg(options::OPT_menable_experimental_extensions);
31 auto ISAInfo =
32 llvm::RISCVISAInfo::parseArchString(Arch, EnableExperimentalExtensions);
33 if (!ISAInfo) {
34 handleAllErrors(ISAInfo.takeError(), [&](llvm::StringError &ErrMsg) {
35 D.Diag(diag::err_drv_invalid_riscv_arch_name)
36 << Arch << ErrMsg.getMessage();
37 });
38
39 return false;
40 }
41
42 for (const std::string &Str : (*ISAInfo)->toFeatures(/*AddAllExtension=*/true,
43 /*IgnoreUnknown=*/false))
44 Features.push_back(Args.MakeArgString(Str));
45
46 if (EnableExperimentalExtensions)
47 Features.push_back(Args.MakeArgString("+experimental"));
48
49 return true;
50 }
51
52 // Get features except standard extension feature
getRISCFeaturesFromMcpu(const Driver & D,const Arg * A,const llvm::Triple & Triple,StringRef Mcpu,std::vector<StringRef> & Features)53 static void getRISCFeaturesFromMcpu(const Driver &D, const Arg *A,
54 const llvm::Triple &Triple,
55 StringRef Mcpu,
56 std::vector<StringRef> &Features) {
57 bool Is64Bit = Triple.isRISCV64();
58 if (!llvm::RISCV::parseCPU(Mcpu, Is64Bit)) {
59 // Try inverting Is64Bit in case the CPU is valid, but for the wrong target.
60 if (llvm::RISCV::parseCPU(Mcpu, !Is64Bit))
61 D.Diag(clang::diag::err_drv_invalid_riscv_cpu_name_for_target)
62 << Mcpu << Is64Bit;
63 else
64 D.Diag(clang::diag::err_drv_unsupported_option_argument)
65 << A->getSpelling() << Mcpu;
66 }
67 }
68
getRISCVTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<StringRef> & Features)69 void riscv::getRISCVTargetFeatures(const Driver &D, const llvm::Triple &Triple,
70 const ArgList &Args,
71 std::vector<StringRef> &Features) {
72 std::string MArch = getRISCVArch(Args, Triple);
73
74 if (!getArchFeatures(D, MArch, Features, Args))
75 return;
76
77 bool CPUFastScalarUnaligned = false;
78 bool CPUFastVectorUnaligned = false;
79
80 // If users give march and mcpu, get std extension feature from MArch
81 // and other features (ex. mirco architecture feature) from mcpu
82 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
83 StringRef CPU = A->getValue();
84 if (CPU == "native")
85 CPU = llvm::sys::getHostCPUName();
86
87 getRISCFeaturesFromMcpu(D, A, Triple, CPU, Features);
88
89 if (llvm::RISCV::hasFastScalarUnalignedAccess(CPU))
90 CPUFastScalarUnaligned = true;
91 if (llvm::RISCV::hasFastVectorUnalignedAccess(CPU))
92 CPUFastVectorUnaligned = true;
93 }
94
95 // Handle features corresponding to "-ffixed-X" options
96 #define RESERVE_REG(REG) \
97 if (Args.hasArg(options::OPT_ffixed_##REG)) \
98 Features.push_back("+reserve-" #REG);
99 RESERVE_REG(x1)
100 RESERVE_REG(x2)
101 RESERVE_REG(x3)
102 RESERVE_REG(x4)
103 RESERVE_REG(x5)
104 RESERVE_REG(x6)
105 RESERVE_REG(x7)
106 RESERVE_REG(x8)
107 RESERVE_REG(x9)
108 RESERVE_REG(x10)
109 RESERVE_REG(x11)
110 RESERVE_REG(x12)
111 RESERVE_REG(x13)
112 RESERVE_REG(x14)
113 RESERVE_REG(x15)
114 RESERVE_REG(x16)
115 RESERVE_REG(x17)
116 RESERVE_REG(x18)
117 RESERVE_REG(x19)
118 RESERVE_REG(x20)
119 RESERVE_REG(x21)
120 RESERVE_REG(x22)
121 RESERVE_REG(x23)
122 RESERVE_REG(x24)
123 RESERVE_REG(x25)
124 RESERVE_REG(x26)
125 RESERVE_REG(x27)
126 RESERVE_REG(x28)
127 RESERVE_REG(x29)
128 RESERVE_REG(x30)
129 RESERVE_REG(x31)
130 #undef RESERVE_REG
131
132 // FreeBSD local, because ld.lld doesn't support relaxations
133 // -mno-relax is default, unless -mrelax is specified.
134 if (Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, false)) {
135 Features.push_back("+relax");
136 // -gsplit-dwarf -mrelax requires DW_AT_high_pc/DW_AT_ranges/... indexing
137 // into .debug_addr, which is currently not implemented.
138 Arg *A;
139 if (getDebugFissionKind(D, Args, A) != DwarfFissionKind::None)
140 D.Diag(clang::diag::err_drv_riscv_unsupported_with_linker_relaxation)
141 << A->getAsString(Args);
142 } else {
143 Features.push_back("-relax");
144 }
145
146 // If -mstrict-align, -mno-strict-align, -mscalar-strict-align, or
147 // -mno-scalar-strict-align is passed, use it. Otherwise, the
148 // unaligned-scalar-mem is enabled if the CPU supports it or the target is
149 // Android.
150 if (const Arg *A = Args.getLastArg(
151 options::OPT_mno_strict_align, options::OPT_mscalar_strict_align,
152 options::OPT_mstrict_align, options::OPT_mno_scalar_strict_align)) {
153 if (A->getOption().matches(options::OPT_mno_strict_align) ||
154 A->getOption().matches(options::OPT_mno_scalar_strict_align)) {
155 Features.push_back("+unaligned-scalar-mem");
156 } else {
157 Features.push_back("-unaligned-scalar-mem");
158 }
159 } else if (CPUFastScalarUnaligned || Triple.isAndroid()) {
160 Features.push_back("+unaligned-scalar-mem");
161 }
162
163 // If -mstrict-align, -mno-strict-align, -mvector-strict-align, or
164 // -mno-vector-strict-align is passed, use it. Otherwise, the
165 // unaligned-vector-mem is enabled if the CPU supports it or the target is
166 // Android.
167 if (const Arg *A = Args.getLastArg(
168 options::OPT_mno_strict_align, options::OPT_mvector_strict_align,
169 options::OPT_mstrict_align, options::OPT_mno_vector_strict_align)) {
170 if (A->getOption().matches(options::OPT_mno_strict_align) ||
171 A->getOption().matches(options::OPT_mno_vector_strict_align)) {
172 Features.push_back("+unaligned-vector-mem");
173 } else {
174 Features.push_back("-unaligned-vector-mem");
175 }
176 } else if (CPUFastVectorUnaligned || Triple.isAndroid()) {
177 Features.push_back("+unaligned-vector-mem");
178 }
179
180 // Now add any that the user explicitly requested on the command line,
181 // which may override the defaults.
182 handleTargetFeaturesGroup(D, Triple, Args, Features,
183 options::OPT_m_riscv_Features_Group);
184 }
185
getRISCVABI(const ArgList & Args,const llvm::Triple & Triple)186 StringRef riscv::getRISCVABI(const ArgList &Args, const llvm::Triple &Triple) {
187 assert(Triple.isRISCV() && "Unexpected triple");
188
189 // GCC's logic around choosing a default `-mabi=` is complex. If GCC is not
190 // configured using `--with-abi=`, then the logic for the default choice is
191 // defined in config.gcc. This function is based on the logic in GCC 9.2.0.
192 //
193 // The logic used in GCC 9.2.0 is the following, in order:
194 // 1. Explicit choices using `--with-abi=`
195 // 2. A default based on `--with-arch=`, if provided
196 // 3. A default based on the target triple's arch
197 //
198 // The logic in config.gcc is a little circular but it is not inconsistent.
199 //
200 // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
201 // and `-mabi=` respectively instead.
202 //
203 // In order to make chosing logic more clear, Clang uses the following logic,
204 // in order:
205 // 1. Explicit choices using `-mabi=`
206 // 2. A default based on the architecture as determined by getRISCVArch
207 // 3. Choose a default based on the triple
208
209 // 1. If `-mabi=` is specified, use it.
210 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
211 return A->getValue();
212
213 // 2. Choose a default based on the target architecture.
214 //
215 // rv32g | rv32*d -> ilp32d
216 // rv32e -> ilp32e
217 // rv32* -> ilp32
218 // rv64g | rv64*d -> lp64d
219 // rv64e -> lp64e
220 // rv64* -> lp64
221 std::string Arch = getRISCVArch(Args, Triple);
222
223 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
224 Arch, /* EnableExperimentalExtension */ true);
225 // Ignore parsing error, just go 3rd step.
226 if (!llvm::errorToBool(ParseResult.takeError()))
227 return (*ParseResult)->computeDefaultABI();
228
229 // 3. Choose a default based on the triple
230 //
231 // We deviate from GCC's defaults here:
232 // - On `riscv{XLEN}-unknown-elf` we use the integer calling convention only.
233 // - On all other OSs we use the double floating point calling convention.
234 if (Triple.isRISCV32()) {
235 if (Triple.getOS() == llvm::Triple::UnknownOS)
236 return "ilp32";
237 else
238 return "ilp32d";
239 } else {
240 if (Triple.getOS() == llvm::Triple::UnknownOS)
241 return "lp64";
242 else
243 return "lp64d";
244 }
245 }
246
getRISCVArch(const llvm::opt::ArgList & Args,const llvm::Triple & Triple)247 std::string riscv::getRISCVArch(const llvm::opt::ArgList &Args,
248 const llvm::Triple &Triple) {
249 assert(Triple.isRISCV() && "Unexpected triple");
250
251 // GCC's logic around choosing a default `-march=` is complex. If GCC is not
252 // configured using `--with-arch=`, then the logic for the default choice is
253 // defined in config.gcc. This function is based on the logic in GCC 9.2.0. We
254 // deviate from GCC's default on additional `-mcpu` option (GCC does not
255 // support `-mcpu`) and baremetal targets (UnknownOS) where neither `-march`
256 // nor `-mabi` is specified.
257 //
258 // The logic used in GCC 9.2.0 is the following, in order:
259 // 1. Explicit choices using `--with-arch=`
260 // 2. A default based on `--with-abi=`, if provided
261 // 3. A default based on the target triple's arch
262 //
263 // The logic in config.gcc is a little circular but it is not inconsistent.
264 //
265 // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
266 // and `-mabi=` respectively instead.
267 //
268 // Clang uses the following logic, in order:
269 // 1. Explicit choices using `-march=`
270 // 2. Based on `-mcpu` if the target CPU has a default ISA string
271 // 3. A default based on `-mabi`, if provided
272 // 4. A default based on the target triple's arch
273 //
274 // Clang does not yet support MULTILIB_REUSE, so we use `rv{XLEN}imafdc`
275 // instead of `rv{XLEN}gc` though they are (currently) equivalent.
276
277 // 1. If `-march=` is specified, use it.
278 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
279 return A->getValue();
280
281 // 2. Get march (isa string) based on `-mcpu=`
282 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
283 StringRef CPU = A->getValue();
284 if (CPU == "native") {
285 CPU = llvm::sys::getHostCPUName();
286 // If the target cpu is unrecognized, use target features.
287 if (CPU.starts_with("generic")) {
288 auto FeatureMap = llvm::sys::getHostCPUFeatures();
289 // hwprobe may be unavailable on older Linux versions.
290 if (!FeatureMap.empty()) {
291 std::vector<std::string> Features;
292 for (auto &F : FeatureMap)
293 Features.push_back(((F.second ? "+" : "-") + F.first()).str());
294 auto ParseResult = llvm::RISCVISAInfo::parseFeatures(
295 Triple.isRISCV32() ? 32 : 64, Features);
296 if (ParseResult)
297 return (*ParseResult)->toString();
298 }
299 }
300 }
301
302 StringRef MArch = llvm::RISCV::getMArchFromMcpu(CPU);
303 // Bypass if target cpu's default march is empty.
304 if (MArch != "")
305 return MArch.str();
306 }
307
308 // 3. Choose a default based on `-mabi=`
309 //
310 // ilp32e -> rv32e
311 // lp64e -> rv64e
312 // ilp32 | ilp32f | ilp32d -> rv32imafdc
313 // lp64 | lp64f | lp64d -> rv64imafdc
314 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
315 StringRef MABI = A->getValue();
316
317 if (MABI.equals_insensitive("ilp32e"))
318 return "rv32e";
319 if (MABI.equals_insensitive("lp64e"))
320 return "rv64e";
321 if (MABI.starts_with_insensitive("ilp32"))
322 return "rv32imafdc";
323 if (MABI.starts_with_insensitive("lp64")) {
324 if (Triple.isAndroid())
325 return "rv64imafdcv_zba_zbb_zbs";
326 if (Triple.isOSFuchsia())
327 return "rva22u64_v";
328 return "rv64imafdc";
329 }
330 }
331
332 // 4. Choose a default based on the triple
333 //
334 // We deviate from GCC's defaults here:
335 // - On `riscv{XLEN}-unknown-elf` we default to `rv{XLEN}imac`
336 // - On all other OSs we use `rv{XLEN}imafdc` (equivalent to `rv{XLEN}gc`)
337 if (Triple.isRISCV32()) {
338 if (Triple.getOS() == llvm::Triple::UnknownOS)
339 return "rv32imac";
340 return "rv32imafdc";
341 }
342
343 if (Triple.getOS() == llvm::Triple::UnknownOS)
344 return "rv64imac";
345 if (Triple.isAndroid())
346 return "rv64imafdcv_zba_zbb_zbs";
347 if (Triple.isOSFuchsia())
348 return "rva22u64_v";
349 return "rv64imafdc";
350 }
351
getRISCVTargetCPU(const llvm::opt::ArgList & Args,const llvm::Triple & Triple)352 std::string riscv::getRISCVTargetCPU(const llvm::opt::ArgList &Args,
353 const llvm::Triple &Triple) {
354 std::string CPU;
355 // If we have -mcpu, use that.
356 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
357 CPU = A->getValue();
358
359 // Handle CPU name is 'native'.
360 if (CPU == "native")
361 CPU = llvm::sys::getHostCPUName();
362
363 if (!CPU.empty())
364 return CPU;
365
366 return Triple.isRISCV64() ? "generic-rv64" : "generic-rv32";
367 }
368