clang  7.0.0
HIP.cpp
Go to the documentation of this file.
1 //===--- HIP.cpp - HIP Tool and ToolChain Implementations -------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "HIP.h"
11 #include "CommonArgs.h"
12 #include "InputInfo.h"
13 #include "clang/Basic/Cuda.h"
15 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/Options.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Path.h"
20 
21 using namespace clang::driver;
22 using namespace clang::driver::toolchains;
23 using namespace clang::driver::tools;
24 using namespace clang;
25 using namespace llvm::opt;
26 
27 namespace {
28 
29 static void addBCLib(Compilation &C, const ArgList &Args,
30  ArgStringList &CmdArgs, ArgStringList LibraryPaths,
31  StringRef BCName) {
32  StringRef FullName;
33  for (std::string LibraryPath : LibraryPaths) {
34  SmallString<128> Path(LibraryPath);
35  llvm::sys::path::append(Path, BCName);
36  FullName = Path;
37  if (llvm::sys::fs::exists(FullName)) {
38  CmdArgs.push_back(Args.MakeArgString(FullName));
39  return;
40  }
41  }
42  C.getDriver().Diag(diag::err_drv_no_such_file) << BCName;
43 }
44 
45 } // namespace
46 
47 const char *AMDGCN::Linker::constructLLVMLinkCommand(
48  Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
49  const ArgList &Args, StringRef SubArchName,
50  StringRef OutputFilePrefix) const {
51  ArgStringList CmdArgs;
52  // Add the input bc's created by compile step.
53  for (const auto &II : Inputs)
54  CmdArgs.push_back(II.getFilename());
55 
56  ArgStringList LibraryPaths;
57 
58  // Find in --hip-device-lib-path and HIP_LIBRARY_PATH.
59  for (auto Path : Args.getAllArgValues(options::OPT_hip_device_lib_path_EQ))
60  LibraryPaths.push_back(Args.MakeArgString(Path));
61 
62  addDirectoryList(Args, LibraryPaths, "-L", "HIP_DEVICE_LIB_PATH");
63 
65 
66  // Add bitcode library in --hip-device-lib.
67  for (auto Lib : Args.getAllArgValues(options::OPT_hip_device_lib_EQ)) {
68  BCLibs.push_back(Args.MakeArgString(Lib));
69  }
70 
71  // If --hip-device-lib is not set, add the default bitcode libraries.
72  if (BCLibs.empty()) {
73  // Get the bc lib file name for ISA version. For example,
74  // gfx803 => oclc_isa_version_803.amdgcn.bc.
75  std::string ISAVerBC =
76  "oclc_isa_version_" + SubArchName.drop_front(3).str() + ".amdgcn.bc";
77 
78  llvm::StringRef FlushDenormalControlBC;
79  if (Args.hasArg(options::OPT_fcuda_flush_denormals_to_zero))
80  FlushDenormalControlBC = "oclc_daz_opt_on.amdgcn.bc";
81  else
82  FlushDenormalControlBC = "oclc_daz_opt_off.amdgcn.bc";
83 
84  BCLibs.append({"opencl.amdgcn.bc",
85  "ocml.amdgcn.bc", "ockl.amdgcn.bc", "irif.amdgcn.bc",
86  "oclc_finite_only_off.amdgcn.bc",
87  FlushDenormalControlBC,
88  "oclc_correctly_rounded_sqrt_on.amdgcn.bc",
89  "oclc_unsafe_math_off.amdgcn.bc", ISAVerBC});
90  }
91  for (auto Lib : BCLibs)
92  addBCLib(C, Args, CmdArgs, LibraryPaths, Lib);
93 
94  // Add an intermediate output file.
95  CmdArgs.push_back("-o");
96  std::string TmpName =
97  C.getDriver().GetTemporaryPath(OutputFilePrefix.str() + "-linked", "bc");
98  const char *OutputFileName =
99  C.addTempFile(C.getArgs().MakeArgString(TmpName));
100  CmdArgs.push_back(OutputFileName);
101  SmallString<128> ExecPath(C.getDriver().Dir);
102  llvm::sys::path::append(ExecPath, "llvm-link");
103  const char *Exec = Args.MakeArgString(ExecPath);
104  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
105  return OutputFileName;
106 }
107 
108 const char *AMDGCN::Linker::constructOptCommand(
109  Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
110  const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
111  llvm::StringRef OutputFilePrefix, const char *InputFileName) const {
112  // Construct opt command.
113  ArgStringList OptArgs;
114  // The input to opt is the output from llvm-link.
115  OptArgs.push_back(InputFileName);
116  // Pass optimization arg to opt.
117  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
118  StringRef OOpt = "3";
119  if (A->getOption().matches(options::OPT_O4) ||
120  A->getOption().matches(options::OPT_Ofast))
121  OOpt = "3";
122  else if (A->getOption().matches(options::OPT_O0))
123  OOpt = "0";
124  else if (A->getOption().matches(options::OPT_O)) {
125  // -Os, -Oz, and -O(anything else) map to -O2
126  OOpt = llvm::StringSwitch<const char *>(A->getValue())
127  .Case("1", "1")
128  .Case("2", "2")
129  .Case("3", "3")
130  .Case("s", "2")
131  .Case("z", "2")
132  .Default("2");
133  }
134  OptArgs.push_back(Args.MakeArgString("-O" + OOpt));
135  }
136  OptArgs.push_back("-mtriple=amdgcn-amd-amdhsa");
137  OptArgs.push_back(Args.MakeArgString("-mcpu=" + SubArchName));
138  OptArgs.push_back("-o");
139  std::string TmpFileName = C.getDriver().GetTemporaryPath(
140  OutputFilePrefix.str() + "-optimized", "bc");
141  const char *OutputFileName =
142  C.addTempFile(C.getArgs().MakeArgString(TmpFileName));
143  OptArgs.push_back(OutputFileName);
144  SmallString<128> OptPath(C.getDriver().Dir);
145  llvm::sys::path::append(OptPath, "opt");
146  const char *OptExec = Args.MakeArgString(OptPath);
147  C.addCommand(llvm::make_unique<Command>(JA, *this, OptExec, OptArgs, Inputs));
148  return OutputFileName;
149 }
150 
151 const char *AMDGCN::Linker::constructLlcCommand(
152  Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
153  const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
154  llvm::StringRef OutputFilePrefix, const char *InputFileName) const {
155  // Construct llc command.
156  ArgStringList LlcArgs{InputFileName, "-mtriple=amdgcn-amd-amdhsa",
157  "-filetype=obj",
158  Args.MakeArgString("-mcpu=" + SubArchName), "-o"};
159  std::string LlcOutputFileName =
160  C.getDriver().GetTemporaryPath(OutputFilePrefix, "o");
161  const char *LlcOutputFile =
162  C.addTempFile(C.getArgs().MakeArgString(LlcOutputFileName));
163  LlcArgs.push_back(LlcOutputFile);
164  SmallString<128> LlcPath(C.getDriver().Dir);
165  llvm::sys::path::append(LlcPath, "llc");
166  const char *Llc = Args.MakeArgString(LlcPath);
167  C.addCommand(llvm::make_unique<Command>(JA, *this, Llc, LlcArgs, Inputs));
168  return LlcOutputFile;
169 }
170 
171 void AMDGCN::Linker::constructLldCommand(Compilation &C, const JobAction &JA,
172  const InputInfoList &Inputs,
173  const InputInfo &Output,
174  const llvm::opt::ArgList &Args,
175  const char *InputFileName) const {
176  // Construct lld command.
177  // The output from ld.lld is an HSA code object file.
178  ArgStringList LldArgs{"-flavor", "gnu", "--no-undefined",
179  "-shared", "-o", Output.getFilename(),
180  InputFileName};
181  SmallString<128> LldPath(C.getDriver().Dir);
182  llvm::sys::path::append(LldPath, "lld");
183  const char *Lld = Args.MakeArgString(LldPath);
184  C.addCommand(llvm::make_unique<Command>(JA, *this, Lld, LldArgs, Inputs));
185 }
186 
187 // For amdgcn the inputs of the linker job are device bitcode and output is
188 // object file. It calls llvm-link, opt, llc, then lld steps.
189 void AMDGCN::Linker::ConstructJob(Compilation &C, const JobAction &JA,
190  const InputInfo &Output,
191  const InputInfoList &Inputs,
192  const ArgList &Args,
193  const char *LinkingOutput) const {
194 
195  assert(getToolChain().getTriple().getArch() == llvm::Triple::amdgcn &&
196  "Unsupported target");
197 
198  std::string SubArchName = JA.getOffloadingArch();
199  assert(StringRef(SubArchName).startswith("gfx") && "Unsupported sub arch");
200 
201  // Prefix for temporary file name.
202  std::string Prefix =
203  llvm::sys::path::stem(Inputs[0].getFilename()).str() + "-" + SubArchName;
204 
205  // Each command outputs different files.
206  const char *LLVMLinkCommand =
207  constructLLVMLinkCommand(C, JA, Inputs, Args, SubArchName, Prefix);
208  const char *OptCommand = constructOptCommand(C, JA, Inputs, Args, SubArchName,
209  Prefix, LLVMLinkCommand);
210  const char *LlcCommand =
211  constructLlcCommand(C, JA, Inputs, Args, SubArchName, Prefix, OptCommand);
212  constructLldCommand(C, JA, Inputs, Output, Args, LlcCommand);
213 }
214 
215 HIPToolChain::HIPToolChain(const Driver &D, const llvm::Triple &Triple,
216  const ToolChain &HostTC, const ArgList &Args)
217  : ToolChain(D, Triple, Args), HostTC(HostTC) {
218  // Lookup binaries into the driver directory, this is used to
219  // discover the clang-offload-bundler executable.
220  getProgramPaths().push_back(getDriver().Dir);
221 }
222 
224  const llvm::opt::ArgList &DriverArgs,
225  llvm::opt::ArgStringList &CC1Args,
226  Action::OffloadKind DeviceOffloadingKind) const {
227  HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
228 
229  StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
230  assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
231  (void) GpuArch;
232  assert(DeviceOffloadingKind == Action::OFK_HIP &&
233  "Only HIP offloading kinds are supported for GPUs.");
234 
235  CC1Args.push_back("-target-cpu");
236  CC1Args.push_back(DriverArgs.MakeArgStringRef(GpuArch));
237  CC1Args.push_back("-fcuda-is-device");
238 
239  if (DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
240  options::OPT_fno_cuda_flush_denormals_to_zero, false))
241  CC1Args.push_back("-fcuda-flush-denormals-to-zero");
242 
243  if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
244  options::OPT_fno_cuda_approx_transcendentals, false))
245  CC1Args.push_back("-fcuda-approx-transcendentals");
246 
247  if (DriverArgs.hasFlag(options::OPT_fcuda_rdc, options::OPT_fno_cuda_rdc,
248  false))
249  CC1Args.push_back("-fcuda-rdc");
250 }
251 
252 llvm::opt::DerivedArgList *
253 HIPToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
254  StringRef BoundArch,
255  Action::OffloadKind DeviceOffloadKind) const {
256  DerivedArgList *DAL =
257  HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
258  if (!DAL)
259  DAL = new DerivedArgList(Args.getBaseArgs());
260 
261  const OptTable &Opts = getDriver().getOpts();
262 
263  for (Arg *A : Args) {
264  if (A->getOption().matches(options::OPT_Xarch__)) {
265  // Skip this argument unless the architecture matches BoundArch.
266  if (BoundArch.empty() || A->getValue(0) != BoundArch)
267  continue;
268 
269  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
270  unsigned Prev = Index;
271  std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
272 
273  // If the argument parsing failed or more than one argument was
274  // consumed, the -Xarch_ argument's parameter tried to consume
275  // extra arguments. Emit an error and ignore.
276  //
277  // We also want to disallow any options which would alter the
278  // driver behavior; that isn't going to work in our model. We
279  // use isDriverOption() as an approximation, although things
280  // like -O4 are going to slip through.
281  if (!XarchArg || Index > Prev + 1) {
282  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
283  << A->getAsString(Args);
284  continue;
285  } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
286  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
287  << A->getAsString(Args);
288  continue;
289  }
290  XarchArg->setBaseArg(A);
291  A = XarchArg.release();
292  DAL->AddSynthesizedArg(A);
293  }
294  DAL->append(A);
295  }
296 
297  if (!BoundArch.empty()) {
298  DAL->eraseArg(options::OPT_march_EQ);
299  DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
300  }
301 
302  return DAL;
303 }
304 
306  assert(getTriple().getArch() == llvm::Triple::amdgcn);
307  return new tools::AMDGCN::Linker(*this);
308 }
309 
310 void HIPToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
312 }
313 
315 HIPToolChain::GetCXXStdlibType(const ArgList &Args) const {
316  return HostTC.GetCXXStdlibType(Args);
317 }
318 
319 void HIPToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
320  ArgStringList &CC1Args) const {
321  HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
322 }
323 
325  ArgStringList &CC1Args) const {
326  HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
327 }
328 
329 void HIPToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
330  ArgStringList &CC1Args) const {
331  HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
332 }
333 
335  // The HIPToolChain only supports sanitizers in the sense that it allows
336  // sanitizer arguments on the command line if they are supported by the host
337  // toolchain. The HIPToolChain will actually ignore any command line
338  // arguments for any of these "supported" sanitizers. That means that no
339  // sanitization of device code is actually supported at this time.
340  //
341  // This behavior is necessary because the host and device toolchains
342  // invocations often share the command line, so the device toolchain must
343  // tolerate flags meant only for the host toolchain.
345 }
346 
348  const ArgList &Args) const {
349  return HostTC.computeMSVCVersion(D, Args);
350 }
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:640
std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const
GetTemporaryPath - Return the pathname of a temporary file to use as part of compilation; the file wi...
Definition: Driver.cpp:4247
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition: HIP.cpp:319
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: ToolChain.cpp:726
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:110
const char * getFilename() const
Definition: InputInfo.h:84
path_list & getProgramPaths()
Definition: ToolChain.h:219
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
Definition: ToolChain.cpp:631
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition: Driver.h:121
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Definition: HIP.cpp:334
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:23
void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use MCU GCC toolchain includes.
Definition: HIP.cpp:329
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:59
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: HIP.cpp:324
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Add warning options that need to be passed to cc1 for this target.
Definition: HIP.cpp:310
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition: HIP.cpp:223
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
Definition: ToolChain.cpp:841
void addCommand(std::unique_ptr< Command > C)
Definition: Compilation.h:206
HIPToolChain(const Driver &D, const llvm::Triple &Triple, const ToolChain &HostTC, const llvm::opt::ArgList &Args)
Definition: HIP.cpp:215
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:197
const llvm::opt::DerivedArgList & getArgs() const
Definition: Compilation.h:187
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: HIP.cpp:253
const Driver & getDriver() const
Definition: ToolChain.h:181
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
Definition: HIP.cpp:315
Dataflow Directional Tag Classes.
Tool - Information on a specific compilation tool.
Definition: Tool.h:34
uint64_t SanitizerMask
Definition: Sanitizers.h:26
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:46
const Driver & getDriver() const
Definition: Compilation.h:134
const llvm::Triple & getTriple() const
Definition: ToolChain.h:183
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:799
VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const override
On Windows, returns the MSVC compatibility version.
Definition: HIP.cpp:347
virtual llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: ToolChain.h:261
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:297
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:668
Tool * buildLinker() const override
Definition: HIP.cpp:305
const char * addTempFile(const char *Name)
addTempFile - Add a file to remove on exit, and returns its argument.
Definition: Compilation.h:233
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
Definition: ToolChain.cpp:824
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:636
const char * getOffloadingArch() const
Definition: Action.h:197
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:88