xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/RISCVToolchain.cpp (revision ec0ea6efa1ad229d75c394c1a9b9cac33af2b1d3)
1 //===--- RISCVToolchain.cpp - RISCV ToolChain Implementations ---*- 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 "RISCVToolchain.h"
10 #include "CommonArgs.h"
11 #include "clang/Driver/Compilation.h"
12 #include "clang/Driver/InputInfo.h"
13 #include "clang/Driver/Options.h"
14 #include "llvm/Option/ArgList.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/Path.h"
17 #include "llvm/Support/raw_ostream.h"
18 
19 using namespace clang::driver;
20 using namespace clang::driver::toolchains;
21 using namespace clang::driver::tools;
22 using namespace clang;
23 using namespace llvm::opt;
24 
25 static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs,
26                                   const Multilib &Multilib,
27                                   StringRef InstallPath,
28                                   ToolChain::path_list &Paths) {
29   if (const auto &PathsCallback = Multilibs.filePathsCallback())
30     for (const auto &Path : PathsCallback(Multilib))
31       addPathIfExists(D, InstallPath + Path, Paths);
32 }
33 
34 // This function tests whether a gcc installation is present either
35 // through gcc-toolchain argument or in the same prefix where clang
36 // is installed. This helps decide whether to instantiate this toolchain
37 // or Baremetal toolchain.
38 bool RISCVToolChain::hasGCCToolchain(const Driver &D,
39                                      const llvm::opt::ArgList &Args) {
40   if (Args.getLastArg(options::OPT_gcc_toolchain))
41     return true;
42 
43   SmallString<128> GCCDir;
44   llvm::sys::path::append(GCCDir, D.Dir, "..", D.getTargetTriple(),
45                           "lib/crt0.o");
46   return llvm::sys::fs::exists(GCCDir);
47 }
48 
49 /// RISCV Toolchain
50 RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple,
51                                const ArgList &Args)
52     : Generic_ELF(D, Triple, Args) {
53   GCCInstallation.init(Triple, Args);
54   if (GCCInstallation.isValid()) {
55     Multilibs = GCCInstallation.getMultilibs();
56     SelectedMultilib = GCCInstallation.getMultilib();
57     path_list &Paths = getFilePaths();
58     // Add toolchain/multilib specific file paths.
59     addMultilibsFilePaths(D, Multilibs, SelectedMultilib,
60                           GCCInstallation.getInstallPath(), Paths);
61     getFilePaths().push_back(GCCInstallation.getInstallPath().str());
62     ToolChain::path_list &PPaths = getProgramPaths();
63     // Multilib cross-compiler GCC installations put ld in a triple-prefixed
64     // directory off of the parent of the GCC installation.
65     PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
66                            GCCInstallation.getTriple().str() + "/bin")
67                          .str());
68     PPaths.push_back((GCCInstallation.getParentLibPath() + "/../bin").str());
69   } else {
70     getProgramPaths().push_back(D.Dir);
71   }
72   getFilePaths().push_back(computeSysRoot() + "/lib");
73 }
74 
75 Tool *RISCVToolChain::buildLinker() const {
76   return new tools::RISCV::Linker(*this);
77 }
78 
79 ToolChain::RuntimeLibType RISCVToolChain::GetDefaultRuntimeLibType() const {
80   return GCCInstallation.isValid() ?
81     ToolChain::RLT_Libgcc : ToolChain::RLT_CompilerRT;
82 }
83 
84 ToolChain::UnwindLibType
85 RISCVToolChain::GetUnwindLibType(const llvm::opt::ArgList &Args) const {
86   return ToolChain::UNW_None;
87 }
88 
89 void RISCVToolChain::addClangTargetOptions(
90     const llvm::opt::ArgList &DriverArgs,
91     llvm::opt::ArgStringList &CC1Args,
92     Action::OffloadKind) const {
93   CC1Args.push_back("-nostdsysteminc");
94 }
95 
96 void RISCVToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
97                                                ArgStringList &CC1Args) const {
98   if (DriverArgs.hasArg(options::OPT_nostdinc))
99     return;
100 
101   if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) {
102     SmallString<128> Dir(computeSysRoot());
103     llvm::sys::path::append(Dir, "include");
104     addSystemInclude(DriverArgs, CC1Args, Dir.str());
105   }
106 }
107 
108 void RISCVToolChain::addLibStdCxxIncludePaths(
109     const llvm::opt::ArgList &DriverArgs,
110     llvm::opt::ArgStringList &CC1Args) const {
111   const GCCVersion &Version = GCCInstallation.getVersion();
112   StringRef TripleStr = GCCInstallation.getTriple().str();
113   const Multilib &Multilib = GCCInstallation.getMultilib();
114   addLibStdCXXIncludePaths(computeSysRoot() + "/include/c++/" + Version.Text,
115                            TripleStr, Multilib.includeSuffix(), DriverArgs,
116                            CC1Args);
117 }
118 
119 std::string RISCVToolChain::computeSysRoot() const {
120   if (!getDriver().SysRoot.empty())
121     return getDriver().SysRoot;
122 
123   SmallString<128> SysRootDir;
124   if (GCCInstallation.isValid()) {
125     StringRef LibDir = GCCInstallation.getParentLibPath();
126     StringRef TripleStr = GCCInstallation.getTriple().str();
127     llvm::sys::path::append(SysRootDir, LibDir, "..", TripleStr);
128   } else {
129     // Use the triple as provided to the driver. Unlike the parsed triple
130     // this has not been normalized to always contain every field.
131     llvm::sys::path::append(SysRootDir, getDriver().Dir, "..",
132                             getDriver().getTargetTriple());
133   }
134 
135   if (!llvm::sys::fs::exists(SysRootDir))
136     return std::string();
137 
138   return std::string(SysRootDir.str());
139 }
140 
141 void RISCV::Linker::ConstructJob(Compilation &C, const JobAction &JA,
142                                  const InputInfo &Output,
143                                  const InputInfoList &Inputs,
144                                  const ArgList &Args,
145                                  const char *LinkingOutput) const {
146   const ToolChain &ToolChain = getToolChain();
147   const Driver &D = ToolChain.getDriver();
148   ArgStringList CmdArgs;
149 
150   if (!D.SysRoot.empty())
151     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
152 
153   bool IsRV64 = ToolChain.getArch() == llvm::Triple::riscv64;
154   CmdArgs.push_back("-m");
155   if (IsRV64) {
156     CmdArgs.push_back("elf64lriscv");
157   } else {
158     CmdArgs.push_back("elf32lriscv");
159   }
160 
161   std::string Linker = getToolChain().GetLinkerPath();
162 
163   bool WantCRTs =
164       !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
165 
166   const char *crtbegin, *crtend;
167   auto RuntimeLib = ToolChain.GetRuntimeLibType(Args);
168   if (RuntimeLib == ToolChain::RLT_Libgcc) {
169     crtbegin = "crtbegin.o";
170     crtend = "crtend.o";
171   } else {
172     assert (RuntimeLib == ToolChain::RLT_CompilerRT);
173     crtbegin = ToolChain.getCompilerRTArgString(Args, "crtbegin",
174                                                 ToolChain::FT_Object);
175     crtend = ToolChain.getCompilerRTArgString(Args, "crtend",
176                                               ToolChain::FT_Object);
177   }
178 
179   if (WantCRTs) {
180     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
181     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
182   }
183 
184   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
185 
186   Args.AddAllArgs(CmdArgs, options::OPT_L);
187   Args.AddAllArgs(CmdArgs, options::OPT_u);
188   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
189   Args.AddAllArgs(CmdArgs,
190                   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
191                    options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
192 
193   // TODO: add C++ includes and libs if compiling C++.
194 
195   if (!Args.hasArg(options::OPT_nostdlib) &&
196       !Args.hasArg(options::OPT_nodefaultlibs)) {
197     if (ToolChain.ShouldLinkCXXStdlib(Args))
198       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
199     CmdArgs.push_back("--start-group");
200     CmdArgs.push_back("-lc");
201     CmdArgs.push_back("-lgloss");
202     CmdArgs.push_back("--end-group");
203     AddRunTimeLibs(ToolChain, ToolChain.getDriver(), CmdArgs, Args);
204   }
205 
206   if (WantCRTs)
207     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
208 
209   CmdArgs.push_back("-o");
210   CmdArgs.push_back(Output.getFilename());
211   C.addCommand(std::make_unique<Command>(
212       JA, *this, ResponseFileSupport::AtFileCurCP(), Args.MakeArgString(Linker),
213       CmdArgs, Inputs, Output));
214 }
215 // RISCV tools end.
216