blob: e0810de9cdca2af5c8ac834d79ca4a74d043e2fa [file] [log] [blame]
Yaxun Liuf6144222018-05-30 00:53:50 +00001//===--- HIP.cpp - HIP Tool and ToolChain Implementations -------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Yaxun Liuf6144222018-05-30 00:53:50 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "HIP.h"
10#include "CommonArgs.h"
11#include "InputInfo.h"
12#include "clang/Basic/Cuda.h"
13#include "clang/Driver/Compilation.h"
14#include "clang/Driver/Driver.h"
15#include "clang/Driver/DriverDiagnostic.h"
16#include "clang/Driver/Options.h"
17#include "llvm/Support/FileSystem.h"
18#include "llvm/Support/Path.h"
19
20using namespace clang::driver;
21using namespace clang::driver::toolchains;
22using namespace clang::driver::tools;
23using namespace clang;
24using namespace llvm::opt;
25
Yaxun Liu4fa83fc2019-01-10 20:09:52 +000026#if _WIN32 || _WIN64
27#define NULL_FILE "nul"
28#else
29#define NULL_FILE "/dev/null"
30#endif
31
Yaxun Liuf6144222018-05-30 00:53:50 +000032namespace {
33
34static void addBCLib(Compilation &C, const ArgList &Args,
35 ArgStringList &CmdArgs, ArgStringList LibraryPaths,
36 StringRef BCName) {
37 StringRef FullName;
38 for (std::string LibraryPath : LibraryPaths) {
39 SmallString<128> Path(LibraryPath);
40 llvm::sys::path::append(Path, BCName);
41 FullName = Path;
42 if (llvm::sys::fs::exists(FullName)) {
43 CmdArgs.push_back(Args.MakeArgString(FullName));
44 return;
45 }
46 }
47 C.getDriver().Diag(diag::err_drv_no_such_file) << BCName;
48}
49
50} // namespace
51
52const char *AMDGCN::Linker::constructLLVMLinkCommand(
53 Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
54 const ArgList &Args, StringRef SubArchName,
55 StringRef OutputFilePrefix) const {
56 ArgStringList CmdArgs;
57 // Add the input bc's created by compile step.
58 for (const auto &II : Inputs)
59 CmdArgs.push_back(II.getFilename());
60
61 ArgStringList LibraryPaths;
62
63 // Find in --hip-device-lib-path and HIP_LIBRARY_PATH.
64 for (auto Path : Args.getAllArgValues(options::OPT_hip_device_lib_path_EQ))
65 LibraryPaths.push_back(Args.MakeArgString(Path));
66
67 addDirectoryList(Args, LibraryPaths, "-L", "HIP_DEVICE_LIB_PATH");
68
69 llvm::SmallVector<std::string, 10> BCLibs;
70
71 // Add bitcode library in --hip-device-lib.
72 for (auto Lib : Args.getAllArgValues(options::OPT_hip_device_lib_EQ)) {
73 BCLibs.push_back(Args.MakeArgString(Lib));
74 }
75
76 // If --hip-device-lib is not set, add the default bitcode libraries.
77 if (BCLibs.empty()) {
78 // Get the bc lib file name for ISA version. For example,
79 // gfx803 => oclc_isa_version_803.amdgcn.bc.
80 std::string ISAVerBC =
81 "oclc_isa_version_" + SubArchName.drop_front(3).str() + ".amdgcn.bc";
82
Aaron Enye Shidfb1bf02018-06-27 18:58:55 +000083 llvm::StringRef FlushDenormalControlBC;
84 if (Args.hasArg(options::OPT_fcuda_flush_denormals_to_zero))
85 FlushDenormalControlBC = "oclc_daz_opt_on.amdgcn.bc";
86 else
87 FlushDenormalControlBC = "oclc_daz_opt_off.amdgcn.bc";
88
Aaron Enye Shie1a353a2018-10-11 19:41:54 +000089 BCLibs.append({"hip.amdgcn.bc", "opencl.amdgcn.bc",
90 "ocml.amdgcn.bc", "ockl.amdgcn.bc",
Yaxun Liuf6144222018-05-30 00:53:50 +000091 "oclc_finite_only_off.amdgcn.bc",
Aaron Enye Shidfb1bf02018-06-27 18:58:55 +000092 FlushDenormalControlBC,
Yaxun Liuf6144222018-05-30 00:53:50 +000093 "oclc_correctly_rounded_sqrt_on.amdgcn.bc",
Aaron Enye Shi5c200be2018-06-26 17:40:36 +000094 "oclc_unsafe_math_off.amdgcn.bc", ISAVerBC});
Yaxun Liuf6144222018-05-30 00:53:50 +000095 }
96 for (auto Lib : BCLibs)
97 addBCLib(C, Args, CmdArgs, LibraryPaths, Lib);
98
99 // Add an intermediate output file.
100 CmdArgs.push_back("-o");
101 std::string TmpName =
102 C.getDriver().GetTemporaryPath(OutputFilePrefix.str() + "-linked", "bc");
103 const char *OutputFileName =
104 C.addTempFile(C.getArgs().MakeArgString(TmpName));
105 CmdArgs.push_back(OutputFileName);
106 SmallString<128> ExecPath(C.getDriver().Dir);
107 llvm::sys::path::append(ExecPath, "llvm-link");
108 const char *Exec = Args.MakeArgString(ExecPath);
109 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
110 return OutputFileName;
111}
112
113const char *AMDGCN::Linker::constructOptCommand(
114 Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
115 const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
116 llvm::StringRef OutputFilePrefix, const char *InputFileName) const {
117 // Construct opt command.
118 ArgStringList OptArgs;
119 // The input to opt is the output from llvm-link.
120 OptArgs.push_back(InputFileName);
121 // Pass optimization arg to opt.
122 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
123 StringRef OOpt = "3";
124 if (A->getOption().matches(options::OPT_O4) ||
125 A->getOption().matches(options::OPT_Ofast))
126 OOpt = "3";
127 else if (A->getOption().matches(options::OPT_O0))
128 OOpt = "0";
129 else if (A->getOption().matches(options::OPT_O)) {
130 // -Os, -Oz, and -O(anything else) map to -O2
131 OOpt = llvm::StringSwitch<const char *>(A->getValue())
132 .Case("1", "1")
133 .Case("2", "2")
134 .Case("3", "3")
135 .Case("s", "2")
136 .Case("z", "2")
137 .Default("2");
138 }
139 OptArgs.push_back(Args.MakeArgString("-O" + OOpt));
140 }
141 OptArgs.push_back("-mtriple=amdgcn-amd-amdhsa");
142 OptArgs.push_back(Args.MakeArgString("-mcpu=" + SubArchName));
143 OptArgs.push_back("-o");
144 std::string TmpFileName = C.getDriver().GetTemporaryPath(
145 OutputFilePrefix.str() + "-optimized", "bc");
146 const char *OutputFileName =
147 C.addTempFile(C.getArgs().MakeArgString(TmpFileName));
148 OptArgs.push_back(OutputFileName);
149 SmallString<128> OptPath(C.getDriver().Dir);
150 llvm::sys::path::append(OptPath, "opt");
151 const char *OptExec = Args.MakeArgString(OptPath);
152 C.addCommand(llvm::make_unique<Command>(JA, *this, OptExec, OptArgs, Inputs));
153 return OutputFileName;
154}
155
156const char *AMDGCN::Linker::constructLlcCommand(
157 Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
158 const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
159 llvm::StringRef OutputFilePrefix, const char *InputFileName) const {
160 // Construct llc command.
161 ArgStringList LlcArgs{InputFileName, "-mtriple=amdgcn-amd-amdhsa",
Aaron Enye Shi7084b562019-02-13 16:12:16 +0000162 "-filetype=obj",
163 Args.MakeArgString("-mcpu=" + SubArchName)};
164
165 // Extract all the -m options
166 std::vector<llvm::StringRef> Features;
167 handleTargetFeaturesGroup(
168 Args, Features, options::OPT_m_amdgpu_Features_Group);
169
170 // Add features to mattr such as code-object-v3 and xnack
171 std::string MAttrString = "-mattr=";
172 for(auto OneFeature : Features) {
173 MAttrString.append(Args.MakeArgString(OneFeature));
174 if (OneFeature != Features.back())
175 MAttrString.append(",");
176 }
177 if(!Features.empty())
178 LlcArgs.push_back(Args.MakeArgString(MAttrString));
179
180 // Add output filename
181 LlcArgs.push_back("-o");
Yaxun Liuf6144222018-05-30 00:53:50 +0000182 std::string LlcOutputFileName =
183 C.getDriver().GetTemporaryPath(OutputFilePrefix, "o");
184 const char *LlcOutputFile =
185 C.addTempFile(C.getArgs().MakeArgString(LlcOutputFileName));
186 LlcArgs.push_back(LlcOutputFile);
187 SmallString<128> LlcPath(C.getDriver().Dir);
188 llvm::sys::path::append(LlcPath, "llc");
189 const char *Llc = Args.MakeArgString(LlcPath);
190 C.addCommand(llvm::make_unique<Command>(JA, *this, Llc, LlcArgs, Inputs));
191 return LlcOutputFile;
192}
193
194void AMDGCN::Linker::constructLldCommand(Compilation &C, const JobAction &JA,
195 const InputInfoList &Inputs,
196 const InputInfo &Output,
197 const llvm::opt::ArgList &Args,
198 const char *InputFileName) const {
199 // Construct lld command.
200 // The output from ld.lld is an HSA code object file.
201 ArgStringList LldArgs{"-flavor", "gnu", "--no-undefined",
202 "-shared", "-o", Output.getFilename(),
203 InputFileName};
204 SmallString<128> LldPath(C.getDriver().Dir);
205 llvm::sys::path::append(LldPath, "lld");
206 const char *Lld = Args.MakeArgString(LldPath);
207 C.addCommand(llvm::make_unique<Command>(JA, *this, Lld, LldArgs, Inputs));
208}
209
Yaxun Liu97670892018-10-02 17:48:54 +0000210// Construct a clang-offload-bundler command to bundle code objects for
211// different GPU's into a HIP fat binary.
212void AMDGCN::constructHIPFatbinCommand(Compilation &C, const JobAction &JA,
213 StringRef OutputFileName, const InputInfoList &Inputs,
214 const llvm::opt::ArgList &Args, const Tool& T) {
215 // Construct clang-offload-bundler command to bundle object files for
216 // for different GPU archs.
217 ArgStringList BundlerArgs;
218 BundlerArgs.push_back(Args.MakeArgString("-type=o"));
219
220 // ToDo: Remove the dummy host binary entry which is required by
221 // clang-offload-bundler.
222 std::string BundlerTargetArg = "-targets=host-x86_64-unknown-linux";
Yaxun Liu4fa83fc2019-01-10 20:09:52 +0000223 std::string BundlerInputArg = "-inputs=" NULL_FILE;
Yaxun Liu97670892018-10-02 17:48:54 +0000224
225 for (const auto &II : Inputs) {
226 const auto* A = II.getAction();
227 BundlerTargetArg = BundlerTargetArg + ",hip-amdgcn-amd-amdhsa-" +
228 StringRef(A->getOffloadingArch()).str();
229 BundlerInputArg = BundlerInputArg + "," + II.getFilename();
230 }
231 BundlerArgs.push_back(Args.MakeArgString(BundlerTargetArg));
232 BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
233
234 auto BundlerOutputArg =
235 Args.MakeArgString(std::string("-outputs=").append(OutputFileName));
236 BundlerArgs.push_back(BundlerOutputArg);
237
238 SmallString<128> BundlerPath(C.getDriver().Dir);
239 llvm::sys::path::append(BundlerPath, "clang-offload-bundler");
240 const char *Bundler = Args.MakeArgString(BundlerPath);
241 C.addCommand(llvm::make_unique<Command>(JA, T, Bundler, BundlerArgs, Inputs));
242}
243
Yaxun Liuf6144222018-05-30 00:53:50 +0000244// For amdgcn the inputs of the linker job are device bitcode and output is
245// object file. It calls llvm-link, opt, llc, then lld steps.
246void AMDGCN::Linker::ConstructJob(Compilation &C, const JobAction &JA,
247 const InputInfo &Output,
248 const InputInfoList &Inputs,
249 const ArgList &Args,
250 const char *LinkingOutput) const {
251
Yaxun Liu97670892018-10-02 17:48:54 +0000252 if (JA.getType() == types::TY_HIP_FATBIN)
253 return constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs, Args, *this);
254
Sam McCall43fdd222018-05-30 08:03:43 +0000255 assert(getToolChain().getTriple().getArch() == llvm::Triple::amdgcn &&
Yaxun Liuf6144222018-05-30 00:53:50 +0000256 "Unsupported target");
257
258 std::string SubArchName = JA.getOffloadingArch();
259 assert(StringRef(SubArchName).startswith("gfx") && "Unsupported sub arch");
260
261 // Prefix for temporary file name.
262 std::string Prefix =
263 llvm::sys::path::stem(Inputs[0].getFilename()).str() + "-" + SubArchName;
264
265 // Each command outputs different files.
266 const char *LLVMLinkCommand =
267 constructLLVMLinkCommand(C, JA, Inputs, Args, SubArchName, Prefix);
268 const char *OptCommand = constructOptCommand(C, JA, Inputs, Args, SubArchName,
269 Prefix, LLVMLinkCommand);
270 const char *LlcCommand =
271 constructLlcCommand(C, JA, Inputs, Args, SubArchName, Prefix, OptCommand);
272 constructLldCommand(C, JA, Inputs, Output, Args, LlcCommand);
273}
274
275HIPToolChain::HIPToolChain(const Driver &D, const llvm::Triple &Triple,
276 const ToolChain &HostTC, const ArgList &Args)
277 : ToolChain(D, Triple, Args), HostTC(HostTC) {
278 // Lookup binaries into the driver directory, this is used to
279 // discover the clang-offload-bundler executable.
280 getProgramPaths().push_back(getDriver().Dir);
281}
282
283void HIPToolChain::addClangTargetOptions(
284 const llvm::opt::ArgList &DriverArgs,
285 llvm::opt::ArgStringList &CC1Args,
286 Action::OffloadKind DeviceOffloadingKind) const {
287 HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
288
289 StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
290 assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
Sam McCall43fdd222018-05-30 08:03:43 +0000291 (void) GpuArch;
Yaxun Liuf6144222018-05-30 00:53:50 +0000292 assert(DeviceOffloadingKind == Action::OFK_HIP &&
293 "Only HIP offloading kinds are supported for GPUs.");
294
Yaxun Liu6c3a74e2018-07-24 01:40:44 +0000295 CC1Args.push_back("-target-cpu");
296 CC1Args.push_back(DriverArgs.MakeArgStringRef(GpuArch));
Yaxun Liuf6144222018-05-30 00:53:50 +0000297 CC1Args.push_back("-fcuda-is-device");
298
299 if (DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
300 options::OPT_fno_cuda_flush_denormals_to_zero, false))
301 CC1Args.push_back("-fcuda-flush-denormals-to-zero");
302
303 if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
304 options::OPT_fno_cuda_approx_transcendentals, false))
305 CC1Args.push_back("-fcuda-approx-transcendentals");
306
Yaxun Liu97670892018-10-02 17:48:54 +0000307 if (DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
Yaxun Liuf6144222018-05-30 00:53:50 +0000308 false))
Yaxun Liu97670892018-10-02 17:48:54 +0000309 CC1Args.push_back("-fgpu-rdc");
Yaxun Liu5e98c2b2018-08-30 15:10:20 +0000310
311 // Default to "hidden" visibility, as object level linking will not be
312 // supported for the foreseeable future.
313 if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
Scott Linderbef26632019-01-28 17:12:19 +0000314 options::OPT_fvisibility_ms_compat)) {
Yaxun Liu5e98c2b2018-08-30 15:10:20 +0000315 CC1Args.append({"-fvisibility", "hidden"});
Scott Linderbef26632019-01-28 17:12:19 +0000316 CC1Args.push_back("-fapply-global-visibility-to-externs");
317 }
Yaxun Liuf6144222018-05-30 00:53:50 +0000318}
319
320llvm::opt::DerivedArgList *
321HIPToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
322 StringRef BoundArch,
323 Action::OffloadKind DeviceOffloadKind) const {
324 DerivedArgList *DAL =
325 HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
326 if (!DAL)
327 DAL = new DerivedArgList(Args.getBaseArgs());
328
329 const OptTable &Opts = getDriver().getOpts();
330
331 for (Arg *A : Args) {
332 if (A->getOption().matches(options::OPT_Xarch__)) {
Aaron Enye Shi4928d512018-06-26 17:12:29 +0000333 // Skip this argument unless the architecture matches BoundArch.
Yaxun Liuf6144222018-05-30 00:53:50 +0000334 if (BoundArch.empty() || A->getValue(0) != BoundArch)
335 continue;
336
337 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
338 unsigned Prev = Index;
339 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
340
341 // If the argument parsing failed or more than one argument was
342 // consumed, the -Xarch_ argument's parameter tried to consume
343 // extra arguments. Emit an error and ignore.
344 //
345 // We also want to disallow any options which would alter the
346 // driver behavior; that isn't going to work in our model. We
347 // use isDriverOption() as an approximation, although things
348 // like -O4 are going to slip through.
349 if (!XarchArg || Index > Prev + 1) {
350 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
351 << A->getAsString(Args);
352 continue;
353 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
354 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
355 << A->getAsString(Args);
356 continue;
357 }
358 XarchArg->setBaseArg(A);
359 A = XarchArg.release();
360 DAL->AddSynthesizedArg(A);
361 }
362 DAL->append(A);
363 }
364
365 if (!BoundArch.empty()) {
366 DAL->eraseArg(options::OPT_march_EQ);
367 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
368 }
369
370 return DAL;
371}
372
373Tool *HIPToolChain::buildLinker() const {
374 assert(getTriple().getArch() == llvm::Triple::amdgcn);
375 return new tools::AMDGCN::Linker(*this);
376}
377
378void HIPToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
379 HostTC.addClangWarningOptions(CC1Args);
380}
381
382ToolChain::CXXStdlibType
383HIPToolChain::GetCXXStdlibType(const ArgList &Args) const {
384 return HostTC.GetCXXStdlibType(Args);
385}
386
387void HIPToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
388 ArgStringList &CC1Args) const {
389 HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
390}
391
392void HIPToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
393 ArgStringList &CC1Args) const {
394 HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
395}
396
397void HIPToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
398 ArgStringList &CC1Args) const {
399 HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
400}
401
402SanitizerMask HIPToolChain::getSupportedSanitizers() const {
403 // The HIPToolChain only supports sanitizers in the sense that it allows
404 // sanitizer arguments on the command line if they are supported by the host
405 // toolchain. The HIPToolChain will actually ignore any command line
406 // arguments for any of these "supported" sanitizers. That means that no
407 // sanitization of device code is actually supported at this time.
408 //
409 // This behavior is necessary because the host and device toolchains
410 // invocations often share the command line, so the device toolchain must
411 // tolerate flags meant only for the host toolchain.
412 return HostTC.getSupportedSanitizers();
413}
414
415VersionTuple HIPToolChain::computeMSVCVersion(const Driver *D,
416 const ArgList &Args) const {
417 return HostTC.computeMSVCVersion(D, Args);
418}