]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Driver/ToolChains/HIP.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Driver / ToolChains / HIP.cpp
1 //===--- HIP.cpp - HIP Tool and 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 "HIP.h"
10 #include "AMDGPU.h"
11 #include "CommonArgs.h"
12 #include "InputInfo.h"
13 #include "clang/Basic/Cuda.h"
14 #include "clang/Driver/Compilation.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/Options.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/TargetParser.h"
21
22 using namespace clang::driver;
23 using namespace clang::driver::toolchains;
24 using namespace clang::driver::tools;
25 using namespace clang;
26 using namespace llvm::opt;
27
28 #if defined(_WIN32) || defined(_WIN64)
29 #define NULL_FILE "nul"
30 #else
31 #define NULL_FILE "/dev/null"
32 #endif
33
34 namespace {
35
36 static void addBCLib(const Driver &D, const ArgList &Args,
37                      ArgStringList &CmdArgs, ArgStringList LibraryPaths,
38                      StringRef BCName) {
39   StringRef FullName;
40   for (std::string LibraryPath : LibraryPaths) {
41     SmallString<128> Path(LibraryPath);
42     llvm::sys::path::append(Path, BCName);
43     FullName = Path;
44     if (llvm::sys::fs::exists(FullName)) {
45       CmdArgs.push_back("-mlink-builtin-bitcode");
46       CmdArgs.push_back(Args.MakeArgString(FullName));
47       return;
48     }
49   }
50   D.Diag(diag::err_drv_no_such_file) << BCName;
51 }
52 } // namespace
53
54 void AMDGCN::Linker::constructLldCommand(Compilation &C, const JobAction &JA,
55                                           const InputInfoList &Inputs,
56                                           const InputInfo &Output,
57                                           const llvm::opt::ArgList &Args) const {
58   // Construct lld command.
59   // The output from ld.lld is an HSA code object file.
60   ArgStringList LldArgs{"-flavor", "gnu", "--no-undefined", "-shared",
61                         "-plugin-opt=-amdgpu-internalize-symbols"};
62
63   auto &TC = getToolChain();
64   auto &D = TC.getDriver();
65   assert(!Inputs.empty() && "Must have at least one input.");
66   addLTOOptions(TC, Args, LldArgs, Output, Inputs[0],
67                 D.getLTOMode() == LTOK_Thin);
68
69   // Extract all the -m options
70   std::vector<llvm::StringRef> Features;
71   amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
72
73   // Add features to mattr such as cumode
74   std::string MAttrString = "-plugin-opt=-mattr=";
75   for (auto OneFeature : unifyTargetFeatures(Features)) {
76     MAttrString.append(Args.MakeArgString(OneFeature));
77     if (OneFeature != Features.back())
78       MAttrString.append(",");
79   }
80   if (!Features.empty())
81     LldArgs.push_back(Args.MakeArgString(MAttrString));
82
83   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
84     LldArgs.push_back(
85         Args.MakeArgString(Twine("-plugin-opt=") + A->getValue(0)));
86   }
87
88   if (C.getDriver().isSaveTempsEnabled())
89     LldArgs.push_back("-save-temps");
90
91   LldArgs.append({"-o", Output.getFilename()});
92   for (auto Input : Inputs)
93     LldArgs.push_back(Input.getFilename());
94   const char *Lld = Args.MakeArgString(getToolChain().GetProgramPath("lld"));
95   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
96                                          Lld, LldArgs, Inputs));
97 }
98
99 // Construct a clang-offload-bundler command to bundle code objects for
100 // different GPU's into a HIP fat binary.
101 void AMDGCN::constructHIPFatbinCommand(Compilation &C, const JobAction &JA,
102                   StringRef OutputFileName, const InputInfoList &Inputs,
103                   const llvm::opt::ArgList &Args, const Tool& T) {
104   // Construct clang-offload-bundler command to bundle object files for
105   // for different GPU archs.
106   ArgStringList BundlerArgs;
107   BundlerArgs.push_back(Args.MakeArgString("-type=o"));
108
109   // ToDo: Remove the dummy host binary entry which is required by
110   // clang-offload-bundler.
111   std::string BundlerTargetArg = "-targets=host-x86_64-unknown-linux";
112   std::string BundlerInputArg = "-inputs=" NULL_FILE;
113
114   for (const auto &II : Inputs) {
115     const auto* A = II.getAction();
116     BundlerTargetArg = BundlerTargetArg + ",hip-amdgcn-amd-amdhsa-" +
117                        StringRef(A->getOffloadingArch()).str();
118     BundlerInputArg = BundlerInputArg + "," + II.getFilename();
119   }
120   BundlerArgs.push_back(Args.MakeArgString(BundlerTargetArg));
121   BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
122
123   auto BundlerOutputArg = Args.MakeArgString(
124       std::string("-outputs=").append(std::string(OutputFileName)));
125   BundlerArgs.push_back(BundlerOutputArg);
126
127   const char *Bundler = Args.MakeArgString(
128       T.getToolChain().GetProgramPath("clang-offload-bundler"));
129   C.addCommand(std::make_unique<Command>(JA, T, ResponseFileSupport::None(),
130                                          Bundler, BundlerArgs, Inputs));
131 }
132
133 /// Add Generated HIP Object File which has device images embedded into the
134 /// host to the argument list for linking. Using MC directives, embed the
135 /// device code and also define symbols required by the code generation so that
136 /// the image can be retrieved at runtime.
137 void AMDGCN::Linker::constructGenerateObjFileFromHIPFatBinary(
138     Compilation &C, const InputInfo &Output,
139     const InputInfoList &Inputs, const ArgList &Args,
140     const JobAction &JA) const {
141   const ToolChain &TC = getToolChain();
142   std::string Name =
143       std::string(llvm::sys::path::stem(Output.getFilename()));
144
145   // Create Temp Object File Generator,
146   // Offload Bundled file and Bundled Object file.
147   // Keep them if save-temps is enabled.
148   const char *McinFile;
149   const char *BundleFile;
150   if (C.getDriver().isSaveTempsEnabled()) {
151     McinFile = C.getArgs().MakeArgString(Name + ".mcin");
152     BundleFile = C.getArgs().MakeArgString(Name + ".hipfb");
153   } else {
154     auto TmpNameMcin = C.getDriver().GetTemporaryPath(Name, "mcin");
155     McinFile = C.addTempFile(C.getArgs().MakeArgString(TmpNameMcin));
156     auto TmpNameFb = C.getDriver().GetTemporaryPath(Name, "hipfb");
157     BundleFile = C.addTempFile(C.getArgs().MakeArgString(TmpNameFb));
158   }
159   constructHIPFatbinCommand(C, JA, BundleFile, Inputs, Args, *this);
160
161   // Create a buffer to write the contents of the temp obj generator.
162   std::string ObjBuffer;
163   llvm::raw_string_ostream ObjStream(ObjBuffer);
164
165   // Add MC directives to embed target binaries. We ensure that each
166   // section and image is 16-byte aligned. This is not mandatory, but
167   // increases the likelihood of data to be aligned with a cache block
168   // in several main host machines.
169   ObjStream << "#       HIP Object Generator\n";
170   ObjStream << "# *** Automatically generated by Clang ***\n";
171   ObjStream << "  .type __hip_fatbin,@object\n";
172   ObjStream << "  .section .hip_fatbin,\"aMS\",@progbits,1\n";
173   ObjStream << "  .data\n";
174   ObjStream << "  .globl __hip_fatbin\n";
175   ObjStream << "  .p2align 3\n";
176   ObjStream << "__hip_fatbin:\n";
177   ObjStream << "  .incbin \"" << BundleFile << "\"\n";
178   ObjStream.flush();
179
180   // Dump the contents of the temp object file gen if the user requested that.
181   // We support this option to enable testing of behavior with -###.
182   if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
183     llvm::errs() << ObjBuffer;
184
185   // Open script file and write the contents.
186   std::error_code EC;
187   llvm::raw_fd_ostream Objf(McinFile, EC, llvm::sys::fs::OF_None);
188
189   if (EC) {
190     C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
191     return;
192   }
193
194   Objf << ObjBuffer;
195
196   ArgStringList McArgs{"-o",      Output.getFilename(),
197                        McinFile,  "--filetype=obj"};
198   const char *Mc = Args.MakeArgString(TC.GetProgramPath("llvm-mc"));
199   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
200                                          Mc, McArgs, Inputs));
201 }
202
203 // For amdgcn the inputs of the linker job are device bitcode and output is
204 // object file. It calls llvm-link, opt, llc, then lld steps.
205 void AMDGCN::Linker::ConstructJob(Compilation &C, const JobAction &JA,
206                                    const InputInfo &Output,
207                                    const InputInfoList &Inputs,
208                                    const ArgList &Args,
209                                    const char *LinkingOutput) const {
210   if (Inputs.size() > 0 &&
211       Inputs[0].getType() == types::TY_Image &&
212       JA.getType() == types::TY_Object)
213     return constructGenerateObjFileFromHIPFatBinary(C, Output, Inputs, Args, JA);
214
215   if (JA.getType() == types::TY_HIP_FATBIN)
216     return constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs, Args, *this);
217
218   return constructLldCommand(C, JA, Inputs, Output, Args);
219 }
220
221 HIPToolChain::HIPToolChain(const Driver &D, const llvm::Triple &Triple,
222                              const ToolChain &HostTC, const ArgList &Args)
223     : ROCMToolChain(D, Triple, Args), HostTC(HostTC) {
224   // Lookup binaries into the driver directory, this is used to
225   // discover the clang-offload-bundler executable.
226   getProgramPaths().push_back(getDriver().Dir);
227 }
228
229 void HIPToolChain::addClangTargetOptions(
230     const llvm::opt::ArgList &DriverArgs,
231     llvm::opt::ArgStringList &CC1Args,
232     Action::OffloadKind DeviceOffloadingKind) const {
233   HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
234
235   StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ);
236   assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
237   (void) GpuArch;
238   assert(DeviceOffloadingKind == Action::OFK_HIP &&
239          "Only HIP offloading kinds are supported for GPUs.");
240   auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
241   const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
242
243   CC1Args.push_back("-fcuda-is-device");
244
245   if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
246                          options::OPT_fno_cuda_approx_transcendentals, false))
247     CC1Args.push_back("-fcuda-approx-transcendentals");
248
249   if (DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
250                          false))
251     CC1Args.push_back("-fgpu-rdc");
252   else
253     CC1Args.append({"-mllvm", "-amdgpu-internalize-symbols"});
254
255   StringRef MaxThreadsPerBlock =
256       DriverArgs.getLastArgValue(options::OPT_gpu_max_threads_per_block_EQ);
257   if (!MaxThreadsPerBlock.empty()) {
258     std::string ArgStr =
259         std::string("--gpu-max-threads-per-block=") + MaxThreadsPerBlock.str();
260     CC1Args.push_back(DriverArgs.MakeArgStringRef(ArgStr));
261   }
262
263   if (DriverArgs.hasFlag(options::OPT_fgpu_allow_device_init,
264                          options::OPT_fno_gpu_allow_device_init, false))
265     CC1Args.push_back("-fgpu-allow-device-init");
266
267   CC1Args.push_back("-fcuda-allow-variadic-functions");
268
269   // Default to "hidden" visibility, as object level linking will not be
270   // supported for the foreseeable future.
271   if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
272                          options::OPT_fvisibility_ms_compat)) {
273     CC1Args.append({"-fvisibility", "hidden"});
274     CC1Args.push_back("-fapply-global-visibility-to-externs");
275   }
276
277   if (DriverArgs.hasArg(options::OPT_nogpulib))
278     return;
279   ArgStringList LibraryPaths;
280
281   // Find in --hip-device-lib-path and HIP_LIBRARY_PATH.
282   for (auto Path : RocmInstallation.getRocmDeviceLibPathArg())
283     LibraryPaths.push_back(DriverArgs.MakeArgString(Path));
284
285   addDirectoryList(DriverArgs, LibraryPaths, "", "HIP_DEVICE_LIB_PATH");
286
287   // Maintain compatability with --hip-device-lib.
288   auto BCLibs = DriverArgs.getAllArgValues(options::OPT_hip_device_lib_EQ);
289   if (!BCLibs.empty()) {
290     for (auto Lib : BCLibs)
291       addBCLib(getDriver(), DriverArgs, CC1Args, LibraryPaths, Lib);
292   } else {
293     if (!RocmInstallation.hasDeviceLibrary()) {
294       getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 0;
295       return;
296     }
297
298     std::string LibDeviceFile = RocmInstallation.getLibDeviceFile(CanonArch);
299     if (LibDeviceFile.empty()) {
300       getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 1 << GpuArch;
301       return;
302     }
303
304     // If --hip-device-lib is not set, add the default bitcode libraries.
305     // TODO: There are way too many flags that change this. Do we need to check
306     // them all?
307     bool DAZ = DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
308                                   options::OPT_fno_cuda_flush_denormals_to_zero,
309                                   getDefaultDenormsAreZeroForTarget(Kind));
310     // TODO: Check standard C++ flags?
311     bool FiniteOnly = false;
312     bool UnsafeMathOpt = false;
313     bool FastRelaxedMath = false;
314     bool CorrectSqrt = true;
315     bool Wave64 = isWave64(DriverArgs, Kind);
316
317     // Add the HIP specific bitcode library.
318     CC1Args.push_back("-mlink-builtin-bitcode");
319     CC1Args.push_back(DriverArgs.MakeArgString(RocmInstallation.getHIPPath()));
320
321     // Add the generic set of libraries.
322     RocmInstallation.addCommonBitcodeLibCC1Args(
323       DriverArgs, CC1Args, LibDeviceFile, Wave64, DAZ, FiniteOnly,
324       UnsafeMathOpt, FastRelaxedMath, CorrectSqrt);
325   }
326 }
327
328 llvm::opt::DerivedArgList *
329 HIPToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
330                              StringRef BoundArch,
331                              Action::OffloadKind DeviceOffloadKind) const {
332   DerivedArgList *DAL =
333       HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
334   if (!DAL)
335     DAL = new DerivedArgList(Args.getBaseArgs());
336
337   const OptTable &Opts = getDriver().getOpts();
338
339   for (Arg *A : Args) {
340     DAL->append(A);
341   }
342
343   if (!BoundArch.empty()) {
344     DAL->eraseArg(options::OPT_mcpu_EQ);
345     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mcpu_EQ), BoundArch);
346   }
347
348   return DAL;
349 }
350
351 Tool *HIPToolChain::buildLinker() const {
352   assert(getTriple().getArch() == llvm::Triple::amdgcn);
353   return new tools::AMDGCN::Linker(*this);
354 }
355
356 void HIPToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
357   HostTC.addClangWarningOptions(CC1Args);
358 }
359
360 ToolChain::CXXStdlibType
361 HIPToolChain::GetCXXStdlibType(const ArgList &Args) const {
362   return HostTC.GetCXXStdlibType(Args);
363 }
364
365 void HIPToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
366                                               ArgStringList &CC1Args) const {
367   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
368 }
369
370 void HIPToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
371                                                  ArgStringList &CC1Args) const {
372   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
373 }
374
375 void HIPToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
376                                         ArgStringList &CC1Args) const {
377   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
378 }
379
380 void HIPToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
381                                      ArgStringList &CC1Args) const {
382   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
383 }
384
385 SanitizerMask HIPToolChain::getSupportedSanitizers() const {
386   // The HIPToolChain only supports sanitizers in the sense that it allows
387   // sanitizer arguments on the command line if they are supported by the host
388   // toolchain. The HIPToolChain will actually ignore any command line
389   // arguments for any of these "supported" sanitizers. That means that no
390   // sanitization of device code is actually supported at this time.
391   //
392   // This behavior is necessary because the host and device toolchains
393   // invocations often share the command line, so the device toolchain must
394   // tolerate flags meant only for the host toolchain.
395   return HostTC.getSupportedSanitizers();
396 }
397
398 VersionTuple HIPToolChain::computeMSVCVersion(const Driver *D,
399                                                const ArgList &Args) const {
400   return HostTC.computeMSVCVersion(D, Args);
401 }