clang 24.0.0git
RISCV.cpp
Go to the documentation of this file.
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"
13#include "clang/Driver/Driver.h"
15#include "llvm/Option/ArgList.h"
16#include "llvm/Support/Error.h"
17#include "llvm/TargetParser/Host.h"
18#include "llvm/TargetParser/RISCVISAInfo.h"
19#include "llvm/TargetParser/RISCVTargetParser.h"
20
21using namespace clang::driver;
22using namespace clang::driver::tools;
23using namespace clang;
24using namespace llvm::opt;
25
26// Returns false if an error is diagnosed.
27static bool getArchFeatures(const Driver &D, StringRef Arch,
28 std::vector<StringRef> &Features,
29 const ArgList &Args) {
30 bool EnableExperimentalExtensions =
31 Args.hasArg(options::OPT_menable_experimental_extensions);
32 auto ISAInfo =
33 llvm::RISCVISAInfo::parseArchString(Arch, EnableExperimentalExtensions);
34 if (!ISAInfo) {
35 handleAllErrors(ISAInfo.takeError(), [&](llvm::StringError &ErrMsg) {
36 D.Diag(diag::err_drv_invalid_riscv_arch_name)
37 << Arch << ErrMsg.getMessage();
38 });
39
40 return false;
41 }
42
43 for (const std::string &Str : (*ISAInfo)->toFeatures(/*AddAllExtension=*/true,
44 /*IgnoreUnknown=*/false))
45 Features.push_back(Args.MakeArgString(Str));
46
47 if (EnableExperimentalExtensions)
48 Features.push_back(Args.MakeArgString("+experimental"));
49
50 return true;
51}
52
53static bool isValidRISCVCPU(const Driver &D, const Arg *A,
54 const llvm::Triple &Triple, StringRef Mcpu) {
55 bool Is64Bit = Triple.isRISCV64();
56 if (!llvm::RISCV::parseCPU(Mcpu, Is64Bit)) {
57 // Try inverting Is64Bit in case the CPU is valid, but for the wrong target.
58 if (llvm::RISCV::parseCPU(Mcpu, !Is64Bit))
59 D.Diag(clang::diag::err_drv_invalid_riscv_cpu_name_for_target)
60 << Mcpu << Is64Bit;
61 else
62 D.Diag(clang::diag::err_drv_unsupported_option_argument)
63 << A->getSpelling() << Mcpu;
64 return false;
65 }
66 return true;
67}
68
69void 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 StringRef CPU;
81 Arg *CPUArg = nullptr;
82
83 if ((CPUArg = Args.getLastArg(options::OPT_mcpu_EQ))) {
84 CPU = CPUArg->getValue();
85 } else if ((CPUArg = Args.getLastArg(options::OPT_march_EQ))) {
86 StringRef MArchValue = CPUArg->getValue();
87 if (MArchValue == "native")
88 CPU = "native";
89 }
90
91 if (!CPU.empty()) {
92 if (CPU == "native")
93 CPU = llvm::sys::getHostCPUName();
94
95 if (!isValidRISCVCPU(D, CPUArg, Triple, CPU))
96 return;
97
98 if (llvm::RISCV::hasFastScalarUnalignedAccess(CPU))
99 CPUFastScalarUnaligned = true;
100 if (llvm::RISCV::hasFastVectorUnalignedAccess(CPU))
101 CPUFastVectorUnaligned = true;
102 }
103
104// Handle features corresponding to "-ffixed-X" options
105#define RESERVE_REG(REG) \
106 if (Args.hasArg(options::OPT_ffixed_##REG)) \
107 Features.push_back("+reserve-" #REG);
108 RESERVE_REG(x1)
109 RESERVE_REG(x2)
110 RESERVE_REG(x3)
111 RESERVE_REG(x4)
112 RESERVE_REG(x5)
113 RESERVE_REG(x6)
114 RESERVE_REG(x7)
115 RESERVE_REG(x8)
116 RESERVE_REG(x9)
117 RESERVE_REG(x10)
118 RESERVE_REG(x11)
119 RESERVE_REG(x12)
120 RESERVE_REG(x13)
121 RESERVE_REG(x14)
122 RESERVE_REG(x15)
123 RESERVE_REG(x16)
124 RESERVE_REG(x17)
125 RESERVE_REG(x18)
126 RESERVE_REG(x19)
127 RESERVE_REG(x20)
128 RESERVE_REG(x21)
129 RESERVE_REG(x22)
130 RESERVE_REG(x23)
131 RESERVE_REG(x24)
132 RESERVE_REG(x25)
133 RESERVE_REG(x26)
134 RESERVE_REG(x27)
135 RESERVE_REG(x28)
136 RESERVE_REG(x29)
137 RESERVE_REG(x30)
138 RESERVE_REG(x31)
139#undef RESERVE_REG
140
141 // -mrelax is default, unless -mno-relax is specified.
142 if (Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true))
143 Features.push_back("+relax");
144 else
145 Features.push_back("-relax");
146
147 // If -mstrict-align, -mno-strict-align, -mscalar-strict-align, or
148 // -mno-scalar-strict-align is passed, use it. Otherwise, the
149 // unaligned-scalar-mem is enabled if the CPU supports it or the target is
150 // Android.
151 if (const Arg *A = Args.getLastArg(
152 options::OPT_mno_strict_align, options::OPT_mscalar_strict_align,
153 options::OPT_mstrict_align, options::OPT_mno_scalar_strict_align)) {
154 if (A->getOption().matches(options::OPT_mno_strict_align) ||
155 A->getOption().matches(options::OPT_mno_scalar_strict_align)) {
156 Features.push_back("+unaligned-scalar-mem");
157 } else {
158 Features.push_back("-unaligned-scalar-mem");
159 }
160 } else if (CPUFastScalarUnaligned || Triple.isAndroid()) {
161 Features.push_back("+unaligned-scalar-mem");
162 }
163
164 // If -mstrict-align, -mno-strict-align, -mvector-strict-align, or
165 // -mno-vector-strict-align is passed, use it. Otherwise, the
166 // unaligned-vector-mem is enabled if the CPU supports it or the target is
167 // Android.
168 if (const Arg *A = Args.getLastArg(
169 options::OPT_mno_strict_align, options::OPT_mvector_strict_align,
170 options::OPT_mstrict_align, options::OPT_mno_vector_strict_align)) {
171 if (A->getOption().matches(options::OPT_mno_strict_align) ||
172 A->getOption().matches(options::OPT_mno_vector_strict_align)) {
173 Features.push_back("+unaligned-vector-mem");
174 } else {
175 Features.push_back("-unaligned-vector-mem");
176 }
177 } else if (CPUFastVectorUnaligned || Triple.isAndroid()) {
178 Features.push_back("+unaligned-vector-mem");
179 }
180
181 if (const Arg *A = Args.getLastArg(options::OPT_mfix_sifive_mal_9174,
182 options::OPT_mno_fix_sifive_mal_9174)) {
183 if (A->getOption().matches(options::OPT_mfix_sifive_mal_9174))
184 Features.push_back("+fix-sifive-mal-9174");
185 else
186 Features.push_back("-fix-sifive-mal-9174");
187 }
188
189 if (Triple.isRISCV32()) {
190 // Handle `-mzilsd-word-align` and `-mzilsd-strict-align` on rv32. These
191 // interact with the scalar alignment options - if unaligned scalar memory
192 // is allowed then that takes precedence over this option, as zilsd accesses
193 // can be 1-byte aligned in this case. Otherwise, the option
194 // `-mzilsd-word-align` option allows zilsd accesses to be 4-byte aligned
195 // rather than the usual 8-byte aligned (`-mzilsd-strict-align`).
196 if (const Arg *A = Args.getLastArg(
197 options::OPT_mstrict_align, options::OPT_mscalar_strict_align,
198 options::OPT_mzilsd_word_align, options::OPT_mno_strict_align,
199 options::OPT_mno_scalar_strict_align,
200 options::OPT_mzilsd_strict_align)) {
201 if (A->getOption().matches(options::OPT_mno_strict_align) ||
202 A->getOption().matches(options::OPT_mno_scalar_strict_align) ||
203 A->getOption().matches(options::OPT_mzilsd_word_align)) {
204 Features.push_back("+zilsd-word-align");
205 } else {
206 Features.push_back("-zilsd-word-align");
207 }
208 }
209 } else {
210 // Zilsd is not available on RV64, so report an error for these options.
211 if (const Arg *A = Args.getLastArg(options::OPT_mzilsd_word_align,
212 options::OPT_mzilsd_strict_align)) {
213 D.Diag(clang::diag::err_drv_unsupported_opt_for_target)
214 << A->getSpelling() << Triple.getTriple();
215 }
216 }
217
218 SmallVector<std::string, 4> TuneFeatures;
219 if (!riscv::getRISCVTuneCPU(D, Args, &TuneFeatures))
220 return;
221 for (const std::string &TF : TuneFeatures)
222 Features.push_back(Args.MakeArgString(TF));
223
224 // Now add any that the user explicitly requested on the command line,
225 // which may override the defaults.
226 handleTargetFeaturesGroup(D, Triple, Args, Features,
227 options::OPT_m_riscv_Features_Group);
228}
229
230StringRef riscv::getRISCVABI(const ArgList &Args, const llvm::Triple &Triple) {
231 assert(Triple.isRISCV() && "Unexpected triple");
232
233 // GCC's logic around choosing a default `-mabi=` is complex. If GCC is not
234 // configured using `--with-abi=`, then the logic for the default choice is
235 // defined in config.gcc. This function is based on the logic in GCC 9.2.0.
236 //
237 // The logic used in GCC 9.2.0 is the following, in order:
238 // 1. Explicit choices using `--with-abi=`
239 // 2. A default based on `--with-arch=`, if provided
240 // 3. A default based on the target triple's arch
241 //
242 // The logic in config.gcc is a little circular but it is not inconsistent.
243 //
244 // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
245 // and `-mabi=` respectively instead.
246 //
247 // In order to make chosing logic more clear, Clang uses the following logic,
248 // in order:
249 // 1. Explicit choices using `-mabi=`
250 // 2. A default based on the architecture as determined by getRISCVArch
251 // 3. Choose a default based on the triple
252
253 // 1. If `-mabi=` is specified, use it.
254 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
255 return A->getValue();
256
257 // 2. Choose a default based on the target architecture.
258 //
259 // rv32g | rv32*d -> ilp32d
260 // rv32e -> ilp32e
261 // rv32* -> ilp32
262 // rv64g | rv64*d -> lp64d
263 // rv64e -> lp64e
264 // rv64* -> lp64
265 std::string Arch = getRISCVArch(Args, Triple);
266
267 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
268 Arch, /* EnableExperimentalExtension */ true);
269 // Ignore parsing error, just go 3rd step.
270 if (!llvm::errorToBool(ParseResult.takeError()))
271 return (*ParseResult)->computeDefaultABI();
272
273 // 3. Choose a default based on the triple
274 //
275 // We deviate from GCC's defaults here:
276 // - On `riscv{XLEN}-unknown-elf` we use the integer calling convention only.
277 // - On all other OSs we use the double floating point calling convention.
278 if (Triple.isRISCV32()) {
279 if (Triple.getOS() == llvm::Triple::UnknownOS)
280 return "ilp32";
281 else
282 return "ilp32d";
283 } else {
284 if (Triple.getOS() == llvm::Triple::UnknownOS)
285 return "lp64";
286 else
287 return "lp64d";
288 }
289}
290
291static std::string getMArchFromMcpu(StringRef CPU, const llvm::Triple &Triple) {
292 if (CPU == "native") {
293 CPU = llvm::sys::getHostCPUName();
294 // If the target cpu is unrecognized, use target features.
295 if (CPU.starts_with("generic")) {
296 auto FeatureMap = llvm::sys::getHostCPUFeatures();
297 // hwprobe may be unavailable on older Linux versions.
298 if (!FeatureMap.empty()) {
299 std::vector<std::string> Features;
300 for (auto &F : FeatureMap)
301 Features.push_back(((F.second ? "+" : "-") + F.first()).str());
302 auto ParseResult = llvm::RISCVISAInfo::parseFeatures(
303 Triple.isRISCV32() ? 32 : 64, Features);
304 if (ParseResult)
305 return (*ParseResult)->toString();
306 }
307 }
308 }
309
310 return llvm::RISCV::getMArchFromMcpu(CPU).str();
311}
312
313std::string riscv::getRISCVArch(const llvm::opt::ArgList &Args,
314 const llvm::Triple &Triple) {
315 assert(Triple.isRISCV() && "Unexpected triple");
316
317 // GCC's logic around choosing a default `-march=` is complex. If GCC is not
318 // configured using `--with-arch=`, then the logic for the default choice is
319 // defined in config.gcc. This function is based on the logic in GCC 9.2.0. We
320 // deviate from GCC's default on additional `-mcpu` option (GCC does not
321 // support `-mcpu`) and baremetal targets (UnknownOS) where neither `-march`
322 // nor `-mabi` is specified.
323 //
324 // The logic used in GCC 9.2.0 is the following, in order:
325 // 1. Explicit choices using `--with-arch=`
326 // 2. A default based on `--with-abi=`, if provided
327 // 3. A default based on the target triple's arch
328 //
329 // The logic in config.gcc is a little circular but it is not inconsistent.
330 //
331 // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
332 // and `-mabi=` respectively instead.
333 //
334 // Clang uses the following logic, in order:
335 // 1. Explicit choices using `-march=` (`-march=native` means the host CPU)
336 // 2. Based on `-mcpu` if `-march=` is not specified and the target CPU has a
337 // default ISA string
338 // 3. A default based on `-mabi`, if provided
339 // 4. A default based on the target triple's arch
340 //
341 // Clang does not yet support MULTILIB_REUSE, so we use `rv{XLEN}imafdc`
342 // instead of `rv{XLEN}gc` though they are (currently) equivalent.
343
344 // 1. If `-march=` is specified, use it unless the value is "unset". A value
345 // of "native" is an alias for `-mcpu=native` and selects the ISA string of
346 // the host CPU.
347 bool HasMArch = false;
348 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
349 StringRef MArchValue = A->getValue();
350 if (MArchValue != "unset") {
351 HasMArch = true;
352 if (MArchValue != "native")
353 return MArchValue.str();
354
355 std::string MArch = getMArchFromMcpu(MArchValue, Triple);
356 if (!MArch.empty())
357 return MArch;
358 }
359 }
360
361 // 2. Get march (isa string) based on `-mcpu=`. This is only used if `-march=`
362 // was not specified, so a `-march=native` that failed to determine the host
363 // ISA string above does not fall back to `-mcpu=`.
364 if (!HasMArch) {
365 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
366 std::string MArch = getMArchFromMcpu(A->getValue(), Triple);
367 // Bypass if target cpu's default march is empty.
368 if (!MArch.empty())
369 return MArch;
370 }
371 }
372
373 // 3. Choose a default based on `-mabi=`
374 //
375 // ilp32e -> rv32e
376 // lp64e -> rv64e
377 // ilp32 | ilp32f | ilp32d -> rv32imafdc
378 // lp64 | lp64f | lp64d -> rv64imafdc
379 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
380 StringRef MABI = A->getValue();
381
382 if (MABI.equals_insensitive("ilp32e"))
383 return "rv32e";
384 if (MABI.equals_insensitive("lp64e"))
385 return "rv64e";
386 if (MABI.starts_with_insensitive("ilp32"))
387 return "rv32imafdc";
388 if (MABI.starts_with_insensitive("lp64")) {
389 if (Triple.isAndroid())
390 return "rv64imafdcv_zba_zbb_zbs";
391 if (Triple.isOSFuchsia())
392 return "rva22u64_v";
393 return "rv64imafdc";
394 }
395 }
396
397 // 4. Choose a default based on the triple
398 //
399 // We deviate from GCC's defaults here:
400 // - On `riscv{XLEN}-unknown-elf` we default to `rv{XLEN}imac`
401 // - On all other OSs we use `rv{XLEN}imafdc` (equivalent to `rv{XLEN}gc`)
402 if (Triple.isRISCV32()) {
403 if (Triple.getOS() == llvm::Triple::UnknownOS)
404 return "rv32imac";
405 return "rv32imafdc";
406 }
407
408 if (Triple.getOS() == llvm::Triple::UnknownOS)
409 return "rv64imac";
410 if (Triple.isAndroid())
411 return "rv64imafdcv_zba_zbb_zbs";
412 if (Triple.isOSFuchsia())
413 return "rva22u64_v";
414 return "rv64imafdc";
415}
416
417std::string riscv::getRISCVTargetCPU(const llvm::opt::ArgList &Args,
418 const llvm::Triple &Triple) {
419 std::string CPU;
420 // If we have -mcpu, use that. Otherwise, check for -march=native.
421 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
422 CPU = A->getValue();
423 } else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
424 // `-march=native` is an alias for `-mcpu=native`.
425 StringRef MArchValue = A->getValue();
426 if (MArchValue == "native")
427 CPU = "native";
428 }
429
430 // Handle CPU name is 'native'.
431 if (CPU == "native")
432 CPU = llvm::sys::getHostCPUName();
433
434 if (!CPU.empty())
435 return CPU;
436
437 return Triple.isRISCV64() ? "generic-rv64" : "generic-rv32";
438}
439
440std::optional<StringRef>
441riscv::getRISCVTuneCPU(const Driver &D, const llvm::opt::ArgList &Args,
442 SmallVectorImpl<std::string> *TuneFeatures) {
443 const Arg *MTuneArg = Args.getLastArg(options::OPT_mtune_EQ);
444 if (!MTuneArg)
445 return "";
446
447 StringRef TuneCPU = MTuneArg->getValue();
448 StringRef TFString;
449
450 auto Idx = TuneCPU.find(':');
451 if (Idx != StringRef::npos) {
452 if (!Args.hasFlag(options::OPT_mexperimental_mtune_syntax,
453 options::OPT_mno_experimental_mtune_syntax, false)) {
454 // Only print this diagnostics if it's used for retrieving tune features
455 // to avoid printing the same error message multiple times.
456 if (TuneFeatures)
457 D.Diag(diag::err_drv_invalid_riscv_mtune_string)
458 << 0 << TuneCPU
459 << "require '-mexperimental-mtune-syntax' to use with tune feature "
460 "string";
461 return std::nullopt;
462 }
463
464 TFString = TuneCPU.substr(Idx + 1);
465 TuneCPU = TuneCPU.slice(0, Idx);
466 }
467
468 if (TuneFeatures && !TFString.empty()) {
469 if (auto E = llvm::RISCV::parseTuneFeatureString(TuneCPU, TFString,
470 *TuneFeatures)) {
471 D.Diag(diag::err_drv_invalid_riscv_mtune_string)
472 << 1 << TFString << llvm::toString(std::move(E));
473 return std::nullopt;
474 }
475 }
476
477 // Apply -mtune=native after applying features. Not all features apply to
478 // all CPUs so an -mtune=native:<feature> may fail depending on what the
479 // native was expanded to.
480 if (TuneCPU == "native")
481 TuneCPU = llvm::sys::getHostCPUName();
482
483 return TuneCPU;
484}
static bool isValidRISCVCPU(const Driver &D, const Arg *A, const llvm::Triple &Triple, StringRef Mcpu)
Definition RISCV.cpp:53
static std::string getMArchFromMcpu(StringRef CPU, const llvm::Triple &Triple)
Definition RISCV.cpp:291
#define RESERVE_REG(REG)
static bool getArchFeatures(const Driver &D, StringRef Arch, std::vector< StringRef > &Features, const ArgList &Args)
Definition RISCV.cpp:27
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:93
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:157
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:313
std::string getRISCVTargetCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:417
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::optional< StringRef > getRISCVTuneCPU(const Driver &D, const llvm::opt::ArgList &Args, SmallVectorImpl< std::string > *TuneFeatures=nullptr)
Return the tune CPU and optionally, the tune features.
Definition RISCV.cpp:441
void getRISCVTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
void handleTargetFeaturesGroup(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< StringRef > &Features, llvm::opt::OptSpecifier Group)
Iterate Args and convert -mxxx to +xxx and -mno-xxx to -xxx and append it to Features.
Top level wrappers for InstallAPI frontend operations.