Coverage Report

Created: 2022-01-22 13:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Driver/ToolChains/AMDGPU.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- AMDGPU.cpp - AMDGPU 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 "AMDGPU.h"
10
#include "CommonArgs.h"
11
#include "clang/Basic/TargetID.h"
12
#include "clang/Driver/Compilation.h"
13
#include "clang/Driver/DriverDiagnostic.h"
14
#include "clang/Driver/InputInfo.h"
15
#include "clang/Driver/Options.h"
16
#include "llvm/Option/ArgList.h"
17
#include "llvm/Support/Error.h"
18
#include "llvm/Support/FileUtilities.h"
19
#include "llvm/Support/LineIterator.h"
20
#include "llvm/Support/Path.h"
21
#include "llvm/Support/VirtualFileSystem.h"
22
#include <system_error>
23
24
0
#define AMDGPU_ARCH_PROGRAM_NAME "amdgpu-arch"
25
26
using namespace clang::driver;
27
using namespace clang::driver::tools;
28
using namespace clang::driver::toolchains;
29
using namespace clang;
30
using namespace llvm::opt;
31
32
// Look for sub-directory starts with PackageName under ROCm candidate path.
33
// If there is one and only one matching sub-directory found, append the
34
// sub-directory to Path. If there is no matching sub-directory or there are
35
// more than one matching sub-directories, diagnose them. Returns the full
36
// path of the package if there is only one matching sub-directory, otherwise
37
// returns an empty string.
38
llvm::SmallString<0>
39
RocmInstallationDetector::findSPACKPackage(const Candidate &Cand,
40
55.1k
                                           StringRef PackageName) {
41
55.1k
  if (!Cand.isSPACK())
42
55.1k
    return {};
43
18.4E
  std::error_code EC;
44
18.4E
  std::string Prefix = Twine(PackageName + "-" + Cand.SPACKReleaseStr).str();
45
18.4E
  llvm::SmallVector<llvm::SmallString<0>> SubDirs;
46
18.4E
  for (llvm::vfs::directory_iterator File = D.getVFS().dir_begin(Cand.Path, EC),
47
18.4E
                                     FileEnd;
48
18.4E
       File != FileEnd && 
!EC0
;
File.increment(EC)0
) {
49
0
    llvm::StringRef FileName = llvm::sys::path::filename(File->path());
50
0
    if (FileName.startswith(Prefix)) {
51
0
      SubDirs.push_back(FileName);
52
0
      if (SubDirs.size() > 1)
53
0
        break;
54
0
    }
55
0
  }
56
18.4E
  if (SubDirs.size() == 1) {
57
0
    auto PackagePath = Cand.Path;
58
0
    llvm::sys::path::append(PackagePath, SubDirs[0]);
59
0
    return PackagePath;
60
0
  }
61
18.4E
  if (SubDirs.size() == 0 && 
Verbose0
) {
62
0
    llvm::errs() << "SPACK package " << Prefix << " not found at " << Cand.Path
63
0
                 << '\n';
64
0
    return {};
65
0
  }
66
67
18.4E
  if (SubDirs.size() > 1 && 
Verbose0
) {
68
0
    llvm::errs() << "Cannot use SPACK package " << Prefix << " at " << Cand.Path
69
0
                 << " due to multiple installations for the same version\n";
70
0
  }
71
18.4E
  return {};
72
18.4E
}
73
74
118
void RocmInstallationDetector::scanLibDevicePath(llvm::StringRef Path) {
75
118
  assert(!Path.empty());
76
77
0
  const StringRef Suffix(".bc");
78
118
  const StringRef Suffix2(".amdgcn.bc");
79
80
118
  std::error_code EC;
81
118
  for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(Path, EC), LE;
82
35.9k
       !EC && LI != LE; 
LI = LI.increment(EC)35.8k
) {
83
35.8k
    StringRef FilePath = LI->path();
84
35.8k
    StringRef FileName = llvm::sys::path::filename(FilePath);
85
35.8k
    if (!FileName.endswith(Suffix))
86
35.8k
      continue;
87
88
0
    StringRef BaseName;
89
0
    if (FileName.endswith(Suffix2))
90
0
      BaseName = FileName.drop_back(Suffix2.size());
91
0
    else if (FileName.endswith(Suffix))
92
0
      BaseName = FileName.drop_back(Suffix.size());
93
94
0
    if (BaseName == "ocml") {
95
0
      OCML = FilePath;
96
0
    } else if (BaseName == "ockl") {
97
0
      OCKL = FilePath;
98
0
    } else if (BaseName == "opencl") {
99
0
      OpenCL = FilePath;
100
0
    } else if (BaseName == "hip") {
101
0
      HIP = FilePath;
102
0
    } else if (BaseName == "asanrtl") {
103
0
      AsanRTL = FilePath;
104
0
    } else if (BaseName == "oclc_finite_only_off") {
105
0
      FiniteOnly.Off = FilePath;
106
0
    } else if (BaseName == "oclc_finite_only_on") {
107
0
      FiniteOnly.On = FilePath;
108
0
    } else if (BaseName == "oclc_daz_opt_on") {
109
0
      DenormalsAreZero.On = FilePath;
110
0
    } else if (BaseName == "oclc_daz_opt_off") {
111
0
      DenormalsAreZero.Off = FilePath;
112
0
    } else if (BaseName == "oclc_correctly_rounded_sqrt_on") {
113
0
      CorrectlyRoundedSqrt.On = FilePath;
114
0
    } else if (BaseName == "oclc_correctly_rounded_sqrt_off") {
115
0
      CorrectlyRoundedSqrt.Off = FilePath;
116
0
    } else if (BaseName == "oclc_unsafe_math_on") {
117
0
      UnsafeMath.On = FilePath;
118
0
    } else if (BaseName == "oclc_unsafe_math_off") {
119
0
      UnsafeMath.Off = FilePath;
120
0
    } else if (BaseName == "oclc_wavefrontsize64_on") {
121
0
      WavefrontSize64.On = FilePath;
122
0
    } else if (BaseName == "oclc_wavefrontsize64_off") {
123
0
      WavefrontSize64.Off = FilePath;
124
0
    } else {
125
      // Process all bitcode filenames that look like
126
      // ocl_isa_version_XXX.amdgcn.bc
127
0
      const StringRef DeviceLibPrefix = "oclc_isa_version_";
128
0
      if (!BaseName.startswith(DeviceLibPrefix))
129
0
        continue;
130
131
0
      StringRef IsaVersionNumber =
132
0
        BaseName.drop_front(DeviceLibPrefix.size());
133
134
0
      llvm::Twine GfxName = Twine("gfx") + IsaVersionNumber;
135
0
      SmallString<8> Tmp;
136
0
      LibDeviceMap.insert(
137
0
        std::make_pair(GfxName.toStringRef(Tmp), FilePath.str()));
138
0
    }
139
0
  }
140
118
}
141
142
// Parse and extract version numbers from `.hipVersion`. Return `true` if
143
// the parsing fails.
144
10
bool RocmInstallationDetector::parseHIPVersionFile(llvm::StringRef V) {
145
10
  SmallVector<StringRef, 4> VersionParts;
146
10
  V.split(VersionParts, '\n');
147
10
  unsigned Major = ~0U;
148
10
  unsigned Minor = ~0U;
149
30
  for (auto Part : VersionParts) {
150
30
    auto Splits = Part.rtrim().split('=');
151
30
    if (Splits.first == "HIP_VERSION_MAJOR") {
152
10
      if (Splits.second.getAsInteger(0, Major))
153
0
        return true;
154
20
    } else if (Splits.first == "HIP_VERSION_MINOR") {
155
10
      if (Splits.second.getAsInteger(0, Minor))
156
0
        return true;
157
10
    } else if (Splits.first == "HIP_VERSION_PATCH")
158
0
      VersionPatch = Splits.second.str();
159
30
  }
160
10
  if (Major == ~0U || Minor == ~0U)
161
0
    return true;
162
10
  VersionMajorMinor = llvm::VersionTuple(Major, Minor);
163
10
  DetectedVersion =
164
10
      (Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();
165
10
  return false;
166
10
}
167
168
/// \returns a list of candidate directories for ROCm installation, which is
169
/// cached and populated only once.
170
const SmallVectorImpl<RocmInstallationDetector::Candidate> &
171
46.6k
RocmInstallationDetector::getInstallationPathCandidates() {
172
173
  // Return the cached candidate list if it has already been populated.
174
46.6k
  if (!ROCmSearchDirs.empty())
175
63
    return ROCmSearchDirs;
176
177
46.5k
  auto DoPrintROCmSearchDirs = [&]() {
178
46.5k
    if (PrintROCmSearchDirs)
179
0
      for (auto Cand : ROCmSearchDirs) {
180
0
        llvm::errs() << "ROCm installation search path";
181
0
        if (Cand.isSPACK())
182
0
          llvm::errs() << " (Spack " << Cand.SPACKReleaseStr << ")";
183
0
        llvm::errs() << ": " << Cand.Path << '\n';
184
0
      }
185
46.5k
  };
186
187
  // For candidate specified by --rocm-path we do not do strict check, i.e.,
188
  // checking existence of HIP version file and device library files.
189
46.5k
  if (!RocmPathArg.empty()) {
190
3
    ROCmSearchDirs.emplace_back(RocmPathArg.str());
191
3
    DoPrintROCmSearchDirs();
192
3
    return ROCmSearchDirs;
193
46.5k
  } else if (const char *RocmPathEnv = ::getenv("ROCM_PATH")) {
194
0
    if (!StringRef(RocmPathEnv).empty()) {
195
0
      ROCmSearchDirs.emplace_back(RocmPathEnv);
196
0
      DoPrintROCmSearchDirs();
197
0
      return ROCmSearchDirs;
198
0
    }
199
0
  }
200
201
  // Try to find relative to the compiler binary.
202
46.5k
  const char *InstallDir = D.getInstalledDir();
203
204
  // Check both a normal Unix prefix position of the clang binary, as well as
205
  // the Windows-esque layout the ROCm packages use with the host architecture
206
  // subdirectory of bin.
207
47.5k
  auto DeduceROCmPath = [](StringRef ClangPath) {
208
    // Strip off directory (usually bin)
209
47.5k
    StringRef ParentDir = llvm::sys::path::parent_path(ClangPath);
210
47.5k
    StringRef ParentName = llvm::sys::path::filename(ParentDir);
211
212
    // Some builds use bin/{host arch}, so go up again.
213
47.5k
    if (ParentName == "bin") {
214
6
      ParentDir = llvm::sys::path::parent_path(ParentDir);
215
6
      ParentName = llvm::sys::path::filename(ParentDir);
216
6
    }
217
218
    // Detect ROCm packages built with SPACK.
219
    // clang is installed at
220
    // <rocm_root>/llvm-amdgpu-<rocm_release_string>-<hash>/bin directory.
221
    // We only consider the parent directory of llvm-amdgpu package as ROCm
222
    // installation candidate for SPACK.
223
47.5k
    if (ParentName.startswith("llvm-amdgpu-")) {
224
0
      auto SPACKPostfix =
225
0
          ParentName.drop_front(strlen("llvm-amdgpu-")).split('-');
226
0
      auto SPACKReleaseStr = SPACKPostfix.first;
227
0
      if (!SPACKReleaseStr.empty()) {
228
0
        ParentDir = llvm::sys::path::parent_path(ParentDir);
229
0
        return Candidate(ParentDir.str(), /*StrictChecking=*/true,
230
0
                         SPACKReleaseStr);
231
0
      }
232
0
    }
233
234
    // Some versions of the rocm llvm package install to /opt/rocm/llvm/bin
235
    // Some versions of the aomp package install to /opt/rocm/aomp/bin
236
47.5k
    if (ParentName == "llvm" || ParentName.startswith("aomp"))
237
0
      ParentDir = llvm::sys::path::parent_path(ParentDir);
238
239
47.5k
    return Candidate(ParentDir.str(), /*StrictChecking=*/true);
240
47.5k
  };
241
242
  // Deduce ROCm path by the path used to invoke clang. Do not resolve symbolic
243
  // link of clang itself.
244
46.5k
  ROCmSearchDirs.emplace_back(DeduceROCmPath(InstallDir));
245
246
  // Deduce ROCm path by the real path of the invoked clang, resolving symbolic
247
  // link of clang itself.
248
46.5k
  llvm::SmallString<256> RealClangPath;
249
46.5k
  llvm::sys::fs::real_path(D.getClangProgramPath(), RealClangPath);
250
46.5k
  auto ParentPath = llvm::sys::path::parent_path(RealClangPath);
251
46.5k
  if (ParentPath != InstallDir)
252
989
    ROCmSearchDirs.emplace_back(DeduceROCmPath(ParentPath));
253
254
  // Device library may be installed in clang or resource directory.
255
46.5k
  auto ClangRoot = llvm::sys::path::parent_path(InstallDir);
256
46.5k
  auto RealClangRoot = llvm::sys::path::parent_path(ParentPath);
257
46.5k
  ROCmSearchDirs.emplace_back(ClangRoot.str(), /*StrictChecking=*/true);
258
46.5k
  if (RealClangRoot != ClangRoot)
259
989
    ROCmSearchDirs.emplace_back(RealClangRoot.str(), /*StrictChecking=*/true);
260
46.5k
  ROCmSearchDirs.emplace_back(D.ResourceDir,
261
46.5k
                              /*StrictChecking=*/true);
262
263
46.5k
  ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/rocm",
264
46.5k
                              /*StrictChecking=*/true);
265
266
  // Find the latest /opt/rocm-{release} directory.
267
46.5k
  std::error_code EC;
268
46.5k
  std::string LatestROCm;
269
46.5k
  llvm::VersionTuple LatestVer;
270
  // Get ROCm version from ROCm directory name.
271
46.5k
  auto GetROCmVersion = [](StringRef DirName) {
272
0
    llvm::VersionTuple V;
273
0
    std::string VerStr = DirName.drop_front(strlen("rocm-")).str();
274
    // The ROCm directory name follows the format of
275
    // rocm-{major}.{minor}.{subMinor}[-{build}]
276
0
    std::replace(VerStr.begin(), VerStr.end(), '-', '.');
277
0
    V.tryParse(VerStr);
278
0
    return V;
279
0
  };
280
46.5k
  for (llvm::vfs::directory_iterator
281
46.5k
           File = D.getVFS().dir_begin(D.SysRoot + "/opt", EC),
282
46.5k
           FileEnd;
283
134k
       File != FileEnd && 
!EC87.4k
;
File.increment(EC)87.4k
) {
284
87.4k
    llvm::StringRef FileName = llvm::sys::path::filename(File->path());
285
87.4k
    if (!FileName.startswith("rocm-"))
286
87.4k
      continue;
287
12
    if (LatestROCm.empty()) {
288
0
      LatestROCm = FileName.str();
289
0
      LatestVer = GetROCmVersion(LatestROCm);
290
0
      continue;
291
0
    }
292
12
    auto Ver = GetROCmVersion(FileName);
293
12
    if (LatestVer < Ver) {
294
0
      LatestROCm = FileName.str();
295
0
      LatestVer = Ver;
296
0
    }
297
12
  }
298
46.5k
  if (!LatestROCm.empty())
299
0
    ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/" + LatestROCm,
300
0
                                /*StrictChecking=*/true);
301
302
46.5k
  DoPrintROCmSearchDirs();
303
46.5k
  return ROCmSearchDirs;
304
46.5k
}
305
306
RocmInstallationDetector::RocmInstallationDetector(
307
    const Driver &D, const llvm::Triple &HostTriple,
308
    const llvm::opt::ArgList &Args, bool DetectHIPRuntime, bool DetectDeviceLib)
309
46.5k
    : D(D) {
310
46.5k
  Verbose = Args.hasArg(options::OPT_v);
311
46.5k
  RocmPathArg = Args.getLastArgValue(clang::driver::options::OPT_rocm_path_EQ);
312
46.5k
  PrintROCmSearchDirs =
313
46.5k
      Args.hasArg(clang::driver::options::OPT_print_rocm_search_dirs);
314
46.5k
  RocmDeviceLibPathArg =
315
46.5k
      Args.getAllArgValues(clang::driver::options::OPT_rocm_device_lib_path_EQ);
316
46.5k
  HIPPathArg = Args.getLastArgValue(clang::driver::options::OPT_hip_path_EQ);
317
46.5k
  if (auto *A = Args.getLastArg(clang::driver::options::OPT_hip_version_EQ)) {
318
0
    HIPVersionArg = A->getValue();
319
0
    unsigned Major = ~0U;
320
0
    unsigned Minor = ~0U;
321
0
    SmallVector<StringRef, 3> Parts;
322
0
    HIPVersionArg.split(Parts, '.');
323
0
    if (Parts.size())
324
0
      Parts[0].getAsInteger(0, Major);
325
0
    if (Parts.size() > 1)
326
0
      Parts[1].getAsInteger(0, Minor);
327
0
    if (Parts.size() > 2)
328
0
      VersionPatch = Parts[2].str();
329
0
    if (VersionPatch.empty())
330
0
      VersionPatch = "0";
331
0
    if (Major != ~0U && Minor == ~0U)
332
0
      Minor = 0;
333
0
    if (Major == ~0U || Minor == ~0U)
334
0
      D.Diag(diag::err_drv_invalid_value)
335
0
          << A->getAsString(Args) << HIPVersionArg;
336
337
0
    VersionMajorMinor = llvm::VersionTuple(Major, Minor);
338
0
    DetectedVersion =
339
0
        (Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();
340
46.5k
  } else {
341
46.5k
    VersionPatch = DefaultVersionPatch;
342
46.5k
    VersionMajorMinor =
343
46.5k
        llvm::VersionTuple(DefaultVersionMajor, DefaultVersionMinor);
344
46.5k
    DetectedVersion = (Twine(DefaultVersionMajor) + "." +
345
46.5k
                       Twine(DefaultVersionMinor) + "." + VersionPatch)
346
46.5k
                          .str();
347
46.5k
  }
348
349
46.5k
  if (DetectHIPRuntime)
350
46.5k
    detectHIPRuntime();
351
46.5k
  if (DetectDeviceLib)
352
0
    detectDeviceLibrary();
353
46.5k
}
354
355
63
void RocmInstallationDetector::detectDeviceLibrary() {
356
63
  assert(LibDevicePath.empty());
357
358
63
  if (!RocmDeviceLibPathArg.empty())
359
0
    LibDevicePath = RocmDeviceLibPathArg[RocmDeviceLibPathArg.size() - 1];
360
63
  else if (const char *LibPathEnv = ::getenv("HIP_DEVICE_LIB_PATH"))
361
0
    LibDevicePath = LibPathEnv;
362
363
63
  auto &FS = D.getVFS();
364
63
  if (!LibDevicePath.empty()) {
365
    // Maintain compatability with HIP flag/envvar pointing directly at the
366
    // bitcode library directory. This points directly at the library path instead
367
    // of the rocm root installation.
368
0
    if (!FS.exists(LibDevicePath))
369
0
      return;
370
371
0
    scanLibDevicePath(LibDevicePath);
372
0
    HasDeviceLibrary = allGenericLibsValid() && !LibDeviceMap.empty();
373
0
    return;
374
0
  }
375
376
  // The install path situation in old versions of ROCm is a real mess, and
377
  // use a different install layout. Multiple copies of the device libraries
378
  // exist for each frontend project, and differ depending on which build
379
  // system produced the packages. Standalone OpenCL builds also have a
380
  // different directory structure from the ROCm OpenCL package.
381
63
  auto &ROCmDirs = getInstallationPathCandidates();
382
249
  for (const auto &Candidate : ROCmDirs) {
383
249
    auto CandidatePath = Candidate.Path;
384
385
    // Check device library exists at the given path.
386
747
    auto CheckDeviceLib = [&](StringRef Path) {
387
747
      bool CheckLibDevice = (!NoBuiltinLibs || 
Candidate.StrictChecking0
);
388
747
      if (CheckLibDevice && !FS.exists(Path))
389
629
        return false;
390
391
118
      scanLibDevicePath(Path);
392
393
118
      if (!NoBuiltinLibs) {
394
        // Check that the required non-target libraries are all available.
395
118
        if (!allGenericLibsValid())
396
118
          return false;
397
398
        // Check that we have found at least one libdevice that we can link in
399
        // if -nobuiltinlib hasn't been specified.
400
0
        if (LibDeviceMap.empty())
401
0
          return false;
402
0
      }
403
0
      return true;
404
118
    };
405
406
    // The possible structures are:
407
    // - ${ROCM_ROOT}/amdgcn/bitcode/*
408
    // - ${ROCM_ROOT}/lib/*
409
    // - ${ROCM_ROOT}/lib/bitcode/*
410
    // so try to detect these layouts.
411
249
    static constexpr std::array<const char *, 2> SubDirsList[] = {
412
249
        {"amdgcn", "bitcode"},
413
249
        {"lib", ""},
414
249
        {"lib", "bitcode"},
415
249
    };
416
417
    // Make a path by appending sub-directories to InstallPath.
418
747
    auto MakePath = [&](const llvm::ArrayRef<const char *> &SubDirs) {
419
747
      auto Path = CandidatePath;
420
747
      for (auto SubDir : SubDirs)
421
1.49k
        llvm::sys::path::append(Path, SubDir);
422
747
      return Path;
423
747
    };
424
425
747
    for (auto SubDirs : SubDirsList) {
426
747
      LibDevicePath = MakePath(SubDirs);
427
747
      HasDeviceLibrary = CheckDeviceLib(LibDevicePath);
428
747
      if (HasDeviceLibrary)
429
0
        return;
430
747
    }
431
249
  }
432
63
}
433
434
46.5k
void RocmInstallationDetector::detectHIPRuntime() {
435
46.5k
  SmallVector<Candidate, 4> HIPSearchDirs;
436
46.5k
  if (!HIPPathArg.empty())
437
10
    HIPSearchDirs.emplace_back(HIPPathArg.str(), /*StrictChecking=*/true);
438
46.5k
  else
439
46.5k
    HIPSearchDirs.append(getInstallationPathCandidates());
440
46.5k
  auto &FS = D.getVFS();
441
442
188k
  for (const auto &Candidate : HIPSearchDirs) {
443
188k
    InstallPath = Candidate.Path;
444
188k
    if (InstallPath.empty() || 
!FS.exists(InstallPath)129k
)
445
133k
      continue;
446
    // HIP runtime built by SPACK is installed to
447
    // <rocm_root>/hip-<rocm_release_string>-<hash> directory.
448
55.0k
    auto SPACKPath = findSPACKPackage(Candidate, "hip");
449
18.4E
    InstallPath = 
SPACKPath.empty()55.0k
?
InstallPath55.1k
: SPACKPath;
450
451
55.0k
    BinPath = InstallPath;
452
55.0k
    llvm::sys::path::append(BinPath, "bin");
453
55.0k
    IncludePath = InstallPath;
454
55.0k
    llvm::sys::path::append(IncludePath, "include");
455
55.0k
    LibPath = InstallPath;
456
55.0k
    llvm::sys::path::append(LibPath, "lib");
457
458
55.0k
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
459
55.0k
        FS.getBufferForFile(BinPath + "/.hipVersion");
460
55.1k
    if (
!VersionFile55.0k
&& Candidate.StrictChecking)
461
55.1k
      continue;
462
463
18.4E
    if (HIPVersionArg.empty() && 
VersionFile10
)
464
10
      if (parseHIPVersionFile((*VersionFile)->getBuffer()))
465
0
        continue;
466
467
18.4E
    HasHIPRuntime = true;
468
18.4E
    return;
469
18.4E
  }
470
46.6k
  HasHIPRuntime = false;
471
46.6k
}
472
473
113
void RocmInstallationDetector::print(raw_ostream &OS) const {
474
113
  if (hasHIPRuntime())
475
0
    OS << "Found HIP installation: " << InstallPath << ", version "
476
0
       << DetectedVersion << '\n';
477
113
}
478
479
void RocmInstallationDetector::AddHIPIncludeArgs(const ArgList &DriverArgs,
480
45
                                                 ArgStringList &CC1Args) const {
481
45
  bool UsesRuntimeWrapper = VersionMajorMinor > llvm::VersionTuple(3, 5) &&
482
45
                            
!DriverArgs.hasArg(options::OPT_nohipwrapperinc)7
;
483
484
45
  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
485
    // HIP header includes standard library wrapper headers under clang
486
    // cuda_wrappers directory. Since these wrapper headers include_next
487
    // standard C++ headers, whereas libc++ headers include_next other clang
488
    // headers. The include paths have to follow this order:
489
    // - wrapper include path
490
    // - standard C++ include path
491
    // - other clang include path
492
    // Since standard C++ and other clang include paths are added in other
493
    // places after this function, here we only need to make sure wrapper
494
    // include path is added.
495
    //
496
    // ROCm 3.5 does not fully support the wrapper headers. Therefore it needs
497
    // a workaround.
498
45
    SmallString<128> P(D.ResourceDir);
499
45
    if (UsesRuntimeWrapper)
500
4
      llvm::sys::path::append(P, "include", "cuda_wrappers");
501
45
    CC1Args.push_back("-internal-isystem");
502
45
    CC1Args.push_back(DriverArgs.MakeArgString(P));
503
45
  }
504
505
45
  if (DriverArgs.hasArg(options::OPT_nogpuinc))
506
39
    return;
507
508
6
  if (!hasHIPRuntime()) {
509
0
    D.Diag(diag::err_drv_no_hip_runtime);
510
0
    return;
511
0
  }
512
513
6
  CC1Args.push_back("-internal-isystem");
514
6
  CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
515
6
  if (UsesRuntimeWrapper)
516
3
    CC1Args.append({"-include", "__clang_hip_runtime_wrapper.h"});
517
6
}
518
519
void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
520
                                  const InputInfo &Output,
521
                                  const InputInfoList &Inputs,
522
                                  const ArgList &Args,
523
24
                                  const char *LinkingOutput) const {
524
525
24
  std::string Linker = getToolChain().GetProgramPath(getShortName());
526
24
  ArgStringList CmdArgs;
527
24
  addLinkerCompressDebugSectionsOption(getToolChain(), Args, CmdArgs);
528
24
  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
529
24
  CmdArgs.push_back("-shared");
530
24
  CmdArgs.push_back("-o");
531
24
  CmdArgs.push_back(Output.getFilename());
532
24
  C.addCommand(std::make_unique<Command>(
533
24
      JA, *this, ResponseFileSupport::AtFileCurCP(), Args.MakeArgString(Linker),
534
24
      CmdArgs, Inputs, Output));
535
24
}
536
537
void amdgpu::getAMDGPUTargetFeatures(const Driver &D,
538
                                     const llvm::Triple &Triple,
539
                                     const llvm::opt::ArgList &Args,
540
184
                                     std::vector<StringRef> &Features) {
541
  // Add target ID features to -target-feature options. No diagnostics should
542
  // be emitted here since invalid target ID is diagnosed at other places.
543
184
  StringRef TargetID = Args.getLastArgValue(options::OPT_mcpu_EQ);
544
184
  if (!TargetID.empty()) {
545
163
    llvm::StringMap<bool> FeatureMap;
546
163
    auto OptionalGpuArch = parseTargetID(Triple, TargetID, &FeatureMap);
547
163
    if (OptionalGpuArch) {
548
161
      StringRef GpuArch = OptionalGpuArch.getValue();
549
      // Iterate through all possible target ID features for the given GPU.
550
      // If it is mapped to true, add +feature.
551
      // If it is mapped to false, add -feature.
552
      // If it is not in the map (default), do not add it
553
161
      for (auto &&Feature : getAllPossibleTargetIDFeatures(Triple, GpuArch)) {
554
52
        auto Pos = FeatureMap.find(Feature);
555
52
        if (Pos == FeatureMap.end())
556
48
          continue;
557
4
        Features.push_back(Args.MakeArgStringRef(
558
4
            (Twine(Pos->second ? 
"+"2
:
"-"2
) + Feature).str()));
559
4
      }
560
161
    }
561
163
  }
562
563
184
  if (Args.hasFlag(options::OPT_mwavefrontsize64,
564
184
                   options::OPT_mno_wavefrontsize64, false))
565
2
    Features.push_back("+wavefrontsize64");
566
567
184
  handleTargetFeaturesGroup(
568
184
    Args, Features, options::OPT_m_amdgpu_Features_Group);
569
184
}
570
571
/// AMDGPU Toolchain
572
AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
573
                                 const ArgList &Args)
574
    : Generic_ELF(D, Triple, Args),
575
      OptionsDefault(
576
78
          {{options::OPT_O, "3"}, {options::OPT_cl_std_EQ, "CL1.2"}}) {
577
  // Check code object version options. Emit warnings for legacy options
578
  // and errors for the last invalid code object version options.
579
  // It is done here to avoid repeated warning or error messages for
580
  // each tool invocation.
581
78
  checkAMDGPUCodeObjectVersion(D, Args);
582
78
}
583
584
24
Tool *AMDGPUToolChain::buildLinker() const {
585
24
  return new tools::amdgpu::Linker(*this);
586
24
}
587
588
DerivedArgList *
589
AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
590
61
                               Action::OffloadKind DeviceOffloadKind) const {
591
592
61
  DerivedArgList *DAL =
593
61
      Generic_ELF::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
594
595
61
  const OptTable &Opts = getDriver().getOpts();
596
597
61
  if (!DAL)
598
61
    DAL = new DerivedArgList(Args.getBaseArgs());
599
600
426
  for (Arg *A : Args) {
601
426
    if (!shouldSkipArgument(A))
602
426
      DAL->append(A);
603
426
  }
604
605
61
  checkTargetID(*DAL);
606
607
61
  if (!Args.getLastArgValue(options::OPT_x).equals("cl"))
608
44
    return DAL;
609
610
  // Phase 1 (.cl -> .bc)
611
17
  if (Args.hasArg(options::OPT_c) && Args.hasArg(options::OPT_emit_llvm)) {
612
17
    DAL->AddFlagArg(nullptr, Opts.getOption(getTriple().isArch64Bit()
613
17
                                                ? options::OPT_m64
614
17
                                                : 
options::OPT_m320
));
615
616
    // Have to check OPT_O4, OPT_O0 & OPT_Ofast separately
617
    // as they defined that way in Options.td
618
17
    if (!Args.hasArg(options::OPT_O, options::OPT_O0, options::OPT_O4,
619
17
                     options::OPT_Ofast))
620
9
      DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_O),
621
9
                        getOptionDefault(options::OPT_O));
622
17
  }
623
624
17
  return DAL;
625
61
}
626
627
bool AMDGPUToolChain::getDefaultDenormsAreZeroForTarget(
628
71
    llvm::AMDGPU::GPUKind Kind) {
629
630
  // Assume nothing without a specific target.
631
71
  if (Kind == llvm::AMDGPU::GK_NONE)
632
19
    return false;
633
634
52
  const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);
635
636
  // Default to enabling f32 denormals by default on subtargets where fma is
637
  // fast with denormals
638
52
  const bool BothDenormAndFMAFast =
639
52
      (ArchAttr & llvm::AMDGPU::FEATURE_FAST_FMA_F32) &&
640
52
      
(ArchAttr & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32)16
;
641
52
  return !BothDenormAndFMAFast;
642
71
}
643
644
llvm::DenormalMode AMDGPUToolChain::getDefaultDenormalModeForType(
645
    const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
646
152
    const llvm::fltSemantics *FPType) const {
647
  // Denormals should always be enabled for f16 and f64.
648
152
  if (!FPType || 
FPType != &llvm::APFloat::IEEEsingle()76
)
649
76
    return llvm::DenormalMode::getIEEE();
650
651
76
  if (JA.getOffloadingDeviceKind() == Action::OFK_HIP ||
652
76
      
JA.getOffloadingDeviceKind() == Action::OFK_Cuda57
) {
653
19
    auto Arch = getProcessorFromTargetID(getTriple(), JA.getOffloadingArch());
654
19
    auto Kind = llvm::AMDGPU::parseArchAMDGCN(Arch);
655
19
    if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&
656
19
        DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,
657
19
                           options::OPT_fno_gpu_flush_denormals_to_zero,
658
19
                           getDefaultDenormsAreZeroForTarget(Kind)))
659
11
      return llvm::DenormalMode::getPreserveSign();
660
661
8
    return llvm::DenormalMode::getIEEE();
662
19
  }
663
664
57
  const StringRef GpuArch = getGPUArch(DriverArgs);
665
57
  auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
666
667
  // TODO: There are way too many flags that change this. Do we need to check
668
  // them all?
669
57
  bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
670
57
             
getDefaultDenormsAreZeroForTarget(Kind)52
;
671
672
  // Outputs are flushed to zero (FTZ), preserving sign. Denormal inputs are
673
  // also implicit treated as zero (DAZ).
674
57
  return DAZ ? 
llvm::DenormalMode::getPreserveSign()30
:
675
57
               
llvm::DenormalMode::getIEEE()27
;
676
76
}
677
678
bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList &DriverArgs,
679
0
                               llvm::AMDGPU::GPUKind Kind) {
680
0
  const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);
681
0
  bool HasWave32 = (ArchAttr & llvm::AMDGPU::FEATURE_WAVE32);
682
683
0
  return !HasWave32 || DriverArgs.hasFlag(
684
0
    options::OPT_mwavefrontsize64, options::OPT_mno_wavefrontsize64, false);
685
0
}
686
687
688
/// ROCM Toolchain
689
ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple,
690
                             const ArgList &Args)
691
63
    : AMDGPUToolChain(D, Triple, Args) {
692
63
  RocmInstallation.detectDeviceLibrary();
693
63
}
694
695
void AMDGPUToolChain::addClangTargetOptions(
696
    const llvm::opt::ArgList &DriverArgs,
697
    llvm::opt::ArgStringList &CC1Args,
698
57
    Action::OffloadKind DeviceOffloadingKind) const {
699
  // Default to "hidden" visibility, as object level linking will not be
700
  // supported for the foreseeable future.
701
57
  if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
702
57
                         options::OPT_fvisibility_ms_compat)) {
703
53
    CC1Args.push_back("-fvisibility");
704
53
    CC1Args.push_back("hidden");
705
53
    CC1Args.push_back("-fapply-global-visibility-to-externs");
706
53
  }
707
57
}
708
709
StringRef
710
57
AMDGPUToolChain::getGPUArch(const llvm::opt::ArgList &DriverArgs) const {
711
57
  return getProcessorFromTargetID(
712
57
      getTriple(), DriverArgs.getLastArgValue(options::OPT_mcpu_EQ));
713
57
}
714
715
AMDGPUToolChain::ParsedTargetIDType
716
83
AMDGPUToolChain::getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const {
717
83
  StringRef TargetID = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ);
718
83
  if (TargetID.empty())
719
20
    return {None, None, None};
720
721
63
  llvm::StringMap<bool> FeatureMap;
722
63
  auto OptionalGpuArch = parseTargetID(getTriple(), TargetID, &FeatureMap);
723
63
  if (!OptionalGpuArch)
724
0
    return {TargetID.str(), None, None};
725
726
63
  return {TargetID.str(), OptionalGpuArch.getValue().str(), FeatureMap};
727
63
}
728
729
void AMDGPUToolChain::checkTargetID(
730
61
    const llvm::opt::ArgList &DriverArgs) const {
731
61
  auto PTID = getParsedTargetID(DriverArgs);
732
61
  if (PTID.OptionalTargetID && 
!PTID.OptionalGPUArch41
) {
733
0
    getDriver().Diag(clang::diag::err_drv_bad_target_id)
734
0
        << PTID.OptionalTargetID.getValue();
735
0
  }
736
61
}
737
738
llvm::Error
739
AMDGPUToolChain::detectSystemGPUs(const ArgList &Args,
740
0
                                  SmallVector<std::string, 1> &GPUArchs) const {
741
0
  std::string Program;
742
0
  if (Arg *A = Args.getLastArg(options::OPT_amdgpu_arch_tool_EQ))
743
0
    Program = A->getValue();
744
0
  else
745
0
    Program = GetProgramPath(AMDGPU_ARCH_PROGRAM_NAME);
746
0
  llvm::SmallString<64> OutputFile;
747
0
  llvm::sys::fs::createTemporaryFile("print-system-gpus", "" /* No Suffix */,
748
0
                                     OutputFile);
749
0
  llvm::FileRemover OutputRemover(OutputFile.c_str());
750
0
  llvm::Optional<llvm::StringRef> Redirects[] = {
751
0
      {""},
752
0
      OutputFile.str(),
753
0
      {""},
754
0
  };
755
756
0
  std::string ErrorMessage;
757
0
  if (int Result = llvm::sys::ExecuteAndWait(
758
0
          Program, {}, {}, Redirects, /* SecondsToWait */ 0,
759
0
          /*MemoryLimit*/ 0, &ErrorMessage)) {
760
0
    if (Result > 0) {
761
0
      ErrorMessage = "Exited with error code " + std::to_string(Result);
762
0
    } else if (Result == -1) {
763
0
      ErrorMessage = "Execute failed: " + ErrorMessage;
764
0
    } else {
765
0
      ErrorMessage = "Crashed: " + ErrorMessage;
766
0
    }
767
768
0
    return llvm::createStringError(std::error_code(),
769
0
                                   Program + ": " + ErrorMessage);
770
0
  }
771
772
0
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> OutputBuf =
773
0
      llvm::MemoryBuffer::getFile(OutputFile.c_str());
774
0
  if (!OutputBuf) {
775
0
    return llvm::createStringError(OutputBuf.getError(),
776
0
                                   "Failed to read stdout of " + Program +
777
0
                                       ": " + OutputBuf.getError().message());
778
0
  }
779
780
0
  for (llvm::line_iterator LineIt(**OutputBuf); !LineIt.is_at_end(); ++LineIt) {
781
0
    GPUArchs.push_back(LineIt->str());
782
0
  }
783
0
  return llvm::Error::success();
784
0
}
785
786
llvm::Error AMDGPUToolChain::getSystemGPUArch(const ArgList &Args,
787
0
                                              std::string &GPUArch) const {
788
  // detect the AMDGPU installed in system
789
0
  SmallVector<std::string, 1> GPUArchs;
790
0
  auto Err = detectSystemGPUs(Args, GPUArchs);
791
0
  if (Err) {
792
0
    return Err;
793
0
  }
794
0
  if (GPUArchs.empty()) {
795
0
    return llvm::createStringError(std::error_code(),
796
0
                                   "No AMD GPU detected in the system");
797
0
  }
798
0
  GPUArch = GPUArchs[0];
799
0
  if (GPUArchs.size() > 1) {
800
0
    bool AllSame = llvm::all_of(GPUArchs, [&](const StringRef &GPUArch) {
801
0
      return GPUArch == GPUArchs.front();
802
0
    });
803
0
    if (!AllSame)
804
0
      return llvm::createStringError(
805
0
          std::error_code(), "Multiple AMD GPUs found with different archs");
806
0
  }
807
0
  return llvm::Error::success();
808
0
}
809
810
void ROCMToolChain::addClangTargetOptions(
811
    const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
812
44
    Action::OffloadKind DeviceOffloadingKind) const {
813
44
  AMDGPUToolChain::addClangTargetOptions(DriverArgs, CC1Args,
814
44
                                         DeviceOffloadingKind);
815
816
  // For the OpenCL case where there is no offload target, accept -nostdlib to
817
  // disable bitcode linking.
818
44
  if (DeviceOffloadingKind == Action::OFK_None &&
819
44
      DriverArgs.hasArg(options::OPT_nostdlib))
820
0
    return;
821
822
44
  if (DriverArgs.hasArg(options::OPT_nogpulib))
823
8
    return;
824
825
36
  if (!RocmInstallation.hasDeviceLibrary()) {
826
36
    getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 0;
827
36
    return;
828
36
  }
829
830
  // Get the device name and canonicalize it
831
0
  const StringRef GpuArch = getGPUArch(DriverArgs);
832
0
  auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
833
0
  const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
834
0
  std::string LibDeviceFile = RocmInstallation.getLibDeviceFile(CanonArch);
835
0
  if (LibDeviceFile.empty()) {
836
0
    getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 1 << GpuArch;
837
0
    return;
838
0
  }
839
840
0
  bool Wave64 = isWave64(DriverArgs, Kind);
841
842
  // TODO: There are way too many flags that change this. Do we need to check
843
  // them all?
844
0
  bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
845
0
             getDefaultDenormsAreZeroForTarget(Kind);
846
0
  bool FiniteOnly = DriverArgs.hasArg(options::OPT_cl_finite_math_only);
847
848
0
  bool UnsafeMathOpt =
849
0
      DriverArgs.hasArg(options::OPT_cl_unsafe_math_optimizations);
850
0
  bool FastRelaxedMath = DriverArgs.hasArg(options::OPT_cl_fast_relaxed_math);
851
0
  bool CorrectSqrt =
852
0
      DriverArgs.hasArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt);
853
854
  // Add the OpenCL specific bitcode library.
855
0
  llvm::SmallVector<std::string, 12> BCLibs;
856
0
  BCLibs.push_back(RocmInstallation.getOpenCLPath().str());
857
858
  // Add the generic set of libraries.
859
0
  BCLibs.append(RocmInstallation.getCommonBitcodeLibs(
860
0
      DriverArgs, LibDeviceFile, Wave64, DAZ, FiniteOnly, UnsafeMathOpt,
861
0
      FastRelaxedMath, CorrectSqrt));
862
863
0
  llvm::for_each(BCLibs, [&](StringRef BCFile) {
864
0
    CC1Args.push_back("-mlink-builtin-bitcode");
865
0
    CC1Args.push_back(DriverArgs.MakeArgString(BCFile));
866
0
  });
867
0
}
868
869
llvm::SmallVector<std::string, 12>
870
RocmInstallationDetector::getCommonBitcodeLibs(
871
    const llvm::opt::ArgList &DriverArgs, StringRef LibDeviceFile, bool Wave64,
872
    bool DAZ, bool FiniteOnly, bool UnsafeMathOpt, bool FastRelaxedMath,
873
0
    bool CorrectSqrt) const {
874
875
0
  llvm::SmallVector<std::string, 12> BCLibs;
876
877
0
  auto AddBCLib = [&](StringRef BCFile) { BCLibs.push_back(BCFile.str()); };
878
879
0
  AddBCLib(getOCMLPath());
880
0
  AddBCLib(getOCKLPath());
881
0
  AddBCLib(getDenormalsAreZeroPath(DAZ));
882
0
  AddBCLib(getUnsafeMathPath(UnsafeMathOpt || FastRelaxedMath));
883
0
  AddBCLib(getFiniteOnlyPath(FiniteOnly || FastRelaxedMath));
884
0
  AddBCLib(getCorrectlyRoundedSqrtPath(CorrectSqrt));
885
0
  AddBCLib(getWavefrontSize64Path(Wave64));
886
0
  AddBCLib(LibDeviceFile);
887
888
0
  return BCLibs;
889
0
}
890
891
1.00k
bool AMDGPUToolChain::shouldSkipArgument(const llvm::opt::Arg *A) const {
892
1.00k
  Option O = A->getOption();
893
1.00k
  if (O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie))
894
0
    return true;
895
1.00k
  return false;
896
1.00k
}
897
898
llvm::SmallVector<std::string, 12>
899
ROCMToolChain::getCommonDeviceLibNames(const llvm::opt::ArgList &DriverArgs,
900
0
                                       const std::string &GPUArch) const {
901
0
  auto Kind = llvm::AMDGPU::parseArchAMDGCN(GPUArch);
902
0
  const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
903
904
0
  std::string LibDeviceFile = RocmInstallation.getLibDeviceFile(CanonArch);
905
0
  if (LibDeviceFile.empty()) {
906
0
    getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 1 << GPUArch;
907
0
    return {};
908
0
  }
909
910
  // If --hip-device-lib is not set, add the default bitcode libraries.
911
  // TODO: There are way too many flags that change this. Do we need to check
912
  // them all?
913
0
  bool DAZ = DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,
914
0
                                options::OPT_fno_gpu_flush_denormals_to_zero,
915
0
                                getDefaultDenormsAreZeroForTarget(Kind));
916
0
  bool FiniteOnly = DriverArgs.hasFlag(
917
0
      options::OPT_ffinite_math_only, options::OPT_fno_finite_math_only, false);
918
0
  bool UnsafeMathOpt =
919
0
      DriverArgs.hasFlag(options::OPT_funsafe_math_optimizations,
920
0
                         options::OPT_fno_unsafe_math_optimizations, false);
921
0
  bool FastRelaxedMath = DriverArgs.hasFlag(options::OPT_ffast_math,
922
0
                                            options::OPT_fno_fast_math, false);
923
0
  bool CorrectSqrt = DriverArgs.hasFlag(
924
0
      options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
925
0
      options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
926
0
  bool Wave64 = isWave64(DriverArgs, Kind);
927
928
0
  return RocmInstallation.getCommonBitcodeLibs(
929
0
      DriverArgs, LibDeviceFile, Wave64, DAZ, FiniteOnly, UnsafeMathOpt,
930
0
      FastRelaxedMath, CorrectSqrt);
931
0
}