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