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 "InputInfo.h" 12 #include "clang/Driver/Compilation.h" 13 #include "clang/Driver/DriverDiagnostic.h" 14 #include "llvm/Option/ArgList.h" 15 #include "llvm/Support/Path.h" 16 #include "llvm/Support/VirtualFileSystem.h" 17 18 using namespace clang::driver; 19 using namespace clang::driver::tools; 20 using namespace clang::driver::toolchains; 21 using namespace clang; 22 using namespace llvm::opt; 23 24 void RocmInstallationDetector::scanLibDevicePath() { 25 assert(!LibDevicePath.empty()); 26 27 const StringRef Suffix(".bc"); 28 29 std::error_code EC; 30 for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE; 31 !EC && LI != LE; LI = LI.increment(EC)) { 32 StringRef FilePath = LI->path(); 33 StringRef FileName = llvm::sys::path::filename(FilePath); 34 if (!FileName.endswith(Suffix)) 35 continue; 36 37 StringRef BaseName = FileName.drop_back(Suffix.size()); 38 39 if (BaseName == "ocml") { 40 OCML = FilePath; 41 } else if (BaseName == "ockl") { 42 OCKL = FilePath; 43 } else if (BaseName == "opencl") { 44 OpenCL = FilePath; 45 } else if (BaseName == "hip") { 46 HIP = FilePath; 47 } else if (BaseName == "oclc_finite_only_off") { 48 FiniteOnly.Off = FilePath; 49 } else if (BaseName == "oclc_finite_only_on") { 50 FiniteOnly.On = FilePath; 51 } else if (BaseName == "oclc_daz_opt_on") { 52 DenormalsAreZero.On = FilePath; 53 } else if (BaseName == "oclc_daz_opt_off") { 54 DenormalsAreZero.Off = FilePath; 55 } else if (BaseName == "oclc_correctly_rounded_sqrt_on") { 56 CorrectlyRoundedSqrt.On = FilePath; 57 } else if (BaseName == "oclc_correctly_rounded_sqrt_off") { 58 CorrectlyRoundedSqrt.Off = FilePath; 59 } else if (BaseName == "oclc_unsafe_math_on") { 60 UnsafeMath.On = FilePath; 61 } else if (BaseName == "oclc_unsafe_math_off") { 62 UnsafeMath.Off = FilePath; 63 } else if (BaseName == "oclc_wavefrontsize64_on") { 64 WavefrontSize64.On = FilePath; 65 } else if (BaseName == "oclc_wavefrontsize64_off") { 66 WavefrontSize64.Off = FilePath; 67 } else { 68 // Process all bitcode filenames that look like 69 // ocl_isa_version_XXX.amdgcn.bc 70 const StringRef DeviceLibPrefix = "oclc_isa_version_"; 71 if (!BaseName.startswith(DeviceLibPrefix)) 72 continue; 73 74 StringRef IsaVersionNumber = 75 BaseName.drop_front(DeviceLibPrefix.size()); 76 77 llvm::Twine GfxName = Twine("gfx") + IsaVersionNumber; 78 SmallString<8> Tmp; 79 LibDeviceMap.insert( 80 std::make_pair(GfxName.toStringRef(Tmp), FilePath.str())); 81 } 82 } 83 } 84 85 RocmInstallationDetector::RocmInstallationDetector( 86 const Driver &D, const llvm::Triple &HostTriple, 87 const llvm::opt::ArgList &Args) 88 : D(D) { 89 struct Candidate { 90 std::string Path; 91 bool StrictChecking; 92 93 Candidate(std::string Path, bool StrictChecking = false) 94 : Path(Path), StrictChecking(StrictChecking) {} 95 }; 96 97 SmallVector<Candidate, 4> Candidates; 98 99 if (Args.hasArg(clang::driver::options::OPT_rocm_path_EQ)) { 100 Candidates.emplace_back( 101 Args.getLastArgValue(clang::driver::options::OPT_rocm_path_EQ).str()); 102 } else { 103 // Try to find relative to the compiler binary. 104 const char *InstallDir = D.getInstalledDir(); 105 106 // Check both a normal Unix prefix position of the clang binary, as well as 107 // the Windows-esque layout the ROCm packages use with the host architecture 108 // subdirectory of bin. 109 110 StringRef ParentDir = llvm::sys::path::parent_path(InstallDir); 111 if (ParentDir == HostTriple.getArchName()) 112 ParentDir = llvm::sys::path::parent_path(ParentDir); 113 114 if (ParentDir == "bin") { 115 Candidates.emplace_back(llvm::sys::path::parent_path(ParentDir).str(), 116 /*StrictChecking=*/true); 117 } 118 119 Candidates.emplace_back(D.SysRoot + "/opt/rocm"); 120 } 121 122 bool NoBuiltinLibs = Args.hasArg(options::OPT_nogpulib); 123 124 assert(LibDevicePath.empty()); 125 126 if (Args.hasArg(clang::driver::options::OPT_hip_device_lib_path_EQ)) { 127 LibDevicePath 128 = Args.getLastArgValue(clang::driver::options::OPT_hip_device_lib_path_EQ); 129 } else if (const char *LibPathEnv = ::getenv("HIP_DEVICE_LIB_PATH")) { 130 LibDevicePath = LibPathEnv; 131 } 132 133 if (!LibDevicePath.empty()) { 134 // Maintain compatability with HIP flag/envvar pointing directly at the 135 // bitcode library directory. This points directly at the library path instead 136 // of the rocm root installation. 137 if (!D.getVFS().exists(LibDevicePath)) 138 return; 139 140 scanLibDevicePath(); 141 IsValid = allGenericLibsValid() && !LibDeviceMap.empty(); 142 return; 143 } 144 145 for (const auto &Candidate : Candidates) { 146 InstallPath = Candidate.Path; 147 if (InstallPath.empty() || !D.getVFS().exists(InstallPath)) 148 continue; 149 150 // The install path situation in old versions of ROCm is a real mess, and 151 // use a different install layout. Multiple copies of the device libraries 152 // exist for each frontend project, and differ depending on which build 153 // system produced the packages. Standalone OpenCL builds also have a 154 // different directory structure from the ROCm OpenCL package. 155 // 156 // The desired structure is (${ROCM_ROOT} or 157 // ${OPENCL_ROOT})/amdgcn/bitcode/*, so try to detect this layout. 158 159 // BinPath = InstallPath + "/bin"; 160 llvm::sys::path::append(IncludePath, InstallPath, "include"); 161 llvm::sys::path::append(LibDevicePath, InstallPath, "amdgcn", "bitcode"); 162 163 auto &FS = D.getVFS(); 164 165 // We don't need the include path for OpenCL, since clang already ships with 166 // the default header. 167 168 bool CheckLibDevice = (!NoBuiltinLibs || Candidate.StrictChecking); 169 if (CheckLibDevice && !FS.exists(LibDevicePath)) 170 continue; 171 172 scanLibDevicePath(); 173 174 if (!NoBuiltinLibs) { 175 // Check that the required non-target libraries are all available. 176 if (!allGenericLibsValid()) 177 continue; 178 179 // Check that we have found at least one libdevice that we can link in if 180 // -nobuiltinlib hasn't been specified. 181 if (LibDeviceMap.empty()) 182 continue; 183 } 184 185 IsValid = true; 186 break; 187 } 188 } 189 190 void RocmInstallationDetector::print(raw_ostream &OS) const { 191 if (isValid()) 192 OS << "Found ROCm installation: " << InstallPath << '\n'; 193 } 194 195 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA, 196 const InputInfo &Output, 197 const InputInfoList &Inputs, 198 const ArgList &Args, 199 const char *LinkingOutput) const { 200 201 std::string Linker = getToolChain().GetProgramPath(getShortName()); 202 ArgStringList CmdArgs; 203 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA); 204 CmdArgs.push_back("-shared"); 205 CmdArgs.push_back("-o"); 206 CmdArgs.push_back(Output.getFilename()); 207 C.addCommand(std::make_unique<Command>(JA, *this, Args.MakeArgString(Linker), 208 CmdArgs, Inputs)); 209 } 210 211 void amdgpu::getAMDGPUTargetFeatures(const Driver &D, 212 const llvm::opt::ArgList &Args, 213 std::vector<StringRef> &Features) { 214 if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) 215 D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args); 216 217 if (Args.getLastArg(options::OPT_mwavefrontsize64)) { 218 Features.push_back("-wavefrontsize16"); 219 Features.push_back("-wavefrontsize32"); 220 Features.push_back("+wavefrontsize64"); 221 } 222 if (Args.getLastArg(options::OPT_mno_wavefrontsize64)) { 223 Features.push_back("-wavefrontsize16"); 224 Features.push_back("+wavefrontsize32"); 225 Features.push_back("-wavefrontsize64"); 226 } 227 228 handleTargetFeaturesGroup( 229 Args, Features, options::OPT_m_amdgpu_Features_Group); 230 } 231 232 /// AMDGPU Toolchain 233 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple, 234 const ArgList &Args) 235 : Generic_ELF(D, Triple, Args), 236 OptionsDefault({{options::OPT_O, "3"}, 237 {options::OPT_cl_std_EQ, "CL1.2"}}) {} 238 239 Tool *AMDGPUToolChain::buildLinker() const { 240 return new tools::amdgpu::Linker(*this); 241 } 242 243 DerivedArgList * 244 AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch, 245 Action::OffloadKind DeviceOffloadKind) const { 246 247 DerivedArgList *DAL = 248 Generic_ELF::TranslateArgs(Args, BoundArch, DeviceOffloadKind); 249 250 // Do nothing if not OpenCL (-x cl) 251 if (!Args.getLastArgValue(options::OPT_x).equals("cl")) 252 return DAL; 253 254 if (!DAL) 255 DAL = new DerivedArgList(Args.getBaseArgs()); 256 for (auto *A : Args) 257 DAL->append(A); 258 259 const OptTable &Opts = getDriver().getOpts(); 260 261 // Phase 1 (.cl -> .bc) 262 if (Args.hasArg(options::OPT_c) && Args.hasArg(options::OPT_emit_llvm)) { 263 DAL->AddFlagArg(nullptr, Opts.getOption(getTriple().isArch64Bit() 264 ? options::OPT_m64 265 : options::OPT_m32)); 266 267 // Have to check OPT_O4, OPT_O0 & OPT_Ofast separately 268 // as they defined that way in Options.td 269 if (!Args.hasArg(options::OPT_O, options::OPT_O0, options::OPT_O4, 270 options::OPT_Ofast)) 271 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_O), 272 getOptionDefault(options::OPT_O)); 273 } 274 275 return DAL; 276 } 277 278 bool AMDGPUToolChain::getDefaultDenormsAreZeroForTarget( 279 llvm::AMDGPU::GPUKind Kind) { 280 281 // Assume nothing without a specific target. 282 if (Kind == llvm::AMDGPU::GK_NONE) 283 return false; 284 285 const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind); 286 287 // Default to enabling f32 denormals by default on subtargets where fma is 288 // fast with denormals 289 const bool BothDenormAndFMAFast = 290 (ArchAttr & llvm::AMDGPU::FEATURE_FAST_FMA_F32) && 291 (ArchAttr & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32); 292 return !BothDenormAndFMAFast; 293 } 294 295 llvm::DenormalMode AMDGPUToolChain::getDefaultDenormalModeForType( 296 const llvm::opt::ArgList &DriverArgs, const JobAction &JA, 297 const llvm::fltSemantics *FPType) const { 298 // Denormals should always be enabled for f16 and f64. 299 if (!FPType || FPType != &llvm::APFloat::IEEEsingle()) 300 return llvm::DenormalMode::getIEEE(); 301 302 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP || 303 JA.getOffloadingDeviceKind() == Action::OFK_Cuda) { 304 auto Kind = llvm::AMDGPU::parseArchAMDGCN(JA.getOffloadingArch()); 305 if (FPType && FPType == &llvm::APFloat::IEEEsingle() && 306 DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero, 307 options::OPT_fno_cuda_flush_denormals_to_zero, 308 getDefaultDenormsAreZeroForTarget(Kind))) 309 return llvm::DenormalMode::getPreserveSign(); 310 311 return llvm::DenormalMode::getIEEE(); 312 } 313 314 const StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ); 315 auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch); 316 317 // TODO: There are way too many flags that change this. Do we need to check 318 // them all? 319 bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) || 320 getDefaultDenormsAreZeroForTarget(Kind); 321 322 // Outputs are flushed to zero (FTZ), preserving sign. Denormal inputs are 323 // also implicit treated as zero (DAZ). 324 return DAZ ? llvm::DenormalMode::getPreserveSign() : 325 llvm::DenormalMode::getIEEE(); 326 } 327 328 bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList &DriverArgs, 329 llvm::AMDGPU::GPUKind Kind) { 330 const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind); 331 static bool HasWave32 = (ArchAttr & llvm::AMDGPU::FEATURE_WAVE32); 332 333 return !HasWave32 || DriverArgs.hasFlag( 334 options::OPT_mwavefrontsize64, options::OPT_mno_wavefrontsize64, false); 335 } 336 337 338 /// ROCM Toolchain 339 ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple, 340 const ArgList &Args) 341 : AMDGPUToolChain(D, Triple, Args), 342 RocmInstallation(D, Triple, Args) { } 343 344 void AMDGPUToolChain::addClangTargetOptions( 345 const llvm::opt::ArgList &DriverArgs, 346 llvm::opt::ArgStringList &CC1Args, 347 Action::OffloadKind DeviceOffloadingKind) const { 348 // Default to "hidden" visibility, as object level linking will not be 349 // supported for the foreseeable future. 350 if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ, 351 options::OPT_fvisibility_ms_compat)) { 352 CC1Args.push_back("-fvisibility"); 353 CC1Args.push_back("hidden"); 354 CC1Args.push_back("-fapply-global-visibility-to-externs"); 355 } 356 } 357 358 void ROCMToolChain::addClangTargetOptions( 359 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, 360 Action::OffloadKind DeviceOffloadingKind) const { 361 AMDGPUToolChain::addClangTargetOptions(DriverArgs, CC1Args, 362 DeviceOffloadingKind); 363 364 if (DriverArgs.hasArg(options::OPT_nogpulib)) 365 return; 366 367 if (!RocmInstallation.isValid()) { 368 getDriver().Diag(diag::err_drv_no_rocm_installation); 369 return; 370 } 371 372 // Get the device name and canonicalize it 373 const StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ); 374 auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch); 375 const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind); 376 std::string LibDeviceFile = RocmInstallation.getLibDeviceFile(CanonArch); 377 if (LibDeviceFile.empty()) { 378 getDriver().Diag(diag::err_drv_no_rocm_device_lib) << GpuArch; 379 return; 380 } 381 382 bool Wave64 = isWave64(DriverArgs, Kind); 383 384 // TODO: There are way too many flags that change this. Do we need to check 385 // them all? 386 bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) || 387 getDefaultDenormsAreZeroForTarget(Kind); 388 bool FiniteOnly = DriverArgs.hasArg(options::OPT_cl_finite_math_only); 389 390 bool UnsafeMathOpt = 391 DriverArgs.hasArg(options::OPT_cl_unsafe_math_optimizations); 392 bool FastRelaxedMath = DriverArgs.hasArg(options::OPT_cl_fast_relaxed_math); 393 bool CorrectSqrt = 394 DriverArgs.hasArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt); 395 396 // Add the OpenCL specific bitcode library. 397 CC1Args.push_back("-mlink-builtin-bitcode"); 398 CC1Args.push_back(DriverArgs.MakeArgString(RocmInstallation.getOpenCLPath())); 399 400 // Add the generic set of libraries. 401 RocmInstallation.addCommonBitcodeLibCC1Args( 402 DriverArgs, CC1Args, LibDeviceFile, Wave64, DAZ, FiniteOnly, 403 UnsafeMathOpt, FastRelaxedMath, CorrectSqrt); 404 } 405 406 void RocmInstallationDetector::addCommonBitcodeLibCC1Args( 407 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, 408 StringRef LibDeviceFile, bool Wave64, bool DAZ, bool FiniteOnly, 409 bool UnsafeMathOpt, bool FastRelaxedMath, bool CorrectSqrt) const { 410 static const char LinkBitcodeFlag[] = "-mlink-builtin-bitcode"; 411 412 CC1Args.push_back(LinkBitcodeFlag); 413 CC1Args.push_back(DriverArgs.MakeArgString(getOCMLPath())); 414 415 CC1Args.push_back(LinkBitcodeFlag); 416 CC1Args.push_back(DriverArgs.MakeArgString(getOCKLPath())); 417 418 CC1Args.push_back(LinkBitcodeFlag); 419 CC1Args.push_back(DriverArgs.MakeArgString(getDenormalsAreZeroPath(DAZ))); 420 421 CC1Args.push_back(LinkBitcodeFlag); 422 CC1Args.push_back(DriverArgs.MakeArgString( 423 getUnsafeMathPath(UnsafeMathOpt || FastRelaxedMath))); 424 425 CC1Args.push_back(LinkBitcodeFlag); 426 CC1Args.push_back(DriverArgs.MakeArgString( 427 getFiniteOnlyPath(FiniteOnly || FastRelaxedMath))); 428 429 CC1Args.push_back(LinkBitcodeFlag); 430 CC1Args.push_back( 431 DriverArgs.MakeArgString(getCorrectlyRoundedSqrtPath(CorrectSqrt))); 432 433 CC1Args.push_back(LinkBitcodeFlag); 434 CC1Args.push_back(DriverArgs.MakeArgString(getWavefrontSize64Path(Wave64))); 435 436 CC1Args.push_back(LinkBitcodeFlag); 437 CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile)); 438 } 439