| 1 | //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===// |
| 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 "clang/Driver/Driver.h" |
| 10 | #include "ToolChains/AIX.h" |
| 11 | #include "ToolChains/AMDGPU.h" |
| 12 | #include "ToolChains/AMDGPUOpenMP.h" |
| 13 | #include "ToolChains/AVR.h" |
| 14 | #include "ToolChains/Arch/RISCV.h" |
| 15 | #include "ToolChains/BareMetal.h" |
| 16 | #include "ToolChains/CSKYToolChain.h" |
| 17 | #include "ToolChains/Clang.h" |
| 18 | #include "ToolChains/CrossWindows.h" |
| 19 | #include "ToolChains/Cuda.h" |
| 20 | #include "ToolChains/Cygwin.h" |
| 21 | #include "ToolChains/Darwin.h" |
| 22 | #include "ToolChains/DragonFly.h" |
| 23 | #include "ToolChains/FreeBSD.h" |
| 24 | #include "ToolChains/Fuchsia.h" |
| 25 | #include "ToolChains/Gnu.h" |
| 26 | #include "ToolChains/HIPAMD.h" |
| 27 | #include "ToolChains/HIPSPV.h" |
| 28 | #include "ToolChains/HLSL.h" |
| 29 | #include "ToolChains/Haiku.h" |
| 30 | #include "ToolChains/Hexagon.h" |
| 31 | #include "ToolChains/Hurd.h" |
| 32 | #include "ToolChains/LFILinux.h" |
| 33 | #include "ToolChains/Lanai.h" |
| 34 | #include "ToolChains/Linux.h" |
| 35 | #include "ToolChains/MSP430.h" |
| 36 | #include "ToolChains/MSVC.h" |
| 37 | #include "ToolChains/Managarm.h" |
| 38 | #include "ToolChains/MinGW.h" |
| 39 | #include "ToolChains/MipsLinux.h" |
| 40 | #include "ToolChains/NetBSD.h" |
| 41 | #include "ToolChains/OHOS.h" |
| 42 | #include "ToolChains/OpenBSD.h" |
| 43 | #include "ToolChains/PPCFreeBSD.h" |
| 44 | #include "ToolChains/PPCLinux.h" |
| 45 | #include "ToolChains/PS4CPU.h" |
| 46 | #include "ToolChains/SPIRV.h" |
| 47 | #include "ToolChains/SPIRVOpenMP.h" |
| 48 | #include "ToolChains/SYCL.h" |
| 49 | #include "ToolChains/Solaris.h" |
| 50 | #include "ToolChains/TCE.h" |
| 51 | #include "ToolChains/UEFI.h" |
| 52 | #include "ToolChains/VEToolchain.h" |
| 53 | #include "ToolChains/WebAssembly.h" |
| 54 | #include "ToolChains/XCore.h" |
| 55 | #include "ToolChains/ZOS.h" |
| 56 | #include "clang/Basic/DiagnosticDriver.h" |
| 57 | #include "clang/Basic/TargetID.h" |
| 58 | #include "clang/Basic/Version.h" |
| 59 | #include "clang/Config/config.h" |
| 60 | #include "clang/Driver/Action.h" |
| 61 | #include "clang/Driver/Compilation.h" |
| 62 | #include "clang/Driver/InputInfo.h" |
| 63 | #include "clang/Driver/Job.h" |
| 64 | #include "clang/Driver/Phases.h" |
| 65 | #include "clang/Driver/SanitizerArgs.h" |
| 66 | #include "clang/Driver/Tool.h" |
| 67 | #include "clang/Driver/ToolChain.h" |
| 68 | #include "clang/Driver/Types.h" |
| 69 | #include "clang/Options/OptionUtils.h" |
| 70 | #include "clang/Options/Options.h" |
| 71 | #include "llvm/ADT/ArrayRef.h" |
| 72 | #include "llvm/ADT/STLExtras.h" |
| 73 | #include "llvm/ADT/SmallSet.h" |
| 74 | #include "llvm/ADT/SmallVector.h" |
| 75 | #include "llvm/ADT/StringExtras.h" |
| 76 | #include "llvm/ADT/StringRef.h" |
| 77 | #include "llvm/ADT/StringSet.h" |
| 78 | #include "llvm/ADT/StringSwitch.h" |
| 79 | #include "llvm/Config/llvm-config.h" |
| 80 | #include "llvm/MC/TargetRegistry.h" |
| 81 | #include "llvm/Option/Arg.h" |
| 82 | #include "llvm/Option/ArgList.h" |
| 83 | #include "llvm/Option/OptSpecifier.h" |
| 84 | #include "llvm/Option/OptTable.h" |
| 85 | #include "llvm/Option/Option.h" |
| 86 | #include "llvm/Support/CommandLine.h" |
| 87 | #include "llvm/Support/ErrorHandling.h" |
| 88 | #include "llvm/Support/ExitCodes.h" |
| 89 | #include "llvm/Support/FileSystem.h" |
| 90 | #include "llvm/Support/FileUtilities.h" |
| 91 | #include "llvm/Support/FormatVariadic.h" |
| 92 | #include "llvm/Support/IOSandbox.h" |
| 93 | #include "llvm/Support/MD5.h" |
| 94 | #include "llvm/Support/Path.h" |
| 95 | #include "llvm/Support/PrettyStackTrace.h" |
| 96 | #include "llvm/Support/Process.h" |
| 97 | #include "llvm/Support/Program.h" |
| 98 | #include "llvm/Support/Regex.h" |
| 99 | #include "llvm/Support/StringSaver.h" |
| 100 | #include "llvm/Support/VirtualFileSystem.h" |
| 101 | #include "llvm/Support/raw_ostream.h" |
| 102 | #include "llvm/TargetParser/Host.h" |
| 103 | #include "llvm/TargetParser/RISCVISAInfo.h" |
| 104 | #include <cstdlib> // ::getenv |
| 105 | #include <map> |
| 106 | #include <memory> |
| 107 | #include <optional> |
| 108 | #include <set> |
| 109 | #include <string> |
| 110 | #include <utility> |
| 111 | #if LLVM_ON_UNIX |
| 112 | #include <unistd.h> // getpid |
| 113 | #endif |
| 114 | |
| 115 | using namespace clang::driver; |
| 116 | using namespace clang; |
| 117 | using namespace llvm::opt; |
| 118 | |
| 119 | template <typename F> static bool usesInput(const ArgList &Args, F &&Fn) { |
| 120 | return llvm::any_of(Args, [&](Arg *A) { |
| 121 | return (A->getOption().matches(ID: options::OPT_x) && |
| 122 | Fn(types::lookupTypeForTypeSpecifier(Name: A->getValue()))) || |
| 123 | (A->getOption().getKind() == Option::InputClass && |
| 124 | StringRef(A->getValue()).rfind(C: '.') != StringRef::npos && |
| 125 | Fn(types::lookupTypeForExtension( |
| 126 | Ext: &A->getValue()[StringRef(A->getValue()).rfind(C: '.') + 1]))); |
| 127 | }); |
| 128 | } |
| 129 | |
| 130 | CUIDOptions::CUIDOptions(llvm::opt::DerivedArgList &Args, const Driver &D) |
| 131 | : UseCUID(Kind::Hash) { |
| 132 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fuse_cuid_EQ)) { |
| 133 | StringRef UseCUIDStr = A->getValue(); |
| 134 | UseCUID = llvm::StringSwitch<Kind>(UseCUIDStr) |
| 135 | .Case(S: "hash" , Value: Kind::Hash) |
| 136 | .Case(S: "random" , Value: Kind::Random) |
| 137 | .Case(S: "none" , Value: Kind::None) |
| 138 | .Default(Value: Kind::Invalid); |
| 139 | if (UseCUID == Kind::Invalid) |
| 140 | D.Diag(DiagID: clang::diag::err_drv_invalid_value) |
| 141 | << A->getAsString(Args) << UseCUIDStr; |
| 142 | } |
| 143 | |
| 144 | FixedCUID = Args.getLastArgValue(Id: options::OPT_cuid_EQ); |
| 145 | if (!FixedCUID.empty()) |
| 146 | UseCUID = Kind::Fixed; |
| 147 | } |
| 148 | |
| 149 | std::string CUIDOptions::getCUID(StringRef InputFile, |
| 150 | llvm::opt::DerivedArgList &Args) const { |
| 151 | std::string CUID = FixedCUID.str(); |
| 152 | if (CUID.empty()) { |
| 153 | if (UseCUID == Kind::Random) |
| 154 | CUID = llvm::utohexstr(X: llvm::sys::Process::GetRandomNumber(), |
| 155 | /*LowerCase=*/true); |
| 156 | else if (UseCUID == Kind::Hash) { |
| 157 | llvm::MD5 Hasher; |
| 158 | llvm::MD5::MD5Result Hash; |
| 159 | Hasher.update(Str: InputFile); |
| 160 | for (auto *A : Args) { |
| 161 | if (A->getOption().matches(ID: options::OPT_INPUT)) |
| 162 | continue; |
| 163 | Hasher.update(Str: A->getAsString(Args)); |
| 164 | } |
| 165 | Hasher.final(Result&: Hash); |
| 166 | CUID = llvm::utohexstr(X: Hash.low(), /*LowerCase=*/true); |
| 167 | } |
| 168 | } |
| 169 | return CUID; |
| 170 | } |
| 171 | Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple, |
| 172 | DiagnosticsEngine &Diags, std::string Title, |
| 173 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) |
| 174 | : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode), |
| 175 | SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), |
| 176 | Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None), |
| 177 | ModulesModeCXX20(false), LTOMode(LTOK_None), |
| 178 | ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT), |
| 179 | DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false), |
| 180 | CCLogDiagnostics(false), CCGenDiagnostics(false), |
| 181 | CCPrintProcessStats(false), CCPrintInternalStats(false), |
| 182 | TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr), |
| 183 | PreferredLinker(CLANG_DEFAULT_LINKER), CheckInputsExist(true), |
| 184 | ProbePrecompiled(true), SuppressMissingInputWarning(false) { |
| 185 | // Provide a sane fallback if no VFS is specified. |
| 186 | if (!this->VFS) |
| 187 | this->VFS = llvm::vfs::getRealFileSystem(); |
| 188 | |
| 189 | Name = std::string(llvm::sys::path::filename(path: ClangExecutable)); |
| 190 | Dir = std::string(llvm::sys::path::parent_path(path: ClangExecutable)); |
| 191 | |
| 192 | if ((!SysRoot.empty()) && llvm::sys::path::is_relative(path: SysRoot)) { |
| 193 | // Prepend InstalledDir if SysRoot is relative |
| 194 | SmallString<128> P(Dir); |
| 195 | llvm::sys::path::append(path&: P, a: SysRoot); |
| 196 | SysRoot = std::string(P); |
| 197 | } |
| 198 | |
| 199 | #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR) |
| 200 | if (llvm::sys::path::is_absolute(CLANG_CONFIG_FILE_SYSTEM_DIR)) { |
| 201 | SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR; |
| 202 | } else { |
| 203 | SmallString<128> configFileDir(Dir); |
| 204 | llvm::sys::path::append(configFileDir, CLANG_CONFIG_FILE_SYSTEM_DIR); |
| 205 | llvm::sys::path::remove_dots(configFileDir, true); |
| 206 | SystemConfigDir = static_cast<std::string>(configFileDir); |
| 207 | } |
| 208 | #endif |
| 209 | #if defined(CLANG_CONFIG_FILE_USER_DIR) |
| 210 | { |
| 211 | SmallString<128> P; |
| 212 | llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR, P); |
| 213 | UserConfigDir = static_cast<std::string>(P); |
| 214 | } |
| 215 | #endif |
| 216 | |
| 217 | // Compute the path to the resource directory. |
| 218 | ResourceDir = GetResourcesPath(BinaryPath: ClangExecutable); |
| 219 | } |
| 220 | |
| 221 | void Driver::setDriverMode(StringRef Value) { |
| 222 | static StringRef OptName = |
| 223 | getOpts().getOption(Opt: options::OPT_driver_mode).getPrefixedName(); |
| 224 | if (auto M = llvm::StringSwitch<std::optional<DriverMode>>(Value) |
| 225 | .Case(S: "gcc" , Value: GCCMode) |
| 226 | .Case(S: "g++" , Value: GXXMode) |
| 227 | .Case(S: "cpp" , Value: CPPMode) |
| 228 | .Case(S: "cl" , Value: CLMode) |
| 229 | .Case(S: "flang" , Value: FlangMode) |
| 230 | .Case(S: "dxc" , Value: DXCMode) |
| 231 | .Default(Value: std::nullopt)) |
| 232 | Mode = *M; |
| 233 | else |
| 234 | Diag(DiagID: diag::err_drv_unsupported_option_argument) << OptName << Value; |
| 235 | } |
| 236 | |
| 237 | InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings, |
| 238 | bool UseDriverMode, |
| 239 | bool &ContainsError) const { |
| 240 | llvm::PrettyStackTraceString CrashInfo("Command line argument parsing" ); |
| 241 | ContainsError = false; |
| 242 | |
| 243 | llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(UseDriverMode); |
| 244 | unsigned MissingArgIndex, MissingArgCount; |
| 245 | InputArgList Args = getOpts().ParseArgs(Args: ArgStrings, MissingArgIndex, |
| 246 | MissingArgCount, VisibilityMask); |
| 247 | |
| 248 | // Check for missing argument error. |
| 249 | if (MissingArgCount) { |
| 250 | Diag(DiagID: diag::err_drv_missing_argument) |
| 251 | << Args.getArgString(Index: MissingArgIndex) << MissingArgCount; |
| 252 | ContainsError |= |
| 253 | Diags.getDiagnosticLevel(DiagID: diag::err_drv_missing_argument, |
| 254 | Loc: SourceLocation()) > DiagnosticsEngine::Warning; |
| 255 | } |
| 256 | |
| 257 | // Check for unsupported options. |
| 258 | for (const Arg *A : Args) { |
| 259 | if (A->getOption().hasFlag(Val: options::Unsupported)) { |
| 260 | Diag(DiagID: diag::err_drv_unsupported_opt) << A->getAsString(Args); |
| 261 | ContainsError |= Diags.getDiagnosticLevel(DiagID: diag::err_drv_unsupported_opt, |
| 262 | Loc: SourceLocation()) > |
| 263 | DiagnosticsEngine::Warning; |
| 264 | continue; |
| 265 | } |
| 266 | |
| 267 | // Warn about -mcpu= without an argument. |
| 268 | if (A->getOption().matches(ID: options::OPT_mcpu_EQ) && A->containsValue(Value: "" )) { |
| 269 | Diag(DiagID: diag::warn_drv_empty_joined_argument) << A->getAsString(Args); |
| 270 | ContainsError |= Diags.getDiagnosticLevel( |
| 271 | DiagID: diag::warn_drv_empty_joined_argument, |
| 272 | Loc: SourceLocation()) > DiagnosticsEngine::Warning; |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | for (const Arg *A : Args.filtered(Ids: options::OPT_UNKNOWN)) { |
| 277 | unsigned DiagID; |
| 278 | auto ArgString = A->getAsString(Args); |
| 279 | std::string Nearest; |
| 280 | if (getOpts().findNearest(Option: ArgString, NearestString&: Nearest, VisibilityMask) > 1) { |
| 281 | if (IsFlangMode()) { |
| 282 | if (getOpts().findExact(Option: ArgString, ExactString&: Nearest, |
| 283 | VisibilityMask: llvm::opt::Visibility(options::FC1Option))) { |
| 284 | DiagID = diag::err_drv_unknown_argument_with_suggestion; |
| 285 | Diags.Report(DiagID) << ArgString << "-Xflang " + Nearest; |
| 286 | } else { |
| 287 | DiagID = diag::err_drv_unknown_argument; |
| 288 | Diags.Report(DiagID) << ArgString; |
| 289 | } |
| 290 | } else if (!IsCLMode() && getOpts().findExact(Option: ArgString, ExactString&: Nearest, |
| 291 | VisibilityMask: llvm::opt::Visibility( |
| 292 | options::CC1Option))) { |
| 293 | DiagID = diag::err_drv_unknown_argument_with_suggestion; |
| 294 | Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest; |
| 295 | } else { |
| 296 | DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl |
| 297 | : diag::err_drv_unknown_argument; |
| 298 | Diags.Report(DiagID) << ArgString; |
| 299 | } |
| 300 | } else { |
| 301 | DiagID = IsCLMode() |
| 302 | ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion |
| 303 | : diag::err_drv_unknown_argument_with_suggestion; |
| 304 | Diags.Report(DiagID) << ArgString << Nearest; |
| 305 | } |
| 306 | ContainsError |= Diags.getDiagnosticLevel(DiagID, Loc: SourceLocation()) > |
| 307 | DiagnosticsEngine::Warning; |
| 308 | } |
| 309 | |
| 310 | for (const Arg *A : Args.filtered(Ids: options::OPT_o)) { |
| 311 | if (ArgStrings[A->getIndex()] == A->getSpelling()) |
| 312 | continue; |
| 313 | |
| 314 | // Warn on joined arguments that are similar to a long argument. |
| 315 | std::string ArgString = ArgStrings[A->getIndex()]; |
| 316 | std::string Nearest; |
| 317 | if (getOpts().findExact(Option: "-" + ArgString, ExactString&: Nearest, VisibilityMask)) |
| 318 | Diags.Report(DiagID: diag::warn_drv_potentially_misspelled_joined_argument) |
| 319 | << A->getAsString(Args) << Nearest; |
| 320 | } |
| 321 | |
| 322 | return Args; |
| 323 | } |
| 324 | |
| 325 | // Determine which compilation mode we are in. We look for options which |
| 326 | // affect the phase, starting with the earliest phases, and record which |
| 327 | // option we used to determine the final phase. |
| 328 | phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, |
| 329 | Arg **FinalPhaseArg) const { |
| 330 | Arg *PhaseArg = nullptr; |
| 331 | phases::ID FinalPhase; |
| 332 | |
| 333 | // -{E,EP,P,M,MM} only run the preprocessor. |
| 334 | if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(Ids: options::OPT_E)) || |
| 335 | (PhaseArg = DAL.getLastArg(Ids: options::OPT__SLASH_EP)) || |
| 336 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_M, Ids: options::OPT_MM)) || |
| 337 | (PhaseArg = DAL.getLastArg(Ids: options::OPT__SLASH_P)) || |
| 338 | CCGenDiagnostics) { |
| 339 | FinalPhase = phases::Preprocess; |
| 340 | |
| 341 | // --precompile only runs up to precompilation. |
| 342 | // Options that cause the output of C++20 compiled module interfaces or |
| 343 | // header units have the same effect. |
| 344 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT__precompile)) || |
| 345 | (PhaseArg = |
| 346 | DAL.getLastArg(Ids: options::OPT__precompile_reduced_bmi)) || |
| 347 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_extract_api)) || |
| 348 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_fmodule_header, |
| 349 | Ids: options::OPT_fmodule_header_EQ))) { |
| 350 | FinalPhase = phases::Precompile; |
| 351 | // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler. |
| 352 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_fsyntax_only)) || |
| 353 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_print_supported_cpus)) || |
| 354 | (PhaseArg = |
| 355 | DAL.getLastArg(Ids: options::OPT_print_enabled_extensions)) || |
| 356 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_module_file_info)) || |
| 357 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_verify_pch)) || |
| 358 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_rewrite_objc)) || |
| 359 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_rewrite_legacy_objc)) || |
| 360 | (PhaseArg = DAL.getLastArg(Ids: options::OPT__analyze)) || |
| 361 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_emit_cir)) || |
| 362 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_emit_ast))) { |
| 363 | FinalPhase = phases::Compile; |
| 364 | |
| 365 | // -S only runs up to the backend. |
| 366 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_S))) { |
| 367 | FinalPhase = phases::Backend; |
| 368 | |
| 369 | // -c compilation only runs up to the assembler. |
| 370 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_c))) { |
| 371 | FinalPhase = phases::Assemble; |
| 372 | |
| 373 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_emit_interface_stubs))) { |
| 374 | FinalPhase = phases::IfsMerge; |
| 375 | |
| 376 | // Otherwise do everything. |
| 377 | } else |
| 378 | FinalPhase = phases::Link; |
| 379 | |
| 380 | if (FinalPhaseArg) |
| 381 | *FinalPhaseArg = PhaseArg; |
| 382 | |
| 383 | return FinalPhase; |
| 384 | } |
| 385 | |
| 386 | llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> |
| 387 | Driver::executeProgram(llvm::ArrayRef<llvm::StringRef> Args) const { |
| 388 | llvm::SmallString<64> OutputFile; |
| 389 | llvm::sys::fs::createTemporaryFile(Prefix: "driver-program" , Suffix: "txt" , ResultPath&: OutputFile, |
| 390 | Flags: llvm::sys::fs::OF_Text); |
| 391 | llvm::FileRemover OutputRemover(OutputFile.c_str()); |
| 392 | std::optional<llvm::StringRef> Redirects[] = { |
| 393 | {"" }, |
| 394 | OutputFile.str(), |
| 395 | {"" }, |
| 396 | }; |
| 397 | |
| 398 | std::string ErrorMessage; |
| 399 | int SecondsToWait = 60; |
| 400 | if (std::optional<std::string> Str = |
| 401 | llvm::sys::Process::GetEnv(name: "CLANG_TOOLCHAIN_PROGRAM_TIMEOUT" )) { |
| 402 | if (!llvm::to_integer(S: *Str, Num&: SecondsToWait)) |
| 403 | return llvm::createStringError(EC: std::error_code(), |
| 404 | S: "CLANG_TOOLCHAIN_PROGRAM_TIMEOUT expected " |
| 405 | "an integer, got '" + |
| 406 | *Str + "'" ); |
| 407 | SecondsToWait = std::max(a: SecondsToWait, b: 0); // infinite |
| 408 | } |
| 409 | StringRef Executable = Args[0]; |
| 410 | if (llvm::sys::ExecuteAndWait(Program: Executable, Args, Env: {}, Redirects, SecondsToWait, |
| 411 | /*MemoryLimit=*/0, ErrMsg: &ErrorMessage)) |
| 412 | return llvm::createStringError(EC: std::error_code(), |
| 413 | S: Executable + ": " + ErrorMessage); |
| 414 | |
| 415 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> OutputBuf = |
| 416 | llvm::MemoryBuffer::getFile(Filename: OutputFile.c_str()); |
| 417 | if (!OutputBuf) |
| 418 | return llvm::createStringError(EC: OutputBuf.getError(), |
| 419 | S: "Failed to read stdout of " + Executable + |
| 420 | ": " + OutputBuf.getError().message()); |
| 421 | return std::move(*OutputBuf); |
| 422 | } |
| 423 | |
| 424 | Arg *clang::driver::makeInputArg(DerivedArgList &Args, const OptTable &Opts, |
| 425 | StringRef Value, bool Claim) { |
| 426 | Arg *A = new Arg(Opts.getOption(Opt: options::OPT_INPUT), Value, |
| 427 | Args.getBaseArgs().MakeIndex(String0: Value), Value.data()); |
| 428 | Args.AddSynthesizedArg(A); |
| 429 | if (Claim) |
| 430 | A->claim(); |
| 431 | return A; |
| 432 | } |
| 433 | |
| 434 | DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { |
| 435 | const llvm::opt::OptTable &Opts = getOpts(); |
| 436 | DerivedArgList *DAL = new DerivedArgList(Args); |
| 437 | |
| 438 | bool HasNostdlib = Args.hasArg(Ids: options::OPT_nostdlib); |
| 439 | bool HasNostdlibxx = Args.hasArg(Ids: options::OPT_nostdlibxx); |
| 440 | bool HasNodefaultlib = Args.hasArg(Ids: options::OPT_nodefaultlibs); |
| 441 | bool IgnoreUnused = false; |
| 442 | for (Arg *A : Args) { |
| 443 | if (IgnoreUnused) |
| 444 | A->claim(); |
| 445 | |
| 446 | if (A->getOption().matches(ID: options::OPT_start_no_unused_arguments)) { |
| 447 | IgnoreUnused = true; |
| 448 | continue; |
| 449 | } |
| 450 | if (A->getOption().matches(ID: options::OPT_end_no_unused_arguments)) { |
| 451 | IgnoreUnused = false; |
| 452 | continue; |
| 453 | } |
| 454 | |
| 455 | // Unfortunately, we have to parse some forwarding options (-Xassembler, |
| 456 | // -Xlinker, -Xpreprocessor) because we either integrate their functionality |
| 457 | // (assembler and preprocessor), or bypass a previous driver ('collect2'). |
| 458 | |
| 459 | // Rewrite linker options, to replace --no-demangle with a custom internal |
| 460 | // option. |
| 461 | if ((A->getOption().matches(ID: options::OPT_Wl_COMMA) || |
| 462 | A->getOption().matches(ID: options::OPT_Xlinker)) && |
| 463 | A->containsValue(Value: "--no-demangle" )) { |
| 464 | // Add the rewritten no-demangle argument. |
| 465 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Z_Xlinker__no_demangle)); |
| 466 | |
| 467 | // Add the remaining values as Xlinker arguments. |
| 468 | for (StringRef Val : A->getValues()) |
| 469 | if (Val != "--no-demangle" ) |
| 470 | DAL->AddSeparateArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Xlinker), Value: Val); |
| 471 | |
| 472 | continue; |
| 473 | } |
| 474 | |
| 475 | // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by |
| 476 | // some build systems. We don't try to be complete here because we don't |
| 477 | // care to encourage this usage model. |
| 478 | if (A->getOption().matches(ID: options::OPT_Wp_COMMA) && |
| 479 | A->getNumValues() > 0 && |
| 480 | (A->getValue(N: 0) == StringRef("-MD" ) || |
| 481 | A->getValue(N: 0) == StringRef("-MMD" ))) { |
| 482 | // Rewrite to -MD/-MMD along with -MF. |
| 483 | if (A->getValue(N: 0) == StringRef("-MD" )) |
| 484 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MD)); |
| 485 | else |
| 486 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MMD)); |
| 487 | if (A->getNumValues() == 2) |
| 488 | DAL->AddSeparateArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MF), Value: A->getValue(N: 1)); |
| 489 | continue; |
| 490 | } |
| 491 | |
| 492 | // Rewrite reserved library names. |
| 493 | if (A->getOption().matches(ID: options::OPT_l)) { |
| 494 | StringRef Value = A->getValue(); |
| 495 | |
| 496 | // Rewrite unless -nostdlib is present. |
| 497 | if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx && |
| 498 | Value == "stdc++" ) { |
| 499 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Z_reserved_lib_stdcxx)); |
| 500 | continue; |
| 501 | } |
| 502 | |
| 503 | // Rewrite unconditionally. |
| 504 | if (Value == "cc_kext" ) { |
| 505 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Z_reserved_lib_cckext)); |
| 506 | continue; |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | // Pick up inputs via the -- option. |
| 511 | if (A->getOption().matches(ID: options::OPT__DASH_DASH)) { |
| 512 | A->claim(); |
| 513 | for (StringRef Val : A->getValues()) |
| 514 | DAL->append(A: makeInputArg(Args&: *DAL, Opts, Value: Val, Claim: false)); |
| 515 | continue; |
| 516 | } |
| 517 | |
| 518 | DAL->append(A); |
| 519 | } |
| 520 | |
| 521 | // DXC mode quits before assembly if an output object file isn't specified. |
| 522 | if (IsDXCMode() && !Args.hasArg(Ids: options::OPT_dxc_Fo)) |
| 523 | DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_S)); |
| 524 | |
| 525 | // Enforce -static if -miamcu is present. |
| 526 | if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) |
| 527 | DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_static)); |
| 528 | |
| 529 | // Add a default value of -mlinker-version=, if one was given and the user |
| 530 | // didn't specify one. |
| 531 | #if defined(HOST_LINK_VERSION) |
| 532 | if (!Args.hasArg(options::OPT_mlinker_version_EQ) && |
| 533 | strlen(HOST_LINK_VERSION) > 0) { |
| 534 | DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ), |
| 535 | HOST_LINK_VERSION); |
| 536 | DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); |
| 537 | } |
| 538 | #endif |
| 539 | |
| 540 | return DAL; |
| 541 | } |
| 542 | |
| 543 | static void setZosTargetVersion(const Driver &D, llvm::Triple &Target, |
| 544 | StringRef ArgTarget) { |
| 545 | |
| 546 | static bool BeSilent = false; |
| 547 | auto IsTooOldToBeSupported = [](int v, int r) -> bool { |
| 548 | return ((v < 2) || ((v == 2) && (r < 4))); |
| 549 | }; |
| 550 | |
| 551 | /* expect CURRENT, zOSV2R[45], or 0xnnnnnnnn */ |
| 552 | if (ArgTarget.equals_insensitive(RHS: "CURRENT" )) { |
| 553 | /* If the user gives CURRENT, then we rely on the LE to set */ |
| 554 | /* __TARGET_LIB__. There's nothing more we need to do. */ |
| 555 | } else { |
| 556 | unsigned int Version = 0; |
| 557 | unsigned int Release = 0; |
| 558 | unsigned int Modification = 0; |
| 559 | bool IsOk = true; |
| 560 | llvm::Regex ZOsvRegex("[zZ][oO][sS][vV]([0-9])[rR]([0-9])" ); |
| 561 | llvm::Regex HexRegex( |
| 562 | "0x4" /* product */ |
| 563 | "([0-9a-fA-F])" /* version */ |
| 564 | "([0-9a-fA-F][0-9a-fA-F])" /* release */ |
| 565 | "([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])" /* modification */); |
| 566 | SmallVector<StringRef> Matches; |
| 567 | |
| 568 | if (ZOsvRegex.match(String: ArgTarget, Matches: &Matches)) { |
| 569 | Matches[1].getAsInteger(Radix: 10, Result&: Version); |
| 570 | Matches[2].getAsInteger(Radix: 10, Result&: Release); |
| 571 | Modification = 0; |
| 572 | if (IsTooOldToBeSupported(Version, Release)) { |
| 573 | if (!BeSilent) |
| 574 | D.Diag(DiagID: diag::err_zos_target_release_discontinued) << ArgTarget; |
| 575 | IsOk = false; |
| 576 | } |
| 577 | } else if (HexRegex.match(String: ArgTarget, Matches: &Matches)) { |
| 578 | Matches[1].getAsInteger(Radix: 16, Result&: Version); |
| 579 | Matches[2].getAsInteger(Radix: 16, Result&: Release); |
| 580 | Matches[3].getAsInteger(Radix: 16, Result&: Modification); |
| 581 | if (IsTooOldToBeSupported(Version, Release)) { |
| 582 | if (!BeSilent) |
| 583 | D.Diag(DiagID: diag::err_zos_target_release_discontinued) << ArgTarget; |
| 584 | IsOk = false; |
| 585 | } |
| 586 | } else { |
| 587 | /* something else: need to report an error */ |
| 588 | if (!BeSilent) |
| 589 | D.Diag(DiagID: diag::err_zos_target_unrecognized_release) << ArgTarget; |
| 590 | IsOk = false; |
| 591 | } |
| 592 | |
| 593 | if (IsOk) { |
| 594 | llvm::VersionTuple V(Version, Release, Modification); |
| 595 | llvm::VersionTuple TV = Target.getOSVersion(); |
| 596 | // The goal is to pick the minimally supported version of |
| 597 | // the OS. Pick the lesser as the target. |
| 598 | if (TV.empty() || V < TV) { |
| 599 | SmallString<16> Str; |
| 600 | Str = llvm::Triple::getOSTypeName(Kind: Target.getOS()); |
| 601 | Str += V.getAsString(); |
| 602 | Target.setOSName(Str); |
| 603 | } |
| 604 | } |
| 605 | } |
| 606 | BeSilent = true; |
| 607 | } |
| 608 | |
| 609 | /// Compute target triple from args. |
| 610 | /// |
| 611 | /// This routine provides the logic to compute a target triple from various |
| 612 | /// args passed to the driver and the default triple string. |
| 613 | static llvm::Triple computeTargetTriple(const Driver &D, |
| 614 | StringRef TargetTriple, |
| 615 | const ArgList &Args, |
| 616 | StringRef DarwinArchName = "" ) { |
| 617 | // FIXME: Already done in Compilation *Driver::BuildCompilation |
| 618 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_target)) |
| 619 | TargetTriple = A->getValue(); |
| 620 | |
| 621 | llvm::Triple Target(llvm::Triple::normalize(Str: TargetTriple)); |
| 622 | |
| 623 | // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made |
| 624 | // -gnu* only, and we can not change this, so we have to detect that case as |
| 625 | // being the Hurd OS. |
| 626 | if (TargetTriple.contains(Other: "-unknown-gnu" ) || TargetTriple.contains(Other: "-pc-gnu" )) |
| 627 | Target.setOSName("hurd" ); |
| 628 | |
| 629 | // Handle Apple-specific options available here. |
| 630 | if (Target.isOSBinFormatMachO()) { |
| 631 | // If an explicit Darwin arch name is given, that trumps all. |
| 632 | if (!DarwinArchName.empty()) { |
| 633 | tools::darwin::setTripleTypeForMachOArchName(T&: Target, Str: DarwinArchName, |
| 634 | Args); |
| 635 | return Target; |
| 636 | } |
| 637 | |
| 638 | // Handle the Darwin '-arch' flag. |
| 639 | if (Arg *A = Args.getLastArg(Ids: options::OPT_arch)) { |
| 640 | StringRef ArchName = A->getValue(); |
| 641 | tools::darwin::setTripleTypeForMachOArchName(T&: Target, Str: ArchName, Args); |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | // Handle pseudo-target flags '-mlittle-endian'/'-EL' and |
| 646 | // '-mbig-endian'/'-EB'. |
| 647 | if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_mlittle_endian, |
| 648 | Ids: options::OPT_mbig_endian)) { |
| 649 | llvm::Triple T = A->getOption().matches(ID: options::OPT_mlittle_endian) |
| 650 | ? Target.getLittleEndianArchVariant() |
| 651 | : Target.getBigEndianArchVariant(); |
| 652 | if (T.getArch() != llvm::Triple::UnknownArch) { |
| 653 | Target = std::move(T); |
| 654 | Args.claimAllArgs(Ids: options::OPT_mlittle_endian, Ids: options::OPT_mbig_endian); |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | // Skip further flag support on OSes which don't support '-m32' or '-m64'. |
| 659 | if (Target.getArch() == llvm::Triple::tce) |
| 660 | return Target; |
| 661 | |
| 662 | // On AIX, the env OBJECT_MODE may affect the resulting arch variant. |
| 663 | if (Target.isOSAIX()) { |
| 664 | if (std::optional<std::string> ObjectModeValue = |
| 665 | llvm::sys::Process::GetEnv(name: "OBJECT_MODE" )) { |
| 666 | StringRef ObjectMode = *ObjectModeValue; |
| 667 | llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; |
| 668 | |
| 669 | if (ObjectMode == "64" ) { |
| 670 | AT = Target.get64BitArchVariant().getArch(); |
| 671 | } else if (ObjectMode == "32" ) { |
| 672 | AT = Target.get32BitArchVariant().getArch(); |
| 673 | } else { |
| 674 | D.Diag(DiagID: diag::err_drv_invalid_object_mode) << ObjectMode; |
| 675 | } |
| 676 | |
| 677 | if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) |
| 678 | Target.setArch(Kind: AT); |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | // Currently the only architecture supported by *-uefi triples are x86_64. |
| 683 | if (Target.isUEFI() && Target.getArch() != llvm::Triple::x86_64) |
| 684 | D.Diag(DiagID: diag::err_target_unknown_triple) << Target.str(); |
| 685 | |
| 686 | // The `-maix[32|64]` flags are only valid for AIX targets. |
| 687 | if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_maix32, Ids: options::OPT_maix64); |
| 688 | A && !Target.isOSAIX()) |
| 689 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 690 | << A->getAsString(Args) << Target.str(); |
| 691 | |
| 692 | // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'. |
| 693 | Arg *A = Args.getLastArg(Ids: options::OPT_m64, Ids: options::OPT_mx32, |
| 694 | Ids: options::OPT_m32, Ids: options::OPT_m16, |
| 695 | Ids: options::OPT_maix32, Ids: options::OPT_maix64); |
| 696 | if (A) { |
| 697 | llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; |
| 698 | |
| 699 | if (A->getOption().matches(ID: options::OPT_m64) || |
| 700 | A->getOption().matches(ID: options::OPT_maix64)) { |
| 701 | AT = Target.get64BitArchVariant().getArch(); |
| 702 | if (Target.getEnvironment() == llvm::Triple::GNUX32 || |
| 703 | Target.getEnvironment() == llvm::Triple::GNUT64) |
| 704 | Target.setEnvironment(llvm::Triple::GNU); |
| 705 | else if (Target.getEnvironment() == llvm::Triple::MuslX32) |
| 706 | Target.setEnvironment(llvm::Triple::Musl); |
| 707 | } else if (A->getOption().matches(ID: options::OPT_mx32) && |
| 708 | Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) { |
| 709 | AT = llvm::Triple::x86_64; |
| 710 | if (Target.getEnvironment() == llvm::Triple::Musl) |
| 711 | Target.setEnvironment(llvm::Triple::MuslX32); |
| 712 | else |
| 713 | Target.setEnvironment(llvm::Triple::GNUX32); |
| 714 | } else if (A->getOption().matches(ID: options::OPT_m32) || |
| 715 | A->getOption().matches(ID: options::OPT_maix32)) { |
| 716 | if (D.IsFlangMode() && !Target.isOSAIX()) { |
| 717 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 718 | << A->getAsString(Args) << Target.str(); |
| 719 | } else { |
| 720 | AT = Target.get32BitArchVariant().getArch(); |
| 721 | if (Target.getEnvironment() == llvm::Triple::GNUX32) |
| 722 | Target.setEnvironment(llvm::Triple::GNU); |
| 723 | else if (Target.getEnvironment() == llvm::Triple::MuslX32) |
| 724 | Target.setEnvironment(llvm::Triple::Musl); |
| 725 | } |
| 726 | } else if (A->getOption().matches(ID: options::OPT_m16) && |
| 727 | Target.get32BitArchVariant().getArch() == llvm::Triple::x86) { |
| 728 | AT = llvm::Triple::x86; |
| 729 | Target.setEnvironment(llvm::Triple::CODE16); |
| 730 | } |
| 731 | |
| 732 | if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) { |
| 733 | Target.setArch(Kind: AT); |
| 734 | if (Target.isWindowsGNUEnvironment()) |
| 735 | toolchains::MinGW::fixTripleArch(D, Triple&: Target, Args); |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | if (Target.isOSzOS()) { |
| 740 | if ((A = Args.getLastArg(Ids: options::OPT_mzos_target_EQ))) { |
| 741 | setZosTargetVersion(D, Target, ArgTarget: A->getValue()); |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | // Handle -miamcu flag. |
| 746 | if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) { |
| 747 | if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86) |
| 748 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) << "-miamcu" |
| 749 | << Target.str(); |
| 750 | |
| 751 | if (A && !A->getOption().matches(ID: options::OPT_m32)) |
| 752 | D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) |
| 753 | << "-miamcu" << A->getBaseArg().getAsString(Args); |
| 754 | |
| 755 | Target.setArch(Kind: llvm::Triple::x86); |
| 756 | Target.setArchName("i586" ); |
| 757 | Target.setEnvironment(llvm::Triple::UnknownEnvironment); |
| 758 | Target.setEnvironmentName("" ); |
| 759 | Target.setOS(llvm::Triple::ELFIAMCU); |
| 760 | Target.setVendor(llvm::Triple::UnknownVendor); |
| 761 | Target.setVendorName("intel" ); |
| 762 | } |
| 763 | |
| 764 | // If target is MIPS adjust the target triple |
| 765 | // accordingly to provided ABI name. |
| 766 | if (Target.isMIPS()) { |
| 767 | if ((A = Args.getLastArg(Ids: options::OPT_mabi_EQ))) { |
| 768 | StringRef ABIName = A->getValue(); |
| 769 | if (ABIName == "32" ) { |
| 770 | Target = Target.get32BitArchVariant(); |
| 771 | if (Target.getEnvironment() == llvm::Triple::GNUABI64 || |
| 772 | Target.getEnvironment() == llvm::Triple::GNUABIN32) |
| 773 | Target.setEnvironment(llvm::Triple::GNU); |
| 774 | } else if (ABIName == "n32" ) { |
| 775 | Target = Target.get64BitArchVariant(); |
| 776 | if (Target.getEnvironment() == llvm::Triple::GNU || |
| 777 | Target.getEnvironment() == llvm::Triple::GNUT64 || |
| 778 | Target.getEnvironment() == llvm::Triple::GNUABI64) |
| 779 | Target.setEnvironment(llvm::Triple::GNUABIN32); |
| 780 | else if (Target.getEnvironment() == llvm::Triple::Musl || |
| 781 | Target.getEnvironment() == llvm::Triple::MuslABI64) |
| 782 | Target.setEnvironment(llvm::Triple::MuslABIN32); |
| 783 | } else if (ABIName == "64" ) { |
| 784 | Target = Target.get64BitArchVariant(); |
| 785 | if (Target.getEnvironment() == llvm::Triple::GNU || |
| 786 | Target.getEnvironment() == llvm::Triple::GNUT64 || |
| 787 | Target.getEnvironment() == llvm::Triple::GNUABIN32) |
| 788 | Target.setEnvironment(llvm::Triple::GNUABI64); |
| 789 | else if (Target.getEnvironment() == llvm::Triple::Musl || |
| 790 | Target.getEnvironment() == llvm::Triple::MuslABIN32) |
| 791 | Target.setEnvironment(llvm::Triple::MuslABI64); |
| 792 | } |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | // If target is RISC-V adjust the target triple according to |
| 797 | // provided architecture name |
| 798 | if (Target.isRISCV()) { |
| 799 | if (Args.hasArg(Ids: options::OPT_march_EQ) || |
| 800 | Args.hasArg(Ids: options::OPT_mcpu_EQ)) { |
| 801 | std::string ArchName = tools::riscv::getRISCVArch(Args, Triple: Target); |
| 802 | auto ISAInfo = llvm::RISCVISAInfo::parseArchString( |
| 803 | Arch: ArchName, /*EnableExperimentalExtensions=*/EnableExperimentalExtension: true); |
| 804 | if (!llvm::errorToBool(Err: ISAInfo.takeError())) { |
| 805 | unsigned XLen = (*ISAInfo)->getXLen(); |
| 806 | if (XLen == 32) { |
| 807 | if (Target.isLittleEndian()) |
| 808 | Target.setArch(Kind: llvm::Triple::riscv32); |
| 809 | else |
| 810 | Target.setArch(Kind: llvm::Triple::riscv32be); |
| 811 | } else if (XLen == 64) { |
| 812 | if (Target.isLittleEndian()) |
| 813 | Target.setArch(Kind: llvm::Triple::riscv64); |
| 814 | else |
| 815 | Target.setArch(Kind: llvm::Triple::riscv64be); |
| 816 | } |
| 817 | } |
| 818 | } |
| 819 | } |
| 820 | |
| 821 | if (Target.getArch() == llvm::Triple::riscv32be || |
| 822 | Target.getArch() == llvm::Triple::riscv64be) { |
| 823 | static bool WarnedRISCVBE = false; |
| 824 | if (!WarnedRISCVBE) { |
| 825 | D.Diag(DiagID: diag::warn_drv_riscv_be_experimental); |
| 826 | WarnedRISCVBE = true; |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | return Target; |
| 831 | } |
| 832 | |
| 833 | // Parse the LTO options and record the type of LTO compilation |
| 834 | // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)? |
| 835 | // option occurs last. |
| 836 | static driver::LTOKind parseLTOMode(Driver &D, const llvm::opt::ArgList &Args, |
| 837 | OptSpecifier OptEq, OptSpecifier OptNeg) { |
| 838 | if (!Args.hasFlag(Pos: OptEq, Neg: OptNeg, Default: false)) |
| 839 | return LTOK_None; |
| 840 | |
| 841 | const Arg *A = Args.getLastArg(Ids: OptEq); |
| 842 | StringRef LTOName = A->getValue(); |
| 843 | |
| 844 | driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName) |
| 845 | .Case(S: "full" , Value: LTOK_Full) |
| 846 | .Case(S: "thin" , Value: LTOK_Thin) |
| 847 | .Default(Value: LTOK_Unknown); |
| 848 | |
| 849 | if (LTOMode == LTOK_Unknown) { |
| 850 | D.Diag(DiagID: diag::err_drv_unsupported_option_argument) |
| 851 | << A->getSpelling() << A->getValue(); |
| 852 | return LTOK_None; |
| 853 | } |
| 854 | return LTOMode; |
| 855 | } |
| 856 | |
| 857 | // Parse the LTO options. |
| 858 | void Driver::setLTOMode(const llvm::opt::ArgList &Args) { |
| 859 | LTOMode = |
| 860 | parseLTOMode(D&: *this, Args, OptEq: options::OPT_flto_EQ, OptNeg: options::OPT_fno_lto); |
| 861 | |
| 862 | OffloadLTOMode = parseLTOMode(D&: *this, Args, OptEq: options::OPT_foffload_lto_EQ, |
| 863 | OptNeg: options::OPT_fno_offload_lto); |
| 864 | |
| 865 | // Try to enable `-foffload-lto=full` if `-fopenmp-target-jit` is on. |
| 866 | if (Args.hasFlag(Pos: options::OPT_fopenmp_target_jit, |
| 867 | Neg: options::OPT_fno_openmp_target_jit, Default: false)) { |
| 868 | if (Arg *A = Args.getLastArg(Ids: options::OPT_foffload_lto_EQ, |
| 869 | Ids: options::OPT_fno_offload_lto)) |
| 870 | if (OffloadLTOMode != LTOK_Full) |
| 871 | Diag(DiagID: diag::err_drv_incompatible_options) |
| 872 | << A->getSpelling() << "-fopenmp-target-jit" ; |
| 873 | OffloadLTOMode = LTOK_Full; |
| 874 | } |
| 875 | } |
| 876 | |
| 877 | /// Compute the desired OpenMP runtime from the flags provided. |
| 878 | Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const { |
| 879 | StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME); |
| 880 | |
| 881 | const Arg *A = Args.getLastArg(Ids: options::OPT_fopenmp_EQ); |
| 882 | if (A) |
| 883 | RuntimeName = A->getValue(); |
| 884 | |
| 885 | auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName) |
| 886 | .Case(S: "libomp" , Value: OMPRT_OMP) |
| 887 | .Case(S: "libgomp" , Value: OMPRT_GOMP) |
| 888 | .Case(S: "libiomp5" , Value: OMPRT_IOMP5) |
| 889 | .Default(Value: OMPRT_Unknown); |
| 890 | |
| 891 | if (RT == OMPRT_Unknown) { |
| 892 | if (A) |
| 893 | Diag(DiagID: diag::err_drv_unsupported_option_argument) |
| 894 | << A->getSpelling() << A->getValue(); |
| 895 | else |
| 896 | // FIXME: We could use a nicer diagnostic here. |
| 897 | Diag(DiagID: diag::err_drv_unsupported_opt) << "-fopenmp" ; |
| 898 | } |
| 899 | |
| 900 | return RT; |
| 901 | } |
| 902 | |
| 903 | // Handles `native` offload architectures by using the 'offload-arch' utility. |
| 904 | static llvm::SmallVector<std::string> |
| 905 | getSystemOffloadArchs(Compilation &C, Action::OffloadKind Kind) { |
| 906 | StringRef Program = C.getArgs().getLastArgValue( |
| 907 | Id: options::OPT_offload_arch_tool_EQ, Default: "offload-arch" ); |
| 908 | |
| 909 | SmallVector<std::string> GPUArchs; |
| 910 | if (llvm::ErrorOr<std::string> Executable = |
| 911 | llvm::sys::findProgramByName(Name: Program, Paths: {C.getDriver().Dir})) { |
| 912 | llvm::SmallVector<StringRef> Args{*Executable}; |
| 913 | if (Kind == Action::OFK_HIP) |
| 914 | Args.push_back(Elt: "--only=amdgpu" ); |
| 915 | else if (Kind == Action::OFK_Cuda) |
| 916 | Args.push_back(Elt: "--only=nvptx" ); |
| 917 | auto StdoutOrErr = C.getDriver().executeProgram(Args); |
| 918 | |
| 919 | if (!StdoutOrErr) { |
| 920 | C.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch) |
| 921 | << Action::GetOffloadKindName(Kind) << StdoutOrErr.takeError() |
| 922 | << "--offload-arch" ; |
| 923 | return GPUArchs; |
| 924 | } |
| 925 | if ((*StdoutOrErr)->getBuffer().empty()) { |
| 926 | C.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch) |
| 927 | << Action::GetOffloadKindName(Kind) << "No GPU detected in the system" |
| 928 | << "--offload-arch" ; |
| 929 | return GPUArchs; |
| 930 | } |
| 931 | |
| 932 | for (StringRef Arch : llvm::split(Str: (*StdoutOrErr)->getBuffer(), Separator: "\n" )) |
| 933 | if (!Arch.empty()) |
| 934 | GPUArchs.push_back(Elt: Arch.str()); |
| 935 | } else { |
| 936 | C.getDriver().Diag(DiagID: diag::err_drv_command_failure) << "offload-arch" ; |
| 937 | } |
| 938 | return GPUArchs; |
| 939 | } |
| 940 | |
| 941 | // Attempts to infer the correct offloading toolchain triple by looking at the |
| 942 | // requested offloading kind and architectures. |
| 943 | static llvm::DenseSet<llvm::StringRef> |
| 944 | inferOffloadToolchains(Compilation &C, Action::OffloadKind Kind) { |
| 945 | std::set<std::string> Archs; |
| 946 | for (Arg *A : C.getInputArgs()) { |
| 947 | for (StringRef Arch : A->getValues()) { |
| 948 | if (A->getOption().matches(ID: options::OPT_offload_arch_EQ)) { |
| 949 | if (Arch == "native" ) { |
| 950 | for (StringRef Str : getSystemOffloadArchs(C, Kind)) |
| 951 | Archs.insert(x: Str.str()); |
| 952 | } else { |
| 953 | Archs.insert(x: Arch.str()); |
| 954 | } |
| 955 | } else if (A->getOption().matches(ID: options::OPT_no_offload_arch_EQ)) { |
| 956 | if (Arch == "all" ) |
| 957 | Archs.clear(); |
| 958 | else |
| 959 | Archs.erase(x: Arch.str()); |
| 960 | } |
| 961 | } |
| 962 | } |
| 963 | |
| 964 | llvm::DenseSet<llvm::StringRef> Triples; |
| 965 | for (llvm::StringRef Arch : Archs) { |
| 966 | OffloadArch ID = StringToOffloadArch(S: Arch); |
| 967 | if (ID == OffloadArch::UNKNOWN) |
| 968 | ID = StringToOffloadArch( |
| 969 | S: getProcessorFromTargetID(T: llvm::Triple("amdgcn-amd-amdhsa" ), OffloadArch: Arch)); |
| 970 | |
| 971 | if (Kind == Action::OFK_HIP && !IsAMDOffloadArch(A: ID)) { |
| 972 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 973 | << "HIP" << Arch; |
| 974 | return llvm::DenseSet<llvm::StringRef>(); |
| 975 | } |
| 976 | if (Kind == Action::OFK_Cuda && !IsNVIDIAOffloadArch(A: ID)) { |
| 977 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 978 | << "CUDA" << Arch; |
| 979 | return llvm::DenseSet<llvm::StringRef>(); |
| 980 | } |
| 981 | if (Kind == Action::OFK_OpenMP && |
| 982 | (ID == OffloadArch::UNKNOWN || ID == OffloadArch::UNUSED)) { |
| 983 | C.getDriver().Diag(DiagID: clang::diag::err_drv_failed_to_deduce_target_from_arch) |
| 984 | << Arch; |
| 985 | return llvm::DenseSet<llvm::StringRef>(); |
| 986 | } |
| 987 | if (ID == OffloadArch::UNKNOWN || ID == OffloadArch::UNUSED) { |
| 988 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 989 | << "offload" << Arch; |
| 990 | return llvm::DenseSet<llvm::StringRef>(); |
| 991 | } |
| 992 | |
| 993 | StringRef Triple; |
| 994 | if (ID == OffloadArch::AMDGCNSPIRV) |
| 995 | Triple = "spirv64-amd-amdhsa" ; |
| 996 | else if (IsNVIDIAOffloadArch(A: ID)) |
| 997 | Triple = C.getDefaultToolChain().getTriple().isArch64Bit() |
| 998 | ? "nvptx64-nvidia-cuda" |
| 999 | : "nvptx-nvidia-cuda" ; |
| 1000 | else if (IsAMDOffloadArch(A: ID)) |
| 1001 | Triple = "amdgcn-amd-amdhsa" ; |
| 1002 | else |
| 1003 | continue; |
| 1004 | |
| 1005 | // Make a new argument that dispatches this argument to the appropriate |
| 1006 | // toolchain. This is required when we infer it and create potentially |
| 1007 | // incompatible toolchains from the global option. |
| 1008 | Option Opt = C.getDriver().getOpts().getOption(Opt: options::OPT_Xarch__); |
| 1009 | unsigned Index = C.getArgs().getBaseArgs().MakeIndex(String0: "-Xarch_" ); |
| 1010 | Arg *A = new Arg(Opt, C.getArgs().getArgString(Index), Index, |
| 1011 | C.getArgs().MakeArgString(Str: Triple.split(Separator: "-" ).first), |
| 1012 | C.getArgs().MakeArgString(Str: "--offload-arch=" + Arch)); |
| 1013 | A->claim(); |
| 1014 | C.getArgs().append(A); |
| 1015 | C.getArgs().AddSynthesizedArg(A); |
| 1016 | Triples.insert(V: Triple); |
| 1017 | } |
| 1018 | |
| 1019 | // Infer the default target triple if no specific architectures are given. |
| 1020 | if (Archs.empty() && Kind == Action::OFK_HIP) |
| 1021 | Triples.insert(V: "amdgcn-amd-amdhsa" ); |
| 1022 | else if (Archs.empty() && Kind == Action::OFK_Cuda) |
| 1023 | Triples.insert(V: C.getDefaultToolChain().getTriple().isArch64Bit() |
| 1024 | ? "nvptx64-nvidia-cuda" |
| 1025 | : "nvptx-nvidia-cuda" ); |
| 1026 | else if (Archs.empty() && Kind == Action::OFK_SYCL) |
| 1027 | Triples.insert(V: C.getDefaultToolChain().getTriple().isArch64Bit() |
| 1028 | ? "spirv64-unknown-unknown" |
| 1029 | : "spirv32-unknown-unknown" ); |
| 1030 | |
| 1031 | // We need to dispatch these to the appropriate toolchain now. |
| 1032 | C.getArgs().eraseArg(Id: options::OPT_offload_arch_EQ); |
| 1033 | C.getArgs().eraseArg(Id: options::OPT_no_offload_arch_EQ); |
| 1034 | |
| 1035 | return Triples; |
| 1036 | } |
| 1037 | |
| 1038 | void Driver::CreateOffloadingDeviceToolChains(Compilation &C, |
| 1039 | InputList &Inputs) { |
| 1040 | bool UseLLVMOffload = C.getInputArgs().hasArg( |
| 1041 | Ids: options::OPT_foffload_via_llvm, Ids: options::OPT_fno_offload_via_llvm, Ids: false); |
| 1042 | bool IsCuda = |
| 1043 | llvm::any_of(Range&: Inputs, |
| 1044 | P: [](std::pair<types::ID, const llvm::opt::Arg *> &I) { |
| 1045 | return types::isCuda(Id: I.first); |
| 1046 | }) && |
| 1047 | !UseLLVMOffload; |
| 1048 | bool IsHIP = |
| 1049 | (llvm::any_of(Range&: Inputs, |
| 1050 | P: [](std::pair<types::ID, const llvm::opt::Arg *> &I) { |
| 1051 | return types::isHIP(Id: I.first); |
| 1052 | }) || |
| 1053 | C.getInputArgs().hasArg(Ids: options::OPT_hip_link) || |
| 1054 | C.getInputArgs().hasArg(Ids: options::OPT_hipstdpar)) && |
| 1055 | !UseLLVMOffload; |
| 1056 | bool IsSYCL = C.getInputArgs().hasFlag(Pos: options::OPT_fsycl, |
| 1057 | Neg: options::OPT_fno_sycl, Default: false); |
| 1058 | bool IsOpenMPOffloading = |
| 1059 | UseLLVMOffload || |
| 1060 | (C.getInputArgs().hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ, |
| 1061 | Neg: options::OPT_fno_openmp, Default: false) && |
| 1062 | (C.getInputArgs().hasArg(Ids: options::OPT_offload_targets_EQ) || |
| 1063 | (C.getInputArgs().hasArg(Ids: options::OPT_offload_arch_EQ) && |
| 1064 | !(IsCuda || IsHIP)))); |
| 1065 | |
| 1066 | llvm::SmallSet<Action::OffloadKind, 4> Kinds; |
| 1067 | const std::pair<bool, Action::OffloadKind> ActiveKinds[] = { |
| 1068 | {IsCuda, Action::OFK_Cuda}, |
| 1069 | {IsHIP, Action::OFK_HIP}, |
| 1070 | {IsOpenMPOffloading, Action::OFK_OpenMP}, |
| 1071 | {IsSYCL, Action::OFK_SYCL}}; |
| 1072 | for (const auto &[Active, Kind] : ActiveKinds) |
| 1073 | if (Active) |
| 1074 | Kinds.insert(V: Kind); |
| 1075 | |
| 1076 | // We currently don't support any kind of mixed offloading. |
| 1077 | if (Kinds.size() > 1) { |
| 1078 | Diag(DiagID: clang::diag::err_drv_mix_offload) |
| 1079 | << Action::GetOffloadKindName(Kind: *Kinds.begin()).upper() |
| 1080 | << Action::GetOffloadKindName(Kind: *(++Kinds.begin())).upper(); |
| 1081 | return; |
| 1082 | } |
| 1083 | |
| 1084 | // Initialize the compilation identifier used for unique CUDA / HIP names. |
| 1085 | if (IsCuda || IsHIP) |
| 1086 | CUIDOpts = CUIDOptions(C.getArgs(), *this); |
| 1087 | |
| 1088 | // Get the list of requested offloading toolchains. If they were not |
| 1089 | // explicitly specified we will infer them based on the offloading language |
| 1090 | // and requested architectures. |
| 1091 | std::multiset<llvm::StringRef> Triples; |
| 1092 | if (C.getInputArgs().hasArg(Ids: options::OPT_offload_targets_EQ)) { |
| 1093 | std::vector<std::string> ArgValues = |
| 1094 | C.getInputArgs().getAllArgValues(Id: options::OPT_offload_targets_EQ); |
| 1095 | for (llvm::StringRef Target : ArgValues) |
| 1096 | Triples.insert(x: C.getInputArgs().MakeArgString(Str: Target)); |
| 1097 | |
| 1098 | if (ArgValues.empty()) |
| 1099 | Diag(DiagID: clang::diag::warn_drv_empty_joined_argument) |
| 1100 | << C.getInputArgs() |
| 1101 | .getLastArg(Ids: options::OPT_offload_targets_EQ) |
| 1102 | ->getAsString(Args: C.getInputArgs()); |
| 1103 | } else if (Kinds.size() > 0) { |
| 1104 | for (Action::OffloadKind Kind : Kinds) { |
| 1105 | llvm::DenseSet<llvm::StringRef> Derived = inferOffloadToolchains(C, Kind); |
| 1106 | Triples.insert(first: Derived.begin(), last: Derived.end()); |
| 1107 | } |
| 1108 | } |
| 1109 | |
| 1110 | // Build an offloading toolchain for every requested target and kind. |
| 1111 | llvm::StringMap<StringRef> FoundNormalizedTriples; |
| 1112 | for (StringRef Target : Triples) { |
| 1113 | // OpenMP offloading requires a compatible libomp. |
| 1114 | if (Kinds.contains(V: Action::OFK_OpenMP)) { |
| 1115 | OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(Args: C.getInputArgs()); |
| 1116 | if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) { |
| 1117 | Diag(DiagID: clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets); |
| 1118 | return; |
| 1119 | } |
| 1120 | } |
| 1121 | |
| 1122 | // Certain options are not allowed when combined with SYCL compilation. |
| 1123 | if (Kinds.contains(V: Action::OFK_SYCL)) { |
| 1124 | for (auto ID : |
| 1125 | {options::OPT_static_libstdcxx, options::OPT_ffreestanding}) |
| 1126 | if (Arg *IncompatArg = C.getInputArgs().getLastArg(Ids: ID)) |
| 1127 | Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with) |
| 1128 | << IncompatArg->getSpelling() << "-fsycl" ; |
| 1129 | } |
| 1130 | |
| 1131 | // Create a device toolchain for every specified kind and triple. |
| 1132 | for (Action::OffloadKind Kind : Kinds) { |
| 1133 | llvm::Triple TT = Kind == Action::OFK_OpenMP |
| 1134 | ? ToolChain::getOpenMPTriple(TripleStr: Target) |
| 1135 | : llvm::Triple(Target); |
| 1136 | if (TT.getArch() == llvm::Triple::ArchType::UnknownArch) { |
| 1137 | Diag(DiagID: diag::err_drv_invalid_or_unsupported_offload_target) << TT.str(); |
| 1138 | continue; |
| 1139 | } |
| 1140 | |
| 1141 | std::string NormalizedName = TT.normalize(); |
| 1142 | auto [TripleIt, Inserted] = |
| 1143 | FoundNormalizedTriples.try_emplace(Key: NormalizedName, Args&: Target); |
| 1144 | if (!Inserted) { |
| 1145 | Diag(DiagID: clang::diag::warn_drv_omp_offload_target_duplicate) |
| 1146 | << Target << TripleIt->second; |
| 1147 | continue; |
| 1148 | } |
| 1149 | |
| 1150 | auto &TC = getOffloadToolChain(Args: C.getInputArgs(), Kind, Target: TT, |
| 1151 | AuxTarget: C.getDefaultToolChain().getTriple()); |
| 1152 | |
| 1153 | // Emit a warning if the detected CUDA version is too new. |
| 1154 | if (Kind == Action::OFK_Cuda) { |
| 1155 | auto &CudaInstallation = |
| 1156 | static_cast<const toolchains::CudaToolChain &>(TC).CudaInstallation; |
| 1157 | if (CudaInstallation.isValid()) |
| 1158 | CudaInstallation.WarnIfUnsupportedVersion(); |
| 1159 | } |
| 1160 | |
| 1161 | C.addOffloadDeviceToolChain(DeviceToolChain: &TC, OffloadKind: Kind); |
| 1162 | } |
| 1163 | } |
| 1164 | } |
| 1165 | |
| 1166 | bool Driver::loadZOSCustomizationFile(llvm::cl::ExpansionContext &ExpCtx) { |
| 1167 | if (IsCLMode() || IsDXCMode() || IsFlangMode()) |
| 1168 | return false; |
| 1169 | |
| 1170 | SmallString<128> CustomizationFile; |
| 1171 | StringRef PathLIBEnv = StringRef(getenv(name: "CLANG_CONFIG_PATH" )).trim(); |
| 1172 | // If the env var is a directory then append "/clang.cfg" and treat |
| 1173 | // that as the config file. Otherwise treat the env var as the |
| 1174 | // config file. |
| 1175 | if (!PathLIBEnv.empty()) { |
| 1176 | llvm::sys::path::append(path&: CustomizationFile, a: PathLIBEnv); |
| 1177 | if (llvm::sys::fs::is_directory(Path: PathLIBEnv)) |
| 1178 | llvm::sys::path::append(path&: CustomizationFile, a: "/clang.cfg" ); |
| 1179 | if (llvm::sys::fs::is_regular_file(Path: CustomizationFile)) |
| 1180 | return readConfigFile(FileName: CustomizationFile, ExpCtx); |
| 1181 | Diag(DiagID: diag::err_drv_config_file_not_found) << CustomizationFile; |
| 1182 | return true; |
| 1183 | } |
| 1184 | |
| 1185 | SmallString<128> BaseDir(llvm::sys::path::parent_path(path: Dir)); |
| 1186 | llvm::sys::path::append(path&: CustomizationFile, a: BaseDir + "/etc/clang.cfg" ); |
| 1187 | if (llvm::sys::fs::is_regular_file(Path: CustomizationFile)) |
| 1188 | return readConfigFile(FileName: CustomizationFile, ExpCtx); |
| 1189 | |
| 1190 | // If no customization file, just return |
| 1191 | return false; |
| 1192 | } |
| 1193 | |
| 1194 | static void appendOneArg(InputArgList &Args, const Arg *Opt) { |
| 1195 | // The args for config files or /clang: flags belong to different InputArgList |
| 1196 | // objects than Args. This copies an Arg from one of those other InputArgLists |
| 1197 | // to the ownership of Args. |
| 1198 | unsigned Index = Args.MakeIndex(String0: Opt->getSpelling()); |
| 1199 | Arg *Copy = new Arg(Opt->getOption(), Args.getArgString(Index), Index); |
| 1200 | Copy->getValues() = Opt->getValues(); |
| 1201 | if (Opt->isClaimed()) |
| 1202 | Copy->claim(); |
| 1203 | Copy->setOwnsValues(Opt->getOwnsValues()); |
| 1204 | Opt->setOwnsValues(false); |
| 1205 | Args.append(A: Copy); |
| 1206 | if (Opt->getAlias()) { |
| 1207 | const Arg *Alias = Opt->getAlias(); |
| 1208 | unsigned Index = Args.MakeIndex(String0: Alias->getSpelling()); |
| 1209 | auto AliasCopy = std::make_unique<Arg>(args: Alias->getOption(), |
| 1210 | args: Args.getArgString(Index), args&: Index); |
| 1211 | AliasCopy->getValues() = Alias->getValues(); |
| 1212 | AliasCopy->setOwnsValues(false); |
| 1213 | if (Alias->isClaimed()) |
| 1214 | AliasCopy->claim(); |
| 1215 | Copy->setAlias(std::move(AliasCopy)); |
| 1216 | } |
| 1217 | } |
| 1218 | |
| 1219 | bool Driver::readConfigFile(StringRef FileName, |
| 1220 | llvm::cl::ExpansionContext &ExpCtx) { |
| 1221 | // Try opening the given file. |
| 1222 | auto Status = getVFS().status(Path: FileName); |
| 1223 | if (!Status) { |
| 1224 | Diag(DiagID: diag::err_drv_cannot_open_config_file) |
| 1225 | << FileName << Status.getError().message(); |
| 1226 | return true; |
| 1227 | } |
| 1228 | if (Status->getType() != llvm::sys::fs::file_type::regular_file) { |
| 1229 | Diag(DiagID: diag::err_drv_cannot_open_config_file) |
| 1230 | << FileName << "not a regular file" ; |
| 1231 | return true; |
| 1232 | } |
| 1233 | |
| 1234 | // Try reading the given file. |
| 1235 | SmallVector<const char *, 32> NewCfgFileArgs; |
| 1236 | if (llvm::Error Err = ExpCtx.readConfigFile(CfgFile: FileName, Argv&: NewCfgFileArgs)) { |
| 1237 | Diag(DiagID: diag::err_drv_cannot_read_config_file) |
| 1238 | << FileName << toString(E: std::move(Err)); |
| 1239 | return true; |
| 1240 | } |
| 1241 | |
| 1242 | // Populate head and tail lists. The tail list is used only when linking. |
| 1243 | SmallVector<const char *, 32> NewCfgHeadArgs, NewCfgTailArgs; |
| 1244 | for (const char *Opt : NewCfgFileArgs) { |
| 1245 | // An $-prefixed option should go to the tail list. |
| 1246 | if (Opt[0] == '$' && Opt[1]) |
| 1247 | NewCfgTailArgs.push_back(Elt: Opt + 1); |
| 1248 | else |
| 1249 | NewCfgHeadArgs.push_back(Elt: Opt); |
| 1250 | } |
| 1251 | |
| 1252 | // Read options from config file. |
| 1253 | llvm::SmallString<128> CfgFileName(FileName); |
| 1254 | llvm::sys::path::native(path&: CfgFileName); |
| 1255 | bool ContainErrors = false; |
| 1256 | auto NewHeadOptions = std::make_unique<InputArgList>( |
| 1257 | args: ParseArgStrings(ArgStrings: NewCfgHeadArgs, /*UseDriverMode=*/true, ContainsError&: ContainErrors)); |
| 1258 | if (ContainErrors) |
| 1259 | return true; |
| 1260 | auto NewTailOptions = std::make_unique<InputArgList>( |
| 1261 | args: ParseArgStrings(ArgStrings: NewCfgTailArgs, /*UseDriverMode=*/true, ContainsError&: ContainErrors)); |
| 1262 | if (ContainErrors) |
| 1263 | return true; |
| 1264 | |
| 1265 | // Claim all arguments that come from a configuration file so that the driver |
| 1266 | // does not warn on any that is unused. |
| 1267 | for (Arg *A : *NewHeadOptions) |
| 1268 | A->claim(); |
| 1269 | for (Arg *A : *NewTailOptions) |
| 1270 | A->claim(); |
| 1271 | |
| 1272 | if (!CfgOptionsHead) |
| 1273 | CfgOptionsHead = std::move(NewHeadOptions); |
| 1274 | else { |
| 1275 | // If this is a subsequent config file, append options to the previous one. |
| 1276 | for (auto *Opt : *NewHeadOptions) |
| 1277 | appendOneArg(Args&: *CfgOptionsHead, Opt); |
| 1278 | } |
| 1279 | |
| 1280 | if (!CfgOptionsTail) |
| 1281 | CfgOptionsTail = std::move(NewTailOptions); |
| 1282 | else { |
| 1283 | // If this is a subsequent config file, append options to the previous one. |
| 1284 | for (auto *Opt : *NewTailOptions) |
| 1285 | appendOneArg(Args&: *CfgOptionsTail, Opt); |
| 1286 | } |
| 1287 | |
| 1288 | ConfigFiles.push_back(x: std::string(CfgFileName)); |
| 1289 | return false; |
| 1290 | } |
| 1291 | |
| 1292 | bool Driver::loadConfigFiles() { |
| 1293 | llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(), |
| 1294 | llvm::cl::tokenizeConfigFile, &getVFS()); |
| 1295 | |
| 1296 | // Process options that change search path for config files. |
| 1297 | if (CLOptions) { |
| 1298 | if (CLOptions->hasArg(Ids: options::OPT_config_system_dir_EQ)) { |
| 1299 | SmallString<128> CfgDir; |
| 1300 | CfgDir.append( |
| 1301 | RHS: CLOptions->getLastArgValue(Id: options::OPT_config_system_dir_EQ)); |
| 1302 | if (CfgDir.empty() || getVFS().makeAbsolute(Path&: CfgDir)) |
| 1303 | SystemConfigDir.clear(); |
| 1304 | else |
| 1305 | SystemConfigDir = static_cast<std::string>(CfgDir); |
| 1306 | } |
| 1307 | if (CLOptions->hasArg(Ids: options::OPT_config_user_dir_EQ)) { |
| 1308 | SmallString<128> CfgDir; |
| 1309 | llvm::sys::fs::expand_tilde( |
| 1310 | path: CLOptions->getLastArgValue(Id: options::OPT_config_user_dir_EQ), output&: CfgDir); |
| 1311 | if (CfgDir.empty() || getVFS().makeAbsolute(Path&: CfgDir)) |
| 1312 | UserConfigDir.clear(); |
| 1313 | else |
| 1314 | UserConfigDir = static_cast<std::string>(CfgDir); |
| 1315 | } |
| 1316 | } |
| 1317 | |
| 1318 | // Prepare list of directories where config file is searched for. |
| 1319 | StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir}; |
| 1320 | ExpCtx.setSearchDirs(CfgFileSearchDirs); |
| 1321 | |
| 1322 | // First try to load configuration from the default files, return on error. |
| 1323 | if (loadDefaultConfigFiles(ExpCtx)) |
| 1324 | return true; |
| 1325 | |
| 1326 | // Then load configuration files specified explicitly. |
| 1327 | SmallString<128> CfgFilePath; |
| 1328 | if (CLOptions) { |
| 1329 | for (auto CfgFileName : CLOptions->getAllArgValues(Id: options::OPT_config)) { |
| 1330 | // If argument contains directory separator, treat it as a path to |
| 1331 | // configuration file. |
| 1332 | if (llvm::sys::path::has_parent_path(path: CfgFileName)) { |
| 1333 | CfgFilePath.assign(RHS: CfgFileName); |
| 1334 | if (llvm::sys::path::is_relative(path: CfgFilePath)) { |
| 1335 | if (getVFS().makeAbsolute(Path&: CfgFilePath)) { |
| 1336 | Diag(DiagID: diag::err_drv_cannot_open_config_file) |
| 1337 | << CfgFilePath << "cannot get absolute path" ; |
| 1338 | return true; |
| 1339 | } |
| 1340 | } |
| 1341 | } else if (!ExpCtx.findConfigFile(FileName: CfgFileName, FilePath&: CfgFilePath)) { |
| 1342 | // Report an error that the config file could not be found. |
| 1343 | Diag(DiagID: diag::err_drv_config_file_not_found) << CfgFileName; |
| 1344 | for (const StringRef &SearchDir : CfgFileSearchDirs) |
| 1345 | if (!SearchDir.empty()) |
| 1346 | Diag(DiagID: diag::note_drv_config_file_searched_in) << SearchDir; |
| 1347 | return true; |
| 1348 | } |
| 1349 | |
| 1350 | // Try to read the config file, return on error. |
| 1351 | if (readConfigFile(FileName: CfgFilePath, ExpCtx)) |
| 1352 | return true; |
| 1353 | } |
| 1354 | } |
| 1355 | |
| 1356 | // No error occurred. |
| 1357 | return false; |
| 1358 | } |
| 1359 | |
| 1360 | static bool findTripleConfigFile(llvm::cl::ExpansionContext &ExpCtx, |
| 1361 | SmallString<128> &ConfigFilePath, |
| 1362 | llvm::Triple Triple, std::string Suffix) { |
| 1363 | // First, try the full unmodified triple. |
| 1364 | if (ExpCtx.findConfigFile(FileName: Triple.str() + Suffix, FilePath&: ConfigFilePath)) |
| 1365 | return true; |
| 1366 | |
| 1367 | // Don't continue if we didn't find a parsable version in the triple. |
| 1368 | VersionTuple OSVersion = Triple.getOSVersion(); |
| 1369 | if (!OSVersion.getMinor().has_value()) |
| 1370 | return false; |
| 1371 | |
| 1372 | std::string BaseOSName = Triple.getOSTypeName(Kind: Triple.getOS()).str(); |
| 1373 | |
| 1374 | // Next try strip the version to only include the major component. |
| 1375 | // e.g. arm64-apple-darwin23.6.0 -> arm64-apple-darwin23 |
| 1376 | if (OSVersion.getMajor() != 0) { |
| 1377 | Triple.setOSName(BaseOSName + llvm::utostr(X: OSVersion.getMajor())); |
| 1378 | if (ExpCtx.findConfigFile(FileName: Triple.str() + Suffix, FilePath&: ConfigFilePath)) |
| 1379 | return true; |
| 1380 | } |
| 1381 | |
| 1382 | // Finally, try without any version suffix at all. |
| 1383 | // e.g. arm64-apple-darwin23.6.0 -> arm64-apple-darwin |
| 1384 | Triple.setOSName(BaseOSName); |
| 1385 | return ExpCtx.findConfigFile(FileName: Triple.str() + Suffix, FilePath&: ConfigFilePath); |
| 1386 | } |
| 1387 | |
| 1388 | bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) { |
| 1389 | // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty |
| 1390 | // value. |
| 1391 | if (const char *NoConfigEnv = ::getenv(name: "CLANG_NO_DEFAULT_CONFIG" )) { |
| 1392 | if (*NoConfigEnv) |
| 1393 | return false; |
| 1394 | } |
| 1395 | if (CLOptions && CLOptions->hasArg(Ids: options::OPT_no_default_config)) |
| 1396 | return false; |
| 1397 | |
| 1398 | std::string RealMode = getExecutableForDriverMode(Mode); |
| 1399 | llvm::Triple Triple; |
| 1400 | |
| 1401 | // If name prefix is present, no --target= override was passed via CLOptions |
| 1402 | // and the name prefix is not a valid triple, force it for backwards |
| 1403 | // compatibility. |
| 1404 | if (!ClangNameParts.TargetPrefix.empty() && |
| 1405 | computeTargetTriple(D: *this, TargetTriple: "/invalid/" , Args: *CLOptions).str() == |
| 1406 | "/invalid/" ) { |
| 1407 | llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix}; |
| 1408 | if (PrefixTriple.getArch() == llvm::Triple::UnknownArch || |
| 1409 | PrefixTriple.isOSUnknown()) |
| 1410 | Triple = PrefixTriple; |
| 1411 | } |
| 1412 | |
| 1413 | // Otherwise, use the real triple as used by the driver. |
| 1414 | llvm::Triple RealTriple = |
| 1415 | computeTargetTriple(D: *this, TargetTriple, Args: *CLOptions); |
| 1416 | if (Triple.str().empty()) { |
| 1417 | Triple = RealTriple; |
| 1418 | assert(!Triple.str().empty()); |
| 1419 | } |
| 1420 | |
| 1421 | // On z/OS, start by loading the customization file before loading |
| 1422 | // the usual default config file(s). |
| 1423 | if (RealTriple.isOSzOS() && loadZOSCustomizationFile(ExpCtx)) |
| 1424 | return true; |
| 1425 | |
| 1426 | // Search for config files in the following order: |
| 1427 | // 1. <triple>-<mode>.cfg using real driver mode |
| 1428 | // (e.g. i386-pc-linux-gnu-clang++.cfg). |
| 1429 | // 2. <triple>-<mode>.cfg using executable suffix |
| 1430 | // (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++). |
| 1431 | // 3. <triple>.cfg + <mode>.cfg using real driver mode |
| 1432 | // (e.g. i386-pc-linux-gnu.cfg + clang++.cfg). |
| 1433 | // 4. <triple>.cfg + <mode>.cfg using executable suffix |
| 1434 | // (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++). |
| 1435 | |
| 1436 | // Try loading <triple>-<mode>.cfg, and return if we find a match. |
| 1437 | SmallString<128> CfgFilePath; |
| 1438 | if (findTripleConfigFile(ExpCtx, ConfigFilePath&: CfgFilePath, Triple, |
| 1439 | Suffix: "-" + RealMode + ".cfg" )) |
| 1440 | return readConfigFile(FileName: CfgFilePath, ExpCtx); |
| 1441 | |
| 1442 | bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() && |
| 1443 | ClangNameParts.ModeSuffix != RealMode; |
| 1444 | if (TryModeSuffix) { |
| 1445 | if (findTripleConfigFile(ExpCtx, ConfigFilePath&: CfgFilePath, Triple, |
| 1446 | Suffix: "-" + ClangNameParts.ModeSuffix + ".cfg" )) |
| 1447 | return readConfigFile(FileName: CfgFilePath, ExpCtx); |
| 1448 | } |
| 1449 | |
| 1450 | // Try loading <mode>.cfg, and return if loading failed. If a matching file |
| 1451 | // was not found, still proceed on to try <triple>.cfg. |
| 1452 | std::string CfgFileName = RealMode + ".cfg" ; |
| 1453 | if (ExpCtx.findConfigFile(FileName: CfgFileName, FilePath&: CfgFilePath)) { |
| 1454 | if (readConfigFile(FileName: CfgFilePath, ExpCtx)) |
| 1455 | return true; |
| 1456 | } else if (TryModeSuffix) { |
| 1457 | CfgFileName = ClangNameParts.ModeSuffix + ".cfg" ; |
| 1458 | if (ExpCtx.findConfigFile(FileName: CfgFileName, FilePath&: CfgFilePath) && |
| 1459 | readConfigFile(FileName: CfgFilePath, ExpCtx)) |
| 1460 | return true; |
| 1461 | } |
| 1462 | |
| 1463 | // Try loading <triple>.cfg and return if we find a match. |
| 1464 | if (findTripleConfigFile(ExpCtx, ConfigFilePath&: CfgFilePath, Triple, Suffix: ".cfg" )) |
| 1465 | return readConfigFile(FileName: CfgFilePath, ExpCtx); |
| 1466 | |
| 1467 | // If we were unable to find a config file deduced from executable name, |
| 1468 | // that is not an error. |
| 1469 | return false; |
| 1470 | } |
| 1471 | |
| 1472 | Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { |
| 1473 | llvm::PrettyStackTraceString CrashInfo("Compilation construction" ); |
| 1474 | |
| 1475 | // FIXME: Handle environment options which affect driver behavior, somewhere |
| 1476 | // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. |
| 1477 | |
| 1478 | // We look for the driver mode option early, because the mode can affect |
| 1479 | // how other options are parsed. |
| 1480 | |
| 1481 | auto DriverMode = getDriverMode(ProgName: ClangExecutable, Args: ArgList.slice(N: 1)); |
| 1482 | if (!DriverMode.empty()) |
| 1483 | setDriverMode(DriverMode); |
| 1484 | |
| 1485 | // FIXME: What are we going to do with -V and -b? |
| 1486 | |
| 1487 | // Arguments specified in command line. |
| 1488 | bool ContainsError; |
| 1489 | CLOptions = std::make_unique<InputArgList>( |
| 1490 | args: ParseArgStrings(ArgStrings: ArgList.slice(N: 1), /*UseDriverMode=*/true, ContainsError)); |
| 1491 | |
| 1492 | // Try parsing configuration file. |
| 1493 | if (!ContainsError) |
| 1494 | ContainsError = loadConfigFiles(); |
| 1495 | bool HasConfigFileHead = !ContainsError && CfgOptionsHead; |
| 1496 | bool HasConfigFileTail = !ContainsError && CfgOptionsTail; |
| 1497 | |
| 1498 | // All arguments, from both config file and command line. |
| 1499 | InputArgList Args = |
| 1500 | HasConfigFileHead ? std::move(*CfgOptionsHead) : std::move(*CLOptions); |
| 1501 | |
| 1502 | if (HasConfigFileHead) |
| 1503 | for (auto *Opt : *CLOptions) |
| 1504 | if (!Opt->getOption().matches(ID: options::OPT_config)) |
| 1505 | appendOneArg(Args, Opt); |
| 1506 | |
| 1507 | // In CL mode, look for any pass-through arguments |
| 1508 | if (IsCLMode() && !ContainsError) { |
| 1509 | SmallVector<const char *, 16> CLModePassThroughArgList; |
| 1510 | for (const auto *A : Args.filtered(Ids: options::OPT__SLASH_clang)) { |
| 1511 | A->claim(); |
| 1512 | CLModePassThroughArgList.push_back(Elt: A->getValue()); |
| 1513 | } |
| 1514 | |
| 1515 | if (!CLModePassThroughArgList.empty()) { |
| 1516 | // Parse any pass through args using default clang processing rather |
| 1517 | // than clang-cl processing. |
| 1518 | auto CLModePassThroughOptions = std::make_unique<InputArgList>( |
| 1519 | args: ParseArgStrings(ArgStrings: CLModePassThroughArgList, /*UseDriverMode=*/false, |
| 1520 | ContainsError)); |
| 1521 | |
| 1522 | if (!ContainsError) |
| 1523 | for (auto *Opt : *CLModePassThroughOptions) |
| 1524 | appendOneArg(Args, Opt); |
| 1525 | } |
| 1526 | } |
| 1527 | |
| 1528 | // Check for working directory option before accessing any files |
| 1529 | if (Arg *WD = Args.getLastArg(Ids: options::OPT_working_directory)) |
| 1530 | if (VFS->setCurrentWorkingDirectory(WD->getValue())) |
| 1531 | Diag(DiagID: diag::err_drv_unable_to_set_working_directory) << WD->getValue(); |
| 1532 | |
| 1533 | // Check for missing include directories. |
| 1534 | if (!Diags.isIgnored(DiagID: diag::warn_missing_include_dirs, Loc: SourceLocation())) { |
| 1535 | for (auto IncludeDir : Args.getAllArgValues(Id: options::OPT_I_Group)) { |
| 1536 | if (!VFS->exists(Path: IncludeDir)) |
| 1537 | Diag(DiagID: diag::warn_missing_include_dirs) << IncludeDir; |
| 1538 | } |
| 1539 | } |
| 1540 | |
| 1541 | // FIXME: This stuff needs to go into the Compilation, not the driver. |
| 1542 | bool CCCPrintPhases; |
| 1543 | |
| 1544 | // -canonical-prefixes, -no-canonical-prefixes are used very early in main. |
| 1545 | Args.ClaimAllArgs(Id0: options::OPT_canonical_prefixes); |
| 1546 | Args.ClaimAllArgs(Id0: options::OPT_no_canonical_prefixes); |
| 1547 | |
| 1548 | // f(no-)integated-cc1 is also used very early in main. |
| 1549 | Args.ClaimAllArgs(Id0: options::OPT_fintegrated_cc1); |
| 1550 | Args.ClaimAllArgs(Id0: options::OPT_fno_integrated_cc1); |
| 1551 | |
| 1552 | // Ignore -pipe. |
| 1553 | Args.ClaimAllArgs(Id0: options::OPT_pipe); |
| 1554 | |
| 1555 | // Extract -ccc args. |
| 1556 | // |
| 1557 | // FIXME: We need to figure out where this behavior should live. Most of it |
| 1558 | // should be outside in the client; the parts that aren't should have proper |
| 1559 | // options, either by introducing new ones or by overloading gcc ones like -V |
| 1560 | // or -b. |
| 1561 | CCCPrintPhases = Args.hasArg(Ids: options::OPT_ccc_print_phases); |
| 1562 | CCCPrintBindings = Args.hasArg(Ids: options::OPT_ccc_print_bindings); |
| 1563 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_ccc_gcc_name)) |
| 1564 | CCCGenericGCCName = A->getValue(); |
| 1565 | |
| 1566 | // Process -fproc-stat-report options. |
| 1567 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_fproc_stat_report_EQ)) { |
| 1568 | CCPrintProcessStats = true; |
| 1569 | CCPrintStatReportFilename = A->getValue(); |
| 1570 | } |
| 1571 | if (Args.hasArg(Ids: options::OPT_fproc_stat_report)) |
| 1572 | CCPrintProcessStats = true; |
| 1573 | |
| 1574 | // FIXME: TargetTriple is used by the target-prefixed calls to as/ld |
| 1575 | // and getToolChain is const. |
| 1576 | if (IsCLMode()) { |
| 1577 | // clang-cl targets MSVC-style Win32. |
| 1578 | llvm::Triple T(TargetTriple); |
| 1579 | T.setOS(llvm::Triple::Win32); |
| 1580 | T.setVendor(llvm::Triple::PC); |
| 1581 | T.setEnvironment(llvm::Triple::MSVC); |
| 1582 | T.setObjectFormat(llvm::Triple::COFF); |
| 1583 | if (Args.hasArg(Ids: options::OPT__SLASH_arm64EC)) |
| 1584 | T.setArch(Kind: llvm::Triple::aarch64, SubArch: llvm::Triple::AArch64SubArch_arm64ec); |
| 1585 | TargetTriple = T.str(); |
| 1586 | } else if (IsDXCMode()) { |
| 1587 | // Build TargetTriple from target_profile option for clang-dxc. |
| 1588 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_target_profile)) { |
| 1589 | StringRef TargetProfile = A->getValue(); |
| 1590 | if (auto Triple = |
| 1591 | toolchains::HLSLToolChain::parseTargetProfile(TargetProfile)) |
| 1592 | TargetTriple = *Triple; |
| 1593 | else |
| 1594 | Diag(DiagID: diag::err_drv_invalid_directx_shader_module) << TargetProfile; |
| 1595 | |
| 1596 | A->claim(); |
| 1597 | |
| 1598 | if (Args.hasArg(Ids: options::OPT_spirv)) { |
| 1599 | const llvm::StringMap<llvm::Triple::SubArchType> ValidTargets = { |
| 1600 | {"vulkan1.2" , llvm::Triple::SPIRVSubArch_v15}, |
| 1601 | {"vulkan1.3" , llvm::Triple::SPIRVSubArch_v16}}; |
| 1602 | llvm::Triple T(TargetTriple); |
| 1603 | |
| 1604 | // Set specific Vulkan version. Default to vulkan1.3. |
| 1605 | auto TargetInfo = ValidTargets.find(Key: "vulkan1.3" ); |
| 1606 | assert(TargetInfo != ValidTargets.end()); |
| 1607 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_fspv_target_env_EQ)) { |
| 1608 | TargetInfo = ValidTargets.find(Key: A->getValue()); |
| 1609 | if (TargetInfo == ValidTargets.end()) { |
| 1610 | Diag(DiagID: diag::err_drv_invalid_value) |
| 1611 | << A->getAsString(Args) << A->getValue(); |
| 1612 | } |
| 1613 | A->claim(); |
| 1614 | } |
| 1615 | if (TargetInfo != ValidTargets.end()) { |
| 1616 | T.setOSName(TargetInfo->getKey()); |
| 1617 | T.setArch(Kind: llvm::Triple::spirv, SubArch: TargetInfo->getValue()); |
| 1618 | TargetTriple = T.str(); |
| 1619 | } |
| 1620 | } |
| 1621 | } else { |
| 1622 | Diag(DiagID: diag::err_drv_dxc_missing_target_profile); |
| 1623 | } |
| 1624 | } |
| 1625 | |
| 1626 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_target)) |
| 1627 | TargetTriple = A->getValue(); |
| 1628 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_ccc_install_dir)) |
| 1629 | Dir = Dir = A->getValue(); |
| 1630 | for (const Arg *A : Args.filtered(Ids: options::OPT_B)) { |
| 1631 | A->claim(); |
| 1632 | PrefixDirs.push_back(Elt: A->getValue(N: 0)); |
| 1633 | } |
| 1634 | if (std::optional<std::string> CompilerPathValue = |
| 1635 | llvm::sys::Process::GetEnv(name: "COMPILER_PATH" )) { |
| 1636 | StringRef CompilerPath = *CompilerPathValue; |
| 1637 | while (!CompilerPath.empty()) { |
| 1638 | std::pair<StringRef, StringRef> Split = |
| 1639 | CompilerPath.split(Separator: llvm::sys::EnvPathSeparator); |
| 1640 | PrefixDirs.push_back(Elt: std::string(Split.first)); |
| 1641 | CompilerPath = Split.second; |
| 1642 | } |
| 1643 | } |
| 1644 | if (const Arg *A = Args.getLastArg(Ids: options::OPT__sysroot_EQ)) |
| 1645 | SysRoot = A->getValue(); |
| 1646 | if (const Arg *A = Args.getLastArg(Ids: options::OPT__dyld_prefix_EQ)) |
| 1647 | DyldPrefix = A->getValue(); |
| 1648 | |
| 1649 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_resource_dir)) |
| 1650 | ResourceDir = A->getValue(); |
| 1651 | |
| 1652 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_save_temps_EQ)) { |
| 1653 | SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue()) |
| 1654 | .Case(S: "cwd" , Value: SaveTempsCwd) |
| 1655 | .Case(S: "obj" , Value: SaveTempsObj) |
| 1656 | .Default(Value: SaveTempsCwd); |
| 1657 | } |
| 1658 | |
| 1659 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_offload_host_only, |
| 1660 | Ids: options::OPT_offload_device_only, |
| 1661 | Ids: options::OPT_offload_host_device)) { |
| 1662 | if (A->getOption().matches(ID: options::OPT_offload_host_only)) |
| 1663 | Offload = OffloadHost; |
| 1664 | else if (A->getOption().matches(ID: options::OPT_offload_device_only)) |
| 1665 | Offload = OffloadDevice; |
| 1666 | else |
| 1667 | Offload = OffloadHostDevice; |
| 1668 | } |
| 1669 | |
| 1670 | setLTOMode(Args); |
| 1671 | |
| 1672 | // Process -fembed-bitcode= flags. |
| 1673 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fembed_bitcode_EQ)) { |
| 1674 | StringRef Name = A->getValue(); |
| 1675 | unsigned Model = llvm::StringSwitch<unsigned>(Name) |
| 1676 | .Case(S: "off" , Value: EmbedNone) |
| 1677 | .Case(S: "all" , Value: EmbedBitcode) |
| 1678 | .Case(S: "bitcode" , Value: EmbedBitcode) |
| 1679 | .Case(S: "marker" , Value: EmbedMarker) |
| 1680 | .Default(Value: ~0U); |
| 1681 | if (Model == ~0U) { |
| 1682 | Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) |
| 1683 | << Name; |
| 1684 | } else |
| 1685 | BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model); |
| 1686 | } |
| 1687 | |
| 1688 | // Remove existing compilation database so that each job can append to it. |
| 1689 | if (Arg *A = Args.getLastArg(Ids: options::OPT_MJ)) |
| 1690 | llvm::sys::fs::remove(path: A->getValue()); |
| 1691 | |
| 1692 | // Setting up the jobs for some precompile cases depends on whether we are |
| 1693 | // treating them as PCH, implicit modules or C++20 ones. |
| 1694 | // TODO: inferring the mode like this seems fragile (it meets the objective |
| 1695 | // of not requiring anything new for operation, however). |
| 1696 | const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ); |
| 1697 | ModulesModeCXX20 = |
| 1698 | !Args.hasArg(Ids: options::OPT_fmodules) && Std && |
| 1699 | (Std->containsValue(Value: "c++20" ) || Std->containsValue(Value: "c++2a" ) || |
| 1700 | Std->containsValue(Value: "c++23" ) || Std->containsValue(Value: "c++2b" ) || |
| 1701 | Std->containsValue(Value: "c++26" ) || Std->containsValue(Value: "c++2c" ) || |
| 1702 | Std->containsValue(Value: "c++latest" )); |
| 1703 | |
| 1704 | // Process -fmodule-header{=} flags. |
| 1705 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_header_EQ, |
| 1706 | Ids: options::OPT_fmodule_header)) { |
| 1707 | // These flags force C++20 handling of headers. |
| 1708 | ModulesModeCXX20 = true; |
| 1709 | if (A->getOption().matches(ID: options::OPT_fmodule_header)) |
| 1710 | CXX20HeaderType = HeaderMode_Default; |
| 1711 | else { |
| 1712 | StringRef ArgName = A->getValue(); |
| 1713 | unsigned Kind = llvm::StringSwitch<unsigned>(ArgName) |
| 1714 | .Case(S: "user" , Value: HeaderMode_User) |
| 1715 | .Case(S: "system" , Value: HeaderMode_System) |
| 1716 | .Default(Value: ~0U); |
| 1717 | if (Kind == ~0U) { |
| 1718 | Diags.Report(DiagID: diag::err_drv_invalid_value) |
| 1719 | << A->getAsString(Args) << ArgName; |
| 1720 | } else |
| 1721 | CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind); |
| 1722 | } |
| 1723 | } |
| 1724 | |
| 1725 | std::unique_ptr<llvm::opt::InputArgList> UArgs = |
| 1726 | std::make_unique<InputArgList>(args: std::move(Args)); |
| 1727 | |
| 1728 | // Owned by the host. |
| 1729 | const ToolChain &TC = |
| 1730 | getToolChain(Args: *UArgs, Target: computeTargetTriple(D: *this, TargetTriple, Args: *UArgs)); |
| 1731 | |
| 1732 | { |
| 1733 | SmallVector<std::string> MultilibMacroDefinesStr = |
| 1734 | TC.getMultilibMacroDefinesStr(Args&: *UArgs); |
| 1735 | SmallVector<const char *> MLMacroDefinesChar( |
| 1736 | llvm::map_range(C&: MultilibMacroDefinesStr, F: [&UArgs](const auto &S) { |
| 1737 | return UArgs->MakeArgString(Str: Twine("-D" ) + Twine(S)); |
| 1738 | })); |
| 1739 | bool MLContainsError; |
| 1740 | auto MultilibMacroDefineList = |
| 1741 | std::make_unique<InputArgList>(args: ParseArgStrings( |
| 1742 | ArgStrings: MLMacroDefinesChar, /*UseDriverMode=*/false, ContainsError&: MLContainsError)); |
| 1743 | if (!MLContainsError) { |
| 1744 | for (auto *Opt : *MultilibMacroDefineList) { |
| 1745 | appendOneArg(Args&: *UArgs, Opt); |
| 1746 | } |
| 1747 | } |
| 1748 | } |
| 1749 | |
| 1750 | // Perform the default argument translations. |
| 1751 | DerivedArgList *TranslatedArgs = TranslateInputArgs(Args: *UArgs); |
| 1752 | |
| 1753 | // Check if the environment version is valid except wasm case. |
| 1754 | llvm::Triple Triple = TC.getTriple(); |
| 1755 | if (!Triple.isWasm()) { |
| 1756 | StringRef TripleVersionName = Triple.getEnvironmentVersionString(); |
| 1757 | StringRef TripleObjectFormat = |
| 1758 | Triple.getObjectFormatTypeName(ObjectFormat: Triple.getObjectFormat()); |
| 1759 | if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "" && |
| 1760 | TripleVersionName != TripleObjectFormat) { |
| 1761 | Diags.Report(DiagID: diag::err_drv_triple_version_invalid) |
| 1762 | << TripleVersionName << TC.getTripleString(); |
| 1763 | ContainsError = true; |
| 1764 | } |
| 1765 | } |
| 1766 | |
| 1767 | // Report warning when arm64EC option is overridden by specified target |
| 1768 | if ((TC.getTriple().getArch() != llvm::Triple::aarch64 || |
| 1769 | TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) && |
| 1770 | UArgs->hasArg(Ids: options::OPT__SLASH_arm64EC)) { |
| 1771 | getDiags().Report(DiagID: clang::diag::warn_target_override_arm64ec) |
| 1772 | << TC.getTriple().str(); |
| 1773 | } |
| 1774 | |
| 1775 | // A common user mistake is specifying a target of aarch64-none-eabi or |
| 1776 | // arm-none-elf whereas the correct names are aarch64-none-elf & |
| 1777 | // arm-none-eabi. Detect these cases and issue a warning. |
| 1778 | if (TC.getTriple().getOS() == llvm::Triple::UnknownOS && |
| 1779 | TC.getTriple().getVendor() == llvm::Triple::UnknownVendor) { |
| 1780 | switch (TC.getTriple().getArch()) { |
| 1781 | case llvm::Triple::arm: |
| 1782 | case llvm::Triple::armeb: |
| 1783 | case llvm::Triple::thumb: |
| 1784 | case llvm::Triple::thumbeb: |
| 1785 | if (TC.getTriple().getEnvironmentName() == "elf" ) { |
| 1786 | Diag(DiagID: diag::warn_target_unrecognized_env) |
| 1787 | << TargetTriple |
| 1788 | << (TC.getTriple().getArchName().str() + "-none-eabi" ); |
| 1789 | } |
| 1790 | break; |
| 1791 | case llvm::Triple::aarch64: |
| 1792 | case llvm::Triple::aarch64_be: |
| 1793 | case llvm::Triple::aarch64_32: |
| 1794 | if (TC.getTriple().getEnvironmentName().starts_with(Prefix: "eabi" )) { |
| 1795 | Diag(DiagID: diag::warn_target_unrecognized_env) |
| 1796 | << TargetTriple |
| 1797 | << (TC.getTriple().getArchName().str() + "-none-elf" ); |
| 1798 | } |
| 1799 | break; |
| 1800 | default: |
| 1801 | break; |
| 1802 | } |
| 1803 | } |
| 1804 | |
| 1805 | // The compilation takes ownership of Args. |
| 1806 | Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs, |
| 1807 | ContainsError); |
| 1808 | |
| 1809 | if (!HandleImmediateArgs(C&: *C)) |
| 1810 | return C; |
| 1811 | |
| 1812 | // Construct the list of inputs. |
| 1813 | InputList Inputs; |
| 1814 | BuildInputs(TC: C->getDefaultToolChain(), Args&: *TranslatedArgs, Inputs); |
| 1815 | if (HasConfigFileTail && Inputs.size()) { |
| 1816 | Arg *FinalPhaseArg; |
| 1817 | if (getFinalPhase(DAL: *TranslatedArgs, FinalPhaseArg: &FinalPhaseArg) == phases::Link) { |
| 1818 | DerivedArgList TranslatedLinkerIns(*CfgOptionsTail); |
| 1819 | for (Arg *A : *CfgOptionsTail) |
| 1820 | TranslatedLinkerIns.append(A); |
| 1821 | BuildInputs(TC: C->getDefaultToolChain(), Args&: TranslatedLinkerIns, Inputs); |
| 1822 | } |
| 1823 | } |
| 1824 | |
| 1825 | // Populate the tool chains for the offloading devices, if any. |
| 1826 | CreateOffloadingDeviceToolChains(C&: *C, Inputs); |
| 1827 | |
| 1828 | // Construct the list of abstract actions to perform for this compilation. On |
| 1829 | // MachO targets this uses the driver-driver and universal actions. |
| 1830 | if (TC.getTriple().isOSBinFormatMachO()) |
| 1831 | BuildUniversalActions(C&: *C, TC: C->getDefaultToolChain(), BAInputs: Inputs); |
| 1832 | else |
| 1833 | BuildActions(C&: *C, Args&: C->getArgs(), Inputs, Actions&: C->getActions()); |
| 1834 | |
| 1835 | if (CCCPrintPhases) { |
| 1836 | PrintActions(C: *C); |
| 1837 | return C; |
| 1838 | } |
| 1839 | |
| 1840 | BuildJobs(C&: *C); |
| 1841 | |
| 1842 | return C; |
| 1843 | } |
| 1844 | |
| 1845 | static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) { |
| 1846 | llvm::opt::ArgStringList ASL; |
| 1847 | for (const auto *A : Args) { |
| 1848 | // Use user's original spelling of flags. For example, use |
| 1849 | // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user |
| 1850 | // wrote the former. |
| 1851 | while (A->getAlias()) |
| 1852 | A = A->getAlias(); |
| 1853 | A->render(Args, Output&: ASL); |
| 1854 | } |
| 1855 | |
| 1856 | for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) { |
| 1857 | if (I != ASL.begin()) |
| 1858 | OS << ' '; |
| 1859 | llvm::sys::printArg(OS, Arg: *I, Quote: true); |
| 1860 | } |
| 1861 | OS << '\n'; |
| 1862 | } |
| 1863 | |
| 1864 | bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename, |
| 1865 | SmallString<128> &CrashDiagDir) { |
| 1866 | using namespace llvm::sys; |
| 1867 | assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() && |
| 1868 | "Only knows about .crash files on Darwin" ); |
| 1869 | // This is not a formal output of the compiler, let's bypass the sandbox. |
| 1870 | auto BypassSandbox = sandbox::scopedDisable(); |
| 1871 | |
| 1872 | // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/ |
| 1873 | // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern |
| 1874 | // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash. |
| 1875 | path::home_directory(result&: CrashDiagDir); |
| 1876 | if (CrashDiagDir.starts_with(Prefix: "/var/root" )) |
| 1877 | CrashDiagDir = "/" ; |
| 1878 | path::append(path&: CrashDiagDir, a: "Library/Logs/DiagnosticReports" ); |
| 1879 | int PID = |
| 1880 | #if LLVM_ON_UNIX |
| 1881 | getpid(); |
| 1882 | #else |
| 1883 | 0; |
| 1884 | #endif |
| 1885 | std::error_code EC; |
| 1886 | fs::file_status FileStatus; |
| 1887 | TimePoint<> LastAccessTime; |
| 1888 | SmallString<128> CrashFilePath; |
| 1889 | // Lookup the .crash files and get the one generated by a subprocess spawned |
| 1890 | // by this driver invocation. |
| 1891 | for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd; |
| 1892 | File != FileEnd && !EC; File.increment(ec&: EC)) { |
| 1893 | StringRef FileName = path::filename(path: File->path()); |
| 1894 | if (!FileName.starts_with(Prefix: Name)) |
| 1895 | continue; |
| 1896 | if (fs::status(path: File->path(), result&: FileStatus)) |
| 1897 | continue; |
| 1898 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile = |
| 1899 | llvm::MemoryBuffer::getFile(Filename: File->path()); |
| 1900 | if (!CrashFile) |
| 1901 | continue; |
| 1902 | // The first line should start with "Process:", otherwise this isn't a real |
| 1903 | // .crash file. |
| 1904 | StringRef Data = CrashFile.get()->getBuffer(); |
| 1905 | if (!Data.starts_with(Prefix: "Process:" )) |
| 1906 | continue; |
| 1907 | // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]" |
| 1908 | size_t ParentProcPos = Data.find(Str: "Parent Process:" ); |
| 1909 | if (ParentProcPos == StringRef::npos) |
| 1910 | continue; |
| 1911 | size_t LineEnd = Data.find_first_of(Chars: "\n" , From: ParentProcPos); |
| 1912 | if (LineEnd == StringRef::npos) |
| 1913 | continue; |
| 1914 | StringRef ParentProcess = Data.slice(Start: ParentProcPos+15, End: LineEnd).trim(); |
| 1915 | int OpenBracket = -1, CloseBracket = -1; |
| 1916 | for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) { |
| 1917 | if (ParentProcess[i] == '[') |
| 1918 | OpenBracket = i; |
| 1919 | if (ParentProcess[i] == ']') |
| 1920 | CloseBracket = i; |
| 1921 | } |
| 1922 | // Extract the parent process PID from the .crash file and check whether |
| 1923 | // it matches this driver invocation pid. |
| 1924 | int CrashPID; |
| 1925 | if (OpenBracket < 0 || CloseBracket < 0 || |
| 1926 | ParentProcess.slice(Start: OpenBracket + 1, End: CloseBracket) |
| 1927 | .getAsInteger(Radix: 10, Result&: CrashPID) || CrashPID != PID) { |
| 1928 | continue; |
| 1929 | } |
| 1930 | |
| 1931 | // Found a .crash file matching the driver pid. To avoid getting an older |
| 1932 | // and misleading crash file, continue looking for the most recent. |
| 1933 | // FIXME: the driver can dispatch multiple cc1 invocations, leading to |
| 1934 | // multiple crashes poiting to the same parent process. Since the driver |
| 1935 | // does not collect pid information for the dispatched invocation there's |
| 1936 | // currently no way to distinguish among them. |
| 1937 | const auto FileAccessTime = FileStatus.getLastModificationTime(); |
| 1938 | if (FileAccessTime > LastAccessTime) { |
| 1939 | CrashFilePath.assign(RHS: File->path()); |
| 1940 | LastAccessTime = FileAccessTime; |
| 1941 | } |
| 1942 | } |
| 1943 | |
| 1944 | // If found, copy it over to the location of other reproducer files. |
| 1945 | if (!CrashFilePath.empty()) { |
| 1946 | EC = fs::copy_file(From: CrashFilePath, To: ReproCrashFilename); |
| 1947 | if (EC) |
| 1948 | return false; |
| 1949 | return true; |
| 1950 | } |
| 1951 | |
| 1952 | return false; |
| 1953 | } |
| 1954 | |
| 1955 | static const char BugReporMsg[] = |
| 1956 | "\n********************\n\n" |
| 1957 | "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" |
| 1958 | "Preprocessed source(s) and associated run script(s) are located at:" ; |
| 1959 | |
| 1960 | // When clang crashes, produce diagnostic information including the fully |
| 1961 | // preprocessed source file(s). Request that the developer attach the |
| 1962 | // diagnostic information to a bug report. |
| 1963 | void Driver::generateCompilationDiagnostics( |
| 1964 | Compilation &C, const Command &FailingCommand, |
| 1965 | StringRef AdditionalInformation, CompilationDiagnosticReport *Report) { |
| 1966 | if (C.getArgs().hasArg(Ids: options::OPT_fno_crash_diagnostics)) |
| 1967 | return; |
| 1968 | |
| 1969 | unsigned Level = 1; |
| 1970 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_fcrash_diagnostics_EQ)) { |
| 1971 | Level = llvm::StringSwitch<unsigned>(A->getValue()) |
| 1972 | .Case(S: "off" , Value: 0) |
| 1973 | .Case(S: "compiler" , Value: 1) |
| 1974 | .Case(S: "all" , Value: 2) |
| 1975 | .Default(Value: 1); |
| 1976 | } |
| 1977 | if (!Level) |
| 1978 | return; |
| 1979 | |
| 1980 | // Don't try to generate diagnostics for dsymutil jobs. |
| 1981 | if (FailingCommand.getCreator().isDsymutilJob()) |
| 1982 | return; |
| 1983 | |
| 1984 | bool IsLLD = false; |
| 1985 | ArgStringList SavedTemps; |
| 1986 | if (FailingCommand.getCreator().isLinkJob()) { |
| 1987 | C.getDefaultToolChain().GetLinkerPath(LinkerIsLLD: &IsLLD); |
| 1988 | if (!IsLLD || Level < 2) |
| 1989 | return; |
| 1990 | |
| 1991 | // If lld crashed, we will re-run the same command with the input it used |
| 1992 | // to have. In that case we should not remove temp files in |
| 1993 | // initCompilationForDiagnostics yet. They will be added back and removed |
| 1994 | // later. |
| 1995 | SavedTemps = std::move(C.getTempFiles()); |
| 1996 | assert(!C.getTempFiles().size()); |
| 1997 | } |
| 1998 | |
| 1999 | // Print the version of the compiler. |
| 2000 | PrintVersion(C, OS&: llvm::errs()); |
| 2001 | |
| 2002 | // Suppress driver output and emit preprocessor output to temp file. |
| 2003 | CCGenDiagnostics = true; |
| 2004 | |
| 2005 | // Save the original job command(s). |
| 2006 | Command Cmd = FailingCommand; |
| 2007 | |
| 2008 | // Keep track of whether we produce any errors while trying to produce |
| 2009 | // preprocessed sources. |
| 2010 | DiagnosticErrorTrap Trap(Diags); |
| 2011 | |
| 2012 | // Suppress tool output. |
| 2013 | C.initCompilationForDiagnostics(); |
| 2014 | |
| 2015 | // If lld failed, rerun it again with --reproduce. |
| 2016 | if (IsLLD) { |
| 2017 | const char *TmpName = CreateTempFile(C, Prefix: "linker-crash" , Suffix: "tar" ); |
| 2018 | Command NewLLDInvocation = Cmd; |
| 2019 | llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments(); |
| 2020 | StringRef ReproduceOption = |
| 2021 | C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() |
| 2022 | ? "/reproduce:" |
| 2023 | : "--reproduce=" ; |
| 2024 | ArgList.push_back(Elt: Saver.save(S: Twine(ReproduceOption) + TmpName).data()); |
| 2025 | NewLLDInvocation.replaceArguments(List: std::move(ArgList)); |
| 2026 | |
| 2027 | // Redirect stdout/stderr to /dev/null. |
| 2028 | NewLLDInvocation.Execute(Redirects: {std::nullopt, {"" }, {"" }}, ErrMsg: nullptr, ExecutionFailed: nullptr); |
| 2029 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg; |
| 2030 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << TmpName; |
| 2031 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2032 | << "\n\n********************" ; |
| 2033 | if (Report) |
| 2034 | Report->TemporaryFiles.push_back(Elt: TmpName); |
| 2035 | return; |
| 2036 | } |
| 2037 | |
| 2038 | // Construct the list of inputs. |
| 2039 | InputList Inputs; |
| 2040 | BuildInputs(TC: C.getDefaultToolChain(), Args&: C.getArgs(), Inputs); |
| 2041 | |
| 2042 | ArgStringList IRInputs; |
| 2043 | for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { |
| 2044 | bool IgnoreInput = false; |
| 2045 | |
| 2046 | // Save IR inputs separately, ignore input from stdin or any other inputs |
| 2047 | // that cannot be preprocessed. Check type first as not all linker inputs |
| 2048 | // have a value. |
| 2049 | if (types::isLLVMIR(Id: it->first)) { |
| 2050 | IRInputs.push_back(Elt: it->second->getValue()); |
| 2051 | IgnoreInput = true; |
| 2052 | } else if (types::getPreprocessedType(Id: it->first) == types::TY_INVALID) { |
| 2053 | IgnoreInput = true; |
| 2054 | } else if (!strcmp(s1: it->second->getValue(), s2: "-" )) { |
| 2055 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2056 | << "Error generating preprocessed source(s) - " |
| 2057 | "ignoring input from stdin." ; |
| 2058 | IgnoreInput = true; |
| 2059 | } |
| 2060 | |
| 2061 | if (IgnoreInput) { |
| 2062 | it = Inputs.erase(CI: it); |
| 2063 | ie = Inputs.end(); |
| 2064 | } else { |
| 2065 | ++it; |
| 2066 | } |
| 2067 | } |
| 2068 | |
| 2069 | if (Inputs.empty() && IRInputs.empty()) { |
| 2070 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2071 | << "Error generating preprocessed source(s) - " |
| 2072 | "no preprocessable inputs." ; |
| 2073 | return; |
| 2074 | } |
| 2075 | |
| 2076 | // Don't attempt to generate preprocessed files if multiple -arch options are |
| 2077 | // used, unless they're all duplicates. |
| 2078 | llvm::StringSet<> ArchNames; |
| 2079 | for (const Arg *A : C.getArgs()) { |
| 2080 | if (A->getOption().matches(ID: options::OPT_arch)) { |
| 2081 | StringRef ArchName = A->getValue(); |
| 2082 | ArchNames.insert(key: ArchName); |
| 2083 | } |
| 2084 | } |
| 2085 | if (ArchNames.size() > 1) { |
| 2086 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2087 | << "Error generating preprocessed source(s) - cannot generate " |
| 2088 | "preprocessed source with multiple -arch options." ; |
| 2089 | return; |
| 2090 | } |
| 2091 | |
| 2092 | // If we only have IR inputs there's no need for preprocessing. |
| 2093 | if (!Inputs.empty()) { |
| 2094 | // Construct the list of abstract actions to perform for this compilation. |
| 2095 | // On Darwin OSes this uses the driver-driver and builds universal actions. |
| 2096 | const ToolChain &TC = C.getDefaultToolChain(); |
| 2097 | if (TC.getTriple().isOSBinFormatMachO()) |
| 2098 | BuildUniversalActions(C, TC, BAInputs: Inputs); |
| 2099 | else |
| 2100 | BuildActions(C, Args&: C.getArgs(), Inputs, Actions&: C.getActions()); |
| 2101 | |
| 2102 | BuildJobs(C); |
| 2103 | |
| 2104 | // If there were errors building the compilation, quit now. |
| 2105 | if (Trap.hasErrorOccurred()) { |
| 2106 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2107 | << "Error generating preprocessed source(s)." ; |
| 2108 | return; |
| 2109 | } |
| 2110 | // Generate preprocessed output. |
| 2111 | SmallVector<std::pair<int, const Command *>, 4> FailingCommands; |
| 2112 | C.ExecuteJobs(Jobs: C.getJobs(), FailingCommands); |
| 2113 | |
| 2114 | // If any of the preprocessing commands failed, clean up and exit. |
| 2115 | if (!FailingCommands.empty()) { |
| 2116 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2117 | << "Error generating preprocessed source(s)." ; |
| 2118 | return; |
| 2119 | } |
| 2120 | |
| 2121 | const ArgStringList &TempFiles = C.getTempFiles(); |
| 2122 | if (TempFiles.empty()) { |
| 2123 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2124 | << "Error generating preprocessed source(s)." ; |
| 2125 | return; |
| 2126 | } |
| 2127 | } |
| 2128 | |
| 2129 | // Copying filenames due to ownership. |
| 2130 | const ArgStringList &Files = C.getTempFiles(); |
| 2131 | SmallVector<std::string> TempFiles(Files.begin(), Files.end()); |
| 2132 | |
| 2133 | // We'd like to copy the IR input file into our own temp file |
| 2134 | // because the build system might try to clean-up after itself. |
| 2135 | for (auto const *Input : IRInputs) { |
| 2136 | int FD; |
| 2137 | llvm::SmallVector<char, 64> Path; |
| 2138 | |
| 2139 | StringRef extension = llvm::sys::path::extension(path: Input); |
| 2140 | if (!extension.empty()) |
| 2141 | extension = extension.drop_front(); |
| 2142 | |
| 2143 | std::error_code EC = llvm::sys::fs::createTemporaryFile( |
| 2144 | Prefix: llvm::sys::path::stem(path: Input), Suffix: extension, ResultFD&: FD, ResultPath&: Path); |
| 2145 | if (EC) { |
| 2146 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2147 | << "Error generating run script: " << "Failed copying IR input files" |
| 2148 | << " " << EC.message(); |
| 2149 | return; |
| 2150 | } |
| 2151 | |
| 2152 | EC = llvm::sys::fs::copy_file(From: Input, ToFD: FD); |
| 2153 | if (EC) { |
| 2154 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2155 | << "Error generating run script: " << "Failed copying IR input files" |
| 2156 | << " " << EC.message(); |
| 2157 | return; |
| 2158 | } |
| 2159 | |
| 2160 | TempFiles.push_back(Elt: std::string(Path.begin(), Path.end())); |
| 2161 | } |
| 2162 | |
| 2163 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg; |
| 2164 | |
| 2165 | SmallString<128> VFS; |
| 2166 | SmallString<128> ReproCrashFilename; |
| 2167 | for (std::string &TempFile : TempFiles) { |
| 2168 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << TempFile; |
| 2169 | if (Report) |
| 2170 | Report->TemporaryFiles.push_back(Elt: TempFile); |
| 2171 | if (ReproCrashFilename.empty()) { |
| 2172 | ReproCrashFilename = TempFile; |
| 2173 | llvm::sys::path::replace_extension(path&: ReproCrashFilename, extension: ".crash" ); |
| 2174 | } |
| 2175 | if (StringRef(TempFile).ends_with(Suffix: ".cache" )) { |
| 2176 | // In some cases (modules) we'll dump extra data to help with reproducing |
| 2177 | // the crash into a directory next to the output. |
| 2178 | VFS = llvm::sys::path::filename(path: TempFile); |
| 2179 | llvm::sys::path::append(path&: VFS, a: "vfs" , b: "vfs.yaml" ); |
| 2180 | } |
| 2181 | } |
| 2182 | |
| 2183 | for (const char *TempFile : SavedTemps) |
| 2184 | TempFiles.push_back(Elt: TempFile); |
| 2185 | |
| 2186 | // Assume associated files are based off of the first temporary file. |
| 2187 | CrashReportInfo CrashInfo(TempFiles[0], VFS); |
| 2188 | |
| 2189 | llvm::SmallString<128> Script(CrashInfo.Filename); |
| 2190 | llvm::sys::path::replace_extension(path&: Script, extension: "sh" ); |
| 2191 | std::error_code EC; |
| 2192 | llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew, |
| 2193 | llvm::sys::fs::FA_Write, |
| 2194 | llvm::sys::fs::OF_Text); |
| 2195 | if (EC) { |
| 2196 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2197 | << "Error generating run script: " << Script << " " << EC.message(); |
| 2198 | } else { |
| 2199 | ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n" |
| 2200 | << "# Driver args: " ; |
| 2201 | printArgList(OS&: ScriptOS, Args: C.getInputArgs()); |
| 2202 | ScriptOS << "# Original command: " ; |
| 2203 | Cmd.Print(OS&: ScriptOS, Terminator: "\n" , /*Quote=*/true); |
| 2204 | Cmd.Print(OS&: ScriptOS, Terminator: "\n" , /*Quote=*/true, CrashInfo: &CrashInfo); |
| 2205 | if (!AdditionalInformation.empty()) |
| 2206 | ScriptOS << "\n# Additional information: " << AdditionalInformation |
| 2207 | << "\n" ; |
| 2208 | if (Report) |
| 2209 | Report->TemporaryFiles.push_back(Elt: std::string(Script)); |
| 2210 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << Script; |
| 2211 | } |
| 2212 | |
| 2213 | // On darwin, provide information about the .crash diagnostic report. |
| 2214 | if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) { |
| 2215 | SmallString<128> CrashDiagDir; |
| 2216 | if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) { |
| 2217 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2218 | << ReproCrashFilename.str(); |
| 2219 | } else { // Suggest a directory for the user to look for .crash files. |
| 2220 | llvm::sys::path::append(path&: CrashDiagDir, a: Name); |
| 2221 | CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash" ; |
| 2222 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2223 | << "Crash backtrace is located in" ; |
| 2224 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2225 | << CrashDiagDir.str(); |
| 2226 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2227 | << "(choose the .crash file that corresponds to your crash)" ; |
| 2228 | } |
| 2229 | } |
| 2230 | |
| 2231 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2232 | << "\n\n********************" ; |
| 2233 | } |
| 2234 | |
| 2235 | void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) { |
| 2236 | // Since commandLineFitsWithinSystemLimits() may underestimate system's |
| 2237 | // capacity if the tool does not support response files, there is a chance/ |
| 2238 | // that things will just work without a response file, so we silently just |
| 2239 | // skip it. |
| 2240 | if (Cmd.getResponseFileSupport().ResponseKind == |
| 2241 | ResponseFileSupport::RF_None || |
| 2242 | llvm::sys::commandLineFitsWithinSystemLimits(Program: Cmd.getExecutable(), |
| 2243 | Args: Cmd.getArguments())) |
| 2244 | return; |
| 2245 | |
| 2246 | std::string TmpName = GetTemporaryPath(Prefix: "response" , Suffix: "txt" ); |
| 2247 | Cmd.setResponseFile(C.addTempFile(Name: C.getArgs().MakeArgString(Str: TmpName))); |
| 2248 | } |
| 2249 | |
| 2250 | int Driver::ExecuteCompilation( |
| 2251 | Compilation &C, |
| 2252 | SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) { |
| 2253 | if (C.getArgs().hasArg(Ids: options::OPT_fdriver_only)) { |
| 2254 | if (C.getArgs().hasArg(Ids: options::OPT_v)) |
| 2255 | C.getJobs().Print(OS&: llvm::errs(), Terminator: "\n" , Quote: true); |
| 2256 | |
| 2257 | C.ExecuteJobs(Jobs: C.getJobs(), FailingCommands, /*LogOnly=*/true); |
| 2258 | |
| 2259 | // If there were errors building the compilation, quit now. |
| 2260 | if (!FailingCommands.empty() || Diags.hasErrorOccurred()) |
| 2261 | return 1; |
| 2262 | |
| 2263 | return 0; |
| 2264 | } |
| 2265 | |
| 2266 | // Just print if -### was present. |
| 2267 | if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH)) { |
| 2268 | C.getJobs().Print(OS&: llvm::errs(), Terminator: "\n" , Quote: true); |
| 2269 | return Diags.hasErrorOccurred() ? 1 : 0; |
| 2270 | } |
| 2271 | |
| 2272 | // If there were errors building the compilation, quit now. |
| 2273 | if (Diags.hasErrorOccurred()) |
| 2274 | return 1; |
| 2275 | |
| 2276 | // Set up response file names for each command, if necessary. |
| 2277 | for (auto &Job : C.getJobs()) |
| 2278 | setUpResponseFiles(C, Cmd&: Job); |
| 2279 | |
| 2280 | C.ExecuteJobs(Jobs: C.getJobs(), FailingCommands); |
| 2281 | |
| 2282 | // If the command succeeded, we are done. |
| 2283 | if (FailingCommands.empty()) |
| 2284 | return 0; |
| 2285 | |
| 2286 | // Otherwise, remove result files and print extra information about abnormal |
| 2287 | // failures. |
| 2288 | int Res = 0; |
| 2289 | for (const auto &CmdPair : FailingCommands) { |
| 2290 | int CommandRes = CmdPair.first; |
| 2291 | const Command *FailingCommand = CmdPair.second; |
| 2292 | |
| 2293 | // Remove result files if we're not saving temps. |
| 2294 | if (!isSaveTempsEnabled()) { |
| 2295 | const JobAction *JA = cast<JobAction>(Val: &FailingCommand->getSource()); |
| 2296 | C.CleanupFileMap(Files: C.getResultFiles(), JA, IssueErrors: true); |
| 2297 | |
| 2298 | // Failure result files are valid unless we crashed. |
| 2299 | if (CommandRes < 0) |
| 2300 | C.CleanupFileMap(Files: C.getFailureResultFiles(), JA, IssueErrors: true); |
| 2301 | } |
| 2302 | |
| 2303 | // llvm/lib/Support/*/Signals.inc will exit with a special return code |
| 2304 | // for SIGPIPE. Do not print diagnostics for this case. |
| 2305 | if (CommandRes == EX_IOERR) { |
| 2306 | Res = CommandRes; |
| 2307 | continue; |
| 2308 | } |
| 2309 | |
| 2310 | // Print extra information about abnormal failures, if possible. |
| 2311 | // |
| 2312 | // This is ad-hoc, but we don't want to be excessively noisy. If the result |
| 2313 | // status was 1, assume the command failed normally. In particular, if it |
| 2314 | // was the compiler then assume it gave a reasonable error code. Failures |
| 2315 | // in other tools are less common, and they generally have worse |
| 2316 | // diagnostics, so always print the diagnostic there. |
| 2317 | const Tool &FailingTool = FailingCommand->getCreator(); |
| 2318 | |
| 2319 | if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) { |
| 2320 | // FIXME: See FIXME above regarding result code interpretation. |
| 2321 | #if LLVM_ON_UNIX |
| 2322 | // On Unix, signals are represented by return codes of 128 plus the |
| 2323 | // signal number. Return code 255 is excluded because some tools, |
| 2324 | // such as llvm-ifs, exit with code 255 (-1) on failure. |
| 2325 | if (CommandRes > 128 && CommandRes != 255) |
| 2326 | #else |
| 2327 | if (CommandRes < 0) |
| 2328 | #endif |
| 2329 | Diag(DiagID: clang::diag::err_drv_command_signalled) |
| 2330 | << FailingTool.getShortName(); |
| 2331 | else |
| 2332 | Diag(DiagID: clang::diag::err_drv_command_failed) |
| 2333 | << FailingTool.getShortName() << CommandRes; |
| 2334 | } |
| 2335 | } |
| 2336 | return Res; |
| 2337 | } |
| 2338 | |
| 2339 | void Driver::PrintHelp(bool ShowHidden) const { |
| 2340 | llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(); |
| 2341 | |
| 2342 | std::string Usage = llvm::formatv(Fmt: "{0} [options] file..." , Vals: Name).str(); |
| 2343 | getOpts().printHelp(OS&: llvm::outs(), Usage: Usage.c_str(), Title: DriverTitle.c_str(), |
| 2344 | ShowHidden, /*ShowAllAliases=*/false, |
| 2345 | VisibilityMask); |
| 2346 | } |
| 2347 | |
| 2348 | void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { |
| 2349 | if (IsFlangMode()) { |
| 2350 | OS << getClangToolFullVersion(ToolName: "flang" ) << '\n'; |
| 2351 | } else { |
| 2352 | // FIXME: The following handlers should use a callback mechanism, we don't |
| 2353 | // know what the client would like to do. |
| 2354 | OS << getClangFullVersion() << '\n'; |
| 2355 | } |
| 2356 | const ToolChain &TC = C.getDefaultToolChain(); |
| 2357 | OS << "Target: " << TC.getTripleString() << '\n'; |
| 2358 | |
| 2359 | // Print the threading model. |
| 2360 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_mthread_model)) { |
| 2361 | // Don't print if the ToolChain would have barfed on it already |
| 2362 | if (TC.isThreadModelSupported(Model: A->getValue())) |
| 2363 | OS << "Thread model: " << A->getValue(); |
| 2364 | } else |
| 2365 | OS << "Thread model: " << TC.getThreadModel(); |
| 2366 | OS << '\n'; |
| 2367 | |
| 2368 | // Print out the install directory. |
| 2369 | OS << "InstalledDir: " << Dir << '\n'; |
| 2370 | |
| 2371 | // Print the build config if it's non-default. |
| 2372 | // Intended to help LLVM developers understand the configs of compilers |
| 2373 | // they're investigating. |
| 2374 | if (!llvm::cl::getCompilerBuildConfig().empty()) |
| 2375 | llvm::cl::printBuildConfig(OS); |
| 2376 | |
| 2377 | // If configuration files were used, print their paths. |
| 2378 | for (auto ConfigFile : ConfigFiles) |
| 2379 | OS << "Configuration file: " << ConfigFile << '\n'; |
| 2380 | } |
| 2381 | |
| 2382 | /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories |
| 2383 | /// option. |
| 2384 | static void PrintDiagnosticCategories(raw_ostream &OS) { |
| 2385 | // Skip the empty category. |
| 2386 | for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max; |
| 2387 | ++i) |
| 2388 | OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(CategoryID: i) << '\n'; |
| 2389 | } |
| 2390 | |
| 2391 | void Driver::HandleAutocompletions(StringRef PassedFlags) const { |
| 2392 | if (PassedFlags == "" ) |
| 2393 | return; |
| 2394 | // Print out all options that start with a given argument. This is used for |
| 2395 | // shell autocompletion. |
| 2396 | std::vector<std::string> SuggestedCompletions; |
| 2397 | std::vector<std::string> Flags; |
| 2398 | |
| 2399 | llvm::opt::Visibility VisibilityMask(options::ClangOption); |
| 2400 | |
| 2401 | // Make sure that Flang-only options don't pollute the Clang output |
| 2402 | // TODO: Make sure that Clang-only options don't pollute Flang output |
| 2403 | if (IsFlangMode()) |
| 2404 | VisibilityMask = llvm::opt::Visibility(options::FlangOption); |
| 2405 | |
| 2406 | // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag," |
| 2407 | // because the latter indicates that the user put space before pushing tab |
| 2408 | // which should end up in a file completion. |
| 2409 | const bool HasSpace = PassedFlags.ends_with(Suffix: "," ); |
| 2410 | |
| 2411 | // Parse PassedFlags by "," as all the command-line flags are passed to this |
| 2412 | // function separated by "," |
| 2413 | StringRef TargetFlags = PassedFlags; |
| 2414 | while (TargetFlags != "" ) { |
| 2415 | StringRef CurFlag; |
| 2416 | std::tie(args&: CurFlag, args&: TargetFlags) = TargetFlags.split(Separator: "," ); |
| 2417 | Flags.push_back(x: std::string(CurFlag)); |
| 2418 | } |
| 2419 | |
| 2420 | // We want to show cc1-only options only when clang is invoked with -cc1 or |
| 2421 | // -Xclang. |
| 2422 | if (llvm::is_contained(Range&: Flags, Element: "-Xclang" ) || llvm::is_contained(Range&: Flags, Element: "-cc1" )) |
| 2423 | VisibilityMask = llvm::opt::Visibility(options::CC1Option); |
| 2424 | |
| 2425 | const llvm::opt::OptTable &Opts = getOpts(); |
| 2426 | StringRef Cur; |
| 2427 | Cur = Flags.at(n: Flags.size() - 1); |
| 2428 | StringRef Prev; |
| 2429 | if (Flags.size() >= 2) { |
| 2430 | Prev = Flags.at(n: Flags.size() - 2); |
| 2431 | SuggestedCompletions = Opts.suggestValueCompletions(Option: Prev, Arg: Cur); |
| 2432 | } |
| 2433 | |
| 2434 | if (SuggestedCompletions.empty()) |
| 2435 | SuggestedCompletions = Opts.suggestValueCompletions(Option: Cur, Arg: "" ); |
| 2436 | |
| 2437 | // If Flags were empty, it means the user typed `clang [tab]` where we should |
| 2438 | // list all possible flags. If there was no value completion and the user |
| 2439 | // pressed tab after a space, we should fall back to a file completion. |
| 2440 | // We're printing a newline to be consistent with what we print at the end of |
| 2441 | // this function. |
| 2442 | if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) { |
| 2443 | llvm::outs() << '\n'; |
| 2444 | return; |
| 2445 | } |
| 2446 | |
| 2447 | // When flag ends with '=' and there was no value completion, return empty |
| 2448 | // string and fall back to the file autocompletion. |
| 2449 | if (SuggestedCompletions.empty() && !Cur.ends_with(Suffix: "=" )) { |
| 2450 | // If the flag is in the form of "--autocomplete=-foo", |
| 2451 | // we were requested to print out all option names that start with "-foo". |
| 2452 | // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only". |
| 2453 | SuggestedCompletions = Opts.findByPrefix( |
| 2454 | Cur, VisibilityMask, |
| 2455 | /*DisableFlags=*/options::Unsupported | options::Ignored); |
| 2456 | |
| 2457 | // We have to query the -W flags manually as they're not in the OptTable. |
| 2458 | // TODO: Find a good way to add them to OptTable instead and them remove |
| 2459 | // this code. |
| 2460 | for (StringRef S : DiagnosticIDs::getDiagnosticFlags()) |
| 2461 | if (S.starts_with(Prefix: Cur)) |
| 2462 | SuggestedCompletions.push_back(x: std::string(S)); |
| 2463 | } |
| 2464 | |
| 2465 | // Sort the autocomplete candidates so that shells print them out in a |
| 2466 | // deterministic order. We could sort in any way, but we chose |
| 2467 | // case-insensitive sorting for consistency with the -help option |
| 2468 | // which prints out options in the case-insensitive alphabetical order. |
| 2469 | llvm::sort(C&: SuggestedCompletions, Comp: [](StringRef A, StringRef B) { |
| 2470 | if (int X = A.compare_insensitive(RHS: B)) |
| 2471 | return X < 0; |
| 2472 | return A.compare(RHS: B) > 0; |
| 2473 | }); |
| 2474 | |
| 2475 | llvm::outs() << llvm::join(R&: SuggestedCompletions, Separator: "\n" ) << '\n'; |
| 2476 | } |
| 2477 | |
| 2478 | bool Driver::HandleImmediateArgs(Compilation &C) { |
| 2479 | // The order these options are handled in gcc is all over the place, but we |
| 2480 | // don't expect inconsistencies w.r.t. that to matter in practice. |
| 2481 | |
| 2482 | if (C.getArgs().hasArg(Ids: options::OPT_dumpmachine)) { |
| 2483 | llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; |
| 2484 | return false; |
| 2485 | } |
| 2486 | |
| 2487 | if (C.getArgs().hasArg(Ids: options::OPT_dumpversion)) { |
| 2488 | // Since -dumpversion is only implemented for pedantic GCC compatibility, we |
| 2489 | // return an answer which matches our definition of __VERSION__. |
| 2490 | llvm::outs() << CLANG_VERSION_STRING << "\n" ; |
| 2491 | return false; |
| 2492 | } |
| 2493 | |
| 2494 | if (C.getArgs().hasArg(Ids: options::OPT__print_diagnostic_categories)) { |
| 2495 | PrintDiagnosticCategories(OS&: llvm::outs()); |
| 2496 | return false; |
| 2497 | } |
| 2498 | |
| 2499 | if (C.getArgs().hasArg(Ids: options::OPT_help) || |
| 2500 | C.getArgs().hasArg(Ids: options::OPT__help_hidden)) { |
| 2501 | PrintHelp(ShowHidden: C.getArgs().hasArg(Ids: options::OPT__help_hidden)); |
| 2502 | return false; |
| 2503 | } |
| 2504 | |
| 2505 | if (C.getArgs().hasArg(Ids: options::OPT__version)) { |
| 2506 | // Follow gcc behavior and use stdout for --version and stderr for -v. |
| 2507 | PrintVersion(C, OS&: llvm::outs()); |
| 2508 | return false; |
| 2509 | } |
| 2510 | |
| 2511 | if (C.getArgs().hasArg(Ids: options::OPT_v) || |
| 2512 | C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH) || |
| 2513 | C.getArgs().hasArg(Ids: options::OPT_print_supported_cpus) || |
| 2514 | C.getArgs().hasArg(Ids: options::OPT_print_supported_extensions) || |
| 2515 | C.getArgs().hasArg(Ids: options::OPT_print_enabled_extensions)) { |
| 2516 | PrintVersion(C, OS&: llvm::errs()); |
| 2517 | SuppressMissingInputWarning = true; |
| 2518 | } |
| 2519 | |
| 2520 | if (C.getArgs().hasArg(Ids: options::OPT_v)) { |
| 2521 | if (!SystemConfigDir.empty()) |
| 2522 | llvm::errs() << "System configuration file directory: " |
| 2523 | << SystemConfigDir << "\n" ; |
| 2524 | if (!UserConfigDir.empty()) |
| 2525 | llvm::errs() << "User configuration file directory: " |
| 2526 | << UserConfigDir << "\n" ; |
| 2527 | } |
| 2528 | |
| 2529 | const ToolChain &TC = C.getDefaultToolChain(); |
| 2530 | |
| 2531 | if (C.getArgs().hasArg(Ids: options::OPT_v)) |
| 2532 | TC.printVerboseInfo(OS&: llvm::errs()); |
| 2533 | |
| 2534 | if (C.getArgs().hasArg(Ids: options::OPT_print_resource_dir)) { |
| 2535 | llvm::outs() << ResourceDir << '\n'; |
| 2536 | return false; |
| 2537 | } |
| 2538 | |
| 2539 | if (C.getArgs().hasArg(Ids: options::OPT_print_search_dirs)) { |
| 2540 | llvm::outs() << "programs: =" ; |
| 2541 | bool separator = false; |
| 2542 | // Print -B and COMPILER_PATH. |
| 2543 | for (const std::string &Path : PrefixDirs) { |
| 2544 | if (separator) |
| 2545 | llvm::outs() << llvm::sys::EnvPathSeparator; |
| 2546 | llvm::outs() << Path; |
| 2547 | separator = true; |
| 2548 | } |
| 2549 | for (const std::string &Path : TC.getProgramPaths()) { |
| 2550 | if (separator) |
| 2551 | llvm::outs() << llvm::sys::EnvPathSeparator; |
| 2552 | llvm::outs() << Path; |
| 2553 | separator = true; |
| 2554 | } |
| 2555 | llvm::outs() << "\n" ; |
| 2556 | llvm::outs() << "libraries: =" << ResourceDir; |
| 2557 | |
| 2558 | StringRef sysroot = C.getSysRoot(); |
| 2559 | |
| 2560 | for (const std::string &Path : TC.getFilePaths()) { |
| 2561 | // Always print a separator. ResourceDir was the first item shown. |
| 2562 | llvm::outs() << llvm::sys::EnvPathSeparator; |
| 2563 | // Interpretation of leading '=' is needed only for NetBSD. |
| 2564 | if (Path[0] == '=') |
| 2565 | llvm::outs() << sysroot << Path.substr(pos: 1); |
| 2566 | else |
| 2567 | llvm::outs() << Path; |
| 2568 | } |
| 2569 | llvm::outs() << "\n" ; |
| 2570 | return false; |
| 2571 | } |
| 2572 | |
| 2573 | if (C.getArgs().hasArg(Ids: options::OPT_print_std_module_manifest_path)) { |
| 2574 | llvm::outs() << GetStdModuleManifestPath(C, TC: C.getDefaultToolChain()) |
| 2575 | << '\n'; |
| 2576 | return false; |
| 2577 | } |
| 2578 | |
| 2579 | if (C.getArgs().hasArg(Ids: options::OPT_print_runtime_dir)) { |
| 2580 | for (auto RuntimePath : |
| 2581 | {TC.getRuntimePath(), std::make_optional(t: TC.getCompilerRTPath())}) { |
| 2582 | if (RuntimePath && getVFS().exists(Path: *RuntimePath)) { |
| 2583 | llvm::outs() << *RuntimePath << '\n'; |
| 2584 | return false; |
| 2585 | } |
| 2586 | } |
| 2587 | llvm::outs() << "(runtime dir is not present)" << '\n'; |
| 2588 | return false; |
| 2589 | } |
| 2590 | |
| 2591 | if (C.getArgs().hasArg(Ids: options::OPT_print_diagnostic_options)) { |
| 2592 | std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags(); |
| 2593 | for (std::size_t I = 0; I != Flags.size(); I += 2) |
| 2594 | llvm::outs() << " " << Flags[I] << "\n " << Flags[I + 1] << "\n\n" ; |
| 2595 | return false; |
| 2596 | } |
| 2597 | |
| 2598 | // FIXME: The following handlers should use a callback mechanism, we don't |
| 2599 | // know what the client would like to do. |
| 2600 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_print_file_name_EQ)) { |
| 2601 | llvm::outs() << GetFilePath(Name: A->getValue(), TC) << "\n" ; |
| 2602 | return false; |
| 2603 | } |
| 2604 | |
| 2605 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_print_prog_name_EQ)) { |
| 2606 | StringRef ProgName = A->getValue(); |
| 2607 | |
| 2608 | // Null program name cannot have a path. |
| 2609 | if (! ProgName.empty()) |
| 2610 | llvm::outs() << GetProgramPath(Name: ProgName, TC); |
| 2611 | |
| 2612 | llvm::outs() << "\n" ; |
| 2613 | return false; |
| 2614 | } |
| 2615 | |
| 2616 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_autocomplete)) { |
| 2617 | StringRef PassedFlags = A->getValue(); |
| 2618 | HandleAutocompletions(PassedFlags); |
| 2619 | return false; |
| 2620 | } |
| 2621 | |
| 2622 | if (C.getArgs().hasArg(Ids: options::OPT_print_libgcc_file_name)) { |
| 2623 | ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args: C.getArgs()); |
| 2624 | const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args: C.getArgs())); |
| 2625 | // The 'Darwin' toolchain is initialized only when its arguments are |
| 2626 | // computed. Get the default arguments for OFK_None to ensure that |
| 2627 | // initialization is performed before trying to access properties of |
| 2628 | // the toolchain in the functions below. |
| 2629 | // FIXME: Remove when darwin's toolchain is initialized during construction. |
| 2630 | // FIXME: For some more esoteric targets the default toolchain is not the |
| 2631 | // correct one. |
| 2632 | C.getArgsForToolChain(TC: &TC, BoundArch: Triple.getArchName(), DeviceOffloadKind: Action::OFK_None); |
| 2633 | RegisterEffectiveTriple TripleRAII(TC, Triple); |
| 2634 | switch (RLT) { |
| 2635 | case ToolChain::RLT_CompilerRT: |
| 2636 | llvm::outs() << TC.getCompilerRT(Args: C.getArgs(), Component: "builtins" ) << "\n" ; |
| 2637 | break; |
| 2638 | case ToolChain::RLT_Libgcc: |
| 2639 | llvm::outs() << GetFilePath(Name: "libgcc.a" , TC) << "\n" ; |
| 2640 | break; |
| 2641 | } |
| 2642 | return false; |
| 2643 | } |
| 2644 | |
| 2645 | if (C.getArgs().hasArg(Ids: options::OPT_print_multi_lib)) { |
| 2646 | for (const Multilib &Multilib : TC.getMultilibs()) |
| 2647 | if (!Multilib.isError()) |
| 2648 | llvm::outs() << Multilib << "\n" ; |
| 2649 | return false; |
| 2650 | } |
| 2651 | |
| 2652 | if (C.getArgs().hasArg(Ids: options::OPT_print_multi_flags)) { |
| 2653 | Multilib::flags_list ArgFlags = TC.getMultilibFlags(C.getArgs()); |
| 2654 | llvm::StringSet<> ExpandedFlags = TC.getMultilibs().expandFlags(ArgFlags); |
| 2655 | std::set<llvm::StringRef> SortedFlags; |
| 2656 | for (const auto &FlagEntry : ExpandedFlags) |
| 2657 | SortedFlags.insert(x: FlagEntry.getKey()); |
| 2658 | for (auto Flag : SortedFlags) |
| 2659 | llvm::outs() << Flag << '\n'; |
| 2660 | return false; |
| 2661 | } |
| 2662 | |
| 2663 | if (C.getArgs().hasArg(Ids: options::OPT_print_multi_directory)) { |
| 2664 | for (const Multilib &Multilib : TC.getSelectedMultilibs()) { |
| 2665 | if (Multilib.gccSuffix().empty()) |
| 2666 | llvm::outs() << ".\n" ; |
| 2667 | else { |
| 2668 | StringRef Suffix(Multilib.gccSuffix()); |
| 2669 | assert(Suffix.front() == '/'); |
| 2670 | llvm::outs() << Suffix.substr(Start: 1) << "\n" ; |
| 2671 | } |
| 2672 | } |
| 2673 | return false; |
| 2674 | } |
| 2675 | |
| 2676 | if (C.getArgs().hasArg(Ids: options::OPT_print_target_triple)) { |
| 2677 | llvm::outs() << TC.getTripleString() << "\n" ; |
| 2678 | return false; |
| 2679 | } |
| 2680 | |
| 2681 | if (C.getArgs().hasArg(Ids: options::OPT_print_effective_triple)) { |
| 2682 | const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args: C.getArgs())); |
| 2683 | llvm::outs() << Triple.getTriple() << "\n" ; |
| 2684 | return false; |
| 2685 | } |
| 2686 | |
| 2687 | if (C.getArgs().hasArg(Ids: options::OPT_print_targets)) { |
| 2688 | llvm::TargetRegistry::printRegisteredTargetsForVersion(OS&: llvm::outs()); |
| 2689 | return false; |
| 2690 | } |
| 2691 | |
| 2692 | return true; |
| 2693 | } |
| 2694 | |
| 2695 | enum { |
| 2696 | TopLevelAction = 0, |
| 2697 | HeadSibAction = 1, |
| 2698 | OtherSibAction = 2, |
| 2699 | }; |
| 2700 | |
| 2701 | // Display an action graph human-readably. Action A is the "sink" node |
| 2702 | // and latest-occuring action. Traversal is in pre-order, visiting the |
| 2703 | // inputs to each action before printing the action itself. |
| 2704 | static unsigned PrintActions1(const Compilation &C, Action *A, |
| 2705 | std::map<Action *, unsigned> &Ids, |
| 2706 | Twine Indent = {}, int Kind = TopLevelAction) { |
| 2707 | if (auto It = Ids.find(x: A); It != Ids.end()) // A was already visited. |
| 2708 | return It->second; |
| 2709 | |
| 2710 | std::string str; |
| 2711 | llvm::raw_string_ostream os(str); |
| 2712 | |
| 2713 | auto getSibIndent = [](int K) -> Twine { |
| 2714 | return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "" ; |
| 2715 | }; |
| 2716 | |
| 2717 | Twine SibIndent = Indent + getSibIndent(Kind); |
| 2718 | int SibKind = HeadSibAction; |
| 2719 | os << Action::getClassName(AC: A->getKind()) << ", " ; |
| 2720 | if (InputAction *IA = dyn_cast<InputAction>(Val: A)) { |
| 2721 | os << "\"" << IA->getInputArg().getValue() << "\"" ; |
| 2722 | } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(Val: A)) { |
| 2723 | os << '"' << BIA->getArchName() << '"' << ", {" |
| 2724 | << PrintActions1(C, A: *BIA->input_begin(), Ids, Indent: SibIndent, Kind: SibKind) << "}" ; |
| 2725 | } else if (OffloadAction *OA = dyn_cast<OffloadAction>(Val: A)) { |
| 2726 | bool IsFirst = true; |
| 2727 | OA->doOnEachDependence( |
| 2728 | Work: [&](Action *A, const ToolChain *TC, const char *BoundArch) { |
| 2729 | assert(TC && "Unknown host toolchain" ); |
| 2730 | // E.g. for two CUDA device dependences whose bound arch is sm_20 and |
| 2731 | // sm_35 this will generate: |
| 2732 | // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device" |
| 2733 | // (nvptx64-nvidia-cuda:sm_35) {#ID} |
| 2734 | if (!IsFirst) |
| 2735 | os << ", " ; |
| 2736 | os << '"'; |
| 2737 | os << A->getOffloadingKindPrefix(); |
| 2738 | os << " (" ; |
| 2739 | os << TC->getTriple().normalize(); |
| 2740 | if (BoundArch) |
| 2741 | os << ":" << BoundArch; |
| 2742 | os << ")" ; |
| 2743 | os << '"'; |
| 2744 | os << " {" << PrintActions1(C, A, Ids, Indent: SibIndent, Kind: SibKind) << "}" ; |
| 2745 | IsFirst = false; |
| 2746 | SibKind = OtherSibAction; |
| 2747 | }); |
| 2748 | } else { |
| 2749 | const ActionList *AL = &A->getInputs(); |
| 2750 | |
| 2751 | if (AL->size()) { |
| 2752 | const char *Prefix = "{" ; |
| 2753 | for (Action *PreRequisite : *AL) { |
| 2754 | os << Prefix << PrintActions1(C, A: PreRequisite, Ids, Indent: SibIndent, Kind: SibKind); |
| 2755 | Prefix = ", " ; |
| 2756 | SibKind = OtherSibAction; |
| 2757 | } |
| 2758 | os << "}" ; |
| 2759 | } else |
| 2760 | os << "{}" ; |
| 2761 | } |
| 2762 | |
| 2763 | // Append offload info for all options other than the offloading action |
| 2764 | // itself (e.g. (cuda-device, sm_20) or (cuda-host)). |
| 2765 | std::string offload_str; |
| 2766 | llvm::raw_string_ostream offload_os(offload_str); |
| 2767 | if (!isa<OffloadAction>(Val: A)) { |
| 2768 | auto S = A->getOffloadingKindPrefix(); |
| 2769 | if (!S.empty()) { |
| 2770 | offload_os << ", (" << S; |
| 2771 | if (A->getOffloadingArch()) |
| 2772 | offload_os << ", " << A->getOffloadingArch(); |
| 2773 | offload_os << ")" ; |
| 2774 | } |
| 2775 | } |
| 2776 | |
| 2777 | auto getSelfIndent = [](int K) -> Twine { |
| 2778 | return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "" ; |
| 2779 | }; |
| 2780 | |
| 2781 | unsigned Id = Ids.size(); |
| 2782 | Ids[A] = Id; |
| 2783 | llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", " |
| 2784 | << types::getTypeName(Id: A->getType()) << offload_os.str() << "\n" ; |
| 2785 | |
| 2786 | return Id; |
| 2787 | } |
| 2788 | |
| 2789 | // Print the action graphs in a compilation C. |
| 2790 | // For example "clang -c file1.c file2.c" is composed of two subgraphs. |
| 2791 | void Driver::PrintActions(const Compilation &C) const { |
| 2792 | std::map<Action *, unsigned> Ids; |
| 2793 | for (Action *A : C.getActions()) |
| 2794 | PrintActions1(C, A, Ids); |
| 2795 | } |
| 2796 | |
| 2797 | /// Check whether the given input tree contains any compilation or |
| 2798 | /// assembly actions. |
| 2799 | static bool ContainsCompileOrAssembleAction(const Action *A) { |
| 2800 | if (isa<CompileJobAction>(Val: A) || isa<BackendJobAction>(Val: A) || |
| 2801 | isa<AssembleJobAction>(Val: A)) |
| 2802 | return true; |
| 2803 | |
| 2804 | return llvm::any_of(Range: A->inputs(), P: ContainsCompileOrAssembleAction); |
| 2805 | } |
| 2806 | |
| 2807 | void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC, |
| 2808 | const InputList &BAInputs) const { |
| 2809 | DerivedArgList &Args = C.getArgs(); |
| 2810 | ActionList &Actions = C.getActions(); |
| 2811 | llvm::PrettyStackTraceString CrashInfo("Building universal build actions" ); |
| 2812 | // Collect the list of architectures. Duplicates are allowed, but should only |
| 2813 | // be handled once (in the order seen). |
| 2814 | llvm::StringSet<> ArchNames; |
| 2815 | SmallVector<const char *, 4> Archs; |
| 2816 | for (Arg *A : Args) { |
| 2817 | if (A->getOption().matches(ID: options::OPT_arch)) { |
| 2818 | // Validate the option here; we don't save the type here because its |
| 2819 | // particular spelling may participate in other driver choices. |
| 2820 | llvm::Triple::ArchType Arch = |
| 2821 | tools::darwin::getArchTypeForMachOArchName(Str: A->getValue()); |
| 2822 | if (Arch == llvm::Triple::UnknownArch) { |
| 2823 | Diag(DiagID: clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args); |
| 2824 | continue; |
| 2825 | } |
| 2826 | |
| 2827 | A->claim(); |
| 2828 | if (ArchNames.insert(key: A->getValue()).second) |
| 2829 | Archs.push_back(Elt: A->getValue()); |
| 2830 | } |
| 2831 | } |
| 2832 | |
| 2833 | // When there is no explicit arch for this platform, make sure we still bind |
| 2834 | // the architecture (to the default) so that -Xarch_ is handled correctly. |
| 2835 | if (!Archs.size()) |
| 2836 | Archs.push_back(Elt: Args.MakeArgString(Str: TC.getDefaultUniversalArchName())); |
| 2837 | |
| 2838 | ActionList SingleActions; |
| 2839 | BuildActions(C, Args, Inputs: BAInputs, Actions&: SingleActions); |
| 2840 | |
| 2841 | // Add in arch bindings for every top level action, as well as lipo and |
| 2842 | // dsymutil steps if needed. |
| 2843 | for (Action* Act : SingleActions) { |
| 2844 | // Make sure we can lipo this kind of output. If not (and it is an actual |
| 2845 | // output) then we disallow, since we can't create an output file with the |
| 2846 | // right name without overwriting it. We could remove this oddity by just |
| 2847 | // changing the output names to include the arch, which would also fix |
| 2848 | // -save-temps. Compatibility wins for now. |
| 2849 | |
| 2850 | if (Archs.size() > 1 && !types::canLipoType(Id: Act->getType())) |
| 2851 | Diag(DiagID: clang::diag::err_drv_invalid_output_with_multiple_archs) |
| 2852 | << types::getTypeName(Id: Act->getType()); |
| 2853 | |
| 2854 | ActionList Inputs; |
| 2855 | for (unsigned i = 0, e = Archs.size(); i != e; ++i) |
| 2856 | Inputs.push_back(Elt: C.MakeAction<BindArchAction>(Arg&: Act, Arg&: Archs[i])); |
| 2857 | |
| 2858 | // Lipo if necessary, we do it this way because we need to set the arch flag |
| 2859 | // so that -Xarch_ gets overwritten. |
| 2860 | if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) |
| 2861 | Actions.append(in_start: Inputs.begin(), in_end: Inputs.end()); |
| 2862 | else |
| 2863 | Actions.push_back(Elt: C.MakeAction<LipoJobAction>(Arg&: Inputs, Arg: Act->getType())); |
| 2864 | |
| 2865 | // Handle debug info queries. |
| 2866 | Arg *A = Args.getLastArg(Ids: options::OPT_g_Group); |
| 2867 | bool enablesDebugInfo = A && !A->getOption().matches(ID: options::OPT_g0) && |
| 2868 | !A->getOption().matches(ID: options::OPT_gstabs); |
| 2869 | if ((enablesDebugInfo || willEmitRemarks(Args)) && |
| 2870 | ContainsCompileOrAssembleAction(A: Actions.back())) { |
| 2871 | |
| 2872 | // Add a 'dsymutil' step if necessary, when debug info is enabled and we |
| 2873 | // have a compile input. We need to run 'dsymutil' ourselves in such cases |
| 2874 | // because the debug info will refer to a temporary object file which |
| 2875 | // will be removed at the end of the compilation process. |
| 2876 | if (Act->getType() == types::TY_Image) { |
| 2877 | ActionList Inputs; |
| 2878 | Inputs.push_back(Elt: Actions.back()); |
| 2879 | Actions.pop_back(); |
| 2880 | Actions.push_back( |
| 2881 | Elt: C.MakeAction<DsymutilJobAction>(Arg&: Inputs, Arg: types::TY_dSYM)); |
| 2882 | } |
| 2883 | |
| 2884 | // Verify the debug info output. |
| 2885 | if (Args.hasArg(Ids: options::OPT_verify_debug_info)) { |
| 2886 | Action *LastAction = Actions.pop_back_val(); |
| 2887 | Actions.push_back(Elt: C.MakeAction<VerifyDebugInfoJobAction>( |
| 2888 | Arg&: LastAction, Arg: types::TY_Nothing)); |
| 2889 | } |
| 2890 | } |
| 2891 | } |
| 2892 | } |
| 2893 | |
| 2894 | bool Driver::DiagnoseInputExistence(StringRef Value, types::ID Ty, |
| 2895 | bool TypoCorrect) const { |
| 2896 | if (!getCheckInputsExist()) |
| 2897 | return true; |
| 2898 | |
| 2899 | // stdin always exists. |
| 2900 | if (Value == "-" ) |
| 2901 | return true; |
| 2902 | |
| 2903 | // If it's a header to be found in the system or user search path, then defer |
| 2904 | // complaints about its absence until those searches can be done. When we |
| 2905 | // are definitely processing headers for C++20 header units, extend this to |
| 2906 | // allow the user to put "-fmodule-header -xc++-header vector" for example. |
| 2907 | if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader || |
| 2908 | (ModulesModeCXX20 && Ty == types::TY_CXXHeader)) |
| 2909 | return true; |
| 2910 | |
| 2911 | if (getVFS().exists(Path: Value)) |
| 2912 | return true; |
| 2913 | |
| 2914 | if (TypoCorrect) { |
| 2915 | // Check if the filename is a typo for an option flag. OptTable thinks |
| 2916 | // that all args that are not known options and that start with / are |
| 2917 | // filenames, but e.g. `/diagnostic:caret` is more likely a typo for |
| 2918 | // the option `/diagnostics:caret` than a reference to a file in the root |
| 2919 | // directory. |
| 2920 | std::string Nearest; |
| 2921 | if (getOpts().findNearest(Option: Value, NearestString&: Nearest, VisibilityMask: getOptionVisibilityMask()) <= 1) { |
| 2922 | Diag(DiagID: clang::diag::err_drv_no_such_file_with_suggestion) |
| 2923 | << Value << Nearest; |
| 2924 | return false; |
| 2925 | } |
| 2926 | } |
| 2927 | |
| 2928 | // In CL mode, don't error on apparently non-existent linker inputs, because |
| 2929 | // they can be influenced by linker flags the clang driver might not |
| 2930 | // understand. |
| 2931 | // Examples: |
| 2932 | // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver |
| 2933 | // module look for an MSVC installation in the registry. (We could ask |
| 2934 | // the MSVCToolChain object if it can find `ole32.lib`, but the logic to |
| 2935 | // look in the registry might move into lld-link in the future so that |
| 2936 | // lld-link invocations in non-MSVC shells just work too.) |
| 2937 | // - `clang-cl ... /link ...` can pass arbitrary flags to the linker, |
| 2938 | // including /libpath:, which is used to find .lib and .obj files. |
| 2939 | // So do not diagnose this on the driver level. Rely on the linker diagnosing |
| 2940 | // it. (If we don't end up invoking the linker, this means we'll emit a |
| 2941 | // "'linker' input unused [-Wunused-command-line-argument]" warning instead |
| 2942 | // of an error.) |
| 2943 | // |
| 2944 | // Only do this skip after the typo correction step above. `/Brepo` is treated |
| 2945 | // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit |
| 2946 | // an error if we have a flag that's within an edit distance of 1 from a |
| 2947 | // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the |
| 2948 | // driver in the unlikely case they run into this.) |
| 2949 | // |
| 2950 | // Don't do this for inputs that start with a '/', else we'd pass options |
| 2951 | // like /libpath: through to the linker silently. |
| 2952 | // |
| 2953 | // Emitting an error for linker inputs can also cause incorrect diagnostics |
| 2954 | // with the gcc driver. The command |
| 2955 | // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o |
| 2956 | // will make lld look for some/dir/file.o, while we will diagnose here that |
| 2957 | // `/file.o` does not exist. However, configure scripts check if |
| 2958 | // `clang /GR-` compiles without error to see if the compiler is cl.exe, |
| 2959 | // so we can't downgrade diagnostics for `/GR-` from an error to a warning |
| 2960 | // in cc mode. (We can in cl mode because cl.exe itself only warns on |
| 2961 | // unknown flags.) |
| 2962 | if (IsCLMode() && Ty == types::TY_Object && !Value.starts_with(Prefix: "/" )) |
| 2963 | return true; |
| 2964 | |
| 2965 | Diag(DiagID: clang::diag::err_drv_no_such_file) << Value; |
| 2966 | return false; |
| 2967 | } |
| 2968 | |
| 2969 | // Get the C++20 Header Unit type corresponding to the input type. |
| 2970 | static types::ID (ModuleHeaderMode HM) { |
| 2971 | switch (HM) { |
| 2972 | case HeaderMode_User: |
| 2973 | return types::TY_CXXUHeader; |
| 2974 | case HeaderMode_System: |
| 2975 | return types::TY_CXXSHeader; |
| 2976 | case HeaderMode_Default: |
| 2977 | break; |
| 2978 | case HeaderMode_None: |
| 2979 | llvm_unreachable("should not be called in this case" ); |
| 2980 | } |
| 2981 | return types::TY_CXXHUHeader; |
| 2982 | } |
| 2983 | |
| 2984 | // Construct a the list of inputs and their types. |
| 2985 | void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, |
| 2986 | InputList &Inputs) const { |
| 2987 | const llvm::opt::OptTable &Opts = getOpts(); |
| 2988 | // Track the current user specified (-x) input. We also explicitly track the |
| 2989 | // argument used to set the type; we only want to claim the type when we |
| 2990 | // actually use it, so we warn about unused -x arguments. |
| 2991 | types::ID InputType = types::TY_Nothing; |
| 2992 | Arg *InputTypeArg = nullptr; |
| 2993 | |
| 2994 | // The last /TC or /TP option sets the input type to C or C++ globally. |
| 2995 | if (Arg *TCTP = Args.getLastArgNoClaim(Ids: options::OPT__SLASH_TC, |
| 2996 | Ids: options::OPT__SLASH_TP)) { |
| 2997 | InputTypeArg = TCTP; |
| 2998 | InputType = TCTP->getOption().matches(ID: options::OPT__SLASH_TC) |
| 2999 | ? types::TY_C |
| 3000 | : types::TY_CXX; |
| 3001 | |
| 3002 | Arg *Previous = nullptr; |
| 3003 | bool ShowNote = false; |
| 3004 | for (Arg *A : |
| 3005 | Args.filtered(Ids: options::OPT__SLASH_TC, Ids: options::OPT__SLASH_TP)) { |
| 3006 | if (Previous) { |
| 3007 | Diag(DiagID: clang::diag::warn_drv_overriding_option) |
| 3008 | << Previous->getSpelling() << A->getSpelling(); |
| 3009 | ShowNote = true; |
| 3010 | } |
| 3011 | Previous = A; |
| 3012 | } |
| 3013 | if (ShowNote) |
| 3014 | Diag(DiagID: clang::diag::note_drv_t_option_is_global); |
| 3015 | } |
| 3016 | |
| 3017 | // Warn -x after last input file has no effect |
| 3018 | { |
| 3019 | Arg *LastXArg = Args.getLastArgNoClaim(Ids: options::OPT_x); |
| 3020 | Arg *LastInputArg = Args.getLastArgNoClaim(Ids: options::OPT_INPUT); |
| 3021 | if (LastXArg && LastInputArg && |
| 3022 | LastInputArg->getIndex() < LastXArg->getIndex()) |
| 3023 | Diag(DiagID: clang::diag::warn_drv_unused_x) << LastXArg->getValue(); |
| 3024 | } |
| 3025 | |
| 3026 | for (Arg *A : Args) { |
| 3027 | if (A->getOption().getKind() == Option::InputClass) { |
| 3028 | const char *Value = A->getValue(); |
| 3029 | types::ID Ty = types::TY_INVALID; |
| 3030 | |
| 3031 | // Infer the input type if necessary. |
| 3032 | if (InputType == types::TY_Nothing) { |
| 3033 | // If there was an explicit arg for this, claim it. |
| 3034 | if (InputTypeArg) |
| 3035 | InputTypeArg->claim(); |
| 3036 | |
| 3037 | // stdin must be handled specially. |
| 3038 | if (memcmp(s1: Value, s2: "-" , n: 2) == 0) { |
| 3039 | if (IsFlangMode()) { |
| 3040 | Ty = types::TY_Fortran; |
| 3041 | } else if (IsDXCMode()) { |
| 3042 | Ty = types::TY_HLSL; |
| 3043 | } else { |
| 3044 | // If running with -E, treat as a C input (this changes the |
| 3045 | // builtin macros, for example). This may be overridden by -ObjC |
| 3046 | // below. |
| 3047 | // |
| 3048 | // Otherwise emit an error but still use a valid type to avoid |
| 3049 | // spurious errors (e.g., no inputs). |
| 3050 | assert(!CCGenDiagnostics && "stdin produces no crash reproducer" ); |
| 3051 | if (!Args.hasArgNoClaim(Ids: options::OPT_E) && !CCCIsCPP()) |
| 3052 | Diag(DiagID: IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl |
| 3053 | : clang::diag::err_drv_unknown_stdin_type); |
| 3054 | Ty = types::TY_C; |
| 3055 | } |
| 3056 | } else { |
| 3057 | // Otherwise lookup by extension. |
| 3058 | // Fallback is C if invoked as C preprocessor, C++ if invoked with |
| 3059 | // clang-cl /E, or Object otherwise. |
| 3060 | // We use a host hook here because Darwin at least has its own |
| 3061 | // idea of what .s is. |
| 3062 | if (const char *Ext = strrchr(s: Value, c: '.')) |
| 3063 | Ty = TC.LookupTypeForExtension(Ext: Ext + 1); |
| 3064 | |
| 3065 | if (Ty == types::TY_INVALID) { |
| 3066 | if (IsCLMode() && (Args.hasArgNoClaim(Ids: options::OPT_E) || CCGenDiagnostics)) |
| 3067 | Ty = types::TY_CXX; |
| 3068 | else if (CCCIsCPP() || CCGenDiagnostics) |
| 3069 | Ty = types::TY_C; |
| 3070 | else if (IsDXCMode()) |
| 3071 | Ty = types::TY_HLSL; |
| 3072 | else |
| 3073 | Ty = types::TY_Object; |
| 3074 | } |
| 3075 | |
| 3076 | // If the driver is invoked as C++ compiler (like clang++ or c++) it |
| 3077 | // should autodetect some input files as C++ for g++ compatibility. |
| 3078 | if (CCCIsCXX()) { |
| 3079 | types::ID OldTy = Ty; |
| 3080 | Ty = types::lookupCXXTypeForCType(Id: Ty); |
| 3081 | |
| 3082 | // Do not complain about foo.h, when we are known to be processing |
| 3083 | // it as a C++20 header unit. |
| 3084 | if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode())) |
| 3085 | Diag(DiagID: clang::diag::warn_drv_treating_input_as_cxx) |
| 3086 | << getTypeName(Id: OldTy) << getTypeName(Id: Ty); |
| 3087 | } |
| 3088 | |
| 3089 | // If running with -fthinlto-index=, extensions that normally identify |
| 3090 | // native object files actually identify LLVM bitcode files. |
| 3091 | if (Args.hasArgNoClaim(Ids: options::OPT_fthinlto_index_EQ) && |
| 3092 | Ty == types::TY_Object) |
| 3093 | Ty = types::TY_LLVM_BC; |
| 3094 | } |
| 3095 | |
| 3096 | // -ObjC and -ObjC++ override the default language, but only for "source |
| 3097 | // files". We just treat everything that isn't a linker input as a |
| 3098 | // source file. |
| 3099 | // |
| 3100 | // FIXME: Clean this up if we move the phase sequence into the type. |
| 3101 | if (Ty != types::TY_Object) { |
| 3102 | if (Args.hasArg(Ids: options::OPT_ObjC)) |
| 3103 | Ty = types::TY_ObjC; |
| 3104 | else if (Args.hasArg(Ids: options::OPT_ObjCXX)) |
| 3105 | Ty = types::TY_ObjCXX; |
| 3106 | } |
| 3107 | |
| 3108 | // Disambiguate headers that are meant to be header units from those |
| 3109 | // intended to be PCH. Avoid missing '.h' cases that are counted as |
| 3110 | // C headers by default - we know we are in C++ mode and we do not |
| 3111 | // want to issue a complaint about compiling things in the wrong mode. |
| 3112 | if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) && |
| 3113 | hasHeaderMode()) |
| 3114 | Ty = CXXHeaderUnitType(HM: CXX20HeaderType); |
| 3115 | } else { |
| 3116 | assert(InputTypeArg && "InputType set w/o InputTypeArg" ); |
| 3117 | if (!InputTypeArg->getOption().matches(ID: options::OPT_x)) { |
| 3118 | // If emulating cl.exe, make sure that /TC and /TP don't affect input |
| 3119 | // object files. |
| 3120 | const char *Ext = strrchr(s: Value, c: '.'); |
| 3121 | if (Ext && TC.LookupTypeForExtension(Ext: Ext + 1) == types::TY_Object) |
| 3122 | Ty = types::TY_Object; |
| 3123 | } |
| 3124 | if (Ty == types::TY_INVALID) { |
| 3125 | Ty = InputType; |
| 3126 | InputTypeArg->claim(); |
| 3127 | } |
| 3128 | } |
| 3129 | |
| 3130 | if ((Ty == types::TY_C || Ty == types::TY_CXX) && |
| 3131 | Args.hasArgNoClaim(Ids: options::OPT_hipstdpar)) |
| 3132 | Ty = types::TY_HIP; |
| 3133 | |
| 3134 | if (DiagnoseInputExistence(Value, Ty, /*TypoCorrect=*/true)) |
| 3135 | Inputs.push_back(Elt: std::make_pair(x&: Ty, y&: A)); |
| 3136 | |
| 3137 | } else if (A->getOption().matches(ID: options::OPT__SLASH_Tc)) { |
| 3138 | StringRef Value = A->getValue(); |
| 3139 | if (DiagnoseInputExistence(Value, Ty: types::TY_C, |
| 3140 | /*TypoCorrect=*/false)) { |
| 3141 | Arg *InputArg = makeInputArg(Args, Opts, Value: A->getValue()); |
| 3142 | Inputs.push_back(Elt: std::make_pair(x: types::TY_C, y&: InputArg)); |
| 3143 | } |
| 3144 | A->claim(); |
| 3145 | } else if (A->getOption().matches(ID: options::OPT__SLASH_Tp)) { |
| 3146 | StringRef Value = A->getValue(); |
| 3147 | if (DiagnoseInputExistence(Value, Ty: types::TY_CXX, |
| 3148 | /*TypoCorrect=*/false)) { |
| 3149 | Arg *InputArg = makeInputArg(Args, Opts, Value: A->getValue()); |
| 3150 | Inputs.push_back(Elt: std::make_pair(x: types::TY_CXX, y&: InputArg)); |
| 3151 | } |
| 3152 | A->claim(); |
| 3153 | } else if (A->getOption().hasFlag(Val: options::LinkerInput)) { |
| 3154 | // Just treat as object type, we could make a special type for this if |
| 3155 | // necessary. |
| 3156 | Inputs.push_back(Elt: std::make_pair(x: types::TY_Object, y&: A)); |
| 3157 | |
| 3158 | } else if (A->getOption().matches(ID: options::OPT_x)) { |
| 3159 | InputTypeArg = A; |
| 3160 | InputType = types::lookupTypeForTypeSpecifier(Name: A->getValue()); |
| 3161 | A->claim(); |
| 3162 | |
| 3163 | // Follow gcc behavior and treat as linker input for invalid -x |
| 3164 | // options. Its not clear why we shouldn't just revert to unknown; but |
| 3165 | // this isn't very important, we might as well be bug compatible. |
| 3166 | if (!InputType) { |
| 3167 | Diag(DiagID: clang::diag::err_drv_unknown_language) << A->getValue(); |
| 3168 | InputType = types::TY_Object; |
| 3169 | } |
| 3170 | |
| 3171 | // If the user has put -fmodule-header{,=} then we treat C++ headers as |
| 3172 | // header unit inputs. So we 'promote' -xc++-header appropriately. |
| 3173 | if (InputType == types::TY_CXXHeader && hasHeaderMode()) |
| 3174 | InputType = CXXHeaderUnitType(HM: CXX20HeaderType); |
| 3175 | } else if (A->getOption().getID() == options::OPT_U) { |
| 3176 | assert(A->getNumValues() == 1 && "The /U option has one value." ); |
| 3177 | StringRef Val = A->getValue(N: 0); |
| 3178 | if (Val.find_first_of(Chars: "/\\" ) != StringRef::npos) { |
| 3179 | // Warn about e.g. "/Users/me/myfile.c". |
| 3180 | Diag(DiagID: diag::warn_slash_u_filename) << Val; |
| 3181 | Diag(DiagID: diag::note_use_dashdash); |
| 3182 | } |
| 3183 | } |
| 3184 | } |
| 3185 | if (CCCIsCPP() && Inputs.empty()) { |
| 3186 | // If called as standalone preprocessor, stdin is processed |
| 3187 | // if no other input is present. |
| 3188 | Arg *A = makeInputArg(Args, Opts, Value: "-" ); |
| 3189 | Inputs.push_back(Elt: std::make_pair(x: types::TY_C, y&: A)); |
| 3190 | } |
| 3191 | } |
| 3192 | |
| 3193 | namespace { |
| 3194 | /// Provides a convenient interface for different programming models to generate |
| 3195 | /// the required device actions. |
| 3196 | class OffloadingActionBuilder final { |
| 3197 | /// Flag used to trace errors in the builder. |
| 3198 | bool IsValid = false; |
| 3199 | |
| 3200 | /// The compilation that is using this builder. |
| 3201 | Compilation &C; |
| 3202 | |
| 3203 | /// Map between an input argument and the offload kinds used to process it. |
| 3204 | std::map<const Arg *, unsigned> InputArgToOffloadKindMap; |
| 3205 | |
| 3206 | /// Map between a host action and its originating input argument. |
| 3207 | std::map<Action *, const Arg *> HostActionToInputArgMap; |
| 3208 | |
| 3209 | /// Builder interface. It doesn't build anything or keep any state. |
| 3210 | class DeviceActionBuilder { |
| 3211 | public: |
| 3212 | typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy; |
| 3213 | |
| 3214 | enum ActionBuilderReturnCode { |
| 3215 | // The builder acted successfully on the current action. |
| 3216 | ABRT_Success, |
| 3217 | // The builder didn't have to act on the current action. |
| 3218 | ABRT_Inactive, |
| 3219 | // The builder was successful and requested the host action to not be |
| 3220 | // generated. |
| 3221 | ABRT_Ignore_Host, |
| 3222 | }; |
| 3223 | |
| 3224 | protected: |
| 3225 | /// Compilation associated with this builder. |
| 3226 | Compilation &C; |
| 3227 | |
| 3228 | /// Tool chains associated with this builder. The same programming |
| 3229 | /// model may have associated one or more tool chains. |
| 3230 | SmallVector<const ToolChain *, 2> ToolChains; |
| 3231 | |
| 3232 | /// The derived arguments associated with this builder. |
| 3233 | DerivedArgList &Args; |
| 3234 | |
| 3235 | /// The inputs associated with this builder. |
| 3236 | const InputList &Inputs; |
| 3237 | |
| 3238 | /// The associated offload kind. |
| 3239 | Action::OffloadKind AssociatedOffloadKind = Action::OFK_None; |
| 3240 | |
| 3241 | public: |
| 3242 | DeviceActionBuilder(Compilation &C, DerivedArgList &Args, |
| 3243 | const InputList &Inputs, |
| 3244 | Action::OffloadKind AssociatedOffloadKind) |
| 3245 | : C(C), Args(Args), Inputs(Inputs), |
| 3246 | AssociatedOffloadKind(AssociatedOffloadKind) {} |
| 3247 | virtual ~DeviceActionBuilder() {} |
| 3248 | |
| 3249 | /// Fill up the array \a DA with all the device dependences that should be |
| 3250 | /// added to the provided host action \a HostAction. By default it is |
| 3251 | /// inactive. |
| 3252 | virtual ActionBuilderReturnCode |
| 3253 | getDeviceDependences(OffloadAction::DeviceDependences &DA, |
| 3254 | phases::ID CurPhase, phases::ID FinalPhase, |
| 3255 | PhasesTy &Phases) { |
| 3256 | return ABRT_Inactive; |
| 3257 | } |
| 3258 | |
| 3259 | /// Update the state to include the provided host action \a HostAction as a |
| 3260 | /// dependency of the current device action. By default it is inactive. |
| 3261 | virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) { |
| 3262 | return ABRT_Inactive; |
| 3263 | } |
| 3264 | |
| 3265 | /// Append top level actions generated by the builder. |
| 3266 | virtual void appendTopLevelActions(ActionList &AL) {} |
| 3267 | |
| 3268 | /// Append linker device actions generated by the builder. |
| 3269 | virtual void appendLinkDeviceActions(ActionList &AL) {} |
| 3270 | |
| 3271 | /// Append linker host action generated by the builder. |
| 3272 | virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; } |
| 3273 | |
| 3274 | /// Append linker actions generated by the builder. |
| 3275 | virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {} |
| 3276 | |
| 3277 | /// Initialize the builder. Return true if any initialization errors are |
| 3278 | /// found. |
| 3279 | virtual bool initialize() { return false; } |
| 3280 | |
| 3281 | /// Return true if the builder can use bundling/unbundling. |
| 3282 | virtual bool canUseBundlerUnbundler() const { return false; } |
| 3283 | |
| 3284 | /// Return true if this builder is valid. We have a valid builder if we have |
| 3285 | /// associated device tool chains. |
| 3286 | bool isValid() { return !ToolChains.empty(); } |
| 3287 | |
| 3288 | /// Return the associated offload kind. |
| 3289 | Action::OffloadKind getAssociatedOffloadKind() { |
| 3290 | return AssociatedOffloadKind; |
| 3291 | } |
| 3292 | }; |
| 3293 | |
| 3294 | /// Base class for CUDA/HIP action builder. It injects device code in |
| 3295 | /// the host backend action. |
| 3296 | class CudaActionBuilderBase : public DeviceActionBuilder { |
| 3297 | protected: |
| 3298 | /// Flags to signal if the user requested host-only or device-only |
| 3299 | /// compilation. |
| 3300 | bool CompileHostOnly = false; |
| 3301 | bool CompileDeviceOnly = false; |
| 3302 | bool EmitLLVM = false; |
| 3303 | bool EmitAsm = false; |
| 3304 | |
| 3305 | /// ID to identify each device compilation. For CUDA it is simply the |
| 3306 | /// GPU arch string. For HIP it is either the GPU arch string or GPU |
| 3307 | /// arch string plus feature strings delimited by a plus sign, e.g. |
| 3308 | /// gfx906+xnack. |
| 3309 | struct TargetID { |
| 3310 | /// Target ID string which is persistent throughout the compilation. |
| 3311 | const char *ID; |
| 3312 | TargetID(OffloadArch Arch) { ID = OffloadArchToString(A: Arch); } |
| 3313 | TargetID(const char *ID) : ID(ID) {} |
| 3314 | operator const char *() { return ID; } |
| 3315 | operator StringRef() { return StringRef(ID); } |
| 3316 | }; |
| 3317 | /// List of GPU architectures to use in this compilation. |
| 3318 | SmallVector<TargetID, 4> GpuArchList; |
| 3319 | |
| 3320 | /// The CUDA actions for the current input. |
| 3321 | ActionList CudaDeviceActions; |
| 3322 | |
| 3323 | /// The CUDA fat binary if it was generated for the current input. |
| 3324 | Action *CudaFatBinary = nullptr; |
| 3325 | |
| 3326 | /// Flag that is set to true if this builder acted on the current input. |
| 3327 | bool IsActive = false; |
| 3328 | |
| 3329 | /// Flag for -fgpu-rdc. |
| 3330 | bool Relocatable = false; |
| 3331 | |
| 3332 | /// Default GPU architecture if there's no one specified. |
| 3333 | OffloadArch DefaultOffloadArch = OffloadArch::UNKNOWN; |
| 3334 | |
| 3335 | /// Compilation unit ID specified by option '-fuse-cuid=' or'-cuid='. |
| 3336 | const CUIDOptions &CUIDOpts; |
| 3337 | |
| 3338 | public: |
| 3339 | CudaActionBuilderBase(Compilation &C, DerivedArgList &Args, |
| 3340 | const InputList &Inputs, Action::OffloadKind OFKind) |
| 3341 | : DeviceActionBuilder(C, Args, Inputs, OFKind), |
| 3342 | CUIDOpts(C.getDriver().getCUIDOpts()) { |
| 3343 | |
| 3344 | CompileDeviceOnly = C.getDriver().offloadDeviceOnly(); |
| 3345 | Relocatable = Args.hasFlag(Pos: options::OPT_fgpu_rdc, |
| 3346 | Neg: options::OPT_fno_gpu_rdc, /*Default=*/false); |
| 3347 | } |
| 3348 | |
| 3349 | ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override { |
| 3350 | // While generating code for CUDA, we only depend on the host input action |
| 3351 | // to trigger the creation of all the CUDA device actions. |
| 3352 | |
| 3353 | // If we are dealing with an input action, replicate it for each GPU |
| 3354 | // architecture. If we are in host-only mode we return 'success' so that |
| 3355 | // the host uses the CUDA offload kind. |
| 3356 | if (auto *IA = dyn_cast<InputAction>(Val: HostAction)) { |
| 3357 | // If the host input is not CUDA or HIP, we don't need to bother about |
| 3358 | // this input. |
| 3359 | if (!(IA->getType() == types::TY_CUDA || |
| 3360 | IA->getType() == types::TY_HIP || |
| 3361 | IA->getType() == types::TY_PP_HIP)) { |
| 3362 | // The builder will ignore this input. |
| 3363 | IsActive = false; |
| 3364 | return ABRT_Inactive; |
| 3365 | } |
| 3366 | |
| 3367 | // Set the flag to true, so that the builder acts on the current input. |
| 3368 | IsActive = true; |
| 3369 | |
| 3370 | if (CUIDOpts.isEnabled()) |
| 3371 | IA->setId(CUIDOpts.getCUID(InputFile: IA->getInputArg().getValue(), Args)); |
| 3372 | |
| 3373 | if (CompileHostOnly) |
| 3374 | return ABRT_Success; |
| 3375 | |
| 3376 | // Replicate inputs for each GPU architecture. |
| 3377 | auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE |
| 3378 | : types::TY_CUDA_DEVICE; |
| 3379 | for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { |
| 3380 | CudaDeviceActions.push_back( |
| 3381 | Elt: C.MakeAction<InputAction>(Arg: IA->getInputArg(), Arg&: Ty, Arg: IA->getId())); |
| 3382 | } |
| 3383 | |
| 3384 | return ABRT_Success; |
| 3385 | } |
| 3386 | |
| 3387 | // If this is an unbundling action use it as is for each CUDA toolchain. |
| 3388 | if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(Val: HostAction)) { |
| 3389 | |
| 3390 | // If -fgpu-rdc is disabled, should not unbundle since there is no |
| 3391 | // device code to link. |
| 3392 | if (UA->getType() == types::TY_Object && !Relocatable) |
| 3393 | return ABRT_Inactive; |
| 3394 | |
| 3395 | CudaDeviceActions.clear(); |
| 3396 | auto *IA = cast<InputAction>(Val: UA->getInputs().back()); |
| 3397 | std::string FileName = IA->getInputArg().getAsString(Args); |
| 3398 | // Check if the type of the file is the same as the action. Do not |
| 3399 | // unbundle it if it is not. Do not unbundle .so files, for example, |
| 3400 | // which are not object files. Files with extension ".lib" is classified |
| 3401 | // as TY_Object but they are actually archives, therefore should not be |
| 3402 | // unbundled here as objects. They will be handled at other places. |
| 3403 | const StringRef LibFileExt = ".lib" ; |
| 3404 | if (IA->getType() == types::TY_Object && |
| 3405 | (!llvm::sys::path::has_extension(path: FileName) || |
| 3406 | types::lookupTypeForExtension( |
| 3407 | Ext: llvm::sys::path::extension(path: FileName).drop_front()) != |
| 3408 | types::TY_Object || |
| 3409 | llvm::sys::path::extension(path: FileName) == LibFileExt)) |
| 3410 | return ABRT_Inactive; |
| 3411 | |
| 3412 | for (auto Arch : GpuArchList) { |
| 3413 | CudaDeviceActions.push_back(Elt: UA); |
| 3414 | UA->registerDependentActionInfo(TC: ToolChains[0], BoundArch: Arch, |
| 3415 | Kind: AssociatedOffloadKind); |
| 3416 | } |
| 3417 | IsActive = true; |
| 3418 | return ABRT_Success; |
| 3419 | } |
| 3420 | |
| 3421 | return IsActive ? ABRT_Success : ABRT_Inactive; |
| 3422 | } |
| 3423 | |
| 3424 | void appendTopLevelActions(ActionList &AL) override { |
| 3425 | // Utility to append actions to the top level list. |
| 3426 | auto AddTopLevel = [&](Action *A, TargetID TargetID) { |
| 3427 | OffloadAction::DeviceDependences Dep; |
| 3428 | Dep.add(A&: *A, TC: *ToolChains.front(), BoundArch: TargetID, OKind: AssociatedOffloadKind); |
| 3429 | AL.push_back(Elt: C.MakeAction<OffloadAction>(Arg&: Dep, Arg: A->getType())); |
| 3430 | }; |
| 3431 | |
| 3432 | // If we have a fat binary, add it to the list. |
| 3433 | if (CudaFatBinary) { |
| 3434 | AddTopLevel(CudaFatBinary, OffloadArch::UNUSED); |
| 3435 | CudaDeviceActions.clear(); |
| 3436 | CudaFatBinary = nullptr; |
| 3437 | return; |
| 3438 | } |
| 3439 | |
| 3440 | if (CudaDeviceActions.empty()) |
| 3441 | return; |
| 3442 | |
| 3443 | // If we have CUDA actions at this point, that's because we have a have |
| 3444 | // partial compilation, so we should have an action for each GPU |
| 3445 | // architecture. |
| 3446 | assert(CudaDeviceActions.size() == GpuArchList.size() && |
| 3447 | "Expecting one action per GPU architecture." ); |
| 3448 | assert(ToolChains.size() == 1 && |
| 3449 | "Expecting to have a single CUDA toolchain." ); |
| 3450 | for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) |
| 3451 | AddTopLevel(CudaDeviceActions[I], GpuArchList[I]); |
| 3452 | |
| 3453 | CudaDeviceActions.clear(); |
| 3454 | } |
| 3455 | |
| 3456 | virtual std::optional<std::pair<llvm::StringRef, llvm::StringRef>> |
| 3457 | getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0; |
| 3458 | |
| 3459 | bool initialize() override { |
| 3460 | assert(AssociatedOffloadKind == Action::OFK_Cuda || |
| 3461 | AssociatedOffloadKind == Action::OFK_HIP); |
| 3462 | |
| 3463 | // We don't need to support CUDA. |
| 3464 | if (AssociatedOffloadKind == Action::OFK_Cuda && |
| 3465 | !C.hasOffloadToolChain<Action::OFK_Cuda>()) |
| 3466 | return false; |
| 3467 | |
| 3468 | // We don't need to support HIP. |
| 3469 | if (AssociatedOffloadKind == Action::OFK_HIP && |
| 3470 | !C.hasOffloadToolChain<Action::OFK_HIP>()) |
| 3471 | return false; |
| 3472 | |
| 3473 | const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); |
| 3474 | assert(HostTC && "No toolchain for host compilation." ); |
| 3475 | if (HostTC->getTriple().isNVPTX() || HostTC->getTriple().isAMDGCN()) { |
| 3476 | // We do not support targeting NVPTX/AMDGCN for host compilation. Throw |
| 3477 | // an error and abort pipeline construction early so we don't trip |
| 3478 | // asserts that assume device-side compilation. |
| 3479 | C.getDriver().Diag(DiagID: diag::err_drv_cuda_host_arch) |
| 3480 | << HostTC->getTriple().getArchName(); |
| 3481 | return true; |
| 3482 | } |
| 3483 | |
| 3484 | std::set<StringRef> GpuArchs; |
| 3485 | for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_HIP}) { |
| 3486 | for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind))) { |
| 3487 | ToolChains.push_back(Elt: I.second); |
| 3488 | |
| 3489 | for (auto Arch : |
| 3490 | C.getDriver().getOffloadArchs(C, Args: C.getArgs(), Kind, TC: *I.second)) |
| 3491 | GpuArchs.insert(x: Arch); |
| 3492 | } |
| 3493 | } |
| 3494 | |
| 3495 | for (auto Arch : GpuArchs) |
| 3496 | GpuArchList.push_back(Elt: Arch.data()); |
| 3497 | |
| 3498 | CompileHostOnly = C.getDriver().offloadHostOnly(); |
| 3499 | EmitLLVM = Args.getLastArg(Ids: options::OPT_emit_llvm); |
| 3500 | EmitAsm = Args.getLastArg(Ids: options::OPT_S); |
| 3501 | |
| 3502 | return false; |
| 3503 | } |
| 3504 | }; |
| 3505 | |
| 3506 | /// \brief CUDA action builder. It injects device code in the host backend |
| 3507 | /// action. |
| 3508 | class CudaActionBuilder final : public CudaActionBuilderBase { |
| 3509 | public: |
| 3510 | CudaActionBuilder(Compilation &C, DerivedArgList &Args, |
| 3511 | const InputList &Inputs) |
| 3512 | : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) { |
| 3513 | DefaultOffloadArch = OffloadArch::CudaDefault; |
| 3514 | } |
| 3515 | |
| 3516 | std::optional<std::pair<llvm::StringRef, llvm::StringRef>> |
| 3517 | getConflictOffloadArchCombination( |
| 3518 | const std::set<StringRef> &GpuArchs) override { |
| 3519 | return std::nullopt; |
| 3520 | } |
| 3521 | |
| 3522 | ActionBuilderReturnCode |
| 3523 | getDeviceDependences(OffloadAction::DeviceDependences &DA, |
| 3524 | phases::ID CurPhase, phases::ID FinalPhase, |
| 3525 | PhasesTy &Phases) override { |
| 3526 | if (!IsActive) |
| 3527 | return ABRT_Inactive; |
| 3528 | |
| 3529 | // If we don't have more CUDA actions, we don't have any dependences to |
| 3530 | // create for the host. |
| 3531 | if (CudaDeviceActions.empty()) |
| 3532 | return ABRT_Success; |
| 3533 | |
| 3534 | assert(CudaDeviceActions.size() == GpuArchList.size() && |
| 3535 | "Expecting one action per GPU architecture." ); |
| 3536 | assert(!CompileHostOnly && |
| 3537 | "Not expecting CUDA actions in host-only compilation." ); |
| 3538 | |
| 3539 | // If we are generating code for the device or we are in a backend phase, |
| 3540 | // we attempt to generate the fat binary. We compile each arch to ptx and |
| 3541 | // assemble to cubin, then feed the cubin *and* the ptx into a device |
| 3542 | // "link" action, which uses fatbinary to combine these cubins into one |
| 3543 | // fatbin. The fatbin is then an input to the host action if not in |
| 3544 | // device-only mode. |
| 3545 | if (CompileDeviceOnly || CurPhase == phases::Backend) { |
| 3546 | ActionList DeviceActions; |
| 3547 | for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { |
| 3548 | // Produce the device action from the current phase up to the assemble |
| 3549 | // phase. |
| 3550 | for (auto Ph : Phases) { |
| 3551 | // Skip the phases that were already dealt with. |
| 3552 | if (Ph < CurPhase) |
| 3553 | continue; |
| 3554 | // We have to be consistent with the host final phase. |
| 3555 | if (Ph > FinalPhase) |
| 3556 | break; |
| 3557 | |
| 3558 | CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction( |
| 3559 | C, Args, Phase: Ph, Input: CudaDeviceActions[I], TargetDeviceOffloadKind: Action::OFK_Cuda); |
| 3560 | |
| 3561 | if (Ph == phases::Assemble) |
| 3562 | break; |
| 3563 | } |
| 3564 | |
| 3565 | // If we didn't reach the assemble phase, we can't generate the fat |
| 3566 | // binary. We don't need to generate the fat binary if we are not in |
| 3567 | // device-only mode. |
| 3568 | if (!isa<AssembleJobAction>(Val: CudaDeviceActions[I]) || |
| 3569 | CompileDeviceOnly) |
| 3570 | continue; |
| 3571 | |
| 3572 | Action *AssembleAction = CudaDeviceActions[I]; |
| 3573 | assert(AssembleAction->getType() == types::TY_Object); |
| 3574 | assert(AssembleAction->getInputs().size() == 1); |
| 3575 | |
| 3576 | Action *BackendAction = AssembleAction->getInputs()[0]; |
| 3577 | assert(BackendAction->getType() == types::TY_PP_Asm); |
| 3578 | |
| 3579 | for (auto &A : {AssembleAction, BackendAction}) { |
| 3580 | OffloadAction::DeviceDependences DDep; |
| 3581 | DDep.add(A&: *A, TC: *ToolChains.front(), BoundArch: GpuArchList[I], OKind: Action::OFK_Cuda); |
| 3582 | DeviceActions.push_back( |
| 3583 | Elt: C.MakeAction<OffloadAction>(Arg&: DDep, Arg: A->getType())); |
| 3584 | } |
| 3585 | } |
| 3586 | |
| 3587 | // We generate the fat binary if we have device input actions. |
| 3588 | if (!DeviceActions.empty()) { |
| 3589 | CudaFatBinary = |
| 3590 | C.MakeAction<LinkJobAction>(Arg&: DeviceActions, Arg: types::TY_CUDA_FATBIN); |
| 3591 | |
| 3592 | if (!CompileDeviceOnly) { |
| 3593 | DA.add(A&: *CudaFatBinary, TC: *ToolChains.front(), /*BoundArch=*/nullptr, |
| 3594 | OKind: Action::OFK_Cuda); |
| 3595 | // Clear the fat binary, it is already a dependence to an host |
| 3596 | // action. |
| 3597 | CudaFatBinary = nullptr; |
| 3598 | } |
| 3599 | |
| 3600 | // Remove the CUDA actions as they are already connected to an host |
| 3601 | // action or fat binary. |
| 3602 | CudaDeviceActions.clear(); |
| 3603 | } |
| 3604 | |
| 3605 | // We avoid creating host action in device-only mode. |
| 3606 | return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; |
| 3607 | } else if (CurPhase > phases::Backend) { |
| 3608 | // If we are past the backend phase and still have a device action, we |
| 3609 | // don't have to do anything as this action is already a device |
| 3610 | // top-level action. |
| 3611 | return ABRT_Success; |
| 3612 | } |
| 3613 | |
| 3614 | assert(CurPhase < phases::Backend && "Generating single CUDA " |
| 3615 | "instructions should only occur " |
| 3616 | "before the backend phase!" ); |
| 3617 | |
| 3618 | // By default, we produce an action for each device arch. |
| 3619 | for (Action *&A : CudaDeviceActions) |
| 3620 | A = C.getDriver().ConstructPhaseAction(C, Args, Phase: CurPhase, Input: A); |
| 3621 | |
| 3622 | return ABRT_Success; |
| 3623 | } |
| 3624 | }; |
| 3625 | /// \brief HIP action builder. It injects device code in the host backend |
| 3626 | /// action. |
| 3627 | class HIPActionBuilder final : public CudaActionBuilderBase { |
| 3628 | /// The linker inputs obtained for each device arch. |
| 3629 | SmallVector<ActionList, 8> DeviceLinkerInputs; |
| 3630 | // The default bundling behavior depends on the type of output, therefore |
| 3631 | // BundleOutput needs to be tri-value: None, true, or false. |
| 3632 | // Bundle code objects except --no-gpu-output is specified for device |
| 3633 | // only compilation. Bundle other type of output files only if |
| 3634 | // --gpu-bundle-output is specified for device only compilation. |
| 3635 | std::optional<bool> BundleOutput; |
| 3636 | std::optional<bool> EmitReloc; |
| 3637 | |
| 3638 | public: |
| 3639 | HIPActionBuilder(Compilation &C, DerivedArgList &Args, |
| 3640 | const InputList &Inputs) |
| 3641 | : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) { |
| 3642 | |
| 3643 | DefaultOffloadArch = OffloadArch::HIPDefault; |
| 3644 | |
| 3645 | if (Args.hasArg(Ids: options::OPT_fhip_emit_relocatable, |
| 3646 | Ids: options::OPT_fno_hip_emit_relocatable)) { |
| 3647 | EmitReloc = Args.hasFlag(Pos: options::OPT_fhip_emit_relocatable, |
| 3648 | Neg: options::OPT_fno_hip_emit_relocatable, Default: false); |
| 3649 | |
| 3650 | if (*EmitReloc) { |
| 3651 | if (Relocatable) { |
| 3652 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_with_opt) |
| 3653 | << "-fhip-emit-relocatable" |
| 3654 | << "-fgpu-rdc" ; |
| 3655 | } |
| 3656 | |
| 3657 | if (!CompileDeviceOnly) { |
| 3658 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_without_opt) |
| 3659 | << "-fhip-emit-relocatable" |
| 3660 | << "--offload-device-only" ; |
| 3661 | } |
| 3662 | } |
| 3663 | } |
| 3664 | |
| 3665 | if (Args.hasArg(Ids: options::OPT_gpu_bundle_output, |
| 3666 | Ids: options::OPT_no_gpu_bundle_output)) |
| 3667 | BundleOutput = Args.hasFlag(Pos: options::OPT_gpu_bundle_output, |
| 3668 | Neg: options::OPT_no_gpu_bundle_output, Default: true) && |
| 3669 | (!EmitReloc || !*EmitReloc); |
| 3670 | } |
| 3671 | |
| 3672 | bool canUseBundlerUnbundler() const override { return true; } |
| 3673 | |
| 3674 | std::optional<std::pair<llvm::StringRef, llvm::StringRef>> |
| 3675 | getConflictOffloadArchCombination( |
| 3676 | const std::set<StringRef> &GpuArchs) override { |
| 3677 | return getConflictTargetIDCombination(TargetIDs: GpuArchs); |
| 3678 | } |
| 3679 | |
| 3680 | ActionBuilderReturnCode |
| 3681 | getDeviceDependences(OffloadAction::DeviceDependences &DA, |
| 3682 | phases::ID CurPhase, phases::ID FinalPhase, |
| 3683 | PhasesTy &Phases) override { |
| 3684 | if (!IsActive) |
| 3685 | return ABRT_Inactive; |
| 3686 | |
| 3687 | // amdgcn does not support linking of object files, therefore we skip |
| 3688 | // backend and assemble phases to output LLVM IR. Except for generating |
| 3689 | // non-relocatable device code, where we generate fat binary for device |
| 3690 | // code and pass to host in Backend phase. |
| 3691 | if (CudaDeviceActions.empty()) |
| 3692 | return ABRT_Success; |
| 3693 | |
| 3694 | assert(((CurPhase == phases::Link && Relocatable) || |
| 3695 | CudaDeviceActions.size() == GpuArchList.size()) && |
| 3696 | "Expecting one action per GPU architecture." ); |
| 3697 | assert(!CompileHostOnly && |
| 3698 | "Not expecting HIP actions in host-only compilation." ); |
| 3699 | |
| 3700 | bool ShouldLink = !EmitReloc || !*EmitReloc; |
| 3701 | |
| 3702 | if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM && |
| 3703 | !EmitAsm && ShouldLink) { |
| 3704 | // If we are in backend phase, we attempt to generate the fat binary. |
| 3705 | // We compile each arch to IR and use a link action to generate code |
| 3706 | // object containing ISA. Then we use a special "link" action to create |
| 3707 | // a fat binary containing all the code objects for different GPU's. |
| 3708 | // The fat binary is then an input to the host action. |
| 3709 | for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { |
| 3710 | if (C.getDriver().isUsingOffloadLTO()) { |
| 3711 | // When LTO is enabled, skip the backend and assemble phases and |
| 3712 | // use lld to link the bitcode. |
| 3713 | ActionList AL; |
| 3714 | AL.push_back(Elt: CudaDeviceActions[I]); |
| 3715 | // Create a link action to link device IR with device library |
| 3716 | // and generate ISA. |
| 3717 | CudaDeviceActions[I] = |
| 3718 | C.MakeAction<LinkJobAction>(Arg&: AL, Arg: types::TY_Image); |
| 3719 | } else { |
| 3720 | // When LTO is not enabled, we follow the conventional |
| 3721 | // compiler phases, including backend and assemble phases. |
| 3722 | ActionList AL; |
| 3723 | Action *BackendAction = nullptr; |
| 3724 | if (ToolChains.front()->getTriple().isSPIRV() || |
| 3725 | (ToolChains.front()->getTriple().isAMDGCN() && |
| 3726 | GpuArchList[I] == StringRef("amdgcnspirv" ))) { |
| 3727 | // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain |
| 3728 | // (HIPSPVToolChain or HIPAMDToolChain) runs post-link LLVM IR |
| 3729 | // passes. |
| 3730 | types::ID Output = Args.hasArg(Ids: options::OPT_S) |
| 3731 | ? types::TY_LLVM_IR |
| 3732 | : types::TY_LLVM_BC; |
| 3733 | BackendAction = |
| 3734 | C.MakeAction<BackendJobAction>(Arg&: CudaDeviceActions[I], Arg&: Output); |
| 3735 | } else |
| 3736 | BackendAction = C.getDriver().ConstructPhaseAction( |
| 3737 | C, Args, Phase: phases::Backend, Input: CudaDeviceActions[I], |
| 3738 | TargetDeviceOffloadKind: AssociatedOffloadKind); |
| 3739 | auto AssembleAction = C.getDriver().ConstructPhaseAction( |
| 3740 | C, Args, Phase: phases::Assemble, Input: BackendAction, |
| 3741 | TargetDeviceOffloadKind: AssociatedOffloadKind); |
| 3742 | AL.push_back(Elt: AssembleAction); |
| 3743 | // Create a link action to link device IR with device library |
| 3744 | // and generate ISA. |
| 3745 | CudaDeviceActions[I] = |
| 3746 | C.MakeAction<LinkJobAction>(Arg&: AL, Arg: types::TY_Image); |
| 3747 | } |
| 3748 | |
| 3749 | // OffloadingActionBuilder propagates device arch until an offload |
| 3750 | // action. Since the next action for creating fatbin does |
| 3751 | // not have device arch, whereas the above link action and its input |
| 3752 | // have device arch, an offload action is needed to stop the null |
| 3753 | // device arch of the next action being propagated to the above link |
| 3754 | // action. |
| 3755 | OffloadAction::DeviceDependences DDep; |
| 3756 | DDep.add(A&: *CudaDeviceActions[I], TC: *ToolChains.front(), BoundArch: GpuArchList[I], |
| 3757 | OKind: AssociatedOffloadKind); |
| 3758 | CudaDeviceActions[I] = C.MakeAction<OffloadAction>( |
| 3759 | Arg&: DDep, Arg: CudaDeviceActions[I]->getType()); |
| 3760 | } |
| 3761 | |
| 3762 | if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) { |
| 3763 | // Create HIP fat binary with a special "link" action. |
| 3764 | CudaFatBinary = C.MakeAction<LinkJobAction>(Arg&: CudaDeviceActions, |
| 3765 | Arg: types::TY_HIP_FATBIN); |
| 3766 | |
| 3767 | if (!CompileDeviceOnly) { |
| 3768 | DA.add(A&: *CudaFatBinary, TC: *ToolChains.front(), /*BoundArch=*/nullptr, |
| 3769 | OKind: AssociatedOffloadKind); |
| 3770 | // Clear the fat binary, it is already a dependence to an host |
| 3771 | // action. |
| 3772 | CudaFatBinary = nullptr; |
| 3773 | } |
| 3774 | |
| 3775 | // Remove the CUDA actions as they are already connected to an host |
| 3776 | // action or fat binary. |
| 3777 | CudaDeviceActions.clear(); |
| 3778 | } |
| 3779 | |
| 3780 | return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; |
| 3781 | } else if (CurPhase == phases::Link) { |
| 3782 | if (!ShouldLink) |
| 3783 | return ABRT_Success; |
| 3784 | // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch. |
| 3785 | // This happens to each device action originated from each input file. |
| 3786 | // Later on, device actions in DeviceLinkerInputs are used to create |
| 3787 | // device link actions in appendLinkDependences and the created device |
| 3788 | // link actions are passed to the offload action as device dependence. |
| 3789 | DeviceLinkerInputs.resize(N: CudaDeviceActions.size()); |
| 3790 | auto LI = DeviceLinkerInputs.begin(); |
| 3791 | for (auto *A : CudaDeviceActions) { |
| 3792 | LI->push_back(Elt: A); |
| 3793 | ++LI; |
| 3794 | } |
| 3795 | |
| 3796 | // We will pass the device action as a host dependence, so we don't |
| 3797 | // need to do anything else with them. |
| 3798 | CudaDeviceActions.clear(); |
| 3799 | return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; |
| 3800 | } |
| 3801 | |
| 3802 | // By default, we produce an action for each device arch. |
| 3803 | for (Action *&A : CudaDeviceActions) |
| 3804 | A = C.getDriver().ConstructPhaseAction(C, Args, Phase: CurPhase, Input: A, |
| 3805 | TargetDeviceOffloadKind: AssociatedOffloadKind); |
| 3806 | |
| 3807 | if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput && |
| 3808 | *BundleOutput) { |
| 3809 | for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { |
| 3810 | OffloadAction::DeviceDependences DDep; |
| 3811 | DDep.add(A&: *CudaDeviceActions[I], TC: *ToolChains.front(), BoundArch: GpuArchList[I], |
| 3812 | OKind: AssociatedOffloadKind); |
| 3813 | CudaDeviceActions[I] = C.MakeAction<OffloadAction>( |
| 3814 | Arg&: DDep, Arg: CudaDeviceActions[I]->getType()); |
| 3815 | } |
| 3816 | CudaFatBinary = |
| 3817 | C.MakeAction<OffloadBundlingJobAction>(Arg&: CudaDeviceActions); |
| 3818 | CudaDeviceActions.clear(); |
| 3819 | } |
| 3820 | |
| 3821 | return (CompileDeviceOnly && |
| 3822 | (CurPhase == FinalPhase || |
| 3823 | (!ShouldLink && CurPhase == phases::Assemble))) |
| 3824 | ? ABRT_Ignore_Host |
| 3825 | : ABRT_Success; |
| 3826 | } |
| 3827 | |
| 3828 | void appendLinkDeviceActions(ActionList &AL) override { |
| 3829 | if (DeviceLinkerInputs.size() == 0) |
| 3830 | return; |
| 3831 | |
| 3832 | assert(DeviceLinkerInputs.size() == GpuArchList.size() && |
| 3833 | "Linker inputs and GPU arch list sizes do not match." ); |
| 3834 | |
| 3835 | ActionList Actions; |
| 3836 | unsigned I = 0; |
| 3837 | // Append a new link action for each device. |
| 3838 | // Each entry in DeviceLinkerInputs corresponds to a GPU arch. |
| 3839 | for (auto &LI : DeviceLinkerInputs) { |
| 3840 | |
| 3841 | types::ID Output = Args.hasArg(Ids: options::OPT_emit_llvm) |
| 3842 | ? types::TY_LLVM_BC |
| 3843 | : types::TY_Image; |
| 3844 | |
| 3845 | auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(Arg&: LI, Arg&: Output); |
| 3846 | // Linking all inputs for the current GPU arch. |
| 3847 | // LI contains all the inputs for the linker. |
| 3848 | OffloadAction::DeviceDependences DeviceLinkDeps; |
| 3849 | DeviceLinkDeps.add(A&: *DeviceLinkAction, TC: *ToolChains[0], |
| 3850 | BoundArch: GpuArchList[I], OKind: AssociatedOffloadKind); |
| 3851 | Actions.push_back(Elt: C.MakeAction<OffloadAction>( |
| 3852 | Arg&: DeviceLinkDeps, Arg: DeviceLinkAction->getType())); |
| 3853 | ++I; |
| 3854 | } |
| 3855 | DeviceLinkerInputs.clear(); |
| 3856 | |
| 3857 | // If emitting LLVM, do not generate final host/device compilation action |
| 3858 | if (Args.hasArg(Ids: options::OPT_emit_llvm)) { |
| 3859 | AL.append(RHS: Actions); |
| 3860 | return; |
| 3861 | } |
| 3862 | |
| 3863 | // Create a host object from all the device images by embedding them |
| 3864 | // in a fat binary for mixed host-device compilation. For device-only |
| 3865 | // compilation, creates a fat binary. |
| 3866 | OffloadAction::DeviceDependences DDeps; |
| 3867 | if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) { |
| 3868 | auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>( |
| 3869 | Arg&: Actions, |
| 3870 | Arg: CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object); |
| 3871 | DDeps.add(A&: *TopDeviceLinkAction, TC: *ToolChains[0], BoundArch: nullptr, |
| 3872 | OKind: AssociatedOffloadKind); |
| 3873 | // Offload the host object to the host linker. |
| 3874 | AL.push_back( |
| 3875 | Elt: C.MakeAction<OffloadAction>(Arg&: DDeps, Arg: TopDeviceLinkAction->getType())); |
| 3876 | } else { |
| 3877 | AL.append(RHS: Actions); |
| 3878 | } |
| 3879 | } |
| 3880 | |
| 3881 | Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); } |
| 3882 | |
| 3883 | void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {} |
| 3884 | }; |
| 3885 | |
| 3886 | /// |
| 3887 | /// TODO: Add the implementation for other specialized builders here. |
| 3888 | /// |
| 3889 | |
| 3890 | /// Specialized builders being used by this offloading action builder. |
| 3891 | SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders; |
| 3892 | |
| 3893 | /// Flag set to true if all valid builders allow file bundling/unbundling. |
| 3894 | bool CanUseBundler; |
| 3895 | |
| 3896 | /// Flag set to false if an argument turns off bundling. |
| 3897 | bool ShouldUseBundler; |
| 3898 | |
| 3899 | public: |
| 3900 | OffloadingActionBuilder(Compilation &C, DerivedArgList &Args, |
| 3901 | const InputList &Inputs) |
| 3902 | : C(C) { |
| 3903 | // Create a specialized builder for each device toolchain. |
| 3904 | |
| 3905 | IsValid = true; |
| 3906 | |
| 3907 | // Create a specialized builder for CUDA. |
| 3908 | SpecializedBuilders.push_back(Elt: new CudaActionBuilder(C, Args, Inputs)); |
| 3909 | |
| 3910 | // Create a specialized builder for HIP. |
| 3911 | SpecializedBuilders.push_back(Elt: new HIPActionBuilder(C, Args, Inputs)); |
| 3912 | |
| 3913 | // |
| 3914 | // TODO: Build other specialized builders here. |
| 3915 | // |
| 3916 | |
| 3917 | // Initialize all the builders, keeping track of errors. If all valid |
| 3918 | // builders agree that we can use bundling, set the flag to true. |
| 3919 | unsigned ValidBuilders = 0u; |
| 3920 | unsigned = 0u; |
| 3921 | for (auto *SB : SpecializedBuilders) { |
| 3922 | IsValid = IsValid && !SB->initialize(); |
| 3923 | |
| 3924 | // Update the counters if the builder is valid. |
| 3925 | if (SB->isValid()) { |
| 3926 | ++ValidBuilders; |
| 3927 | if (SB->canUseBundlerUnbundler()) |
| 3928 | ++ValidBuildersSupportingBundling; |
| 3929 | } |
| 3930 | } |
| 3931 | CanUseBundler = |
| 3932 | ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling; |
| 3933 | |
| 3934 | ShouldUseBundler = Args.hasFlag(Pos: options::OPT_gpu_bundle_output, |
| 3935 | Neg: options::OPT_no_gpu_bundle_output, Default: true); |
| 3936 | } |
| 3937 | |
| 3938 | ~OffloadingActionBuilder() { |
| 3939 | for (auto *SB : SpecializedBuilders) |
| 3940 | delete SB; |
| 3941 | } |
| 3942 | |
| 3943 | /// Record a host action and its originating input argument. |
| 3944 | void recordHostAction(Action *HostAction, const Arg *InputArg) { |
| 3945 | assert(HostAction && "Invalid host action" ); |
| 3946 | assert(InputArg && "Invalid input argument" ); |
| 3947 | auto Loc = HostActionToInputArgMap.try_emplace(k: HostAction, args&: InputArg).first; |
| 3948 | assert(Loc->second == InputArg && |
| 3949 | "host action mapped to multiple input arguments" ); |
| 3950 | (void)Loc; |
| 3951 | } |
| 3952 | |
| 3953 | /// Generate an action that adds device dependences (if any) to a host action. |
| 3954 | /// If no device dependence actions exist, just return the host action \a |
| 3955 | /// HostAction. If an error is found or if no builder requires the host action |
| 3956 | /// to be generated, return nullptr. |
| 3957 | Action * |
| 3958 | addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg, |
| 3959 | phases::ID CurPhase, phases::ID FinalPhase, |
| 3960 | DeviceActionBuilder::PhasesTy &Phases) { |
| 3961 | if (!IsValid) |
| 3962 | return nullptr; |
| 3963 | |
| 3964 | if (SpecializedBuilders.empty()) |
| 3965 | return HostAction; |
| 3966 | |
| 3967 | assert(HostAction && "Invalid host action!" ); |
| 3968 | recordHostAction(HostAction, InputArg); |
| 3969 | |
| 3970 | OffloadAction::DeviceDependences DDeps; |
| 3971 | // Check if all the programming models agree we should not emit the host |
| 3972 | // action. Also, keep track of the offloading kinds employed. |
| 3973 | auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; |
| 3974 | unsigned InactiveBuilders = 0u; |
| 3975 | unsigned IgnoringBuilders = 0u; |
| 3976 | for (auto *SB : SpecializedBuilders) { |
| 3977 | if (!SB->isValid()) { |
| 3978 | ++InactiveBuilders; |
| 3979 | continue; |
| 3980 | } |
| 3981 | auto RetCode = |
| 3982 | SB->getDeviceDependences(DA&: DDeps, CurPhase, FinalPhase, Phases); |
| 3983 | |
| 3984 | // If the builder explicitly says the host action should be ignored, |
| 3985 | // we need to increment the variable that tracks the builders that request |
| 3986 | // the host object to be ignored. |
| 3987 | if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host) |
| 3988 | ++IgnoringBuilders; |
| 3989 | |
| 3990 | // Unless the builder was inactive for this action, we have to record the |
| 3991 | // offload kind because the host will have to use it. |
| 3992 | if (RetCode != DeviceActionBuilder::ABRT_Inactive) |
| 3993 | OffloadKind |= SB->getAssociatedOffloadKind(); |
| 3994 | } |
| 3995 | |
| 3996 | // If all builders agree that the host object should be ignored, just return |
| 3997 | // nullptr. |
| 3998 | if (IgnoringBuilders && |
| 3999 | SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders)) |
| 4000 | return nullptr; |
| 4001 | |
| 4002 | if (DDeps.getActions().empty()) |
| 4003 | return HostAction; |
| 4004 | |
| 4005 | // We have dependences we need to bundle together. We use an offload action |
| 4006 | // for that. |
| 4007 | OffloadAction::HostDependence HDep( |
| 4008 | *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), |
| 4009 | /*BoundArch=*/nullptr, DDeps); |
| 4010 | return C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: DDeps); |
| 4011 | } |
| 4012 | |
| 4013 | /// Generate an action that adds a host dependence to a device action. The |
| 4014 | /// results will be kept in this action builder. Return true if an error was |
| 4015 | /// found. |
| 4016 | bool addHostDependenceToDeviceActions(Action *&HostAction, |
| 4017 | const Arg *InputArg) { |
| 4018 | if (!IsValid) |
| 4019 | return true; |
| 4020 | |
| 4021 | recordHostAction(HostAction, InputArg); |
| 4022 | |
| 4023 | // If we are supporting bundling/unbundling and the current action is an |
| 4024 | // input action of non-source file, we replace the host action by the |
| 4025 | // unbundling action. The bundler tool has the logic to detect if an input |
| 4026 | // is a bundle or not and if the input is not a bundle it assumes it is a |
| 4027 | // host file. Therefore it is safe to create an unbundling action even if |
| 4028 | // the input is not a bundle. |
| 4029 | if (CanUseBundler && isa<InputAction>(Val: HostAction) && |
| 4030 | InputArg->getOption().getKind() == llvm::opt::Option::InputClass && |
| 4031 | (!types::isSrcFile(Id: HostAction->getType()) || |
| 4032 | HostAction->getType() == types::TY_PP_HIP)) { |
| 4033 | auto UnbundlingHostAction = |
| 4034 | C.MakeAction<OffloadUnbundlingJobAction>(Arg&: HostAction); |
| 4035 | UnbundlingHostAction->registerDependentActionInfo( |
| 4036 | TC: C.getSingleOffloadToolChain<Action::OFK_Host>(), |
| 4037 | /*BoundArch=*/StringRef(), Kind: Action::OFK_Host); |
| 4038 | HostAction = UnbundlingHostAction; |
| 4039 | recordHostAction(HostAction, InputArg); |
| 4040 | } |
| 4041 | |
| 4042 | assert(HostAction && "Invalid host action!" ); |
| 4043 | |
| 4044 | // Register the offload kinds that are used. |
| 4045 | auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; |
| 4046 | for (auto *SB : SpecializedBuilders) { |
| 4047 | if (!SB->isValid()) |
| 4048 | continue; |
| 4049 | |
| 4050 | auto RetCode = SB->addDeviceDependences(HostAction); |
| 4051 | |
| 4052 | // Host dependences for device actions are not compatible with that same |
| 4053 | // action being ignored. |
| 4054 | assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host && |
| 4055 | "Host dependence not expected to be ignored.!" ); |
| 4056 | |
| 4057 | // Unless the builder was inactive for this action, we have to record the |
| 4058 | // offload kind because the host will have to use it. |
| 4059 | if (RetCode != DeviceActionBuilder::ABRT_Inactive) |
| 4060 | OffloadKind |= SB->getAssociatedOffloadKind(); |
| 4061 | } |
| 4062 | |
| 4063 | // Do not use unbundler if the Host does not depend on device action. |
| 4064 | if (OffloadKind == Action::OFK_None && CanUseBundler) |
| 4065 | if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(Val: HostAction)) |
| 4066 | HostAction = UA->getInputs().back(); |
| 4067 | |
| 4068 | return false; |
| 4069 | } |
| 4070 | |
| 4071 | /// Add the offloading top level actions to the provided action list. This |
| 4072 | /// function can replace the host action by a bundling action if the |
| 4073 | /// programming models allow it. |
| 4074 | bool appendTopLevelActions(ActionList &AL, Action *HostAction, |
| 4075 | const Arg *InputArg) { |
| 4076 | if (HostAction) |
| 4077 | recordHostAction(HostAction, InputArg); |
| 4078 | |
| 4079 | // Get the device actions to be appended. |
| 4080 | ActionList OffloadAL; |
| 4081 | for (auto *SB : SpecializedBuilders) { |
| 4082 | if (!SB->isValid()) |
| 4083 | continue; |
| 4084 | SB->appendTopLevelActions(AL&: OffloadAL); |
| 4085 | } |
| 4086 | |
| 4087 | // If we can and should use the bundler, replace the host action by the |
| 4088 | // bundling one in the resulting list. Otherwise, just append the device |
| 4089 | // actions. For device only compilation, HostAction is a null pointer, |
| 4090 | // therefore only do this when HostAction is not a null pointer. |
| 4091 | if (CanUseBundler && ShouldUseBundler && HostAction && |
| 4092 | HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) { |
| 4093 | // Add the host action to the list in order to create the bundling action. |
| 4094 | OffloadAL.push_back(Elt: HostAction); |
| 4095 | |
| 4096 | // We expect that the host action was just appended to the action list |
| 4097 | // before this method was called. |
| 4098 | assert(HostAction == AL.back() && "Host action not in the list??" ); |
| 4099 | HostAction = C.MakeAction<OffloadBundlingJobAction>(Arg&: OffloadAL); |
| 4100 | recordHostAction(HostAction, InputArg); |
| 4101 | AL.back() = HostAction; |
| 4102 | } else |
| 4103 | AL.append(in_start: OffloadAL.begin(), in_end: OffloadAL.end()); |
| 4104 | |
| 4105 | // Propagate to the current host action (if any) the offload information |
| 4106 | // associated with the current input. |
| 4107 | if (HostAction) |
| 4108 | HostAction->propagateHostOffloadInfo(OKinds: InputArgToOffloadKindMap[InputArg], |
| 4109 | /*BoundArch=*/OArch: nullptr); |
| 4110 | return false; |
| 4111 | } |
| 4112 | |
| 4113 | void appendDeviceLinkActions(ActionList &AL) { |
| 4114 | for (DeviceActionBuilder *SB : SpecializedBuilders) { |
| 4115 | if (!SB->isValid()) |
| 4116 | continue; |
| 4117 | SB->appendLinkDeviceActions(AL); |
| 4118 | } |
| 4119 | } |
| 4120 | |
| 4121 | Action *makeHostLinkAction() { |
| 4122 | // Build a list of device linking actions. |
| 4123 | ActionList DeviceAL; |
| 4124 | appendDeviceLinkActions(AL&: DeviceAL); |
| 4125 | if (DeviceAL.empty()) |
| 4126 | return nullptr; |
| 4127 | |
| 4128 | // Let builders add host linking actions. |
| 4129 | Action* HA = nullptr; |
| 4130 | for (DeviceActionBuilder *SB : SpecializedBuilders) { |
| 4131 | if (!SB->isValid()) |
| 4132 | continue; |
| 4133 | HA = SB->appendLinkHostActions(AL&: DeviceAL); |
| 4134 | // This created host action has no originating input argument, therefore |
| 4135 | // needs to set its offloading kind directly. |
| 4136 | if (HA) |
| 4137 | HA->propagateHostOffloadInfo(OKinds: SB->getAssociatedOffloadKind(), |
| 4138 | /*BoundArch=*/OArch: nullptr); |
| 4139 | } |
| 4140 | return HA; |
| 4141 | } |
| 4142 | |
| 4143 | /// Processes the host linker action. This currently consists of replacing it |
| 4144 | /// with an offload action if there are device link objects and propagate to |
| 4145 | /// the host action all the offload kinds used in the current compilation. The |
| 4146 | /// resulting action is returned. |
| 4147 | Action *processHostLinkAction(Action *HostAction) { |
| 4148 | // Add all the dependences from the device linking actions. |
| 4149 | OffloadAction::DeviceDependences DDeps; |
| 4150 | for (auto *SB : SpecializedBuilders) { |
| 4151 | if (!SB->isValid()) |
| 4152 | continue; |
| 4153 | |
| 4154 | SB->appendLinkDependences(DA&: DDeps); |
| 4155 | } |
| 4156 | |
| 4157 | // Calculate all the offload kinds used in the current compilation. |
| 4158 | unsigned ActiveOffloadKinds = 0u; |
| 4159 | for (auto &I : InputArgToOffloadKindMap) |
| 4160 | ActiveOffloadKinds |= I.second; |
| 4161 | |
| 4162 | // If we don't have device dependencies, we don't have to create an offload |
| 4163 | // action. |
| 4164 | if (DDeps.getActions().empty()) { |
| 4165 | // Set all the active offloading kinds to the link action. Given that it |
| 4166 | // is a link action it is assumed to depend on all actions generated so |
| 4167 | // far. |
| 4168 | HostAction->setHostOffloadInfo(OKinds: ActiveOffloadKinds, |
| 4169 | /*BoundArch=*/OArch: nullptr); |
| 4170 | // Propagate active offloading kinds for each input to the link action. |
| 4171 | // Each input may have different active offloading kind. |
| 4172 | for (auto *A : HostAction->inputs()) { |
| 4173 | auto ArgLoc = HostActionToInputArgMap.find(x: A); |
| 4174 | if (ArgLoc == HostActionToInputArgMap.end()) |
| 4175 | continue; |
| 4176 | auto OFKLoc = InputArgToOffloadKindMap.find(x: ArgLoc->second); |
| 4177 | if (OFKLoc == InputArgToOffloadKindMap.end()) |
| 4178 | continue; |
| 4179 | A->propagateHostOffloadInfo(OKinds: OFKLoc->second, /*BoundArch=*/OArch: nullptr); |
| 4180 | } |
| 4181 | return HostAction; |
| 4182 | } |
| 4183 | |
| 4184 | // Create the offload action with all dependences. When an offload action |
| 4185 | // is created the kinds are propagated to the host action, so we don't have |
| 4186 | // to do that explicitly here. |
| 4187 | OffloadAction::HostDependence HDep( |
| 4188 | *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), |
| 4189 | /*BoundArch*/ nullptr, ActiveOffloadKinds); |
| 4190 | return C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: DDeps); |
| 4191 | } |
| 4192 | }; |
| 4193 | } // anonymous namespace. |
| 4194 | |
| 4195 | void Driver::handleArguments(Compilation &C, DerivedArgList &Args, |
| 4196 | const InputList &Inputs, |
| 4197 | ActionList &Actions) const { |
| 4198 | |
| 4199 | // Diagnose misuse of /Fo. |
| 4200 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_Fo)) { |
| 4201 | StringRef V = A->getValue(); |
| 4202 | if (Inputs.size() > 1 && !V.empty() && |
| 4203 | !llvm::sys::path::is_separator(value: V.back())) { |
| 4204 | // Check whether /Fo tries to name an output file for multiple inputs. |
| 4205 | Diag(DiagID: clang::diag::err_drv_out_file_argument_with_multiple_sources) |
| 4206 | << A->getSpelling() << V; |
| 4207 | Args.eraseArg(Id: options::OPT__SLASH_Fo); |
| 4208 | } |
| 4209 | } |
| 4210 | |
| 4211 | // Diagnose misuse of /Fa. |
| 4212 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_Fa)) { |
| 4213 | StringRef V = A->getValue(); |
| 4214 | if (Inputs.size() > 1 && !V.empty() && |
| 4215 | !llvm::sys::path::is_separator(value: V.back())) { |
| 4216 | // Check whether /Fa tries to name an asm file for multiple inputs. |
| 4217 | Diag(DiagID: clang::diag::err_drv_out_file_argument_with_multiple_sources) |
| 4218 | << A->getSpelling() << V; |
| 4219 | Args.eraseArg(Id: options::OPT__SLASH_Fa); |
| 4220 | } |
| 4221 | } |
| 4222 | |
| 4223 | // Diagnose misuse of /o. |
| 4224 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_o)) { |
| 4225 | if (A->getValue()[0] == '\0') { |
| 4226 | // It has to have a value. |
| 4227 | Diag(DiagID: clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; |
| 4228 | Args.eraseArg(Id: options::OPT__SLASH_o); |
| 4229 | } |
| 4230 | } |
| 4231 | |
| 4232 | // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames. |
| 4233 | Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc); |
| 4234 | Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu); |
| 4235 | if (YcArg && YuArg && strcmp(s1: YcArg->getValue(), s2: YuArg->getValue()) != 0) { |
| 4236 | Diag(DiagID: clang::diag::warn_drv_ycyu_different_arg_clang_cl); |
| 4237 | Args.eraseArg(Id: options::OPT__SLASH_Yc); |
| 4238 | Args.eraseArg(Id: options::OPT__SLASH_Yu); |
| 4239 | YcArg = YuArg = nullptr; |
| 4240 | } |
| 4241 | if (YcArg && Inputs.size() > 1) { |
| 4242 | Diag(DiagID: clang::diag::warn_drv_yc_multiple_inputs_clang_cl); |
| 4243 | Args.eraseArg(Id: options::OPT__SLASH_Yc); |
| 4244 | YcArg = nullptr; |
| 4245 | } |
| 4246 | |
| 4247 | Arg *FinalPhaseArg; |
| 4248 | phases::ID FinalPhase = getFinalPhase(DAL: Args, FinalPhaseArg: &FinalPhaseArg); |
| 4249 | |
| 4250 | if (FinalPhase == phases::Link) { |
| 4251 | if (Args.hasArgNoClaim(Ids: options::OPT_hipstdpar)) { |
| 4252 | Args.AddFlagArg(BaseArg: nullptr, Opt: getOpts().getOption(Opt: options::OPT_hip_link)); |
| 4253 | Args.AddFlagArg(BaseArg: nullptr, |
| 4254 | Opt: getOpts().getOption(Opt: options::OPT_frtlib_add_rpath)); |
| 4255 | } |
| 4256 | // Emitting LLVM while linking disabled except in the HIPAMD or SPIR-V |
| 4257 | // Toolchains |
| 4258 | if (Args.hasArg(Ids: options::OPT_emit_llvm) && |
| 4259 | !Args.hasArg(Ids: options::OPT_hip_link) && |
| 4260 | !C.getDefaultToolChain().getTriple().isSPIRV()) |
| 4261 | Diag(DiagID: clang::diag::err_drv_emit_llvm_link); |
| 4262 | if (C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() && |
| 4263 | LTOMode != LTOK_None && |
| 4264 | !Args.getLastArgValue(Id: options::OPT_fuse_ld_EQ) |
| 4265 | .starts_with_insensitive(Prefix: "lld" )) |
| 4266 | Diag(DiagID: clang::diag::err_drv_lto_without_lld); |
| 4267 | |
| 4268 | // If -dumpdir is not specified, give a default prefix derived from the link |
| 4269 | // output filename. For example, `clang -g -gsplit-dwarf a.c -o x` passes |
| 4270 | // `-dumpdir x-` to cc1. If -o is unspecified, use |
| 4271 | // stem(getDefaultImageName()) (usually stem("a.out") = "a"). |
| 4272 | if (!Args.hasArg(Ids: options::OPT_dumpdir)) { |
| 4273 | Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_o); |
| 4274 | Arg *Arg = Args.MakeSeparateArg( |
| 4275 | BaseArg: nullptr, Opt: getOpts().getOption(Opt: options::OPT_dumpdir), |
| 4276 | Value: Args.MakeArgString( |
| 4277 | Str: (FinalOutput ? FinalOutput->getValue() |
| 4278 | : llvm::sys::path::stem(path: getDefaultImageName())) + |
| 4279 | "-" )); |
| 4280 | Arg->claim(); |
| 4281 | Args.append(A: Arg); |
| 4282 | } |
| 4283 | } |
| 4284 | |
| 4285 | if (FinalPhase == phases::Preprocess || Args.hasArg(Ids: options::OPT__SLASH_Y_)) { |
| 4286 | // If only preprocessing or /Y- is used, all pch handling is disabled. |
| 4287 | // Rather than check for it everywhere, just remove clang-cl pch-related |
| 4288 | // flags here. |
| 4289 | Args.eraseArg(Id: options::OPT__SLASH_Fp); |
| 4290 | Args.eraseArg(Id: options::OPT__SLASH_Yc); |
| 4291 | Args.eraseArg(Id: options::OPT__SLASH_Yu); |
| 4292 | YcArg = YuArg = nullptr; |
| 4293 | } |
| 4294 | |
| 4295 | if (Args.hasArg(Ids: options::OPT_include_pch) && |
| 4296 | Args.hasArg(Ids: options::OPT_ignore_pch)) { |
| 4297 | // If -ignore-pch is used, -include-pch is disabled. Since -emit-pch is |
| 4298 | // CC1option, it will not be added to command argments if -ignore-pch is |
| 4299 | // used. |
| 4300 | Args.eraseArg(Id: options::OPT_include_pch); |
| 4301 | } |
| 4302 | |
| 4303 | bool LinkOnly = phases::Link == FinalPhase && Inputs.size() > 0; |
| 4304 | for (auto &I : Inputs) { |
| 4305 | types::ID InputType = I.first; |
| 4306 | const Arg *InputArg = I.second; |
| 4307 | |
| 4308 | auto PL = types::getCompilationPhases(Id: InputType); |
| 4309 | |
| 4310 | phases::ID InitialPhase = PL[0]; |
| 4311 | LinkOnly = LinkOnly && phases::Link == InitialPhase && PL.size() == 1; |
| 4312 | |
| 4313 | // If the first step comes after the final phase we are doing as part of |
| 4314 | // this compilation, warn the user about it. |
| 4315 | if (InitialPhase > FinalPhase) { |
| 4316 | if (InputArg->isClaimed()) |
| 4317 | continue; |
| 4318 | |
| 4319 | // Claim here to avoid the more general unused warning. |
| 4320 | InputArg->claim(); |
| 4321 | |
| 4322 | // Suppress all unused style warnings with -Qunused-arguments |
| 4323 | if (Args.hasArg(Ids: options::OPT_Qunused_arguments)) |
| 4324 | continue; |
| 4325 | |
| 4326 | // Special case when final phase determined by binary name, rather than |
| 4327 | // by a command-line argument with a corresponding Arg. |
| 4328 | if (CCCIsCPP()) |
| 4329 | Diag(DiagID: clang::diag::warn_drv_input_file_unused_by_cpp) |
| 4330 | << InputArg->getAsString(Args) << getPhaseName(Id: InitialPhase); |
| 4331 | // Special case '-E' warning on a previously preprocessed file to make |
| 4332 | // more sense. |
| 4333 | else if (InitialPhase == phases::Compile && |
| 4334 | (Args.getLastArg(Ids: options::OPT__SLASH_EP, |
| 4335 | Ids: options::OPT__SLASH_P) || |
| 4336 | Args.getLastArg(Ids: options::OPT_E) || |
| 4337 | Args.getLastArg(Ids: options::OPT_M, Ids: options::OPT_MM)) && |
| 4338 | getPreprocessedType(Id: InputType) == types::TY_INVALID) |
| 4339 | Diag(DiagID: clang::diag::warn_drv_preprocessed_input_file_unused) |
| 4340 | << InputArg->getAsString(Args) << !!FinalPhaseArg |
| 4341 | << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "" ); |
| 4342 | else |
| 4343 | Diag(DiagID: clang::diag::warn_drv_input_file_unused) |
| 4344 | << InputArg->getAsString(Args) << getPhaseName(Id: InitialPhase) |
| 4345 | << !!FinalPhaseArg |
| 4346 | << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "" ); |
| 4347 | continue; |
| 4348 | } |
| 4349 | |
| 4350 | if (YcArg) { |
| 4351 | // Add a separate precompile phase for the compile phase. |
| 4352 | if (FinalPhase >= phases::Compile) { |
| 4353 | const types::ID = lookupHeaderTypeForSourceType(Id: InputType); |
| 4354 | // Build the pipeline for the pch file. |
| 4355 | Action *ClangClPch = C.MakeAction<InputAction>(Arg: *InputArg, Arg: HeaderType); |
| 4356 | for (phases::ID Phase : types::getCompilationPhases(Id: HeaderType)) |
| 4357 | ClangClPch = ConstructPhaseAction(C, Args, Phase, Input: ClangClPch); |
| 4358 | assert(ClangClPch); |
| 4359 | Actions.push_back(Elt: ClangClPch); |
| 4360 | // The driver currently exits after the first failed command. This |
| 4361 | // relies on that behavior, to make sure if the pch generation fails, |
| 4362 | // the main compilation won't run. |
| 4363 | // FIXME: If the main compilation fails, the PCH generation should |
| 4364 | // probably not be considered successful either. |
| 4365 | } |
| 4366 | } |
| 4367 | } |
| 4368 | |
| 4369 | // Claim any options which are obviously only used for compilation. |
| 4370 | if (LinkOnly) { |
| 4371 | Args.ClaimAllArgs(Id0: options::OPT_CompileOnly_Group); |
| 4372 | Args.ClaimAllArgs(Id0: options::OPT_cl_compile_Group); |
| 4373 | } |
| 4374 | } |
| 4375 | |
| 4376 | void Driver::BuildActions(Compilation &C, DerivedArgList &Args, |
| 4377 | const InputList &Inputs, ActionList &Actions) const { |
| 4378 | llvm::PrettyStackTraceString CrashInfo("Building compilation actions" ); |
| 4379 | |
| 4380 | if (!SuppressMissingInputWarning && Inputs.empty()) { |
| 4381 | Diag(DiagID: clang::diag::err_drv_no_input_files); |
| 4382 | return; |
| 4383 | } |
| 4384 | |
| 4385 | handleArguments(C, Args, Inputs, Actions); |
| 4386 | |
| 4387 | bool UseNewOffloadingDriver = Args.hasFlag( |
| 4388 | Pos: options::OPT_offload_new_driver, Neg: options::OPT_no_offload_new_driver, |
| 4389 | Default: C.getActiveOffloadKinds() != Action::OFK_None); |
| 4390 | |
| 4391 | // Builder to be used to build offloading actions. |
| 4392 | std::unique_ptr<OffloadingActionBuilder> OffloadBuilder = |
| 4393 | !UseNewOffloadingDriver |
| 4394 | ? std::make_unique<OffloadingActionBuilder>(args&: C, args&: Args, args: Inputs) |
| 4395 | : nullptr; |
| 4396 | |
| 4397 | // Construct the actions to perform. |
| 4398 | ExtractAPIJobAction * = nullptr; |
| 4399 | ActionList LinkerInputs; |
| 4400 | ActionList MergerInputs; |
| 4401 | |
| 4402 | for (auto &I : Inputs) { |
| 4403 | types::ID InputType = I.first; |
| 4404 | const Arg *InputArg = I.second; |
| 4405 | |
| 4406 | auto PL = types::getCompilationPhases(Driver: *this, DAL&: Args, Id: InputType); |
| 4407 | if (PL.empty()) |
| 4408 | continue; |
| 4409 | |
| 4410 | auto FullPL = types::getCompilationPhases(Id: InputType); |
| 4411 | |
| 4412 | // Build the pipeline for this file. |
| 4413 | Action *Current = C.MakeAction<InputAction>(Arg: *InputArg, Arg&: InputType); |
| 4414 | |
| 4415 | std::string CUID; |
| 4416 | if (CUIDOpts.isEnabled() && types::isSrcFile(Id: InputType)) { |
| 4417 | CUID = CUIDOpts.getCUID(InputFile: InputArg->getValue(), Args); |
| 4418 | cast<InputAction>(Val: Current)->setId(CUID); |
| 4419 | } |
| 4420 | |
| 4421 | // Use the current host action in any of the offloading actions, if |
| 4422 | // required. |
| 4423 | if (!UseNewOffloadingDriver) |
| 4424 | if (OffloadBuilder->addHostDependenceToDeviceActions(HostAction&: Current, InputArg)) |
| 4425 | break; |
| 4426 | |
| 4427 | for (phases::ID Phase : PL) { |
| 4428 | |
| 4429 | // Add any offload action the host action depends on. |
| 4430 | if (!UseNewOffloadingDriver) |
| 4431 | Current = OffloadBuilder->addDeviceDependencesToHostAction( |
| 4432 | HostAction: Current, InputArg, CurPhase: Phase, FinalPhase: PL.back(), Phases: FullPL); |
| 4433 | if (!Current) |
| 4434 | break; |
| 4435 | |
| 4436 | // Queue linker inputs. |
| 4437 | if (Phase == phases::Link) { |
| 4438 | assert(Phase == PL.back() && "linking must be final compilation step." ); |
| 4439 | // We don't need to generate additional link commands if emitting AMD |
| 4440 | // bitcode or compiling only for the offload device |
| 4441 | if (!(C.getInputArgs().hasArg(Ids: options::OPT_hip_link) && |
| 4442 | (C.getInputArgs().hasArg(Ids: options::OPT_emit_llvm))) && |
| 4443 | !offloadDeviceOnly()) |
| 4444 | LinkerInputs.push_back(Elt: Current); |
| 4445 | Current = nullptr; |
| 4446 | break; |
| 4447 | } |
| 4448 | |
| 4449 | // TODO: Consider removing this because the merged may not end up being |
| 4450 | // the final Phase in the pipeline. Perhaps the merged could just merge |
| 4451 | // and then pass an artifact of some sort to the Link Phase. |
| 4452 | // Queue merger inputs. |
| 4453 | if (Phase == phases::IfsMerge) { |
| 4454 | assert(Phase == PL.back() && "merging must be final compilation step." ); |
| 4455 | MergerInputs.push_back(Elt: Current); |
| 4456 | Current = nullptr; |
| 4457 | break; |
| 4458 | } |
| 4459 | |
| 4460 | if (Phase == phases::Precompile && ExtractAPIAction) { |
| 4461 | ExtractAPIAction->addHeaderInput(Input: Current); |
| 4462 | Current = nullptr; |
| 4463 | break; |
| 4464 | } |
| 4465 | |
| 4466 | // FIXME: Should we include any prior module file outputs as inputs of |
| 4467 | // later actions in the same command line? |
| 4468 | |
| 4469 | // Otherwise construct the appropriate action. |
| 4470 | Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Input: Current); |
| 4471 | |
| 4472 | // We didn't create a new action, so we will just move to the next phase. |
| 4473 | if (NewCurrent == Current) |
| 4474 | continue; |
| 4475 | |
| 4476 | if (auto *EAA = dyn_cast<ExtractAPIJobAction>(Val: NewCurrent)) |
| 4477 | ExtractAPIAction = EAA; |
| 4478 | |
| 4479 | Current = NewCurrent; |
| 4480 | |
| 4481 | // Try to build the offloading actions and add the result as a dependency |
| 4482 | // to the host. |
| 4483 | if (UseNewOffloadingDriver) |
| 4484 | Current = BuildOffloadingActions(C, Args, Input: I, CUID, HostAction: Current); |
| 4485 | // Use the current host action in any of the offloading actions, if |
| 4486 | // required. |
| 4487 | else if (OffloadBuilder->addHostDependenceToDeviceActions(HostAction&: Current, |
| 4488 | InputArg)) |
| 4489 | break; |
| 4490 | |
| 4491 | if (Current->getType() == types::TY_Nothing) |
| 4492 | break; |
| 4493 | } |
| 4494 | |
| 4495 | // If we ended with something, add to the output list. |
| 4496 | if (Current) |
| 4497 | Actions.push_back(Elt: Current); |
| 4498 | |
| 4499 | // Add any top level actions generated for offloading. |
| 4500 | if (!UseNewOffloadingDriver) |
| 4501 | OffloadBuilder->appendTopLevelActions(AL&: Actions, HostAction: Current, InputArg); |
| 4502 | else if (Current) |
| 4503 | Current->propagateHostOffloadInfo(OKinds: C.getActiveOffloadKinds(), |
| 4504 | /*BoundArch=*/OArch: nullptr); |
| 4505 | } |
| 4506 | |
| 4507 | // Add a link action if necessary. |
| 4508 | |
| 4509 | if (LinkerInputs.empty()) { |
| 4510 | Arg *FinalPhaseArg; |
| 4511 | if (getFinalPhase(DAL: Args, FinalPhaseArg: &FinalPhaseArg) == phases::Link) |
| 4512 | if (!UseNewOffloadingDriver) |
| 4513 | OffloadBuilder->appendDeviceLinkActions(AL&: Actions); |
| 4514 | } |
| 4515 | |
| 4516 | if (!LinkerInputs.empty()) { |
| 4517 | if (!UseNewOffloadingDriver) |
| 4518 | if (Action *Wrapper = OffloadBuilder->makeHostLinkAction()) |
| 4519 | LinkerInputs.push_back(Elt: Wrapper); |
| 4520 | Action *LA; |
| 4521 | // Check if this Linker Job should emit a static library. |
| 4522 | if (ShouldEmitStaticLibrary(Args)) { |
| 4523 | LA = C.MakeAction<StaticLibJobAction>(Arg&: LinkerInputs, Arg: types::TY_Image); |
| 4524 | } else if (UseNewOffloadingDriver || |
| 4525 | Args.hasArg(Ids: options::OPT_offload_link)) { |
| 4526 | LA = C.MakeAction<LinkerWrapperJobAction>(Arg&: LinkerInputs, Arg: types::TY_Image); |
| 4527 | LA->propagateHostOffloadInfo(OKinds: C.getActiveOffloadKinds(), |
| 4528 | /*BoundArch=*/OArch: nullptr); |
| 4529 | } else { |
| 4530 | // If we are linking but were passed -emit-llvm, we will be calling |
| 4531 | // llvm-link, so set the output type accordingly. This is only allowed in |
| 4532 | // rare cases, so make sure we aren't going to error about it. |
| 4533 | bool LinkingIR = Args.hasArg(Ids: options::OPT_emit_llvm) && |
| 4534 | C.getDefaultToolChain().getTriple().isSPIRV(); |
| 4535 | types::ID LT = LinkingIR && !Diags.hasErrorOccurred() ? types::TY_LLVM_BC |
| 4536 | : types::TY_Image; |
| 4537 | LA = C.MakeAction<LinkJobAction>(Arg&: LinkerInputs, Arg&: LT); |
| 4538 | } |
| 4539 | if (!UseNewOffloadingDriver) |
| 4540 | LA = OffloadBuilder->processHostLinkAction(HostAction: LA); |
| 4541 | Actions.push_back(Elt: LA); |
| 4542 | } |
| 4543 | |
| 4544 | // Add an interface stubs merge action if necessary. |
| 4545 | if (!MergerInputs.empty()) |
| 4546 | Actions.push_back( |
| 4547 | Elt: C.MakeAction<IfsMergeJobAction>(Arg&: MergerInputs, Arg: types::TY_Image)); |
| 4548 | |
| 4549 | if (Args.hasArg(Ids: options::OPT_emit_interface_stubs)) { |
| 4550 | auto PhaseList = types::getCompilationPhases( |
| 4551 | Id: types::TY_IFS_CPP, |
| 4552 | LastPhase: Args.hasArg(Ids: options::OPT_c) ? phases::Compile : phases::IfsMerge); |
| 4553 | |
| 4554 | ActionList MergerInputs; |
| 4555 | |
| 4556 | for (auto &I : Inputs) { |
| 4557 | types::ID InputType = I.first; |
| 4558 | const Arg *InputArg = I.second; |
| 4559 | |
| 4560 | // Currently clang and the llvm assembler do not support generating symbol |
| 4561 | // stubs from assembly, so we skip the input on asm files. For ifs files |
| 4562 | // we rely on the normal pipeline setup in the pipeline setup code above. |
| 4563 | if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm || |
| 4564 | InputType == types::TY_Asm) |
| 4565 | continue; |
| 4566 | |
| 4567 | Action *Current = C.MakeAction<InputAction>(Arg: *InputArg, Arg&: InputType); |
| 4568 | |
| 4569 | for (auto Phase : PhaseList) { |
| 4570 | switch (Phase) { |
| 4571 | default: |
| 4572 | llvm_unreachable( |
| 4573 | "IFS Pipeline can only consist of Compile followed by IfsMerge." ); |
| 4574 | case phases::Compile: { |
| 4575 | // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs |
| 4576 | // files where the .o file is located. The compile action can not |
| 4577 | // handle this. |
| 4578 | if (InputType == types::TY_Object) |
| 4579 | break; |
| 4580 | |
| 4581 | Current = C.MakeAction<CompileJobAction>(Arg&: Current, Arg: types::TY_IFS_CPP); |
| 4582 | break; |
| 4583 | } |
| 4584 | case phases::IfsMerge: { |
| 4585 | assert(Phase == PhaseList.back() && |
| 4586 | "merging must be final compilation step." ); |
| 4587 | MergerInputs.push_back(Elt: Current); |
| 4588 | Current = nullptr; |
| 4589 | break; |
| 4590 | } |
| 4591 | } |
| 4592 | } |
| 4593 | |
| 4594 | // If we ended with something, add to the output list. |
| 4595 | if (Current) |
| 4596 | Actions.push_back(Elt: Current); |
| 4597 | } |
| 4598 | |
| 4599 | // Add an interface stubs merge action if necessary. |
| 4600 | if (!MergerInputs.empty()) |
| 4601 | Actions.push_back( |
| 4602 | Elt: C.MakeAction<IfsMergeJobAction>(Arg&: MergerInputs, Arg: types::TY_Image)); |
| 4603 | } |
| 4604 | |
| 4605 | for (auto Opt : {options::OPT_print_supported_cpus, |
| 4606 | options::OPT_print_supported_extensions, |
| 4607 | options::OPT_print_enabled_extensions}) { |
| 4608 | // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a |
| 4609 | // custom Compile phase that prints out supported cpu models and quits. |
| 4610 | // |
| 4611 | // If either --print-supported-extensions or --print-enabled-extensions is |
| 4612 | // specified, call the corresponding helper function that prints out the |
| 4613 | // supported/enabled extensions and quits. |
| 4614 | if (Arg *A = Args.getLastArg(Ids: Opt)) { |
| 4615 | if (Opt == options::OPT_print_supported_extensions && |
| 4616 | !C.getDefaultToolChain().getTriple().isRISCV() && |
| 4617 | !C.getDefaultToolChain().getTriple().isAArch64() && |
| 4618 | !C.getDefaultToolChain().getTriple().isARM()) { |
| 4619 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_on_target) |
| 4620 | << "--print-supported-extensions" ; |
| 4621 | return; |
| 4622 | } |
| 4623 | if (Opt == options::OPT_print_enabled_extensions && |
| 4624 | !C.getDefaultToolChain().getTriple().isRISCV() && |
| 4625 | !C.getDefaultToolChain().getTriple().isAArch64()) { |
| 4626 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_on_target) |
| 4627 | << "--print-enabled-extensions" ; |
| 4628 | return; |
| 4629 | } |
| 4630 | |
| 4631 | // Use the -mcpu=? flag as the dummy input to cc1. |
| 4632 | Actions.clear(); |
| 4633 | Action *InputAc = C.MakeAction<InputAction>( |
| 4634 | Arg&: *A, Arg: IsFlangMode() ? types::TY_Fortran : types::TY_C); |
| 4635 | Actions.push_back( |
| 4636 | Elt: C.MakeAction<PrecompileJobAction>(Arg&: InputAc, Arg: types::TY_Nothing)); |
| 4637 | for (auto &I : Inputs) |
| 4638 | I.second->claim(); |
| 4639 | } |
| 4640 | } |
| 4641 | |
| 4642 | if (C.getDefaultToolChain().getTriple().isDXIL()) { |
| 4643 | const auto &TC = |
| 4644 | static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain()); |
| 4645 | |
| 4646 | // Call objcopy for manipulation of the unvalidated DXContainer when an |
| 4647 | // option in Args requires it. |
| 4648 | if (TC.requiresObjcopy(Args)) { |
| 4649 | Action *LastAction = Actions.back(); |
| 4650 | // llvm-objcopy expects an unvalidated DXIL container (TY_OBJECT). |
| 4651 | if (LastAction->getType() == types::TY_Object) |
| 4652 | Actions.push_back( |
| 4653 | Elt: C.MakeAction<ObjcopyJobAction>(Arg&: LastAction, Arg: types::TY_Object)); |
| 4654 | } |
| 4655 | |
| 4656 | // Call validator for dxil when -Vd not in Args. |
| 4657 | if (TC.requiresValidation(Args)) { |
| 4658 | Action *LastAction = Actions.back(); |
| 4659 | Actions.push_back(Elt: C.MakeAction<BinaryAnalyzeJobAction>( |
| 4660 | Arg&: LastAction, Arg: types::TY_DX_CONTAINER)); |
| 4661 | } |
| 4662 | |
| 4663 | // Call metal-shaderconverter when targeting metal. |
| 4664 | if (TC.requiresBinaryTranslation(Args)) { |
| 4665 | Action *LastAction = Actions.back(); |
| 4666 | // Metal shader converter runs on DXIL containers, which can either be |
| 4667 | // validated (in which case they are TY_DX_CONTAINER), or unvalidated |
| 4668 | // (TY_OBJECT). |
| 4669 | if (LastAction->getType() == types::TY_DX_CONTAINER || |
| 4670 | LastAction->getType() == types::TY_Object) |
| 4671 | Actions.push_back(Elt: C.MakeAction<BinaryTranslatorJobAction>( |
| 4672 | Arg&: LastAction, Arg: types::TY_DX_CONTAINER)); |
| 4673 | } |
| 4674 | } |
| 4675 | |
| 4676 | // Claim ignored clang-cl options. |
| 4677 | Args.ClaimAllArgs(Id0: options::OPT_cl_ignored_Group); |
| 4678 | } |
| 4679 | |
| 4680 | /// Returns the canonical name for the offloading architecture when using a HIP |
| 4681 | /// or CUDA architecture. |
| 4682 | static StringRef getCanonicalArchString(Compilation &C, |
| 4683 | const llvm::opt::DerivedArgList &Args, |
| 4684 | StringRef ArchStr, |
| 4685 | const llvm::Triple &Triple) { |
| 4686 | // Lookup the CUDA / HIP architecture string. Only report an error if we were |
| 4687 | // expecting the triple to be only NVPTX / AMDGPU. |
| 4688 | OffloadArch Arch = |
| 4689 | StringToOffloadArch(S: getProcessorFromTargetID(T: Triple, OffloadArch: ArchStr)); |
| 4690 | if (Triple.isNVPTX() && |
| 4691 | (Arch == OffloadArch::UNKNOWN || !IsNVIDIAOffloadArch(A: Arch))) { |
| 4692 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 4693 | << "CUDA" << ArchStr; |
| 4694 | return StringRef(); |
| 4695 | } else if (Triple.isAMDGPU() && |
| 4696 | (Arch == OffloadArch::UNKNOWN || !IsAMDOffloadArch(A: Arch))) { |
| 4697 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 4698 | << "HIP" << ArchStr; |
| 4699 | return StringRef(); |
| 4700 | } |
| 4701 | |
| 4702 | if (IsNVIDIAOffloadArch(A: Arch)) |
| 4703 | return Args.MakeArgStringRef(Str: OffloadArchToString(A: Arch)); |
| 4704 | |
| 4705 | if (IsAMDOffloadArch(A: Arch)) { |
| 4706 | llvm::StringMap<bool> Features; |
| 4707 | std::optional<StringRef> Arch = parseTargetID(T: Triple, OffloadArch: ArchStr, FeatureMap: &Features); |
| 4708 | if (!Arch) { |
| 4709 | C.getDriver().Diag(DiagID: clang::diag::err_drv_bad_target_id) << ArchStr; |
| 4710 | return StringRef(); |
| 4711 | } |
| 4712 | return Args.MakeArgStringRef(Str: getCanonicalTargetID(Processor: *Arch, Features)); |
| 4713 | } |
| 4714 | |
| 4715 | // If the input isn't CUDA or HIP just return the architecture. |
| 4716 | return ArchStr; |
| 4717 | } |
| 4718 | |
| 4719 | /// Checks if the set offloading architectures does not conflict. Returns the |
| 4720 | /// incompatible pair if a conflict occurs. |
| 4721 | static std::optional<std::pair<llvm::StringRef, llvm::StringRef>> |
| 4722 | getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs, |
| 4723 | llvm::Triple Triple) { |
| 4724 | if (!Triple.isAMDGPU()) |
| 4725 | return std::nullopt; |
| 4726 | |
| 4727 | std::set<StringRef> ArchSet; |
| 4728 | llvm::copy(Range: Archs, Out: std::inserter(x&: ArchSet, i: ArchSet.begin())); |
| 4729 | return getConflictTargetIDCombination(TargetIDs: ArchSet); |
| 4730 | } |
| 4731 | |
| 4732 | llvm::SmallVector<StringRef> |
| 4733 | Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, |
| 4734 | Action::OffloadKind Kind, const ToolChain &TC) const { |
| 4735 | // --offload and --offload-arch options are mutually exclusive. |
| 4736 | if (Args.hasArgNoClaim(Ids: options::OPT_offload_EQ) && |
| 4737 | Args.hasArgNoClaim(Ids: options::OPT_offload_arch_EQ, |
| 4738 | Ids: options::OPT_no_offload_arch_EQ)) { |
| 4739 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_with_opt) |
| 4740 | << "--offload" |
| 4741 | << (Args.hasArgNoClaim(Ids: options::OPT_offload_arch_EQ) |
| 4742 | ? "--offload-arch" |
| 4743 | : "--no-offload-arch" ); |
| 4744 | } |
| 4745 | |
| 4746 | llvm::DenseSet<StringRef> Archs; |
| 4747 | for (auto *Arg : C.getArgsForToolChain(TC: &TC, /*BoundArch=*/"" , DeviceOffloadKind: Kind)) { |
| 4748 | // Add or remove the seen architectures in order of appearance. If an |
| 4749 | // invalid architecture is given we simply exit. |
| 4750 | if (Arg->getOption().matches(ID: options::OPT_offload_arch_EQ)) { |
| 4751 | for (StringRef Arch : Arg->getValues()) { |
| 4752 | if (Arch == "native" || Arch.empty()) { |
| 4753 | auto GPUsOrErr = TC.getSystemGPUArchs(Args); |
| 4754 | if (!GPUsOrErr) { |
| 4755 | TC.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch) |
| 4756 | << llvm::Triple::getArchTypeName(Kind: TC.getArch()) |
| 4757 | << llvm::toString(E: GPUsOrErr.takeError()) << "--offload-arch" ; |
| 4758 | continue; |
| 4759 | } |
| 4760 | |
| 4761 | for (auto ArchStr : *GPUsOrErr) { |
| 4762 | StringRef CanonicalStr = getCanonicalArchString( |
| 4763 | C, Args, ArchStr: Args.MakeArgString(Str: ArchStr), Triple: TC.getTriple()); |
| 4764 | if (!CanonicalStr.empty()) |
| 4765 | Archs.insert(V: CanonicalStr); |
| 4766 | else |
| 4767 | return llvm::SmallVector<StringRef>(); |
| 4768 | } |
| 4769 | } else { |
| 4770 | StringRef CanonicalStr = |
| 4771 | getCanonicalArchString(C, Args, ArchStr: Arch, Triple: TC.getTriple()); |
| 4772 | if (!CanonicalStr.empty()) |
| 4773 | Archs.insert(V: CanonicalStr); |
| 4774 | else |
| 4775 | return llvm::SmallVector<StringRef>(); |
| 4776 | } |
| 4777 | } |
| 4778 | } else if (Arg->getOption().matches(ID: options::OPT_no_offload_arch_EQ)) { |
| 4779 | for (StringRef Arch : Arg->getValues()) { |
| 4780 | if (Arch == "all" ) { |
| 4781 | Archs.clear(); |
| 4782 | } else { |
| 4783 | StringRef ArchStr = |
| 4784 | getCanonicalArchString(C, Args, ArchStr: Arch, Triple: TC.getTriple()); |
| 4785 | Archs.erase(V: ArchStr); |
| 4786 | } |
| 4787 | } |
| 4788 | } |
| 4789 | } |
| 4790 | |
| 4791 | if (auto ConflictingArchs = |
| 4792 | getConflictOffloadArchCombination(Archs, Triple: TC.getTriple())) |
| 4793 | C.getDriver().Diag(DiagID: clang::diag::err_drv_bad_offload_arch_combo) |
| 4794 | << ConflictingArchs->first << ConflictingArchs->second; |
| 4795 | |
| 4796 | // Fill in the default architectures if not provided explicitly. |
| 4797 | if (Archs.empty()) { |
| 4798 | if (Kind == Action::OFK_Cuda) { |
| 4799 | Archs.insert(V: OffloadArchToString(A: OffloadArch::CudaDefault)); |
| 4800 | } else if (Kind == Action::OFK_HIP) { |
| 4801 | Archs.insert(V: OffloadArchToString(A: TC.getTriple().isSPIRV() |
| 4802 | ? OffloadArch::Generic |
| 4803 | : OffloadArch::HIPDefault)); |
| 4804 | } else if (Kind == Action::OFK_SYCL) { |
| 4805 | Archs.insert(V: StringRef()); |
| 4806 | } else if (Kind == Action::OFK_OpenMP) { |
| 4807 | // Accept legacy `-march` device arguments for OpenMP. |
| 4808 | if (auto *Arg = C.getArgsForToolChain(TC: &TC, /*BoundArch=*/"" , DeviceOffloadKind: Kind) |
| 4809 | .getLastArg(Ids: options::OPT_march_EQ)) { |
| 4810 | Archs.insert(V: Arg->getValue()); |
| 4811 | } else { |
| 4812 | auto ArchsOrErr = TC.getSystemGPUArchs(Args); |
| 4813 | if (!ArchsOrErr) { |
| 4814 | TC.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch) |
| 4815 | << llvm::Triple::getArchTypeName(Kind: TC.getArch()) |
| 4816 | << llvm::toString(E: ArchsOrErr.takeError()) << "--offload-arch" ; |
| 4817 | } else if (!ArchsOrErr->empty()) { |
| 4818 | for (auto Arch : *ArchsOrErr) |
| 4819 | Archs.insert(V: Args.MakeArgStringRef(Str: Arch)); |
| 4820 | } else { |
| 4821 | Archs.insert(V: StringRef()); |
| 4822 | } |
| 4823 | } |
| 4824 | } |
| 4825 | } |
| 4826 | Args.ClaimAllArgs(Id0: options::OPT_offload_arch_EQ); |
| 4827 | Args.ClaimAllArgs(Id0: options::OPT_no_offload_arch_EQ); |
| 4828 | |
| 4829 | SmallVector<StringRef> Sorted(Archs.begin(), Archs.end()); |
| 4830 | llvm::sort(C&: Sorted); |
| 4831 | return Sorted; |
| 4832 | } |
| 4833 | |
| 4834 | Action *Driver::BuildOffloadingActions(Compilation &C, |
| 4835 | llvm::opt::DerivedArgList &Args, |
| 4836 | const InputTy &Input, StringRef CUID, |
| 4837 | Action *HostAction) const { |
| 4838 | // Don't build offloading actions if explicitly disabled or we do not have a |
| 4839 | // valid source input. |
| 4840 | if (offloadHostOnly() || !types::isSrcFile(Id: Input.first)) |
| 4841 | return HostAction; |
| 4842 | |
| 4843 | bool HIPNoRDC = |
| 4844 | C.isOffloadingHostKind(Kind: Action::OFK_HIP) && |
| 4845 | !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false); |
| 4846 | |
| 4847 | bool HIPRelocatableObj = |
| 4848 | C.isOffloadingHostKind(Kind: Action::OFK_HIP) && |
| 4849 | Args.hasFlag(Pos: options::OPT_fhip_emit_relocatable, |
| 4850 | Neg: options::OPT_fno_hip_emit_relocatable, Default: false); |
| 4851 | |
| 4852 | if (!HIPNoRDC && HIPRelocatableObj) |
| 4853 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_with_opt) |
| 4854 | << "-fhip-emit-relocatable" |
| 4855 | << "-fgpu-rdc" ; |
| 4856 | |
| 4857 | if (!offloadDeviceOnly() && HIPRelocatableObj) |
| 4858 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_without_opt) |
| 4859 | << "-fhip-emit-relocatable" |
| 4860 | << "--offload-device-only" ; |
| 4861 | |
| 4862 | // Don't build offloading actions if we do not have a compile action. If |
| 4863 | // preprocessing only ignore embedding. |
| 4864 | if (!(isa<CompileJobAction>(Val: HostAction) || |
| 4865 | getFinalPhase(DAL: Args) == phases::Preprocess)) |
| 4866 | return HostAction; |
| 4867 | |
| 4868 | ActionList OffloadActions; |
| 4869 | OffloadAction::DeviceDependences DDeps; |
| 4870 | |
| 4871 | const Action::OffloadKind OffloadKinds[] = { |
| 4872 | Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP, Action::OFK_SYCL}; |
| 4873 | |
| 4874 | for (Action::OffloadKind Kind : OffloadKinds) { |
| 4875 | SmallVector<const ToolChain *, 2> ToolChains; |
| 4876 | ActionList DeviceActions; |
| 4877 | |
| 4878 | auto TCRange = C.getOffloadToolChains(Kind); |
| 4879 | for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI) |
| 4880 | ToolChains.push_back(Elt: TI->second); |
| 4881 | |
| 4882 | if (ToolChains.empty()) |
| 4883 | continue; |
| 4884 | |
| 4885 | types::ID InputType = Input.first; |
| 4886 | const Arg *InputArg = Input.second; |
| 4887 | |
| 4888 | // The toolchain can be active for unsupported file types. |
| 4889 | if ((Kind == Action::OFK_Cuda && !types::isCuda(Id: InputType)) || |
| 4890 | (Kind == Action::OFK_HIP && !types::isHIP(Id: InputType))) |
| 4891 | continue; |
| 4892 | |
| 4893 | // Get the product of all bound architectures and toolchains. |
| 4894 | SmallVector<std::pair<const ToolChain *, StringRef>> TCAndArchs; |
| 4895 | for (const ToolChain *TC : ToolChains) { |
| 4896 | for (StringRef Arch : getOffloadArchs(C, Args: C.getArgs(), Kind, TC: *TC)) { |
| 4897 | TCAndArchs.push_back(Elt: std::make_pair(x&: TC, y&: Arch)); |
| 4898 | DeviceActions.push_back( |
| 4899 | Elt: C.MakeAction<InputAction>(Arg: *InputArg, Arg&: InputType, Arg&: CUID)); |
| 4900 | } |
| 4901 | } |
| 4902 | |
| 4903 | if (DeviceActions.empty()) |
| 4904 | return HostAction; |
| 4905 | |
| 4906 | // FIXME: Do not collapse the host side for Darwin targets with SYCL offload |
| 4907 | // compilations. The toolchain is not properly initialized for the target. |
| 4908 | if (isa<CompileJobAction>(Val: HostAction) && Kind == Action::OFK_SYCL && |
| 4909 | HostAction->getType() != types::TY_Nothing && |
| 4910 | C.getSingleOffloadToolChain<Action::OFK_Host>() |
| 4911 | ->getTriple() |
| 4912 | .isOSDarwin()) |
| 4913 | HostAction->setCannotBeCollapsedWithNextDependentAction(); |
| 4914 | |
| 4915 | auto PL = types::getCompilationPhases(Driver: *this, DAL&: Args, Id: InputType); |
| 4916 | |
| 4917 | for (phases::ID Phase : PL) { |
| 4918 | if (Phase == phases::Link) { |
| 4919 | assert(Phase == PL.back() && "linking must be final compilation step." ); |
| 4920 | break; |
| 4921 | } |
| 4922 | |
| 4923 | // Assemble actions are not used for the SYCL device side. Both compile |
| 4924 | // and backend actions are used to generate IR and textual IR if needed. |
| 4925 | if (Kind == Action::OFK_SYCL && Phase == phases::Assemble) |
| 4926 | continue; |
| 4927 | |
| 4928 | auto *TCAndArch = TCAndArchs.begin(); |
| 4929 | for (Action *&A : DeviceActions) { |
| 4930 | if (A->getType() == types::TY_Nothing) |
| 4931 | continue; |
| 4932 | |
| 4933 | // Propagate the ToolChain so we can use it in ConstructPhaseAction. |
| 4934 | A->propagateDeviceOffloadInfo(OKind: Kind, OArch: TCAndArch->second.data(), |
| 4935 | OToolChain: TCAndArch->first); |
| 4936 | A = ConstructPhaseAction(C, Args, Phase, Input: A, TargetDeviceOffloadKind: Kind); |
| 4937 | |
| 4938 | if (isa<CompileJobAction>(Val: A) && isa<CompileJobAction>(Val: HostAction) && |
| 4939 | Kind == Action::OFK_OpenMP && |
| 4940 | HostAction->getType() != types::TY_Nothing) { |
| 4941 | // OpenMP offloading has a dependency on the host compile action to |
| 4942 | // identify which declarations need to be emitted. This shouldn't be |
| 4943 | // collapsed with any other actions so we can use it in the device. |
| 4944 | HostAction->setCannotBeCollapsedWithNextDependentAction(); |
| 4945 | OffloadAction::HostDependence HDep( |
| 4946 | *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), |
| 4947 | TCAndArch->second.data(), Kind); |
| 4948 | OffloadAction::DeviceDependences DDep; |
| 4949 | DDep.add(A&: *A, TC: *TCAndArch->first, BoundArch: TCAndArch->second.data(), OKind: Kind); |
| 4950 | A = C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: DDep); |
| 4951 | } |
| 4952 | |
| 4953 | ++TCAndArch; |
| 4954 | } |
| 4955 | } |
| 4956 | |
| 4957 | // Compiling HIP in device-only non-RDC mode requires linking each action |
| 4958 | // individually. |
| 4959 | for (Action *&A : DeviceActions) { |
| 4960 | auto *OffloadTriple = A->getOffloadingToolChain() |
| 4961 | ? &A->getOffloadingToolChain()->getTriple() |
| 4962 | : nullptr; |
| 4963 | bool IsHIPSPV = |
| 4964 | OffloadTriple && OffloadTriple->isSPIRV() && |
| 4965 | (OffloadTriple->getOS() == llvm::Triple::OSType::AMDHSA || |
| 4966 | OffloadTriple->getOS() == llvm::Triple::OSType::ChipStar); |
| 4967 | bool UseSPIRVBackend = Args.hasFlag(Pos: options::OPT_use_spirv_backend, |
| 4968 | Neg: options::OPT_no_use_spirv_backend, |
| 4969 | /*Default=*/false); |
| 4970 | |
| 4971 | // Special handling for the HIP SPIR-V toolchains in device-only. |
| 4972 | // The translator path has a linking step, whereas the SPIR-V backend path |
| 4973 | // does not to avoid any external dependency such as spirv-link. The |
| 4974 | // linking step is skipped for the SPIR-V backend path. |
| 4975 | bool IsAMDGCNSPIRVWithBackend = |
| 4976 | IsHIPSPV && OffloadTriple->getOS() == llvm::Triple::OSType::AMDHSA && |
| 4977 | UseSPIRVBackend; |
| 4978 | |
| 4979 | if ((A->getType() != types::TY_Object && !IsHIPSPV && |
| 4980 | A->getType() != types::TY_LTO_BC) || |
| 4981 | HIPRelocatableObj || !HIPNoRDC || !offloadDeviceOnly() || |
| 4982 | (IsAMDGCNSPIRVWithBackend && offloadDeviceOnly())) |
| 4983 | continue; |
| 4984 | ActionList LinkerInput = {A}; |
| 4985 | A = C.MakeAction<LinkJobAction>(Arg&: LinkerInput, Arg: types::TY_Image); |
| 4986 | } |
| 4987 | |
| 4988 | auto *TCAndArch = TCAndArchs.begin(); |
| 4989 | for (Action *A : DeviceActions) { |
| 4990 | DDeps.add(A&: *A, TC: *TCAndArch->first, BoundArch: TCAndArch->second.data(), OKind: Kind); |
| 4991 | OffloadAction::DeviceDependences DDep; |
| 4992 | DDep.add(A&: *A, TC: *TCAndArch->first, BoundArch: TCAndArch->second.data(), OKind: Kind); |
| 4993 | |
| 4994 | // Compiling CUDA in non-RDC mode uses the PTX output if available. |
| 4995 | for (Action *Input : A->getInputs()) |
| 4996 | if (Kind == Action::OFK_Cuda && A->getType() == types::TY_Object && |
| 4997 | !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, |
| 4998 | Default: false)) |
| 4999 | DDep.add(A&: *Input, TC: *TCAndArch->first, BoundArch: TCAndArch->second.data(), OKind: Kind); |
| 5000 | OffloadActions.push_back(Elt: C.MakeAction<OffloadAction>(Arg&: DDep, Arg: A->getType())); |
| 5001 | |
| 5002 | ++TCAndArch; |
| 5003 | } |
| 5004 | } |
| 5005 | |
| 5006 | // HIP code in device-only non-RDC mode will bundle the output if it invoked |
| 5007 | // the linker or if the user explicitly requested it. |
| 5008 | bool ShouldBundleHIP = |
| 5009 | Args.hasFlag(Pos: options::OPT_gpu_bundle_output, |
| 5010 | Neg: options::OPT_no_gpu_bundle_output, Default: false) || |
| 5011 | (!Args.getLastArg(Ids: options::OPT_no_gpu_bundle_output) && HIPNoRDC && |
| 5012 | offloadDeviceOnly() && llvm::none_of(Range&: OffloadActions, P: [](Action *A) { |
| 5013 | return A->getType() != types::TY_Image; |
| 5014 | })); |
| 5015 | |
| 5016 | // All kinds exit now in device-only mode except for non-RDC mode HIP. |
| 5017 | if (offloadDeviceOnly() && !ShouldBundleHIP) |
| 5018 | return C.MakeAction<OffloadAction>(Arg&: DDeps, Arg: types::TY_Nothing); |
| 5019 | |
| 5020 | if (OffloadActions.empty()) |
| 5021 | return HostAction; |
| 5022 | |
| 5023 | OffloadAction::DeviceDependences DDep; |
| 5024 | if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) && |
| 5025 | !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false)) { |
| 5026 | // If we are not in RDC-mode we just emit the final CUDA fatbinary for |
| 5027 | // each translation unit without requiring any linking. |
| 5028 | Action *FatbinAction = |
| 5029 | C.MakeAction<LinkJobAction>(Arg&: OffloadActions, Arg: types::TY_CUDA_FATBIN); |
| 5030 | DDep.add(A&: *FatbinAction, TC: *C.getSingleOffloadToolChain<Action::OFK_Cuda>(), |
| 5031 | BoundArch: nullptr, OKind: Action::OFK_Cuda); |
| 5032 | } else if (HIPNoRDC && offloadDeviceOnly()) { |
| 5033 | // If we are in device-only non-RDC-mode we just emit the final HIP |
| 5034 | // fatbinary for each translation unit, linking each input individually. |
| 5035 | Action *FatbinAction = |
| 5036 | C.MakeAction<LinkJobAction>(Arg&: OffloadActions, Arg: types::TY_HIP_FATBIN); |
| 5037 | DDep.add(A&: *FatbinAction, |
| 5038 | TC: *C.getOffloadToolChains<Action::OFK_HIP>().first->second, BoundArch: nullptr, |
| 5039 | OKind: Action::OFK_HIP); |
| 5040 | } else if (HIPNoRDC) { |
| 5041 | // Package all the offloading actions into a single output that can be |
| 5042 | // embedded in the host and linked. |
| 5043 | Action *PackagerAction = |
| 5044 | C.MakeAction<OffloadPackagerJobAction>(Arg&: OffloadActions, Arg: types::TY_Image); |
| 5045 | |
| 5046 | // For HIP non-RDC compilation, wrap the device binary with linker wrapper |
| 5047 | // before bundling with host code. Do not bind a specific GPU arch here, |
| 5048 | // as the packaged image may contain entries for multiple GPUs. |
| 5049 | ActionList AL{PackagerAction}; |
| 5050 | PackagerAction = |
| 5051 | C.MakeAction<LinkerWrapperJobAction>(Arg&: AL, Arg: types::TY_HIP_FATBIN); |
| 5052 | DDep.add(A&: *PackagerAction, |
| 5053 | TC: *C.getOffloadToolChains<Action::OFK_HIP>().first->second, |
| 5054 | /*BoundArch=*/nullptr, OKind: Action::OFK_HIP); |
| 5055 | } else { |
| 5056 | // Package all the offloading actions into a single output that can be |
| 5057 | // embedded in the host and linked. |
| 5058 | Action *PackagerAction = |
| 5059 | C.MakeAction<OffloadPackagerJobAction>(Arg&: OffloadActions, Arg: types::TY_Image); |
| 5060 | DDep.add(A&: *PackagerAction, TC: *C.getSingleOffloadToolChain<Action::OFK_Host>(), |
| 5061 | BoundArch: nullptr, OffloadKindMask: C.getActiveOffloadKinds()); |
| 5062 | } |
| 5063 | |
| 5064 | // HIP wants '--offload-device-only' to create a fatbinary by default. |
| 5065 | if (offloadDeviceOnly()) |
| 5066 | return C.MakeAction<OffloadAction>(Arg&: DDep, Arg: types::TY_Nothing); |
| 5067 | |
| 5068 | // If we are unable to embed a single device output into the host, we need to |
| 5069 | // add each device output as a host dependency to ensure they are still built. |
| 5070 | bool SingleDeviceOutput = !llvm::any_of(Range&: OffloadActions, P: [](Action *A) { |
| 5071 | return A->getType() == types::TY_Nothing; |
| 5072 | }) && isa<CompileJobAction>(Val: HostAction); |
| 5073 | OffloadAction::HostDependence HDep( |
| 5074 | *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), |
| 5075 | /*BoundArch=*/nullptr, SingleDeviceOutput ? DDep : DDeps); |
| 5076 | return C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: SingleDeviceOutput ? DDep : DDeps); |
| 5077 | } |
| 5078 | |
| 5079 | Action *Driver::ConstructPhaseAction( |
| 5080 | Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input, |
| 5081 | Action::OffloadKind TargetDeviceOffloadKind) const { |
| 5082 | llvm::PrettyStackTraceString CrashInfo("Constructing phase actions" ); |
| 5083 | |
| 5084 | // Some types skip the assembler phase (e.g., llvm-bc), but we can't |
| 5085 | // encode this in the steps because the intermediate type depends on |
| 5086 | // arguments. Just special case here. |
| 5087 | if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm) |
| 5088 | return Input; |
| 5089 | |
| 5090 | // Use of --sycl-link will only allow for the link phase to occur. This is |
| 5091 | // for all input files. |
| 5092 | if (Args.hasArg(Ids: options::OPT_sycl_link) && Phase != phases::Link) |
| 5093 | return Input; |
| 5094 | |
| 5095 | // Build the appropriate action. |
| 5096 | switch (Phase) { |
| 5097 | case phases::Link: |
| 5098 | llvm_unreachable("link action invalid here." ); |
| 5099 | case phases::IfsMerge: |
| 5100 | llvm_unreachable("ifsmerge action invalid here." ); |
| 5101 | case phases::Preprocess: { |
| 5102 | types::ID OutputTy; |
| 5103 | // -M and -MM specify the dependency file name by altering the output type, |
| 5104 | // -if -MD and -MMD are not specified. |
| 5105 | if (Args.hasArg(Ids: options::OPT_M, Ids: options::OPT_MM) && |
| 5106 | !Args.hasArg(Ids: options::OPT_MD, Ids: options::OPT_MMD)) { |
| 5107 | OutputTy = types::TY_Dependencies; |
| 5108 | } else { |
| 5109 | OutputTy = Input->getType(); |
| 5110 | // For these cases, the preprocessor is only translating forms, the Output |
| 5111 | // still needs preprocessing. |
| 5112 | if (!Args.hasFlag(Pos: options::OPT_frewrite_includes, |
| 5113 | Neg: options::OPT_fno_rewrite_includes, Default: false) && |
| 5114 | !Args.hasFlag(Pos: options::OPT_frewrite_imports, |
| 5115 | Neg: options::OPT_fno_rewrite_imports, Default: false) && |
| 5116 | !Args.hasFlag(Pos: options::OPT_fdirectives_only, |
| 5117 | Neg: options::OPT_fno_directives_only, Default: false) && |
| 5118 | !CCGenDiagnostics) |
| 5119 | OutputTy = types::getPreprocessedType(Id: OutputTy); |
| 5120 | assert(OutputTy != types::TY_INVALID && |
| 5121 | "Cannot preprocess this input type!" ); |
| 5122 | } |
| 5123 | return C.MakeAction<PreprocessJobAction>(Arg&: Input, Arg&: OutputTy); |
| 5124 | } |
| 5125 | case phases::Precompile: { |
| 5126 | // API extraction should not generate an actual precompilation action. |
| 5127 | if (Args.hasArg(Ids: options::OPT_extract_api)) |
| 5128 | return C.MakeAction<ExtractAPIJobAction>(Arg&: Input, Arg: types::TY_API_INFO); |
| 5129 | |
| 5130 | // With 'fmodules-reduced-bmi', we don't want to run the |
| 5131 | // precompile phase unless the user specified '--precompile' or |
| 5132 | // '--precompile-reduced-bmi'. If '--precompile' is specified, we will try |
| 5133 | // to emit the reduced BMI as a by product in |
| 5134 | // GenerateModuleInterfaceAction. If '--precompile-reduced-bmi' is |
| 5135 | // specified, we will generate the reduced BMI directly. |
| 5136 | if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi) && |
| 5137 | (Input->getType() == driver::types::TY_CXXModule || |
| 5138 | Input->getType() == driver::types::TY_PP_CXXModule) && |
| 5139 | !Args.getLastArg(Ids: options::OPT__precompile) && |
| 5140 | !Args.getLastArg(Ids: options::OPT__precompile_reduced_bmi)) |
| 5141 | return Input; |
| 5142 | |
| 5143 | types::ID OutputTy = getPrecompiledType(Id: Input->getType()); |
| 5144 | assert(OutputTy != types::TY_INVALID && |
| 5145 | "Cannot precompile this input type!" ); |
| 5146 | |
| 5147 | // If we're given a module name, precompile header file inputs as a |
| 5148 | // module, not as a precompiled header. |
| 5149 | const char *ModName = nullptr; |
| 5150 | if (OutputTy == types::TY_PCH) { |
| 5151 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_name_EQ)) |
| 5152 | ModName = A->getValue(); |
| 5153 | if (ModName) |
| 5154 | OutputTy = types::TY_ModuleFile; |
| 5155 | } |
| 5156 | |
| 5157 | if (Args.hasArg(Ids: options::OPT_fsyntax_only)) { |
| 5158 | // Syntax checks should not emit a PCH file |
| 5159 | OutputTy = types::TY_Nothing; |
| 5160 | } |
| 5161 | |
| 5162 | return C.MakeAction<PrecompileJobAction>(Arg&: Input, Arg&: OutputTy); |
| 5163 | } |
| 5164 | case phases::Compile: { |
| 5165 | if (Args.hasArg(Ids: options::OPT_fsyntax_only)) |
| 5166 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_Nothing); |
| 5167 | if (Args.hasArg(Ids: options::OPT_rewrite_objc)) |
| 5168 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_RewrittenObjC); |
| 5169 | if (Args.hasArg(Ids: options::OPT_rewrite_legacy_objc)) |
| 5170 | return C.MakeAction<CompileJobAction>(Arg&: Input, |
| 5171 | Arg: types::TY_RewrittenLegacyObjC); |
| 5172 | if (Args.hasArg(Ids: options::OPT__analyze)) |
| 5173 | return C.MakeAction<AnalyzeJobAction>(Arg&: Input, Arg: types::TY_Plist); |
| 5174 | if (Args.hasArg(Ids: options::OPT_emit_ast)) |
| 5175 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_AST); |
| 5176 | if (Args.hasArg(Ids: options::OPT_emit_cir)) |
| 5177 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_CIR); |
| 5178 | if (Args.hasArg(Ids: options::OPT_module_file_info)) |
| 5179 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_ModuleFile); |
| 5180 | if (Args.hasArg(Ids: options::OPT_verify_pch)) |
| 5181 | return C.MakeAction<VerifyPCHJobAction>(Arg&: Input, Arg: types::TY_Nothing); |
| 5182 | if (Args.hasArg(Ids: options::OPT_extract_api)) |
| 5183 | return C.MakeAction<ExtractAPIJobAction>(Arg&: Input, Arg: types::TY_API_INFO); |
| 5184 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_LLVM_BC); |
| 5185 | } |
| 5186 | case phases::Backend: { |
| 5187 | // Skip a redundant Backend phase for HIP device code when using the new |
| 5188 | // offload driver, where mid-end is done in linker wrapper. |
| 5189 | if (TargetDeviceOffloadKind == Action::OFK_HIP && |
| 5190 | Args.hasFlag(Pos: options::OPT_offload_new_driver, |
| 5191 | Neg: options::OPT_no_offload_new_driver, |
| 5192 | Default: C.getActiveOffloadKinds() != Action::OFK_None) && |
| 5193 | !offloadDeviceOnly()) |
| 5194 | return Input; |
| 5195 | |
| 5196 | if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) { |
| 5197 | types::ID Output; |
| 5198 | if (Args.hasArg(Ids: options::OPT_ffat_lto_objects) && |
| 5199 | !Args.hasArg(Ids: options::OPT_emit_llvm)) |
| 5200 | Output = types::TY_PP_Asm; |
| 5201 | else if (Args.hasArg(Ids: options::OPT_S)) |
| 5202 | Output = types::TY_LTO_IR; |
| 5203 | else |
| 5204 | Output = types::TY_LTO_BC; |
| 5205 | return C.MakeAction<BackendJobAction>(Arg&: Input, Arg&: Output); |
| 5206 | } |
| 5207 | if (isUsingOffloadLTO() && TargetDeviceOffloadKind != Action::OFK_None) { |
| 5208 | types::ID Output = |
| 5209 | Args.hasArg(Ids: options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; |
| 5210 | return C.MakeAction<BackendJobAction>(Arg&: Input, Arg&: Output); |
| 5211 | } |
| 5212 | bool UseSPIRVBackend = Args.hasFlag(Pos: options::OPT_use_spirv_backend, |
| 5213 | Neg: options::OPT_no_use_spirv_backend, |
| 5214 | /*Default=*/false); |
| 5215 | |
| 5216 | auto OffloadingToolChain = Input->getOffloadingToolChain(); |
| 5217 | // For AMD SPIRV, if offloadDeviceOnly(), we call the SPIRV backend unless |
| 5218 | // LLVM bitcode was requested explicitly or RDC is set. If |
| 5219 | // !offloadDeviceOnly, we emit LLVM bitcode, and clang-linker-wrapper will |
| 5220 | // compile it to SPIRV. |
| 5221 | bool UseSPIRVBackendForHipDeviceOnlyNoRDC = |
| 5222 | TargetDeviceOffloadKind == Action::OFK_HIP && OffloadingToolChain && |
| 5223 | OffloadingToolChain->getTriple().isSPIRV() && UseSPIRVBackend && |
| 5224 | offloadDeviceOnly() && |
| 5225 | !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false); |
| 5226 | |
| 5227 | auto &DefaultToolChain = C.getDefaultToolChain(); |
| 5228 | auto DefaultToolChainTriple = DefaultToolChain.getTriple(); |
| 5229 | // For regular C/C++ to AMD SPIRV emit bitcode to avoid spirv-link |
| 5230 | // dependency, SPIRVAMDToolChain's linker takes care of the generation of |
| 5231 | // the final SPIRV. The only exception is -S without -emit-llvm to output |
| 5232 | // textual SPIRV assembly, which fits the default compilation path. |
| 5233 | bool EmitBitcodeForNonOffloadAMDSPIRV = |
| 5234 | !OffloadingToolChain && DefaultToolChainTriple.isSPIRV() && |
| 5235 | DefaultToolChainTriple.getVendor() == llvm::Triple::VendorType::AMD && |
| 5236 | !(Args.hasArg(Ids: options::OPT_S) && !Args.hasArg(Ids: options::OPT_emit_llvm)); |
| 5237 | |
| 5238 | if (Args.hasArg(Ids: options::OPT_emit_llvm) || |
| 5239 | EmitBitcodeForNonOffloadAMDSPIRV || |
| 5240 | TargetDeviceOffloadKind == Action::OFK_SYCL || |
| 5241 | (((Input->getOffloadingToolChain() && |
| 5242 | Input->getOffloadingToolChain()->getTriple().isAMDGPU() && |
| 5243 | TargetDeviceOffloadKind != Action::OFK_None) || |
| 5244 | TargetDeviceOffloadKind == Action::OFK_HIP) && |
| 5245 | !UseSPIRVBackendForHipDeviceOnlyNoRDC && |
| 5246 | ((Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, |
| 5247 | Default: false) || |
| 5248 | (Args.hasFlag(Pos: options::OPT_offload_new_driver, |
| 5249 | Neg: options::OPT_no_offload_new_driver, |
| 5250 | Default: C.getActiveOffloadKinds() != Action::OFK_None) && |
| 5251 | (!offloadDeviceOnly() || |
| 5252 | (Input->getOffloadingToolChain() && |
| 5253 | TargetDeviceOffloadKind == Action::OFK_HIP && |
| 5254 | Input->getOffloadingToolChain()->getTriple().isSPIRV())))) || |
| 5255 | TargetDeviceOffloadKind == Action::OFK_OpenMP))) { |
| 5256 | types::ID Output = |
| 5257 | Args.hasArg(Ids: options::OPT_S) && |
| 5258 | (TargetDeviceOffloadKind == Action::OFK_None || |
| 5259 | offloadDeviceOnly() || |
| 5260 | (TargetDeviceOffloadKind == Action::OFK_HIP && |
| 5261 | !Args.hasFlag(Pos: options::OPT_offload_new_driver, |
| 5262 | Neg: options::OPT_no_offload_new_driver, |
| 5263 | Default: C.getActiveOffloadKinds() != |
| 5264 | Action::OFK_None))) |
| 5265 | ? types::TY_LLVM_IR |
| 5266 | : types::TY_LLVM_BC; |
| 5267 | return C.MakeAction<BackendJobAction>(Arg&: Input, Arg&: Output); |
| 5268 | } |
| 5269 | |
| 5270 | // The SPIRV backend compilation path for HIP must avoid external |
| 5271 | // dependencies. The default compilation path assembles and links its |
| 5272 | // output, but the SPIRV assembler and linker are external tools. This code |
| 5273 | // ensures the backend emits binary SPIRV directly to bypass those steps and |
| 5274 | // avoid failures. Without -save-temps, the compiler may already skip |
| 5275 | // assembling and linking. With -save-temps, these steps must be explicitly |
| 5276 | // disabled, as done here. We also force skipping these steps regardless of |
| 5277 | // -save-temps to avoid relying on optimizations (unless -S is set). |
| 5278 | // The current HIP bundling expects the type to be types::TY_Image |
| 5279 | if (UseSPIRVBackendForHipDeviceOnlyNoRDC && !Args.hasArg(Ids: options::OPT_S)) |
| 5280 | return C.MakeAction<BackendJobAction>(Arg&: Input, Arg: types::TY_Image); |
| 5281 | |
| 5282 | return C.MakeAction<BackendJobAction>(Arg&: Input, Arg: types::TY_PP_Asm); |
| 5283 | } |
| 5284 | case phases::Assemble: |
| 5285 | return C.MakeAction<AssembleJobAction>(Arg: std::move(Input), Arg: types::TY_Object); |
| 5286 | } |
| 5287 | |
| 5288 | llvm_unreachable("invalid phase in ConstructPhaseAction" ); |
| 5289 | } |
| 5290 | |
| 5291 | void Driver::BuildJobs(Compilation &C) const { |
| 5292 | llvm::PrettyStackTraceString CrashInfo("Building compilation jobs" ); |
| 5293 | |
| 5294 | Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o); |
| 5295 | |
| 5296 | // It is an error to provide a -o option if we are making multiple output |
| 5297 | // files. There are exceptions: |
| 5298 | // |
| 5299 | // IfsMergeJob: when generating interface stubs enabled we want to be able to |
| 5300 | // generate the stub file at the same time that we generate the real |
| 5301 | // library/a.out. So when a .o, .so, etc are the output, with clang interface |
| 5302 | // stubs there will also be a .ifs and .ifso at the same location. |
| 5303 | // |
| 5304 | // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled |
| 5305 | // and -c is passed, we still want to be able to generate a .ifs file while |
| 5306 | // we are also generating .o files. So we allow more than one output file in |
| 5307 | // this case as well. |
| 5308 | // |
| 5309 | // OffloadClass of type TY_Nothing: device-only output will place many outputs |
| 5310 | // into a single offloading action. We should count all inputs to the action |
| 5311 | // as outputs. Also ignore device-only outputs if we're compiling with |
| 5312 | // -fsyntax-only. |
| 5313 | if (FinalOutput) { |
| 5314 | unsigned NumOutputs = 0; |
| 5315 | unsigned NumIfsOutputs = 0; |
| 5316 | for (const Action *A : C.getActions()) { |
| 5317 | // The actions below do not increase the number of outputs, when operating |
| 5318 | // on DX containers. |
| 5319 | if (A->getType() == types::TY_DX_CONTAINER && |
| 5320 | (A->getKind() == clang::driver::Action::BinaryAnalyzeJobClass || |
| 5321 | A->getKind() == clang::driver::Action::BinaryTranslatorJobClass)) |
| 5322 | continue; |
| 5323 | |
| 5324 | if (A->getType() != types::TY_Nothing && |
| 5325 | !(A->getKind() == Action::IfsMergeJobClass || |
| 5326 | (A->getType() == clang::driver::types::TY_IFS_CPP && |
| 5327 | A->getKind() == clang::driver::Action::CompileJobClass && |
| 5328 | 0 == NumIfsOutputs++) || |
| 5329 | (A->getKind() == Action::BindArchClass && A->getInputs().size() && |
| 5330 | A->getInputs().front()->getKind() == Action::IfsMergeJobClass))) |
| 5331 | ++NumOutputs; |
| 5332 | else if (A->getKind() == Action::OffloadClass && |
| 5333 | A->getType() == types::TY_Nothing && |
| 5334 | !C.getArgs().hasArg(Ids: options::OPT_fsyntax_only)) |
| 5335 | NumOutputs += A->size(); |
| 5336 | } |
| 5337 | |
| 5338 | if (NumOutputs > 1) { |
| 5339 | Diag(DiagID: clang::diag::err_drv_output_argument_with_multiple_files); |
| 5340 | FinalOutput = nullptr; |
| 5341 | } |
| 5342 | } |
| 5343 | |
| 5344 | const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple(); |
| 5345 | |
| 5346 | // Collect the list of architectures. |
| 5347 | llvm::StringSet<> ArchNames; |
| 5348 | if (RawTriple.isOSBinFormatMachO()) |
| 5349 | for (const Arg *A : C.getArgs()) |
| 5350 | if (A->getOption().matches(ID: options::OPT_arch)) |
| 5351 | ArchNames.insert(key: A->getValue()); |
| 5352 | |
| 5353 | // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. |
| 5354 | std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults; |
| 5355 | for (Action *A : C.getActions()) { |
| 5356 | // If we are linking an image for multiple archs then the linker wants |
| 5357 | // -arch_multiple and -final_output <final image name>. Unfortunately, this |
| 5358 | // doesn't fit in cleanly because we have to pass this information down. |
| 5359 | // |
| 5360 | // FIXME: This is a hack; find a cleaner way to integrate this into the |
| 5361 | // process. |
| 5362 | const char *LinkingOutput = nullptr; |
| 5363 | if (isa<LipoJobAction>(Val: A)) { |
| 5364 | if (FinalOutput) |
| 5365 | LinkingOutput = FinalOutput->getValue(); |
| 5366 | else |
| 5367 | LinkingOutput = getDefaultImageName(); |
| 5368 | } |
| 5369 | |
| 5370 | BuildJobsForAction(C, A, TC: &C.getDefaultToolChain(), |
| 5371 | /*BoundArch*/ StringRef(), |
| 5372 | /*AtTopLevel*/ true, |
| 5373 | /*MultipleArchs*/ ArchNames.size() > 1, |
| 5374 | /*LinkingOutput*/ LinkingOutput, CachedResults, |
| 5375 | /*TargetDeviceOffloadKind*/ Action::OFK_None); |
| 5376 | } |
| 5377 | |
| 5378 | // If we have more than one job, then disable integrated-cc1 for now. Do this |
| 5379 | // also when we need to report process execution statistics. |
| 5380 | if (C.getJobs().size() > 1 || CCPrintProcessStats) |
| 5381 | for (auto &J : C.getJobs()) |
| 5382 | J.InProcess = false; |
| 5383 | |
| 5384 | if (CCPrintProcessStats) { |
| 5385 | C.setPostCallback([=](const Command &Cmd, int Res) { |
| 5386 | std::optional<llvm::sys::ProcessStatistics> ProcStat = |
| 5387 | Cmd.getProcessStatistics(); |
| 5388 | if (!ProcStat) |
| 5389 | return; |
| 5390 | |
| 5391 | const char *LinkingOutput = nullptr; |
| 5392 | if (FinalOutput) |
| 5393 | LinkingOutput = FinalOutput->getValue(); |
| 5394 | else if (!Cmd.getOutputFilenames().empty()) |
| 5395 | LinkingOutput = Cmd.getOutputFilenames().front().c_str(); |
| 5396 | else |
| 5397 | LinkingOutput = getDefaultImageName(); |
| 5398 | |
| 5399 | if (CCPrintStatReportFilename.empty()) { |
| 5400 | using namespace llvm; |
| 5401 | // Human readable output. |
| 5402 | outs() << sys::path::filename(path: Cmd.getExecutable()) << ": " |
| 5403 | << "output=" << LinkingOutput; |
| 5404 | outs() << ", total=" |
| 5405 | << format(Fmt: "%.3f" , Vals: ProcStat->TotalTime.count() / 1000.) << " ms" |
| 5406 | << ", user=" |
| 5407 | << format(Fmt: "%.3f" , Vals: ProcStat->UserTime.count() / 1000.) << " ms" |
| 5408 | << ", mem=" << ProcStat->PeakMemory << " Kb\n" ; |
| 5409 | } else { |
| 5410 | // CSV format. |
| 5411 | std::string Buffer; |
| 5412 | llvm::raw_string_ostream Out(Buffer); |
| 5413 | llvm::sys::printArg(OS&: Out, Arg: llvm::sys::path::filename(path: Cmd.getExecutable()), |
| 5414 | /*Quote*/ true); |
| 5415 | Out << ','; |
| 5416 | llvm::sys::printArg(OS&: Out, Arg: LinkingOutput, Quote: true); |
| 5417 | Out << ',' << ProcStat->TotalTime.count() << ',' |
| 5418 | << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory |
| 5419 | << '\n'; |
| 5420 | Out.flush(); |
| 5421 | std::error_code EC; |
| 5422 | llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC, |
| 5423 | llvm::sys::fs::OF_Append | |
| 5424 | llvm::sys::fs::OF_Text); |
| 5425 | if (EC) |
| 5426 | return; |
| 5427 | auto L = OS.lock(); |
| 5428 | if (!L) { |
| 5429 | llvm::errs() << "ERROR: Cannot lock file " |
| 5430 | << CCPrintStatReportFilename << ": " |
| 5431 | << toString(E: L.takeError()) << "\n" ; |
| 5432 | return; |
| 5433 | } |
| 5434 | OS << Buffer; |
| 5435 | OS.flush(); |
| 5436 | } |
| 5437 | }); |
| 5438 | } |
| 5439 | |
| 5440 | // If the user passed -Qunused-arguments or there were errors, don't |
| 5441 | // warn about any unused arguments. |
| 5442 | bool ReportUnusedArguments = |
| 5443 | !Diags.hasErrorOccurred() && |
| 5444 | !C.getArgs().hasArg(Ids: options::OPT_Qunused_arguments); |
| 5445 | |
| 5446 | // Claim -fdriver-only here. |
| 5447 | (void)C.getArgs().hasArg(Ids: options::OPT_fdriver_only); |
| 5448 | // Claim -### here. |
| 5449 | (void)C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH); |
| 5450 | |
| 5451 | // Claim --driver-mode, --rsp-quoting, it was handled earlier. |
| 5452 | (void)C.getArgs().hasArg(Ids: options::OPT_driver_mode); |
| 5453 | (void)C.getArgs().hasArg(Ids: options::OPT_rsp_quoting); |
| 5454 | |
| 5455 | bool HasAssembleJob = llvm::any_of(Range&: C.getJobs(), P: [](auto &J) { |
| 5456 | // Match ClangAs and other derived assemblers of Tool. ClangAs uses a |
| 5457 | // longer ShortName "clang integrated assembler" while other assemblers just |
| 5458 | // use "assembler". |
| 5459 | return strstr(J.getCreator().getShortName(), "assembler" ); |
| 5460 | }); |
| 5461 | for (Arg *A : C.getArgs()) { |
| 5462 | // FIXME: It would be nice to be able to send the argument to the |
| 5463 | // DiagnosticsEngine, so that extra values, position, and so on could be |
| 5464 | // printed. |
| 5465 | if (!A->isClaimed()) { |
| 5466 | if (A->getOption().hasFlag(Val: options::NoArgumentUnused)) |
| 5467 | continue; |
| 5468 | |
| 5469 | // Suppress the warning automatically if this is just a flag, and it is an |
| 5470 | // instance of an argument we already claimed. |
| 5471 | const Option &Opt = A->getOption(); |
| 5472 | if (Opt.getKind() == Option::FlagClass) { |
| 5473 | bool DuplicateClaimed = false; |
| 5474 | |
| 5475 | for (const Arg *AA : C.getArgs().filtered(Ids: &Opt)) { |
| 5476 | if (AA->isClaimed()) { |
| 5477 | DuplicateClaimed = true; |
| 5478 | break; |
| 5479 | } |
| 5480 | } |
| 5481 | |
| 5482 | if (DuplicateClaimed) |
| 5483 | continue; |
| 5484 | } |
| 5485 | |
| 5486 | // In clang-cl, don't mention unknown arguments here since they have |
| 5487 | // already been warned about. |
| 5488 | if (!IsCLMode() || !A->getOption().matches(ID: options::OPT_UNKNOWN)) { |
| 5489 | if (A->getOption().hasFlag(Val: options::TargetSpecific) && |
| 5490 | !A->isIgnoredTargetSpecific() && !HasAssembleJob && |
| 5491 | // When for example -### or -v is used |
| 5492 | // without a file, target specific options are not |
| 5493 | // consumed/validated. |
| 5494 | // Instead emitting an error emit a warning instead. |
| 5495 | !C.getActions().empty()) { |
| 5496 | Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 5497 | << A->getSpelling() << getTargetTriple(); |
| 5498 | } else if (ReportUnusedArguments) { |
| 5499 | Diag(DiagID: clang::diag::warn_drv_unused_argument) |
| 5500 | << A->getAsString(Args: C.getArgs()); |
| 5501 | } |
| 5502 | } |
| 5503 | } |
| 5504 | } |
| 5505 | } |
| 5506 | |
| 5507 | namespace { |
| 5508 | /// Utility class to control the collapse of dependent actions and select the |
| 5509 | /// tools accordingly. |
| 5510 | class ToolSelector final { |
| 5511 | /// The tool chain this selector refers to. |
| 5512 | const ToolChain &TC; |
| 5513 | |
| 5514 | /// The compilation this selector refers to. |
| 5515 | const Compilation &C; |
| 5516 | |
| 5517 | /// The base action this selector refers to. |
| 5518 | const JobAction *BaseAction; |
| 5519 | |
| 5520 | /// Set to true if the current toolchain refers to host actions. |
| 5521 | bool IsHostSelector; |
| 5522 | |
| 5523 | /// Set to true if save-temps and embed-bitcode functionalities are active. |
| 5524 | bool SaveTemps; |
| 5525 | bool EmbedBitcode; |
| 5526 | |
| 5527 | /// Get previous dependent action or null if that does not exist. If |
| 5528 | /// \a CanBeCollapsed is false, that action must be legal to collapse or |
| 5529 | /// null will be returned. |
| 5530 | const JobAction *getPrevDependentAction(const ActionList &Inputs, |
| 5531 | ActionList &SavedOffloadAction, |
| 5532 | bool CanBeCollapsed = true) { |
| 5533 | // An option can be collapsed only if it has a single input. |
| 5534 | if (Inputs.size() != 1) |
| 5535 | return nullptr; |
| 5536 | |
| 5537 | Action *CurAction = *Inputs.begin(); |
| 5538 | if (CanBeCollapsed && |
| 5539 | !CurAction->isCollapsingWithNextDependentActionLegal()) |
| 5540 | return nullptr; |
| 5541 | |
| 5542 | // If the input action is an offload action. Look through it and save any |
| 5543 | // offload action that can be dropped in the event of a collapse. |
| 5544 | if (auto *OA = dyn_cast<OffloadAction>(Val: CurAction)) { |
| 5545 | // If the dependent action is a device action, we will attempt to collapse |
| 5546 | // only with other device actions. Otherwise, we would do the same but |
| 5547 | // with host actions only. |
| 5548 | if (!IsHostSelector) { |
| 5549 | if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) { |
| 5550 | CurAction = |
| 5551 | OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true); |
| 5552 | if (CanBeCollapsed && |
| 5553 | !CurAction->isCollapsingWithNextDependentActionLegal()) |
| 5554 | return nullptr; |
| 5555 | SavedOffloadAction.push_back(Elt: OA); |
| 5556 | return dyn_cast<JobAction>(Val: CurAction); |
| 5557 | } |
| 5558 | } else if (OA->hasHostDependence()) { |
| 5559 | CurAction = OA->getHostDependence(); |
| 5560 | if (CanBeCollapsed && |
| 5561 | !CurAction->isCollapsingWithNextDependentActionLegal()) |
| 5562 | return nullptr; |
| 5563 | SavedOffloadAction.push_back(Elt: OA); |
| 5564 | return dyn_cast<JobAction>(Val: CurAction); |
| 5565 | } |
| 5566 | return nullptr; |
| 5567 | } |
| 5568 | |
| 5569 | return dyn_cast<JobAction>(Val: CurAction); |
| 5570 | } |
| 5571 | |
| 5572 | /// Return true if an assemble action can be collapsed. |
| 5573 | bool canCollapseAssembleAction() const { |
| 5574 | return TC.useIntegratedAs() && !SaveTemps && |
| 5575 | !C.getArgs().hasArg(Ids: options::OPT_via_file_asm) && |
| 5576 | !C.getArgs().hasArg(Ids: options::OPT__SLASH_FA) && |
| 5577 | !C.getArgs().hasArg(Ids: options::OPT__SLASH_Fa) && |
| 5578 | !C.getArgs().hasArg(Ids: options::OPT_dxc_Fc); |
| 5579 | } |
| 5580 | |
| 5581 | /// Return true if a preprocessor action can be collapsed. |
| 5582 | bool canCollapsePreprocessorAction() const { |
| 5583 | return !C.getArgs().hasArg(Ids: options::OPT_no_integrated_cpp) && |
| 5584 | !C.getArgs().hasArg(Ids: options::OPT_traditional_cpp) && !SaveTemps && |
| 5585 | !C.getArgs().hasArg(Ids: options::OPT_rewrite_objc); |
| 5586 | } |
| 5587 | |
| 5588 | /// Struct that relates an action with the offload actions that would be |
| 5589 | /// collapsed with it. |
| 5590 | struct JobActionInfo final { |
| 5591 | /// The action this info refers to. |
| 5592 | const JobAction *JA = nullptr; |
| 5593 | /// The offload actions we need to take care off if this action is |
| 5594 | /// collapsed. |
| 5595 | ActionList SavedOffloadAction; |
| 5596 | }; |
| 5597 | |
| 5598 | /// Append collapsed offload actions from the give nnumber of elements in the |
| 5599 | /// action info array. |
| 5600 | static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction, |
| 5601 | ArrayRef<JobActionInfo> &ActionInfo, |
| 5602 | unsigned ElementNum) { |
| 5603 | assert(ElementNum <= ActionInfo.size() && "Invalid number of elements." ); |
| 5604 | for (unsigned I = 0; I < ElementNum; ++I) |
| 5605 | CollapsedOffloadAction.append(in_start: ActionInfo[I].SavedOffloadAction.begin(), |
| 5606 | in_end: ActionInfo[I].SavedOffloadAction.end()); |
| 5607 | } |
| 5608 | |
| 5609 | /// Functions that attempt to perform the combining. They detect if that is |
| 5610 | /// legal, and if so they update the inputs \a Inputs and the offload action |
| 5611 | /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with |
| 5612 | /// the combined action is returned. If the combining is not legal or if the |
| 5613 | /// tool does not exist, null is returned. |
| 5614 | /// Currently three kinds of collapsing are supported: |
| 5615 | /// - Assemble + Backend + Compile; |
| 5616 | /// - Assemble + Backend ; |
| 5617 | /// - Backend + Compile. |
| 5618 | const Tool * |
| 5619 | combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo, |
| 5620 | ActionList &Inputs, |
| 5621 | ActionList &CollapsedOffloadAction) { |
| 5622 | if (ActionInfo.size() < 3 || !canCollapseAssembleAction()) |
| 5623 | return nullptr; |
| 5624 | auto *AJ = dyn_cast<AssembleJobAction>(Val: ActionInfo[0].JA); |
| 5625 | auto *BJ = dyn_cast<BackendJobAction>(Val: ActionInfo[1].JA); |
| 5626 | auto *CJ = dyn_cast<CompileJobAction>(Val: ActionInfo[2].JA); |
| 5627 | if (!AJ || !BJ || !CJ) |
| 5628 | return nullptr; |
| 5629 | |
| 5630 | // Get compiler tool. |
| 5631 | const Tool *T = TC.SelectTool(JA: *CJ); |
| 5632 | if (!T) |
| 5633 | return nullptr; |
| 5634 | |
| 5635 | // Can't collapse if we don't have codegen support unless we are |
| 5636 | // emitting LLVM IR. |
| 5637 | bool OutputIsLLVM = types::isLLVMIR(Id: ActionInfo[0].JA->getType()); |
| 5638 | if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) |
| 5639 | return nullptr; |
| 5640 | |
| 5641 | // When using -fembed-bitcode, it is required to have the same tool (clang) |
| 5642 | // for both CompilerJA and BackendJA. Otherwise, combine two stages. |
| 5643 | if (EmbedBitcode) { |
| 5644 | const Tool *BT = TC.SelectTool(JA: *BJ); |
| 5645 | if (BT == T) |
| 5646 | return nullptr; |
| 5647 | } |
| 5648 | |
| 5649 | if (!T->hasIntegratedAssembler()) |
| 5650 | return nullptr; |
| 5651 | |
| 5652 | Inputs = CJ->getInputs(); |
| 5653 | AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, |
| 5654 | /*NumElements=*/ElementNum: 3); |
| 5655 | return T; |
| 5656 | } |
| 5657 | const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo, |
| 5658 | ActionList &Inputs, |
| 5659 | ActionList &CollapsedOffloadAction) { |
| 5660 | if (ActionInfo.size() < 2 || !canCollapseAssembleAction()) |
| 5661 | return nullptr; |
| 5662 | auto *AJ = dyn_cast<AssembleJobAction>(Val: ActionInfo[0].JA); |
| 5663 | auto *BJ = dyn_cast<BackendJobAction>(Val: ActionInfo[1].JA); |
| 5664 | if (!AJ || !BJ) |
| 5665 | return nullptr; |
| 5666 | |
| 5667 | // Get backend tool. |
| 5668 | const Tool *T = TC.SelectTool(JA: *BJ); |
| 5669 | if (!T) |
| 5670 | return nullptr; |
| 5671 | |
| 5672 | if (!T->hasIntegratedAssembler()) |
| 5673 | return nullptr; |
| 5674 | |
| 5675 | Inputs = BJ->getInputs(); |
| 5676 | AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, |
| 5677 | /*NumElements=*/ElementNum: 2); |
| 5678 | return T; |
| 5679 | } |
| 5680 | const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo, |
| 5681 | ActionList &Inputs, |
| 5682 | ActionList &CollapsedOffloadAction) { |
| 5683 | if (ActionInfo.size() < 2) |
| 5684 | return nullptr; |
| 5685 | auto *BJ = dyn_cast<BackendJobAction>(Val: ActionInfo[0].JA); |
| 5686 | auto *CJ = dyn_cast<CompileJobAction>(Val: ActionInfo[1].JA); |
| 5687 | if (!BJ || !CJ) |
| 5688 | return nullptr; |
| 5689 | |
| 5690 | auto HasBitcodeInput = [](const JobActionInfo &AI) { |
| 5691 | for (auto &Input : AI.JA->getInputs()) |
| 5692 | if (!types::isLLVMIR(Id: Input->getType())) |
| 5693 | return false; |
| 5694 | return true; |
| 5695 | }; |
| 5696 | |
| 5697 | // Check if the initial input (to the compile job or its predessor if one |
| 5698 | // exists) is LLVM bitcode. In that case, no preprocessor step is required |
| 5699 | // and we can still collapse the compile and backend jobs when we have |
| 5700 | // -save-temps. I.e. there is no need for a separate compile job just to |
| 5701 | // emit unoptimized bitcode. |
| 5702 | bool InputIsBitcode = all_of(Range&: ActionInfo, P: HasBitcodeInput); |
| 5703 | if (SaveTemps && !InputIsBitcode) |
| 5704 | return nullptr; |
| 5705 | |
| 5706 | // Get compiler tool. |
| 5707 | const Tool *T = TC.SelectTool(JA: *CJ); |
| 5708 | if (!T) |
| 5709 | return nullptr; |
| 5710 | |
| 5711 | // Can't collapse if we don't have codegen support unless we are |
| 5712 | // emitting LLVM IR. |
| 5713 | bool OutputIsLLVM = types::isLLVMIR(Id: ActionInfo[0].JA->getType()); |
| 5714 | if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) |
| 5715 | return nullptr; |
| 5716 | |
| 5717 | if (T->canEmitIR() && EmbedBitcode) |
| 5718 | return nullptr; |
| 5719 | |
| 5720 | Inputs = CJ->getInputs(); |
| 5721 | AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, |
| 5722 | /*NumElements=*/ElementNum: 2); |
| 5723 | return T; |
| 5724 | } |
| 5725 | |
| 5726 | /// Updates the inputs if the obtained tool supports combining with |
| 5727 | /// preprocessor action, and the current input is indeed a preprocessor |
| 5728 | /// action. If combining results in the collapse of offloading actions, those |
| 5729 | /// are appended to \a CollapsedOffloadAction. |
| 5730 | void combineWithPreprocessor(const Tool *T, ActionList &Inputs, |
| 5731 | ActionList &CollapsedOffloadAction) { |
| 5732 | if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP()) |
| 5733 | return; |
| 5734 | |
| 5735 | // Attempt to get a preprocessor action dependence. |
| 5736 | ActionList PreprocessJobOffloadActions; |
| 5737 | ActionList NewInputs; |
| 5738 | for (Action *A : Inputs) { |
| 5739 | auto *PJ = getPrevDependentAction(Inputs: {A}, SavedOffloadAction&: PreprocessJobOffloadActions); |
| 5740 | if (!PJ || !isa<PreprocessJobAction>(Val: PJ)) { |
| 5741 | NewInputs.push_back(Elt: A); |
| 5742 | continue; |
| 5743 | } |
| 5744 | |
| 5745 | // This is legal to combine. Append any offload action we found and add the |
| 5746 | // current input to preprocessor inputs. |
| 5747 | CollapsedOffloadAction.append(in_start: PreprocessJobOffloadActions.begin(), |
| 5748 | in_end: PreprocessJobOffloadActions.end()); |
| 5749 | NewInputs.append(in_start: PJ->input_begin(), in_end: PJ->input_end()); |
| 5750 | } |
| 5751 | Inputs = NewInputs; |
| 5752 | } |
| 5753 | |
| 5754 | public: |
| 5755 | ToolSelector(const JobAction *BaseAction, const ToolChain &TC, |
| 5756 | const Compilation &C, bool SaveTemps, bool EmbedBitcode) |
| 5757 | : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps), |
| 5758 | EmbedBitcode(EmbedBitcode) { |
| 5759 | assert(BaseAction && "Invalid base action." ); |
| 5760 | IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None; |
| 5761 | } |
| 5762 | |
| 5763 | /// Check if a chain of actions can be combined and return the tool that can |
| 5764 | /// handle the combination of actions. The pointer to the current inputs \a |
| 5765 | /// Inputs and the list of offload actions \a CollapsedOffloadActions |
| 5766 | /// connected to collapsed actions are updated accordingly. The latter enables |
| 5767 | /// the caller of the selector to process them afterwards instead of just |
| 5768 | /// dropping them. If no suitable tool is found, null will be returned. |
| 5769 | const Tool *getTool(ActionList &Inputs, |
| 5770 | ActionList &CollapsedOffloadAction) { |
| 5771 | // |
| 5772 | // Get the largest chain of actions that we could combine. |
| 5773 | // |
| 5774 | |
| 5775 | SmallVector<JobActionInfo, 5> ActionChain(1); |
| 5776 | ActionChain.back().JA = BaseAction; |
| 5777 | while (ActionChain.back().JA) { |
| 5778 | const Action *CurAction = ActionChain.back().JA; |
| 5779 | |
| 5780 | // Grow the chain by one element. |
| 5781 | ActionChain.resize(N: ActionChain.size() + 1); |
| 5782 | JobActionInfo &AI = ActionChain.back(); |
| 5783 | |
| 5784 | // Attempt to fill it with the |
| 5785 | AI.JA = |
| 5786 | getPrevDependentAction(Inputs: CurAction->getInputs(), SavedOffloadAction&: AI.SavedOffloadAction); |
| 5787 | } |
| 5788 | |
| 5789 | // Pop the last action info as it could not be filled. |
| 5790 | ActionChain.pop_back(); |
| 5791 | |
| 5792 | // |
| 5793 | // Attempt to combine actions. If all combining attempts failed, just return |
| 5794 | // the tool of the provided action. At the end we attempt to combine the |
| 5795 | // action with any preprocessor action it may depend on. |
| 5796 | // |
| 5797 | |
| 5798 | const Tool *T = combineAssembleBackendCompile(ActionInfo: ActionChain, Inputs, |
| 5799 | CollapsedOffloadAction); |
| 5800 | if (!T) |
| 5801 | T = combineAssembleBackend(ActionInfo: ActionChain, Inputs, CollapsedOffloadAction); |
| 5802 | if (!T) |
| 5803 | T = combineBackendCompile(ActionInfo: ActionChain, Inputs, CollapsedOffloadAction); |
| 5804 | if (!T) { |
| 5805 | Inputs = BaseAction->getInputs(); |
| 5806 | T = TC.SelectTool(JA: *BaseAction); |
| 5807 | } |
| 5808 | |
| 5809 | combineWithPreprocessor(T, Inputs, CollapsedOffloadAction); |
| 5810 | return T; |
| 5811 | } |
| 5812 | }; |
| 5813 | } |
| 5814 | |
| 5815 | /// Return a string that uniquely identifies the result of a job. The bound arch |
| 5816 | /// is not necessarily represented in the toolchain's triple -- for example, |
| 5817 | /// armv7 and armv7s both map to the same triple -- so we need both in our map. |
| 5818 | /// Also, we need to add the offloading device kind, as the same tool chain can |
| 5819 | /// be used for host and device for some programming models, e.g. OpenMP. |
| 5820 | static std::string GetTriplePlusArchString(const ToolChain *TC, |
| 5821 | StringRef BoundArch, |
| 5822 | Action::OffloadKind OffloadKind) { |
| 5823 | std::string TriplePlusArch = TC->getTriple().normalize(); |
| 5824 | if (!BoundArch.empty()) { |
| 5825 | TriplePlusArch += "-" ; |
| 5826 | TriplePlusArch += BoundArch; |
| 5827 | } |
| 5828 | TriplePlusArch += "-" ; |
| 5829 | TriplePlusArch += Action::GetOffloadKindName(Kind: OffloadKind); |
| 5830 | return TriplePlusArch; |
| 5831 | } |
| 5832 | |
| 5833 | InputInfoList Driver::BuildJobsForAction( |
| 5834 | Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, |
| 5835 | bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, |
| 5836 | std::map<std::pair<const Action *, std::string>, InputInfoList> |
| 5837 | &CachedResults, |
| 5838 | Action::OffloadKind TargetDeviceOffloadKind) const { |
| 5839 | std::pair<const Action *, std::string> ActionTC = { |
| 5840 | A, GetTriplePlusArchString(TC, BoundArch, OffloadKind: TargetDeviceOffloadKind)}; |
| 5841 | auto CachedResult = CachedResults.find(x: ActionTC); |
| 5842 | if (CachedResult != CachedResults.end()) { |
| 5843 | return CachedResult->second; |
| 5844 | } |
| 5845 | InputInfoList Result = BuildJobsForActionNoCache( |
| 5846 | C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput, |
| 5847 | CachedResults, TargetDeviceOffloadKind); |
| 5848 | CachedResults[ActionTC] = Result; |
| 5849 | return Result; |
| 5850 | } |
| 5851 | |
| 5852 | static void handleTimeTrace(Compilation &C, const ArgList &Args, |
| 5853 | const JobAction *JA, const char *BaseInput, |
| 5854 | const InputInfo &Result) { |
| 5855 | Arg *A = |
| 5856 | Args.getLastArg(Ids: options::OPT_ftime_trace, Ids: options::OPT_ftime_trace_EQ); |
| 5857 | if (!A) |
| 5858 | return; |
| 5859 | SmallString<128> Path; |
| 5860 | if (A->getOption().matches(ID: options::OPT_ftime_trace_EQ)) { |
| 5861 | Path = A->getValue(); |
| 5862 | if (llvm::sys::fs::is_directory(Path)) { |
| 5863 | SmallString<128> Tmp(Result.getFilename()); |
| 5864 | llvm::sys::path::replace_extension(path&: Tmp, extension: "json" ); |
| 5865 | llvm::sys::path::append(path&: Path, a: llvm::sys::path::filename(path: Tmp)); |
| 5866 | } |
| 5867 | } else { |
| 5868 | if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) { |
| 5869 | // The trace file is ${dumpdir}${basename}.json. Note that dumpdir may not |
| 5870 | // end with a path separator. |
| 5871 | Path = DumpDir->getValue(); |
| 5872 | Path += llvm::sys::path::filename(path: BaseInput); |
| 5873 | } else { |
| 5874 | Path = Result.getFilename(); |
| 5875 | } |
| 5876 | llvm::sys::path::replace_extension(path&: Path, extension: "json" ); |
| 5877 | } |
| 5878 | const char *ResultFile = C.getArgs().MakeArgString(Str: Path); |
| 5879 | C.addTimeTraceFile(Name: ResultFile, JA); |
| 5880 | C.addResultFile(Name: ResultFile, JA); |
| 5881 | } |
| 5882 | |
| 5883 | InputInfoList Driver::BuildJobsForActionNoCache( |
| 5884 | Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, |
| 5885 | bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, |
| 5886 | std::map<std::pair<const Action *, std::string>, InputInfoList> |
| 5887 | &CachedResults, |
| 5888 | Action::OffloadKind TargetDeviceOffloadKind) const { |
| 5889 | llvm::PrettyStackTraceString CrashInfo("Building compilation jobs" ); |
| 5890 | |
| 5891 | InputInfoList OffloadDependencesInputInfo; |
| 5892 | bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None; |
| 5893 | if (const OffloadAction *OA = dyn_cast<OffloadAction>(Val: A)) { |
| 5894 | // The 'Darwin' toolchain is initialized only when its arguments are |
| 5895 | // computed. Get the default arguments for OFK_None to ensure that |
| 5896 | // initialization is performed before processing the offload action. |
| 5897 | // FIXME: Remove when darwin's toolchain is initialized during construction. |
| 5898 | C.getArgsForToolChain(TC, BoundArch, DeviceOffloadKind: Action::OFK_None); |
| 5899 | |
| 5900 | // The offload action is expected to be used in four different situations. |
| 5901 | // |
| 5902 | // a) Set a toolchain/architecture/kind for a host action: |
| 5903 | // Host Action 1 -> OffloadAction -> Host Action 2 |
| 5904 | // |
| 5905 | // b) Set a toolchain/architecture/kind for a device action; |
| 5906 | // Device Action 1 -> OffloadAction -> Device Action 2 |
| 5907 | // |
| 5908 | // c) Specify a device dependence to a host action; |
| 5909 | // Device Action 1 _ |
| 5910 | // \ |
| 5911 | // Host Action 1 ---> OffloadAction -> Host Action 2 |
| 5912 | // |
| 5913 | // d) Specify a host dependence to a device action. |
| 5914 | // Host Action 1 _ |
| 5915 | // \ |
| 5916 | // Device Action 1 ---> OffloadAction -> Device Action 2 |
| 5917 | // |
| 5918 | // For a) and b), we just return the job generated for the dependences. For |
| 5919 | // c) and d) we override the current action with the host/device dependence |
| 5920 | // if the current toolchain is host/device and set the offload dependences |
| 5921 | // info with the jobs obtained from the device/host dependence(s). |
| 5922 | |
| 5923 | // If there is a single device option or has no host action, just generate |
| 5924 | // the job for it. |
| 5925 | if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) { |
| 5926 | InputInfoList DevA; |
| 5927 | OA->doOnEachDeviceDependence(Work: [&](Action *DepA, const ToolChain *DepTC, |
| 5928 | const char *DepBoundArch) { |
| 5929 | DevA.append(RHS: BuildJobsForAction(C, A: DepA, TC: DepTC, BoundArch: DepBoundArch, AtTopLevel, |
| 5930 | /*MultipleArchs*/ !!DepBoundArch, |
| 5931 | LinkingOutput, CachedResults, |
| 5932 | TargetDeviceOffloadKind: DepA->getOffloadingDeviceKind())); |
| 5933 | }); |
| 5934 | return DevA; |
| 5935 | } |
| 5936 | |
| 5937 | // If 'Action 2' is host, we generate jobs for the device dependences and |
| 5938 | // override the current action with the host dependence. Otherwise, we |
| 5939 | // generate the host dependences and override the action with the device |
| 5940 | // dependence. The dependences can't therefore be a top-level action. |
| 5941 | OA->doOnEachDependence( |
| 5942 | /*IsHostDependence=*/BuildingForOffloadDevice, |
| 5943 | Work: [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { |
| 5944 | OffloadDependencesInputInfo.append(RHS: BuildJobsForAction( |
| 5945 | C, A: DepA, TC: DepTC, BoundArch: DepBoundArch, /*AtTopLevel=*/false, |
| 5946 | /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, |
| 5947 | TargetDeviceOffloadKind: DepA->getOffloadingDeviceKind())); |
| 5948 | }); |
| 5949 | |
| 5950 | A = BuildingForOffloadDevice |
| 5951 | ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) |
| 5952 | : OA->getHostDependence(); |
| 5953 | |
| 5954 | // We may have already built this action as a part of the offloading |
| 5955 | // toolchain, return the cached input if so. |
| 5956 | std::pair<const Action *, std::string> ActionTC = { |
| 5957 | OA->getHostDependence(), |
| 5958 | GetTriplePlusArchString(TC, BoundArch, OffloadKind: TargetDeviceOffloadKind)}; |
| 5959 | auto It = CachedResults.find(x: ActionTC); |
| 5960 | if (It != CachedResults.end()) { |
| 5961 | InputInfoList Inputs = It->second; |
| 5962 | Inputs.append(RHS: OffloadDependencesInputInfo); |
| 5963 | return Inputs; |
| 5964 | } |
| 5965 | } |
| 5966 | |
| 5967 | if (const InputAction *IA = dyn_cast<InputAction>(Val: A)) { |
| 5968 | // FIXME: It would be nice to not claim this here; maybe the old scheme of |
| 5969 | // just using Args was better? |
| 5970 | const Arg &Input = IA->getInputArg(); |
| 5971 | Input.claim(); |
| 5972 | if (Input.getOption().matches(ID: options::OPT_INPUT)) { |
| 5973 | const char *Name = Input.getValue(); |
| 5974 | return {InputInfo(A, Name, /* _BaseInput = */ Name)}; |
| 5975 | } |
| 5976 | return {InputInfo(A, &Input, /* _BaseInput = */ "" )}; |
| 5977 | } |
| 5978 | |
| 5979 | if (const BindArchAction *BAA = dyn_cast<BindArchAction>(Val: A)) { |
| 5980 | const ToolChain *TC; |
| 5981 | StringRef ArchName = BAA->getArchName(); |
| 5982 | |
| 5983 | if (!ArchName.empty()) |
| 5984 | TC = &getToolChain(Args: C.getArgs(), |
| 5985 | Target: computeTargetTriple(D: *this, TargetTriple, |
| 5986 | Args: C.getArgs(), DarwinArchName: ArchName)); |
| 5987 | else |
| 5988 | TC = &C.getDefaultToolChain(); |
| 5989 | |
| 5990 | return BuildJobsForAction(C, A: *BAA->input_begin(), TC, BoundArch: ArchName, AtTopLevel, |
| 5991 | MultipleArchs, LinkingOutput, CachedResults, |
| 5992 | TargetDeviceOffloadKind); |
| 5993 | } |
| 5994 | |
| 5995 | |
| 5996 | ActionList Inputs = A->getInputs(); |
| 5997 | |
| 5998 | const JobAction *JA = cast<JobAction>(Val: A); |
| 5999 | ActionList CollapsedOffloadActions; |
| 6000 | |
| 6001 | ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), |
| 6002 | embedBitcodeInObject() && !isUsingLTO()); |
| 6003 | const Tool *T = TS.getTool(Inputs, CollapsedOffloadAction&: CollapsedOffloadActions); |
| 6004 | |
| 6005 | if (!T) |
| 6006 | return {InputInfo()}; |
| 6007 | |
| 6008 | // If we've collapsed action list that contained OffloadAction we |
| 6009 | // need to build jobs for host/device-side inputs it may have held. |
| 6010 | for (const auto *OA : CollapsedOffloadActions) |
| 6011 | cast<OffloadAction>(Val: OA)->doOnEachDependence( |
| 6012 | /*IsHostDependence=*/BuildingForOffloadDevice, |
| 6013 | Work: [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { |
| 6014 | OffloadDependencesInputInfo.append(RHS: BuildJobsForAction( |
| 6015 | C, A: DepA, TC: DepTC, BoundArch: DepBoundArch, /* AtTopLevel */ false, |
| 6016 | /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, |
| 6017 | TargetDeviceOffloadKind: DepA->getOffloadingDeviceKind())); |
| 6018 | }); |
| 6019 | |
| 6020 | // Only use pipes when there is exactly one input. |
| 6021 | InputInfoList InputInfos; |
| 6022 | for (const Action *Input : Inputs) { |
| 6023 | // Treat dsymutil and verify sub-jobs as being at the top-level too, they |
| 6024 | // shouldn't get temporary output names. |
| 6025 | // FIXME: Clean this up. |
| 6026 | bool SubJobAtTopLevel = |
| 6027 | AtTopLevel && (isa<DsymutilJobAction>(Val: A) || isa<VerifyJobAction>(Val: A)); |
| 6028 | InputInfos.append(RHS: BuildJobsForAction( |
| 6029 | C, A: Input, TC, BoundArch, AtTopLevel: SubJobAtTopLevel, MultipleArchs, LinkingOutput, |
| 6030 | CachedResults, TargetDeviceOffloadKind: A->getOffloadingDeviceKind())); |
| 6031 | } |
| 6032 | |
| 6033 | // Always use the first file input as the base input. |
| 6034 | const char *BaseInput = InputInfos[0].getBaseInput(); |
| 6035 | for (auto &Info : InputInfos) { |
| 6036 | if (Info.isFilename()) { |
| 6037 | BaseInput = Info.getBaseInput(); |
| 6038 | break; |
| 6039 | } |
| 6040 | } |
| 6041 | |
| 6042 | // ... except dsymutil actions, which use their actual input as the base |
| 6043 | // input. |
| 6044 | if (JA->getType() == types::TY_dSYM) |
| 6045 | BaseInput = InputInfos[0].getFilename(); |
| 6046 | |
| 6047 | // Append outputs of offload device jobs to the input list |
| 6048 | if (!OffloadDependencesInputInfo.empty()) |
| 6049 | InputInfos.append(in_start: OffloadDependencesInputInfo.begin(), |
| 6050 | in_end: OffloadDependencesInputInfo.end()); |
| 6051 | |
| 6052 | // Set the effective triple of the toolchain for the duration of this job. |
| 6053 | llvm::Triple EffectiveTriple; |
| 6054 | const ToolChain &ToolTC = T->getToolChain(); |
| 6055 | const ArgList &Args = |
| 6056 | C.getArgsForToolChain(TC, BoundArch, DeviceOffloadKind: A->getOffloadingDeviceKind()); |
| 6057 | if (InputInfos.size() != 1) { |
| 6058 | EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args)); |
| 6059 | } else { |
| 6060 | // Pass along the input type if it can be unambiguously determined. |
| 6061 | EffectiveTriple = llvm::Triple( |
| 6062 | ToolTC.ComputeEffectiveClangTriple(Args, InputType: InputInfos[0].getType())); |
| 6063 | } |
| 6064 | RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple); |
| 6065 | |
| 6066 | // Determine the place to write output to, if any. |
| 6067 | InputInfo Result; |
| 6068 | InputInfoList UnbundlingResults; |
| 6069 | if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(Val: JA)) { |
| 6070 | // If we have an unbundling job, we need to create results for all the |
| 6071 | // outputs. We also update the results cache so that other actions using |
| 6072 | // this unbundling action can get the right results. |
| 6073 | for (auto &UI : UA->getDependentActionsInfo()) { |
| 6074 | assert(UI.DependentOffloadKind != Action::OFK_None && |
| 6075 | "Unbundling with no offloading??" ); |
| 6076 | |
| 6077 | // Unbundling actions are never at the top level. When we generate the |
| 6078 | // offloading prefix, we also do that for the host file because the |
| 6079 | // unbundling action does not change the type of the output which can |
| 6080 | // cause a overwrite. |
| 6081 | std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( |
| 6082 | Kind: UI.DependentOffloadKind, |
| 6083 | NormalizedTriple: UI.DependentToolChain->getTriple().normalize(), |
| 6084 | /*CreatePrefixForHost=*/true); |
| 6085 | auto CurI = InputInfo( |
| 6086 | UA, |
| 6087 | GetNamedOutputPath(C, JA: *UA, BaseInput, BoundArch: UI.DependentBoundArch, |
| 6088 | /*AtTopLevel=*/false, |
| 6089 | MultipleArchs: MultipleArchs || |
| 6090 | UI.DependentOffloadKind == Action::OFK_HIP, |
| 6091 | NormalizedTriple: OffloadingPrefix), |
| 6092 | BaseInput); |
| 6093 | // Save the unbundling result. |
| 6094 | UnbundlingResults.push_back(Elt: CurI); |
| 6095 | |
| 6096 | // Get the unique string identifier for this dependence and cache the |
| 6097 | // result. |
| 6098 | StringRef Arch; |
| 6099 | if (TargetDeviceOffloadKind == Action::OFK_HIP) { |
| 6100 | if (UI.DependentOffloadKind == Action::OFK_Host) |
| 6101 | Arch = StringRef(); |
| 6102 | else |
| 6103 | Arch = UI.DependentBoundArch; |
| 6104 | } else |
| 6105 | Arch = BoundArch; |
| 6106 | |
| 6107 | CachedResults[{A, GetTriplePlusArchString(TC: UI.DependentToolChain, BoundArch: Arch, |
| 6108 | OffloadKind: UI.DependentOffloadKind)}] = { |
| 6109 | CurI}; |
| 6110 | } |
| 6111 | |
| 6112 | // Now that we have all the results generated, select the one that should be |
| 6113 | // returned for the current depending action. |
| 6114 | std::pair<const Action *, std::string> ActionTC = { |
| 6115 | A, GetTriplePlusArchString(TC, BoundArch, OffloadKind: TargetDeviceOffloadKind)}; |
| 6116 | assert(CachedResults.find(ActionTC) != CachedResults.end() && |
| 6117 | "Result does not exist??" ); |
| 6118 | Result = CachedResults[ActionTC].front(); |
| 6119 | } else if (JA->getType() == types::TY_Nothing) |
| 6120 | Result = {InputInfo(A, BaseInput)}; |
| 6121 | else { |
| 6122 | // We only have to generate a prefix for the host if this is not a top-level |
| 6123 | // action. |
| 6124 | std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( |
| 6125 | Kind: A->getOffloadingDeviceKind(), NormalizedTriple: EffectiveTriple.normalize(), |
| 6126 | /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(Val: A) || |
| 6127 | !(A->getOffloadingHostActiveKinds() == Action::OFK_None || |
| 6128 | AtTopLevel)); |
| 6129 | Result = InputInfo(A, GetNamedOutputPath(C, JA: *JA, BaseInput, BoundArch, |
| 6130 | AtTopLevel, MultipleArchs, |
| 6131 | NormalizedTriple: OffloadingPrefix), |
| 6132 | BaseInput); |
| 6133 | if (T->canEmitIR() && OffloadingPrefix.empty()) |
| 6134 | handleTimeTrace(C, Args, JA, BaseInput, Result); |
| 6135 | } |
| 6136 | |
| 6137 | if (CCCPrintBindings && !CCGenDiagnostics) { |
| 6138 | llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' |
| 6139 | << " - \"" << T->getName() << "\", inputs: [" ; |
| 6140 | for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { |
| 6141 | llvm::errs() << InputInfos[i].getAsString(); |
| 6142 | if (i + 1 != e) |
| 6143 | llvm::errs() << ", " ; |
| 6144 | } |
| 6145 | if (UnbundlingResults.empty()) |
| 6146 | llvm::errs() << "], output: " << Result.getAsString() << "\n" ; |
| 6147 | else { |
| 6148 | llvm::errs() << "], outputs: [" ; |
| 6149 | for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) { |
| 6150 | llvm::errs() << UnbundlingResults[i].getAsString(); |
| 6151 | if (i + 1 != e) |
| 6152 | llvm::errs() << ", " ; |
| 6153 | } |
| 6154 | llvm::errs() << "] \n" ; |
| 6155 | } |
| 6156 | } else { |
| 6157 | if (UnbundlingResults.empty()) |
| 6158 | T->ConstructJob(C, JA: *JA, Output: Result, Inputs: InputInfos, TCArgs: Args, LinkingOutput); |
| 6159 | else |
| 6160 | T->ConstructJobMultipleOutputs(C, JA: *JA, Outputs: UnbundlingResults, Inputs: InputInfos, |
| 6161 | TCArgs: Args, LinkingOutput); |
| 6162 | } |
| 6163 | return {Result}; |
| 6164 | } |
| 6165 | |
| 6166 | const char *Driver::getDefaultImageName() const { |
| 6167 | llvm::Triple Target(llvm::Triple::normalize(Str: TargetTriple)); |
| 6168 | return Target.isOSWindows() ? "a.exe" : "a.out" ; |
| 6169 | } |
| 6170 | |
| 6171 | /// Create output filename based on ArgValue, which could either be a |
| 6172 | /// full filename, filename without extension, or a directory. If ArgValue |
| 6173 | /// does not provide a filename, then use BaseName, and use the extension |
| 6174 | /// suitable for FileType. |
| 6175 | static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, |
| 6176 | StringRef BaseName, |
| 6177 | types::ID FileType) { |
| 6178 | SmallString<128> Filename = ArgValue; |
| 6179 | |
| 6180 | if (ArgValue.empty()) { |
| 6181 | // If the argument is empty, output to BaseName in the current dir. |
| 6182 | Filename = BaseName; |
| 6183 | } else if (llvm::sys::path::is_separator(value: Filename.back())) { |
| 6184 | // If the argument is a directory, output to BaseName in that dir. |
| 6185 | llvm::sys::path::append(path&: Filename, a: BaseName); |
| 6186 | } |
| 6187 | |
| 6188 | if (!llvm::sys::path::has_extension(path: ArgValue)) { |
| 6189 | // If the argument didn't provide an extension, then set it. |
| 6190 | const char *Extension = types::getTypeTempSuffix(Id: FileType, CLStyle: true); |
| 6191 | |
| 6192 | if (FileType == types::TY_Image && |
| 6193 | Args.hasArg(Ids: options::OPT__SLASH_LD, Ids: options::OPT__SLASH_LDd)) { |
| 6194 | // The output file is a dll. |
| 6195 | Extension = "dll" ; |
| 6196 | } |
| 6197 | |
| 6198 | llvm::sys::path::replace_extension(path&: Filename, extension: Extension); |
| 6199 | } |
| 6200 | |
| 6201 | return Args.MakeArgString(Str: Filename.c_str()); |
| 6202 | } |
| 6203 | |
| 6204 | static bool HasPreprocessOutput(const Action &JA) { |
| 6205 | if (isa<PreprocessJobAction>(Val: JA)) |
| 6206 | return true; |
| 6207 | if (isa<OffloadAction>(Val: JA) && isa<PreprocessJobAction>(Val: JA.getInputs()[0])) |
| 6208 | return true; |
| 6209 | if (isa<OffloadBundlingJobAction>(Val: JA) && |
| 6210 | HasPreprocessOutput(JA: *(JA.getInputs()[0]))) |
| 6211 | return true; |
| 6212 | return false; |
| 6213 | } |
| 6214 | |
| 6215 | const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix, |
| 6216 | StringRef Suffix, bool MultipleArchs, |
| 6217 | StringRef BoundArch, |
| 6218 | bool NeedUniqueDirectory) const { |
| 6219 | SmallString<128> TmpName; |
| 6220 | Arg *A = C.getArgs().getLastArg(Ids: options::OPT_fcrash_diagnostics_dir); |
| 6221 | std::optional<std::string> CrashDirectory = |
| 6222 | CCGenDiagnostics && A |
| 6223 | ? std::string(A->getValue()) |
| 6224 | : llvm::sys::Process::GetEnv(name: "CLANG_CRASH_DIAGNOSTICS_DIR" ); |
| 6225 | if (CrashDirectory) { |
| 6226 | if (!getVFS().exists(Path: *CrashDirectory)) |
| 6227 | llvm::sys::fs::create_directories(path: *CrashDirectory); |
| 6228 | SmallString<128> Path(*CrashDirectory); |
| 6229 | llvm::sys::path::append(path&: Path, a: Prefix); |
| 6230 | const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%" ; |
| 6231 | if (std::error_code EC = |
| 6232 | llvm::sys::fs::createUniqueFile(Model: Path + Middle + Suffix, ResultPath&: TmpName)) { |
| 6233 | Diag(DiagID: clang::diag::err_unable_to_make_temp) << EC.message(); |
| 6234 | return "" ; |
| 6235 | } |
| 6236 | } else { |
| 6237 | if (MultipleArchs && !BoundArch.empty()) { |
| 6238 | if (NeedUniqueDirectory) { |
| 6239 | TmpName = GetTemporaryDirectory(Prefix); |
| 6240 | llvm::sys::path::append(path&: TmpName, |
| 6241 | a: Twine(Prefix) + "-" + BoundArch + "." + Suffix); |
| 6242 | } else { |
| 6243 | TmpName = |
| 6244 | GetTemporaryPath(Prefix: (Twine(Prefix) + "-" + BoundArch).str(), Suffix); |
| 6245 | } |
| 6246 | |
| 6247 | } else { |
| 6248 | TmpName = GetTemporaryPath(Prefix, Suffix); |
| 6249 | } |
| 6250 | } |
| 6251 | return C.addTempFile(Name: C.getArgs().MakeArgString(Str: TmpName)); |
| 6252 | } |
| 6253 | |
| 6254 | // Calculate the output path of the module file when compiling a module unit |
| 6255 | // with the `-fmodule-output` option or `-fmodule-output=` option specified. |
| 6256 | // The behavior is: |
| 6257 | // - If `-fmodule-output=` is specfied, then the module file is |
| 6258 | // writing to the value. |
| 6259 | // - Otherwise if the output object file of the module unit is specified, the |
| 6260 | // output path |
| 6261 | // of the module file should be the same with the output object file except |
| 6262 | // the corresponding suffix. This requires both `-o` and `-c` are specified. |
| 6263 | // - Otherwise, the output path of the module file will be the same with the |
| 6264 | // input with the corresponding suffix. |
| 6265 | static const char *GetModuleOutputPath(Compilation &C, const JobAction &JA, |
| 6266 | const char *BaseInput) { |
| 6267 | assert(isa<PrecompileJobAction>(JA) && JA.getType() == types::TY_ModuleFile && |
| 6268 | (C.getArgs().hasArg(options::OPT_fmodule_output) || |
| 6269 | C.getArgs().hasArg(options::OPT_fmodule_output_EQ))); |
| 6270 | |
| 6271 | SmallString<256> OutputPath = |
| 6272 | tools::getCXX20NamedModuleOutputPath(Args: C.getArgs(), BaseInput); |
| 6273 | |
| 6274 | return C.addResultFile(Name: C.getArgs().MakeArgString(Str: OutputPath.c_str()), JA: &JA); |
| 6275 | } |
| 6276 | |
| 6277 | const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, |
| 6278 | const char *BaseInput, |
| 6279 | StringRef OrigBoundArch, bool AtTopLevel, |
| 6280 | bool MultipleArchs, |
| 6281 | StringRef OffloadingPrefix) const { |
| 6282 | std::string BoundArch = sanitizeTargetIDInFileName(TargetID: OrigBoundArch); |
| 6283 | |
| 6284 | llvm::PrettyStackTraceString CrashInfo("Computing output path" ); |
| 6285 | // Output to a user requested destination? |
| 6286 | if (AtTopLevel && !isa<DsymutilJobAction>(Val: JA) && !isa<VerifyJobAction>(Val: JA)) { |
| 6287 | if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) |
| 6288 | return C.addResultFile(Name: FinalOutput->getValue(), JA: &JA); |
| 6289 | } |
| 6290 | |
| 6291 | // For /P, preprocess to file named after BaseInput. |
| 6292 | if (C.getArgs().hasArg(Ids: options::OPT__SLASH_P)) { |
| 6293 | assert(AtTopLevel && isa<PreprocessJobAction>(JA)); |
| 6294 | StringRef BaseName = llvm::sys::path::filename(path: BaseInput); |
| 6295 | StringRef NameArg; |
| 6296 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fi)) |
| 6297 | NameArg = A->getValue(); |
| 6298 | return C.addResultFile( |
| 6299 | Name: MakeCLOutputFilename(Args: C.getArgs(), ArgValue: NameArg, BaseName, FileType: types::TY_PP_C), |
| 6300 | JA: &JA); |
| 6301 | } |
| 6302 | |
| 6303 | // Default to writing to stdout? |
| 6304 | if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) { |
| 6305 | return "-" ; |
| 6306 | } |
| 6307 | |
| 6308 | if (JA.getType() == types::TY_ModuleFile && |
| 6309 | C.getArgs().getLastArg(Ids: options::OPT_module_file_info)) { |
| 6310 | return "-" ; |
| 6311 | } |
| 6312 | |
| 6313 | if (JA.getType() == types::TY_PP_Asm && |
| 6314 | C.getArgs().hasArg(Ids: options::OPT_dxc_Fc)) { |
| 6315 | StringRef FcValue = C.getArgs().getLastArgValue(Id: options::OPT_dxc_Fc); |
| 6316 | // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably |
| 6317 | // handle this as part of the SLASH_Fa handling below. |
| 6318 | return C.addResultFile(Name: C.getArgs().MakeArgString(Str: FcValue.str()), JA: &JA); |
| 6319 | } |
| 6320 | |
| 6321 | if ((JA.getType() == types::TY_Object && |
| 6322 | C.getArgs().hasArg(Ids: options::OPT_dxc_Fo)) || |
| 6323 | JA.getType() == types::TY_DX_CONTAINER) { |
| 6324 | StringRef FoValue = C.getArgs().getLastArgValue(Id: options::OPT_dxc_Fo); |
| 6325 | // If we are targeting DXIL and not validating/translating/objcopying, we |
| 6326 | // should set the final result file. Otherwise we should emit to a |
| 6327 | // temporary. |
| 6328 | if (C.getDefaultToolChain().getTriple().isDXIL()) { |
| 6329 | const auto &TC = static_cast<const toolchains::HLSLToolChain &>( |
| 6330 | C.getDefaultToolChain()); |
| 6331 | // Fo can be empty here if the validator is running for a compiler flow |
| 6332 | // that is using Fc or just printing disassembly. |
| 6333 | if (TC.isLastJob(Args&: C.getArgs(), AC: JA.getKind()) && !FoValue.empty()) |
| 6334 | return C.addResultFile(Name: C.getArgs().MakeArgString(Str: FoValue.str()), JA: &JA); |
| 6335 | StringRef Name = llvm::sys::path::filename(path: BaseInput); |
| 6336 | std::pair<StringRef, StringRef> Split = Name.split(Separator: '.'); |
| 6337 | const char *Suffix = types::getTypeTempSuffix(Id: JA.getType(), CLStyle: true); |
| 6338 | return CreateTempFile(C, Prefix: Split.first, Suffix, MultipleArchs: false); |
| 6339 | } |
| 6340 | // We don't have SPIRV-val integrated (yet), so for now we can assume this |
| 6341 | // is the final output. |
| 6342 | assert(C.getDefaultToolChain().getTriple().isSPIRV()); |
| 6343 | return C.addResultFile(Name: C.getArgs().MakeArgString(Str: FoValue.str()), JA: &JA); |
| 6344 | } |
| 6345 | |
| 6346 | // Is this the assembly listing for /FA? |
| 6347 | if (JA.getType() == types::TY_PP_Asm && |
| 6348 | (C.getArgs().hasArg(Ids: options::OPT__SLASH_FA) || |
| 6349 | C.getArgs().hasArg(Ids: options::OPT__SLASH_Fa))) { |
| 6350 | // Use /Fa and the input filename to determine the asm file name. |
| 6351 | StringRef BaseName = llvm::sys::path::filename(path: BaseInput); |
| 6352 | StringRef FaValue = C.getArgs().getLastArgValue(Id: options::OPT__SLASH_Fa); |
| 6353 | return C.addResultFile( |
| 6354 | Name: MakeCLOutputFilename(Args: C.getArgs(), ArgValue: FaValue, BaseName, FileType: JA.getType()), |
| 6355 | JA: &JA); |
| 6356 | } |
| 6357 | |
| 6358 | if (JA.getType() == types::TY_API_INFO && |
| 6359 | C.getArgs().hasArg(Ids: options::OPT_emit_extension_symbol_graphs) && |
| 6360 | C.getArgs().hasArg(Ids: options::OPT_o)) |
| 6361 | Diag(DiagID: clang::diag::err_drv_unexpected_symbol_graph_output) |
| 6362 | << C.getArgs().getLastArgValue(Id: options::OPT_o); |
| 6363 | |
| 6364 | // DXC defaults to standard out when generating assembly. We check this after |
| 6365 | // any DXC flags that might specify a file. |
| 6366 | if (AtTopLevel && JA.getType() == types::TY_PP_Asm && IsDXCMode()) |
| 6367 | return "-" ; |
| 6368 | |
| 6369 | bool SpecifiedModuleOutput = |
| 6370 | C.getArgs().hasArg(Ids: options::OPT_fmodule_output) || |
| 6371 | C.getArgs().hasArg(Ids: options::OPT_fmodule_output_EQ); |
| 6372 | if (MultipleArchs && SpecifiedModuleOutput) |
| 6373 | Diag(DiagID: clang::diag::err_drv_module_output_with_multiple_arch); |
| 6374 | |
| 6375 | // If we're emitting a module output with the specified option |
| 6376 | // `-fmodule-output`. |
| 6377 | if (!AtTopLevel && isa<PrecompileJobAction>(Val: JA) && |
| 6378 | JA.getType() == types::TY_ModuleFile && SpecifiedModuleOutput) { |
| 6379 | assert(C.getArgs().hasArg(options::OPT_fno_modules_reduced_bmi)); |
| 6380 | return GetModuleOutputPath(C, JA, BaseInput); |
| 6381 | } |
| 6382 | |
| 6383 | // Output to a temporary file? |
| 6384 | if ((!AtTopLevel && !isSaveTempsEnabled() && |
| 6385 | !C.getArgs().hasArg(Ids: options::OPT__SLASH_Fo)) || |
| 6386 | CCGenDiagnostics) { |
| 6387 | StringRef Name = llvm::sys::path::filename(path: BaseInput); |
| 6388 | std::pair<StringRef, StringRef> Split = Name.split(Separator: '.'); |
| 6389 | const char *Suffix = |
| 6390 | types::getTypeTempSuffix(Id: JA.getType(), CLStyle: IsCLMode() || IsDXCMode()); |
| 6391 | // The non-offloading toolchain on Darwin requires deterministic input |
| 6392 | // file name for binaries to be deterministic, therefore it needs unique |
| 6393 | // directory. |
| 6394 | llvm::Triple Triple(C.getDriver().getTargetTriple()); |
| 6395 | bool NeedUniqueDirectory = |
| 6396 | (JA.getOffloadingDeviceKind() == Action::OFK_None || |
| 6397 | JA.getOffloadingDeviceKind() == Action::OFK_Host) && |
| 6398 | Triple.isOSDarwin(); |
| 6399 | return CreateTempFile(C, Prefix: Split.first, Suffix, MultipleArchs, BoundArch, |
| 6400 | NeedUniqueDirectory); |
| 6401 | } |
| 6402 | |
| 6403 | SmallString<128> BasePath(BaseInput); |
| 6404 | SmallString<128> ExternalPath("" ); |
| 6405 | StringRef BaseName; |
| 6406 | |
| 6407 | // Dsymutil actions should use the full path. |
| 6408 | if (isa<DsymutilJobAction>(Val: JA) && C.getArgs().hasArg(Ids: options::OPT_dsym_dir)) { |
| 6409 | ExternalPath += C.getArgs().getLastArg(Ids: options::OPT_dsym_dir)->getValue(); |
| 6410 | // We use posix style here because the tests (specifically |
| 6411 | // darwin-dsymutil.c) demonstrate that posix style paths are acceptable |
| 6412 | // even on Windows and if we don't then the similar test covering this |
| 6413 | // fails. |
| 6414 | llvm::sys::path::append(path&: ExternalPath, style: llvm::sys::path::Style::posix, |
| 6415 | a: llvm::sys::path::filename(path: BasePath)); |
| 6416 | BaseName = ExternalPath; |
| 6417 | } else if (isa<DsymutilJobAction>(Val: JA) || isa<VerifyJobAction>(Val: JA)) |
| 6418 | BaseName = BasePath; |
| 6419 | else |
| 6420 | BaseName = llvm::sys::path::filename(path: BasePath); |
| 6421 | |
| 6422 | // Determine what the derived output name should be. |
| 6423 | const char *NamedOutput; |
| 6424 | |
| 6425 | if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) && |
| 6426 | C.getArgs().hasArg(Ids: options::OPT__SLASH_Fo, Ids: options::OPT__SLASH_o)) { |
| 6427 | // The /Fo or /o flag decides the object filename. |
| 6428 | StringRef Val = |
| 6429 | C.getArgs() |
| 6430 | .getLastArg(Ids: options::OPT__SLASH_Fo, Ids: options::OPT__SLASH_o) |
| 6431 | ->getValue(); |
| 6432 | NamedOutput = |
| 6433 | MakeCLOutputFilename(Args: C.getArgs(), ArgValue: Val, BaseName, FileType: types::TY_Object); |
| 6434 | } else if (JA.getType() == types::TY_Image && |
| 6435 | C.getArgs().hasArg(Ids: options::OPT__SLASH_Fe, |
| 6436 | Ids: options::OPT__SLASH_o)) { |
| 6437 | // The /Fe or /o flag names the linked file. |
| 6438 | StringRef Val = |
| 6439 | C.getArgs() |
| 6440 | .getLastArg(Ids: options::OPT__SLASH_Fe, Ids: options::OPT__SLASH_o) |
| 6441 | ->getValue(); |
| 6442 | NamedOutput = |
| 6443 | MakeCLOutputFilename(Args: C.getArgs(), ArgValue: Val, BaseName, FileType: types::TY_Image); |
| 6444 | } else if (JA.getType() == types::TY_Image) { |
| 6445 | if (IsCLMode()) { |
| 6446 | // clang-cl uses BaseName for the executable name. |
| 6447 | NamedOutput = |
| 6448 | MakeCLOutputFilename(Args: C.getArgs(), ArgValue: "" , BaseName, FileType: types::TY_Image); |
| 6449 | } else { |
| 6450 | SmallString<128> Output(getDefaultImageName()); |
| 6451 | // HIP image for device compilation with -fno-gpu-rdc is per compilation |
| 6452 | // unit. |
| 6453 | bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP && |
| 6454 | !C.getArgs().hasFlag(Pos: options::OPT_fgpu_rdc, |
| 6455 | Neg: options::OPT_fno_gpu_rdc, Default: false); |
| 6456 | bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(Val: JA); |
| 6457 | if (UseOutExtension) { |
| 6458 | Output = BaseName; |
| 6459 | llvm::sys::path::replace_extension(path&: Output, extension: "" ); |
| 6460 | } |
| 6461 | Output += OffloadingPrefix; |
| 6462 | if (MultipleArchs && !BoundArch.empty()) { |
| 6463 | Output += "-" ; |
| 6464 | Output.append(RHS: BoundArch); |
| 6465 | } |
| 6466 | if (UseOutExtension) |
| 6467 | Output += ".out" ; |
| 6468 | NamedOutput = C.getArgs().MakeArgString(Str: Output.c_str()); |
| 6469 | } |
| 6470 | } else if (JA.getType() == types::TY_PCH && IsCLMode()) { |
| 6471 | NamedOutput = C.getArgs().MakeArgString(Str: GetClPchPath(C, BaseName)); |
| 6472 | } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) && |
| 6473 | C.getArgs().hasArg(Ids: options::OPT__SLASH_o)) { |
| 6474 | StringRef Val = |
| 6475 | C.getArgs() |
| 6476 | .getLastArg(Ids: options::OPT__SLASH_o) |
| 6477 | ->getValue(); |
| 6478 | NamedOutput = |
| 6479 | MakeCLOutputFilename(Args: C.getArgs(), ArgValue: Val, BaseName, FileType: types::TY_Object); |
| 6480 | } else { |
| 6481 | const char *Suffix = |
| 6482 | types::getTypeTempSuffix(Id: JA.getType(), CLStyle: IsCLMode() || IsDXCMode()); |
| 6483 | assert(Suffix && "All types used for output should have a suffix." ); |
| 6484 | |
| 6485 | std::string::size_type End = std::string::npos; |
| 6486 | if (!types::appendSuffixForType(Id: JA.getType())) |
| 6487 | End = BaseName.rfind(C: '.'); |
| 6488 | SmallString<128> Suffixed(BaseName.substr(Start: 0, N: End)); |
| 6489 | Suffixed += OffloadingPrefix; |
| 6490 | if (MultipleArchs && !BoundArch.empty()) { |
| 6491 | Suffixed += "-" ; |
| 6492 | Suffixed.append(RHS: BoundArch); |
| 6493 | } |
| 6494 | // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for |
| 6495 | // the unoptimized bitcode so that it does not get overwritten by the ".bc" |
| 6496 | // optimized bitcode output. |
| 6497 | auto IsAMDRDCInCompilePhase = [](const JobAction &JA, |
| 6498 | const llvm::opt::DerivedArgList &Args) { |
| 6499 | // The relocatable compilation in HIP and OpenMP implies -emit-llvm. |
| 6500 | // Similarly, use a ".tmp.bc" suffix for the unoptimized bitcode |
| 6501 | // (generated in the compile phase.) |
| 6502 | const ToolChain *TC = JA.getOffloadingToolChain(); |
| 6503 | return isa<CompileJobAction>(Val: JA) && |
| 6504 | ((JA.getOffloadingDeviceKind() == Action::OFK_HIP && |
| 6505 | Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, |
| 6506 | Default: false)) || |
| 6507 | (JA.getOffloadingDeviceKind() == Action::OFK_OpenMP && TC && |
| 6508 | TC->getTriple().isAMDGPU())); |
| 6509 | }; |
| 6510 | |
| 6511 | // The linker wrapper may not support the input and output files to be the |
| 6512 | // same one, and without it -save-temps can fail. |
| 6513 | bool IsLinkerWrapper = |
| 6514 | JA.getType() == types::TY_Object && isa<LinkerWrapperJobAction>(Val: JA); |
| 6515 | bool IsEmitBitcode = JA.getType() == types::TY_LLVM_BC && |
| 6516 | (C.getArgs().hasArg(Ids: options::OPT_emit_llvm) || |
| 6517 | IsAMDRDCInCompilePhase(JA, C.getArgs())); |
| 6518 | |
| 6519 | if (!AtTopLevel && (IsLinkerWrapper || IsEmitBitcode)) |
| 6520 | Suffixed += ".tmp" ; |
| 6521 | Suffixed += '.'; |
| 6522 | Suffixed += Suffix; |
| 6523 | NamedOutput = C.getArgs().MakeArgString(Str: Suffixed.c_str()); |
| 6524 | } |
| 6525 | |
| 6526 | // Prepend object file path if -save-temps=obj |
| 6527 | if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(Ids: options::OPT_o) && |
| 6528 | JA.getType() != types::TY_PCH) { |
| 6529 | Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o); |
| 6530 | SmallString<128> TempPath(FinalOutput->getValue()); |
| 6531 | llvm::sys::path::remove_filename(path&: TempPath); |
| 6532 | StringRef OutputFileName = llvm::sys::path::filename(path: NamedOutput); |
| 6533 | llvm::sys::path::append(path&: TempPath, a: OutputFileName); |
| 6534 | NamedOutput = C.getArgs().MakeArgString(Str: TempPath.c_str()); |
| 6535 | } |
| 6536 | |
| 6537 | // If we're saving temps and the temp file conflicts with the input file, |
| 6538 | // then avoid overwriting input file. |
| 6539 | if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { |
| 6540 | bool SameFile = false; |
| 6541 | SmallString<256> Result; |
| 6542 | llvm::sys::fs::current_path(result&: Result); |
| 6543 | llvm::sys::path::append(path&: Result, a: BaseName); |
| 6544 | llvm::sys::fs::equivalent(A: BaseInput, B: Result.c_str(), result&: SameFile); |
| 6545 | // Must share the same path to conflict. |
| 6546 | if (SameFile) { |
| 6547 | StringRef Name = llvm::sys::path::filename(path: BaseInput); |
| 6548 | std::pair<StringRef, StringRef> Split = Name.split(Separator: '.'); |
| 6549 | std::string TmpName = GetTemporaryPath( |
| 6550 | Prefix: Split.first, |
| 6551 | Suffix: types::getTypeTempSuffix(Id: JA.getType(), CLStyle: IsCLMode() || IsDXCMode())); |
| 6552 | return C.addTempFile(Name: C.getArgs().MakeArgString(Str: TmpName)); |
| 6553 | } |
| 6554 | } |
| 6555 | |
| 6556 | // As an annoying special case, PCH generation doesn't strip the pathname. |
| 6557 | if (JA.getType() == types::TY_PCH && !IsCLMode()) { |
| 6558 | llvm::sys::path::remove_filename(path&: BasePath); |
| 6559 | if (BasePath.empty()) |
| 6560 | BasePath = NamedOutput; |
| 6561 | else |
| 6562 | llvm::sys::path::append(path&: BasePath, a: NamedOutput); |
| 6563 | return C.addResultFile(Name: C.getArgs().MakeArgString(Str: BasePath.c_str()), JA: &JA); |
| 6564 | } |
| 6565 | |
| 6566 | return C.addResultFile(Name: NamedOutput, JA: &JA); |
| 6567 | } |
| 6568 | |
| 6569 | std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const { |
| 6570 | // Search for Name in a list of paths. |
| 6571 | auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P) |
| 6572 | -> std::optional<std::string> { |
| 6573 | // Respect a limited subset of the '-Bprefix' functionality in GCC by |
| 6574 | // attempting to use this prefix when looking for file paths. |
| 6575 | for (const auto &Dir : P) { |
| 6576 | if (Dir.empty()) |
| 6577 | continue; |
| 6578 | SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(pos: 1) : Dir); |
| 6579 | llvm::sys::path::append(path&: P, a: Name); |
| 6580 | if (llvm::sys::fs::exists(Path: Twine(P))) |
| 6581 | return std::string(P); |
| 6582 | } |
| 6583 | return std::nullopt; |
| 6584 | }; |
| 6585 | |
| 6586 | if (auto P = SearchPaths(PrefixDirs)) |
| 6587 | return *P; |
| 6588 | |
| 6589 | SmallString<128> R(ResourceDir); |
| 6590 | llvm::sys::path::append(path&: R, a: Name); |
| 6591 | if (llvm::sys::fs::exists(Path: Twine(R))) |
| 6592 | return std::string(R); |
| 6593 | |
| 6594 | SmallString<128> P(TC.getCompilerRTPath()); |
| 6595 | llvm::sys::path::append(path&: P, a: Name); |
| 6596 | if (llvm::sys::fs::exists(Path: Twine(P))) |
| 6597 | return std::string(P); |
| 6598 | |
| 6599 | SmallString<128> D(Dir); |
| 6600 | llvm::sys::path::append(path&: D, a: ".." , b: Name); |
| 6601 | if (llvm::sys::fs::exists(Path: Twine(D))) |
| 6602 | return std::string(D); |
| 6603 | |
| 6604 | if (auto P = SearchPaths(TC.getLibraryPaths())) |
| 6605 | return *P; |
| 6606 | |
| 6607 | if (auto P = SearchPaths(TC.getFilePaths())) |
| 6608 | return *P; |
| 6609 | |
| 6610 | SmallString<128> R2(ResourceDir); |
| 6611 | llvm::sys::path::append(path&: R2, a: ".." , b: ".." , c: Name); |
| 6612 | if (llvm::sys::fs::exists(Path: Twine(R2))) |
| 6613 | return std::string(R2); |
| 6614 | |
| 6615 | return std::string(Name); |
| 6616 | } |
| 6617 | |
| 6618 | void Driver::generatePrefixedToolNames( |
| 6619 | StringRef Tool, const ToolChain &TC, |
| 6620 | SmallVectorImpl<std::string> &Names) const { |
| 6621 | // FIXME: Needs a better variable than TargetTriple |
| 6622 | Names.emplace_back(Args: (TargetTriple + "-" + Tool).str()); |
| 6623 | Names.emplace_back(Args&: Tool); |
| 6624 | } |
| 6625 | |
| 6626 | static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) { |
| 6627 | llvm::sys::path::append(path&: Dir, a: Name); |
| 6628 | if (llvm::sys::fs::can_execute(Path: Twine(Dir))) |
| 6629 | return true; |
| 6630 | llvm::sys::path::remove_filename(path&: Dir); |
| 6631 | return false; |
| 6632 | } |
| 6633 | |
| 6634 | std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const { |
| 6635 | SmallVector<std::string, 2> TargetSpecificExecutables; |
| 6636 | generatePrefixedToolNames(Tool: Name, TC, Names&: TargetSpecificExecutables); |
| 6637 | |
| 6638 | // Respect a limited subset of the '-Bprefix' functionality in GCC by |
| 6639 | // attempting to use this prefix when looking for program paths. |
| 6640 | for (const auto &PrefixDir : PrefixDirs) { |
| 6641 | if (llvm::sys::fs::is_directory(Path: PrefixDir)) { |
| 6642 | SmallString<128> P(PrefixDir); |
| 6643 | if (ScanDirForExecutable(Dir&: P, Name)) |
| 6644 | return std::string(P); |
| 6645 | } else { |
| 6646 | SmallString<128> P((PrefixDir + Name).str()); |
| 6647 | if (llvm::sys::fs::can_execute(Path: Twine(P))) |
| 6648 | return std::string(P); |
| 6649 | } |
| 6650 | } |
| 6651 | |
| 6652 | const ToolChain::path_list &List = TC.getProgramPaths(); |
| 6653 | for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) { |
| 6654 | // For each possible name of the tool look for it in |
| 6655 | // program paths first, then the path. |
| 6656 | // Higher priority names will be first, meaning that |
| 6657 | // a higher priority name in the path will be found |
| 6658 | // instead of a lower priority name in the program path. |
| 6659 | // E.g. <triple>-gcc on the path will be found instead |
| 6660 | // of gcc in the program path |
| 6661 | for (const auto &Path : List) { |
| 6662 | SmallString<128> P(Path); |
| 6663 | if (ScanDirForExecutable(Dir&: P, Name: TargetSpecificExecutable)) |
| 6664 | return std::string(P); |
| 6665 | } |
| 6666 | |
| 6667 | // Fall back to the path |
| 6668 | if (llvm::ErrorOr<std::string> P = |
| 6669 | llvm::sys::findProgramByName(Name: TargetSpecificExecutable)) |
| 6670 | return *P; |
| 6671 | } |
| 6672 | |
| 6673 | return std::string(Name); |
| 6674 | } |
| 6675 | |
| 6676 | std::string Driver::GetStdModuleManifestPath(const Compilation &C, |
| 6677 | const ToolChain &TC) const { |
| 6678 | std::string error = "<NOT PRESENT>" ; |
| 6679 | |
| 6680 | if (C.getArgs().hasArg(Ids: options::OPT_nostdlib)) |
| 6681 | return error; |
| 6682 | |
| 6683 | switch (TC.GetCXXStdlibType(Args: C.getArgs())) { |
| 6684 | case ToolChain::CST_Libcxx: { |
| 6685 | auto evaluate = [&](const char *library) -> std::optional<std::string> { |
| 6686 | std::string lib = GetFilePath(Name: library, TC); |
| 6687 | |
| 6688 | // Note when there are multiple flavours of libc++ the module json needs |
| 6689 | // to look at the command-line arguments for the proper json. These |
| 6690 | // flavours do not exist at the moment, but there are plans to provide a |
| 6691 | // variant that is built with sanitizer instrumentation enabled. |
| 6692 | |
| 6693 | // For example |
| 6694 | // StringRef modules = [&] { |
| 6695 | // const SanitizerArgs &Sanitize = TC.getSanitizerArgs(C.getArgs()); |
| 6696 | // if (Sanitize.needsAsanRt()) |
| 6697 | // return "libc++.modules-asan.json"; |
| 6698 | // return "libc++.modules.json"; |
| 6699 | // }(); |
| 6700 | |
| 6701 | SmallString<128> path(lib.begin(), lib.end()); |
| 6702 | llvm::sys::path::remove_filename(path); |
| 6703 | llvm::sys::path::append(path, a: "libc++.modules.json" ); |
| 6704 | if (TC.getVFS().exists(Path: path)) |
| 6705 | return static_cast<std::string>(path); |
| 6706 | |
| 6707 | return {}; |
| 6708 | }; |
| 6709 | |
| 6710 | if (std::optional<std::string> result = evaluate("libc++.so" ); result) |
| 6711 | return *result; |
| 6712 | |
| 6713 | return evaluate("libc++.a" ).value_or(u&: error); |
| 6714 | } |
| 6715 | |
| 6716 | case ToolChain::CST_Libstdcxx: { |
| 6717 | auto evaluate = [&](const char *library) -> std::optional<std::string> { |
| 6718 | std::string lib = GetFilePath(Name: library, TC); |
| 6719 | |
| 6720 | SmallString<128> path(lib.begin(), lib.end()); |
| 6721 | llvm::sys::path::remove_filename(path); |
| 6722 | llvm::sys::path::append(path, a: "libstdc++.modules.json" ); |
| 6723 | if (TC.getVFS().exists(Path: path)) |
| 6724 | return static_cast<std::string>(path); |
| 6725 | |
| 6726 | return {}; |
| 6727 | }; |
| 6728 | |
| 6729 | if (std::optional<std::string> result = evaluate("libstdc++.so" ); result) |
| 6730 | return *result; |
| 6731 | |
| 6732 | return evaluate("libstdc++.a" ).value_or(u&: error); |
| 6733 | } |
| 6734 | } |
| 6735 | |
| 6736 | return error; |
| 6737 | } |
| 6738 | |
| 6739 | std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const { |
| 6740 | SmallString<128> Path; |
| 6741 | std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, ResultPath&: Path); |
| 6742 | if (EC) { |
| 6743 | Diag(DiagID: clang::diag::err_unable_to_make_temp) << EC.message(); |
| 6744 | return "" ; |
| 6745 | } |
| 6746 | |
| 6747 | return std::string(Path); |
| 6748 | } |
| 6749 | |
| 6750 | std::string Driver::GetTemporaryDirectory(StringRef Prefix) const { |
| 6751 | SmallString<128> Path; |
| 6752 | std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, ResultPath&: Path); |
| 6753 | if (EC) { |
| 6754 | Diag(DiagID: clang::diag::err_unable_to_make_temp) << EC.message(); |
| 6755 | return "" ; |
| 6756 | } |
| 6757 | |
| 6758 | return std::string(Path); |
| 6759 | } |
| 6760 | |
| 6761 | std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { |
| 6762 | SmallString<128> Output; |
| 6763 | if (Arg *FpArg = C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fp)) { |
| 6764 | // FIXME: If anybody needs it, implement this obscure rule: |
| 6765 | // "If you specify a directory without a file name, the default file name |
| 6766 | // is VCx0.pch., where x is the major version of Visual C++ in use." |
| 6767 | Output = FpArg->getValue(); |
| 6768 | |
| 6769 | // "If you do not specify an extension as part of the path name, an |
| 6770 | // extension of .pch is assumed. " |
| 6771 | if (!llvm::sys::path::has_extension(path: Output)) |
| 6772 | Output += ".pch" ; |
| 6773 | } else { |
| 6774 | if (Arg *YcArg = C.getArgs().getLastArg(Ids: options::OPT__SLASH_Yc)) |
| 6775 | Output = YcArg->getValue(); |
| 6776 | if (Output.empty()) |
| 6777 | Output = BaseName; |
| 6778 | llvm::sys::path::replace_extension(path&: Output, extension: ".pch" ); |
| 6779 | } |
| 6780 | return std::string(Output); |
| 6781 | } |
| 6782 | |
| 6783 | const ToolChain &Driver::getOffloadToolChain( |
| 6784 | const llvm::opt::ArgList &Args, const Action::OffloadKind Kind, |
| 6785 | const llvm::Triple &Target, const llvm::Triple &AuxTarget) const { |
| 6786 | std::unique_ptr<ToolChain> &TC = |
| 6787 | ToolChains[Target.str() + "/" + AuxTarget.str()]; |
| 6788 | std::unique_ptr<ToolChain> &HostTC = ToolChains[AuxTarget.str()]; |
| 6789 | |
| 6790 | assert(HostTC && "Host toolchain for offloading doesn't exit?" ); |
| 6791 | if (!TC) { |
| 6792 | // Detect the toolchain based off of the target operating system. |
| 6793 | switch (Target.getOS()) { |
| 6794 | case llvm::Triple::CUDA: |
| 6795 | TC = std::make_unique<toolchains::CudaToolChain>(args: *this, args: Target, args&: *HostTC, |
| 6796 | args: Args); |
| 6797 | break; |
| 6798 | case llvm::Triple::AMDHSA: |
| 6799 | if (Kind == Action::OFK_HIP) |
| 6800 | TC = std::make_unique<toolchains::HIPAMDToolChain>(args: *this, args: Target, |
| 6801 | args&: *HostTC, args: Args); |
| 6802 | else if (Kind == Action::OFK_OpenMP) |
| 6803 | TC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(args: *this, args: Target, |
| 6804 | args&: *HostTC, args: Args); |
| 6805 | break; |
| 6806 | default: |
| 6807 | break; |
| 6808 | } |
| 6809 | } |
| 6810 | if (!TC) { |
| 6811 | // Detect the toolchain based off of the target architecture if that failed. |
| 6812 | switch (Target.getArch()) { |
| 6813 | case llvm::Triple::spir: |
| 6814 | case llvm::Triple::spir64: |
| 6815 | case llvm::Triple::spirv: |
| 6816 | case llvm::Triple::spirv32: |
| 6817 | case llvm::Triple::spirv64: |
| 6818 | switch (Kind) { |
| 6819 | case Action::OFK_SYCL: |
| 6820 | TC = std::make_unique<toolchains::SYCLToolChain>(args: *this, args: Target, args&: *HostTC, |
| 6821 | args: Args); |
| 6822 | break; |
| 6823 | case Action::OFK_HIP: |
| 6824 | TC = std::make_unique<toolchains::HIPSPVToolChain>(args: *this, args: Target, |
| 6825 | args&: *HostTC, args: Args); |
| 6826 | break; |
| 6827 | case Action::OFK_OpenMP: |
| 6828 | TC = std::make_unique<toolchains::SPIRVOpenMPToolChain>(args: *this, args: Target, |
| 6829 | args&: *HostTC, args: Args); |
| 6830 | break; |
| 6831 | case Action::OFK_Cuda: |
| 6832 | TC = std::make_unique<toolchains::CudaToolChain>(args: *this, args: Target, args&: *HostTC, |
| 6833 | args: Args); |
| 6834 | break; |
| 6835 | default: |
| 6836 | break; |
| 6837 | } |
| 6838 | break; |
| 6839 | default: |
| 6840 | break; |
| 6841 | } |
| 6842 | } |
| 6843 | |
| 6844 | // If all else fails, just look up the normal toolchain for the target. |
| 6845 | if (!TC) |
| 6846 | return getToolChain(Args, Target); |
| 6847 | return *TC; |
| 6848 | } |
| 6849 | |
| 6850 | const ToolChain &Driver::getToolChain(const ArgList &Args, |
| 6851 | const llvm::Triple &Target) const { |
| 6852 | |
| 6853 | auto &TC = ToolChains[Target.str()]; |
| 6854 | if (!TC) { |
| 6855 | switch (Target.getOS()) { |
| 6856 | case llvm::Triple::AIX: |
| 6857 | TC = std::make_unique<toolchains::AIX>(args: *this, args: Target, args: Args); |
| 6858 | break; |
| 6859 | case llvm::Triple::Haiku: |
| 6860 | TC = std::make_unique<toolchains::Haiku>(args: *this, args: Target, args: Args); |
| 6861 | break; |
| 6862 | case llvm::Triple::Darwin: |
| 6863 | case llvm::Triple::MacOSX: |
| 6864 | case llvm::Triple::IOS: |
| 6865 | case llvm::Triple::TvOS: |
| 6866 | case llvm::Triple::WatchOS: |
| 6867 | case llvm::Triple::XROS: |
| 6868 | case llvm::Triple::DriverKit: |
| 6869 | TC = std::make_unique<toolchains::DarwinClang>(args: *this, args: Target, args: Args); |
| 6870 | break; |
| 6871 | case llvm::Triple::DragonFly: |
| 6872 | TC = std::make_unique<toolchains::DragonFly>(args: *this, args: Target, args: Args); |
| 6873 | break; |
| 6874 | case llvm::Triple::OpenBSD: |
| 6875 | TC = std::make_unique<toolchains::OpenBSD>(args: *this, args: Target, args: Args); |
| 6876 | break; |
| 6877 | case llvm::Triple::NetBSD: |
| 6878 | TC = std::make_unique<toolchains::NetBSD>(args: *this, args: Target, args: Args); |
| 6879 | break; |
| 6880 | case llvm::Triple::FreeBSD: |
| 6881 | if (Target.isPPC()) |
| 6882 | TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(args: *this, args: Target, |
| 6883 | args: Args); |
| 6884 | else |
| 6885 | TC = std::make_unique<toolchains::FreeBSD>(args: *this, args: Target, args: Args); |
| 6886 | break; |
| 6887 | case llvm::Triple::Linux: |
| 6888 | case llvm::Triple::ELFIAMCU: |
| 6889 | if (Target.getArch() == llvm::Triple::hexagon) |
| 6890 | TC = std::make_unique<toolchains::HexagonToolChain>(args: *this, args: Target, |
| 6891 | args: Args); |
| 6892 | else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && |
| 6893 | !Target.hasEnvironment()) |
| 6894 | TC = std::make_unique<toolchains::MipsLLVMToolChain>(args: *this, args: Target, |
| 6895 | args: Args); |
| 6896 | else if (Target.isPPC()) |
| 6897 | TC = std::make_unique<toolchains::PPCLinuxToolChain>(args: *this, args: Target, |
| 6898 | args: Args); |
| 6899 | else if (Target.getArch() == llvm::Triple::ve) |
| 6900 | TC = std::make_unique<toolchains::VEToolChain>(args: *this, args: Target, args: Args); |
| 6901 | else if (Target.isOHOSFamily()) |
| 6902 | TC = std::make_unique<toolchains::OHOS>(args: *this, args: Target, args: Args); |
| 6903 | else if (Target.isWALI()) |
| 6904 | TC = std::make_unique<toolchains::WebAssembly>(args: *this, args: Target, args: Args); |
| 6905 | else if (Target.isLFI()) |
| 6906 | TC = std::make_unique<toolchains::LFILinux>(args: *this, args: Target, args: Args); |
| 6907 | else |
| 6908 | TC = std::make_unique<toolchains::Linux>(args: *this, args: Target, args: Args); |
| 6909 | break; |
| 6910 | case llvm::Triple::Fuchsia: |
| 6911 | TC = std::make_unique<toolchains::Fuchsia>(args: *this, args: Target, args: Args); |
| 6912 | break; |
| 6913 | case llvm::Triple::Managarm: |
| 6914 | TC = std::make_unique<toolchains::Managarm>(args: *this, args: Target, args: Args); |
| 6915 | break; |
| 6916 | case llvm::Triple::Solaris: |
| 6917 | TC = std::make_unique<toolchains::Solaris>(args: *this, args: Target, args: Args); |
| 6918 | break; |
| 6919 | case llvm::Triple::CUDA: |
| 6920 | TC = std::make_unique<toolchains::NVPTXToolChain>(args: *this, args: Target, args: Args); |
| 6921 | break; |
| 6922 | case llvm::Triple::AMDHSA: { |
| 6923 | if (Target.getArch() == llvm::Triple::spirv64) { |
| 6924 | TC = std::make_unique<toolchains::SPIRVAMDToolChain>(args: *this, args: Target, |
| 6925 | args: Args); |
| 6926 | } else { |
| 6927 | bool DL = usesInput(Args, Fn&: types::isOpenCL) || |
| 6928 | usesInput(Args, Fn&: types::isLLVMIR); |
| 6929 | TC = DL ? std::make_unique<toolchains::ROCMToolChain>(args: *this, args: Target, |
| 6930 | args: Args) |
| 6931 | : std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, |
| 6932 | args: Args); |
| 6933 | } |
| 6934 | break; |
| 6935 | } |
| 6936 | case llvm::Triple::AMDPAL: |
| 6937 | case llvm::Triple::Mesa3D: |
| 6938 | TC = std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, args: Args); |
| 6939 | break; |
| 6940 | case llvm::Triple::UEFI: |
| 6941 | TC = std::make_unique<toolchains::UEFI>(args: *this, args: Target, args: Args); |
| 6942 | break; |
| 6943 | case llvm::Triple::Win32: |
| 6944 | switch (Target.getEnvironment()) { |
| 6945 | default: |
| 6946 | if (Target.isOSBinFormatELF()) |
| 6947 | TC = std::make_unique<toolchains::Generic_ELF>(args: *this, args: Target, args: Args); |
| 6948 | else if (Target.isOSBinFormatMachO()) |
| 6949 | TC = std::make_unique<toolchains::MachO>(args: *this, args: Target, args: Args); |
| 6950 | else |
| 6951 | TC = std::make_unique<toolchains::Generic_GCC>(args: *this, args: Target, args: Args); |
| 6952 | break; |
| 6953 | case llvm::Triple::GNU: |
| 6954 | TC = std::make_unique<toolchains::MinGW>(args: *this, args: Target, args: Args); |
| 6955 | break; |
| 6956 | case llvm::Triple::Cygnus: |
| 6957 | TC = std::make_unique<toolchains::Cygwin>(args: *this, args: Target, args: Args); |
| 6958 | break; |
| 6959 | case llvm::Triple::Itanium: |
| 6960 | TC = std::make_unique<toolchains::CrossWindowsToolChain>(args: *this, args: Target, |
| 6961 | args: Args); |
| 6962 | break; |
| 6963 | case llvm::Triple::MSVC: |
| 6964 | case llvm::Triple::UnknownEnvironment: |
| 6965 | if (Args.getLastArgValue(Id: options::OPT_fuse_ld_EQ) |
| 6966 | .starts_with_insensitive(Prefix: "bfd" )) |
| 6967 | TC = std::make_unique<toolchains::CrossWindowsToolChain>( |
| 6968 | args: *this, args: Target, args: Args); |
| 6969 | else |
| 6970 | TC = |
| 6971 | std::make_unique<toolchains::MSVCToolChain>(args: *this, args: Target, args: Args); |
| 6972 | break; |
| 6973 | } |
| 6974 | break; |
| 6975 | case llvm::Triple::PS4: |
| 6976 | TC = std::make_unique<toolchains::PS4CPU>(args: *this, args: Target, args: Args); |
| 6977 | break; |
| 6978 | case llvm::Triple::PS5: |
| 6979 | TC = std::make_unique<toolchains::PS5CPU>(args: *this, args: Target, args: Args); |
| 6980 | break; |
| 6981 | case llvm::Triple::Hurd: |
| 6982 | TC = std::make_unique<toolchains::Hurd>(args: *this, args: Target, args: Args); |
| 6983 | break; |
| 6984 | case llvm::Triple::LiteOS: |
| 6985 | TC = std::make_unique<toolchains::OHOS>(args: *this, args: Target, args: Args); |
| 6986 | break; |
| 6987 | case llvm::Triple::ZOS: |
| 6988 | TC = std::make_unique<toolchains::ZOS>(args: *this, args: Target, args: Args); |
| 6989 | break; |
| 6990 | case llvm::Triple::Vulkan: |
| 6991 | case llvm::Triple::ShaderModel: |
| 6992 | TC = std::make_unique<toolchains::HLSLToolChain>(args: *this, args: Target, args: Args); |
| 6993 | break; |
| 6994 | case llvm::Triple::ChipStar: |
| 6995 | TC = std::make_unique<toolchains::HIPSPVToolChain>(args: *this, args: Target, args: Args); |
| 6996 | break; |
| 6997 | default: |
| 6998 | // Of these targets, Hexagon is the only one that might have |
| 6999 | // an OS of Linux, in which case it got handled above already. |
| 7000 | switch (Target.getArch()) { |
| 7001 | case llvm::Triple::tce: |
| 7002 | TC = std::make_unique<toolchains::TCEToolChain>(args: *this, args: Target, args: Args); |
| 7003 | break; |
| 7004 | case llvm::Triple::tcele: |
| 7005 | TC = std::make_unique<toolchains::TCELEToolChain>(args: *this, args: Target, args: Args); |
| 7006 | break; |
| 7007 | case llvm::Triple::hexagon: |
| 7008 | TC = std::make_unique<toolchains::HexagonToolChain>(args: *this, args: Target, |
| 7009 | args: Args); |
| 7010 | break; |
| 7011 | case llvm::Triple::lanai: |
| 7012 | TC = std::make_unique<toolchains::LanaiToolChain>(args: *this, args: Target, args: Args); |
| 7013 | break; |
| 7014 | case llvm::Triple::xcore: |
| 7015 | TC = std::make_unique<toolchains::XCoreToolChain>(args: *this, args: Target, args: Args); |
| 7016 | break; |
| 7017 | case llvm::Triple::wasm32: |
| 7018 | case llvm::Triple::wasm64: |
| 7019 | TC = std::make_unique<toolchains::WebAssembly>(args: *this, args: Target, args: Args); |
| 7020 | break; |
| 7021 | case llvm::Triple::avr: |
| 7022 | TC = std::make_unique<toolchains::AVRToolChain>(args: *this, args: Target, args: Args); |
| 7023 | break; |
| 7024 | case llvm::Triple::msp430: |
| 7025 | TC = std::make_unique<toolchains::MSP430ToolChain>(args: *this, args: Target, args: Args); |
| 7026 | break; |
| 7027 | case llvm::Triple::riscv32: |
| 7028 | case llvm::Triple::riscv64: |
| 7029 | case llvm::Triple::riscv32be: |
| 7030 | case llvm::Triple::riscv64be: |
| 7031 | TC = std::make_unique<toolchains::BareMetal>(args: *this, args: Target, args: Args); |
| 7032 | break; |
| 7033 | case llvm::Triple::ve: |
| 7034 | TC = std::make_unique<toolchains::VEToolChain>(args: *this, args: Target, args: Args); |
| 7035 | break; |
| 7036 | case llvm::Triple::spirv32: |
| 7037 | case llvm::Triple::spirv64: |
| 7038 | TC = std::make_unique<toolchains::SPIRVToolChain>(args: *this, args: Target, args: Args); |
| 7039 | break; |
| 7040 | case llvm::Triple::csky: |
| 7041 | TC = std::make_unique<toolchains::CSKYToolChain>(args: *this, args: Target, args: Args); |
| 7042 | break; |
| 7043 | default: |
| 7044 | if (toolchains::BareMetal::handlesTarget(Triple: Target)) |
| 7045 | TC = std::make_unique<toolchains::BareMetal>(args: *this, args: Target, args: Args); |
| 7046 | else if (Target.isOSBinFormatELF()) |
| 7047 | TC = std::make_unique<toolchains::Generic_ELF>(args: *this, args: Target, args: Args); |
| 7048 | else if (Target.isAppleFirmware()) |
| 7049 | TC = std::make_unique<toolchains::DarwinClang>(args: *this, args: Target, args: Args); |
| 7050 | else if (Target.isAppleMachO()) |
| 7051 | TC = std::make_unique<toolchains::AppleMachO>(args: *this, args: Target, args: Args); |
| 7052 | else if (Target.isOSBinFormatMachO()) |
| 7053 | TC = std::make_unique<toolchains::MachO>(args: *this, args: Target, args: Args); |
| 7054 | else |
| 7055 | TC = std::make_unique<toolchains::Generic_GCC>(args: *this, args: Target, args: Args); |
| 7056 | } |
| 7057 | } |
| 7058 | } |
| 7059 | |
| 7060 | return *TC; |
| 7061 | } |
| 7062 | |
| 7063 | bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { |
| 7064 | // Say "no" if there is not exactly one input of a type clang understands. |
| 7065 | if (JA.size() != 1 || |
| 7066 | !types::isAcceptedByClang(Id: (*JA.input_begin())->getType())) |
| 7067 | return false; |
| 7068 | |
| 7069 | // And say "no" if this is not a kind of action clang understands. |
| 7070 | if (!isa<PreprocessJobAction>(Val: JA) && !isa<PrecompileJobAction>(Val: JA) && |
| 7071 | !isa<CompileJobAction>(Val: JA) && !isa<BackendJobAction>(Val: JA) && |
| 7072 | !isa<ExtractAPIJobAction>(Val: JA)) |
| 7073 | return false; |
| 7074 | |
| 7075 | return true; |
| 7076 | } |
| 7077 | |
| 7078 | bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const { |
| 7079 | // Say "no" if there is not exactly one input of a type flang understands. |
| 7080 | if (JA.size() != 1 || |
| 7081 | !types::isAcceptedByFlang(Id: (*JA.input_begin())->getType())) |
| 7082 | return false; |
| 7083 | |
| 7084 | // And say "no" if this is not a kind of action flang understands. |
| 7085 | if (!isa<PreprocessJobAction>(Val: JA) && !isa<PrecompileJobAction>(Val: JA) && |
| 7086 | !isa<CompileJobAction>(Val: JA) && !isa<BackendJobAction>(Val: JA)) |
| 7087 | return false; |
| 7088 | |
| 7089 | return true; |
| 7090 | } |
| 7091 | |
| 7092 | bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const { |
| 7093 | // Only emit static library if the flag is set explicitly. |
| 7094 | if (Args.hasArg(Ids: options::OPT_emit_static_lib)) |
| 7095 | return true; |
| 7096 | return false; |
| 7097 | } |
| 7098 | |
| 7099 | /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the |
| 7100 | /// grouped values as integers. Numbers which are not provided are set to 0. |
| 7101 | /// |
| 7102 | /// \return True if the entire string was parsed (9.2), or all groups were |
| 7103 | /// parsed (10.3.5extrastuff). |
| 7104 | bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, |
| 7105 | unsigned &Micro, bool &) { |
| 7106 | HadExtra = false; |
| 7107 | |
| 7108 | Major = Minor = Micro = 0; |
| 7109 | if (Str.empty()) |
| 7110 | return false; |
| 7111 | |
| 7112 | if (Str.consumeInteger(Radix: 10, Result&: Major)) |
| 7113 | return false; |
| 7114 | if (Str.empty()) |
| 7115 | return true; |
| 7116 | if (!Str.consume_front(Prefix: "." )) |
| 7117 | return false; |
| 7118 | |
| 7119 | if (Str.consumeInteger(Radix: 10, Result&: Minor)) |
| 7120 | return false; |
| 7121 | if (Str.empty()) |
| 7122 | return true; |
| 7123 | if (!Str.consume_front(Prefix: "." )) |
| 7124 | return false; |
| 7125 | |
| 7126 | if (Str.consumeInteger(Radix: 10, Result&: Micro)) |
| 7127 | return false; |
| 7128 | if (!Str.empty()) |
| 7129 | HadExtra = true; |
| 7130 | return true; |
| 7131 | } |
| 7132 | |
| 7133 | /// Parse digits from a string \p Str and fulfill \p Digits with |
| 7134 | /// the parsed numbers. This method assumes that the max number of |
| 7135 | /// digits to look for is equal to Digits.size(). |
| 7136 | /// |
| 7137 | /// \return True if the entire string was parsed and there are |
| 7138 | /// no extra characters remaining at the end. |
| 7139 | bool Driver::GetReleaseVersion(StringRef Str, |
| 7140 | MutableArrayRef<unsigned> Digits) { |
| 7141 | if (Str.empty()) |
| 7142 | return false; |
| 7143 | |
| 7144 | unsigned CurDigit = 0; |
| 7145 | while (CurDigit < Digits.size()) { |
| 7146 | unsigned Digit; |
| 7147 | if (Str.consumeInteger(Radix: 10, Result&: Digit)) |
| 7148 | return false; |
| 7149 | Digits[CurDigit] = Digit; |
| 7150 | if (Str.empty()) |
| 7151 | return true; |
| 7152 | if (!Str.consume_front(Prefix: "." )) |
| 7153 | return false; |
| 7154 | CurDigit++; |
| 7155 | } |
| 7156 | |
| 7157 | // More digits than requested, bail out... |
| 7158 | return false; |
| 7159 | } |
| 7160 | |
| 7161 | llvm::opt::Visibility |
| 7162 | Driver::getOptionVisibilityMask(bool UseDriverMode) const { |
| 7163 | if (!UseDriverMode) |
| 7164 | return llvm::opt::Visibility(options::ClangOption); |
| 7165 | if (IsCLMode()) |
| 7166 | return llvm::opt::Visibility(options::CLOption); |
| 7167 | if (IsDXCMode()) |
| 7168 | return llvm::opt::Visibility(options::DXCOption); |
| 7169 | if (IsFlangMode()) { |
| 7170 | return llvm::opt::Visibility(options::FlangOption); |
| 7171 | } |
| 7172 | return llvm::opt::Visibility(options::ClangOption); |
| 7173 | } |
| 7174 | |
| 7175 | const char *Driver::getExecutableForDriverMode(DriverMode Mode) { |
| 7176 | switch (Mode) { |
| 7177 | case GCCMode: |
| 7178 | return "clang" ; |
| 7179 | case GXXMode: |
| 7180 | return "clang++" ; |
| 7181 | case CPPMode: |
| 7182 | return "clang-cpp" ; |
| 7183 | case CLMode: |
| 7184 | return "clang-cl" ; |
| 7185 | case FlangMode: |
| 7186 | return "flang" ; |
| 7187 | case DXCMode: |
| 7188 | return "clang-dxc" ; |
| 7189 | } |
| 7190 | |
| 7191 | llvm_unreachable("Unhandled Mode" ); |
| 7192 | } |
| 7193 | |
| 7194 | bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { |
| 7195 | return Args.hasFlag(Pos: options::OPT_Ofast, Neg: options::OPT_O_Group, Default: false); |
| 7196 | } |
| 7197 | |
| 7198 | bool clang::driver::(const ArgList &Args) { |
| 7199 | // -fsave-optimization-record enables it. |
| 7200 | if (Args.hasFlag(Pos: options::OPT_fsave_optimization_record, |
| 7201 | Neg: options::OPT_fno_save_optimization_record, Default: false)) |
| 7202 | return true; |
| 7203 | |
| 7204 | // -fsave-optimization-record=<format> enables it as well. |
| 7205 | if (Args.hasFlag(Pos: options::OPT_fsave_optimization_record_EQ, |
| 7206 | Neg: options::OPT_fno_save_optimization_record, Default: false)) |
| 7207 | return true; |
| 7208 | |
| 7209 | // -foptimization-record-file alone enables it too. |
| 7210 | if (Args.hasFlag(Pos: options::OPT_foptimization_record_file_EQ, |
| 7211 | Neg: options::OPT_fno_save_optimization_record, Default: false)) |
| 7212 | return true; |
| 7213 | |
| 7214 | // -foptimization-record-passes alone enables it too. |
| 7215 | if (Args.hasFlag(Pos: options::OPT_foptimization_record_passes_EQ, |
| 7216 | Neg: options::OPT_fno_save_optimization_record, Default: false)) |
| 7217 | return true; |
| 7218 | return false; |
| 7219 | } |
| 7220 | |
| 7221 | llvm::StringRef clang::driver::getDriverMode(StringRef ProgName, |
| 7222 | ArrayRef<const char *> Args) { |
| 7223 | static StringRef OptName = |
| 7224 | getDriverOptTable().getOption(Opt: options::OPT_driver_mode).getPrefixedName(); |
| 7225 | llvm::StringRef Opt; |
| 7226 | for (StringRef Arg : Args) { |
| 7227 | if (!Arg.starts_with(Prefix: OptName)) |
| 7228 | continue; |
| 7229 | Opt = Arg; |
| 7230 | } |
| 7231 | if (Opt.empty()) |
| 7232 | Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode; |
| 7233 | return Opt.consume_front(Prefix: OptName) ? Opt : "" ; |
| 7234 | } |
| 7235 | |
| 7236 | bool driver::IsClangCL(StringRef DriverMode) { return DriverMode == "cl" ; } |
| 7237 | |
| 7238 | llvm::Error driver::expandResponseFiles(SmallVectorImpl<const char *> &Args, |
| 7239 | bool ClangCLMode, |
| 7240 | llvm::BumpPtrAllocator &Alloc, |
| 7241 | llvm::vfs::FileSystem *FS) { |
| 7242 | // Parse response files using the GNU syntax, unless we're in CL mode. There |
| 7243 | // are two ways to put clang in CL compatibility mode: ProgName is either |
| 7244 | // clang-cl or cl, or --driver-mode=cl is on the command line. The normal |
| 7245 | // command line parsing can't happen until after response file parsing, so we |
| 7246 | // have to manually search for a --driver-mode=cl argument the hard way. |
| 7247 | // Finally, our -cc1 tools don't care which tokenization mode we use because |
| 7248 | // response files written by clang will tokenize the same way in either mode. |
| 7249 | enum { Default, POSIX, Windows } RSPQuoting = Default; |
| 7250 | for (const char *F : Args) { |
| 7251 | if (strcmp(s1: F, s2: "--rsp-quoting=posix" ) == 0) |
| 7252 | RSPQuoting = POSIX; |
| 7253 | else if (strcmp(s1: F, s2: "--rsp-quoting=windows" ) == 0) |
| 7254 | RSPQuoting = Windows; |
| 7255 | } |
| 7256 | |
| 7257 | // Determines whether we want nullptr markers in Args to indicate response |
| 7258 | // files end-of-lines. We only use this for the /LINK driver argument with |
| 7259 | // clang-cl.exe on Windows. |
| 7260 | bool MarkEOLs = ClangCLMode; |
| 7261 | |
| 7262 | llvm::cl::TokenizerCallback Tokenizer; |
| 7263 | if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode)) |
| 7264 | Tokenizer = &llvm::cl::TokenizeWindowsCommandLine; |
| 7265 | else |
| 7266 | Tokenizer = &llvm::cl::TokenizeGNUCommandLine; |
| 7267 | |
| 7268 | if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).starts_with(Prefix: "-cc1" )) |
| 7269 | MarkEOLs = false; |
| 7270 | |
| 7271 | llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer); |
| 7272 | ECtx.setMarkEOLs(MarkEOLs); |
| 7273 | if (FS) |
| 7274 | ECtx.setVFS(FS); |
| 7275 | |
| 7276 | if (llvm::Error Err = ECtx.expandResponseFiles(Argv&: Args)) |
| 7277 | return Err; |
| 7278 | |
| 7279 | // If -cc1 came from a response file, remove the EOL sentinels. |
| 7280 | auto FirstArg = llvm::find_if(Range: llvm::drop_begin(RangeOrContainer&: Args), |
| 7281 | P: [](const char *A) { return A != nullptr; }); |
| 7282 | if (FirstArg != Args.end() && StringRef(*FirstArg).starts_with(Prefix: "-cc1" )) { |
| 7283 | // If -cc1 came from a response file, remove the EOL sentinels. |
| 7284 | if (MarkEOLs) { |
| 7285 | auto newEnd = std::remove(first: Args.begin(), last: Args.end(), value: nullptr); |
| 7286 | Args.resize(N: newEnd - Args.begin()); |
| 7287 | } |
| 7288 | } |
| 7289 | |
| 7290 | return llvm::Error::success(); |
| 7291 | } |
| 7292 | |
| 7293 | static const char *GetStableCStr(llvm::StringSet<> &SavedStrings, StringRef S) { |
| 7294 | return SavedStrings.insert(key: S).first->getKeyData(); |
| 7295 | } |
| 7296 | |
| 7297 | /// Apply a list of edits to the input argument lists. |
| 7298 | /// |
| 7299 | /// The input string is a space separated list of edits to perform, |
| 7300 | /// they are applied in order to the input argument lists. Edits |
| 7301 | /// should be one of the following forms: |
| 7302 | /// |
| 7303 | /// '#': Silence information about the changes to the command line arguments. |
| 7304 | /// |
| 7305 | /// '^FOO': Add FOO as a new argument at the beginning of the command line |
| 7306 | /// right after the name of the compiler executable. |
| 7307 | /// |
| 7308 | /// '+FOO': Add FOO as a new argument at the end of the command line. |
| 7309 | /// |
| 7310 | /// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command |
| 7311 | /// line. |
| 7312 | /// |
| 7313 | /// 'xOPTION': Removes all instances of the literal argument OPTION. |
| 7314 | /// |
| 7315 | /// 'XOPTION': Removes all instances of the literal argument OPTION, |
| 7316 | /// and the following argument. |
| 7317 | /// |
| 7318 | /// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox' |
| 7319 | /// at the end of the command line. |
| 7320 | /// |
| 7321 | /// \param OS - The stream to write edit information to. |
| 7322 | /// \param Args - The vector of command line arguments. |
| 7323 | /// \param Edit - The override command to perform. |
| 7324 | /// \param SavedStrings - Set to use for storing string representations. |
| 7325 | static void applyOneOverrideOption(raw_ostream &OS, |
| 7326 | SmallVectorImpl<const char *> &Args, |
| 7327 | StringRef Edit, |
| 7328 | llvm::StringSet<> &SavedStrings) { |
| 7329 | // This does not need to be efficient. |
| 7330 | |
| 7331 | if (Edit[0] == '^') { |
| 7332 | const char *Str = GetStableCStr(SavedStrings, S: Edit.substr(Start: 1)); |
| 7333 | OS << "### Adding argument " << Str << " at beginning\n" ; |
| 7334 | Args.insert(I: Args.begin() + 1, Elt: Str); |
| 7335 | } else if (Edit[0] == '+') { |
| 7336 | const char *Str = GetStableCStr(SavedStrings, S: Edit.substr(Start: 1)); |
| 7337 | OS << "### Adding argument " << Str << " at end\n" ; |
| 7338 | Args.push_back(Elt: Str); |
| 7339 | } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.ends_with(Suffix: "/" ) && |
| 7340 | Edit.slice(Start: 2, End: Edit.size() - 1).contains(C: '/')) { |
| 7341 | StringRef MatchPattern = Edit.substr(Start: 2).split(Separator: '/').first; |
| 7342 | StringRef ReplPattern = Edit.substr(Start: 2).split(Separator: '/').second; |
| 7343 | ReplPattern = ReplPattern.slice(Start: 0, End: ReplPattern.size() - 1); |
| 7344 | |
| 7345 | for (unsigned i = 1, e = Args.size(); i != e; ++i) { |
| 7346 | // Ignore end-of-line response file markers |
| 7347 | if (Args[i] == nullptr) |
| 7348 | continue; |
| 7349 | std::string Repl = llvm::Regex(MatchPattern).sub(Repl: ReplPattern, String: Args[i]); |
| 7350 | |
| 7351 | if (Repl != Args[i]) { |
| 7352 | OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n" ; |
| 7353 | Args[i] = GetStableCStr(SavedStrings, S: Repl); |
| 7354 | } |
| 7355 | } |
| 7356 | } else if (Edit[0] == 'x' || Edit[0] == 'X') { |
| 7357 | auto Option = Edit.substr(Start: 1); |
| 7358 | for (unsigned i = 1; i < Args.size();) { |
| 7359 | if (Option == Args[i]) { |
| 7360 | OS << "### Deleting argument " << Args[i] << '\n'; |
| 7361 | Args.erase(CI: Args.begin() + i); |
| 7362 | if (Edit[0] == 'X') { |
| 7363 | if (i < Args.size()) { |
| 7364 | OS << "### Deleting argument " << Args[i] << '\n'; |
| 7365 | Args.erase(CI: Args.begin() + i); |
| 7366 | } else |
| 7367 | OS << "### Invalid X edit, end of command line!\n" ; |
| 7368 | } |
| 7369 | } else |
| 7370 | ++i; |
| 7371 | } |
| 7372 | } else if (Edit[0] == 'O') { |
| 7373 | for (unsigned i = 1; i < Args.size();) { |
| 7374 | const char *A = Args[i]; |
| 7375 | // Ignore end-of-line response file markers |
| 7376 | if (A == nullptr) |
| 7377 | continue; |
| 7378 | if (A[0] == '-' && A[1] == 'O' && |
| 7379 | (A[2] == '\0' || (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' || |
| 7380 | ('0' <= A[2] && A[2] <= '9'))))) { |
| 7381 | OS << "### Deleting argument " << Args[i] << '\n'; |
| 7382 | Args.erase(CI: Args.begin() + i); |
| 7383 | } else |
| 7384 | ++i; |
| 7385 | } |
| 7386 | OS << "### Adding argument " << Edit << " at end\n" ; |
| 7387 | Args.push_back(Elt: GetStableCStr(SavedStrings, S: '-' + Edit.str())); |
| 7388 | } else { |
| 7389 | OS << "### Unrecognized edit: " << Edit << "\n" ; |
| 7390 | } |
| 7391 | } |
| 7392 | |
| 7393 | void driver::applyOverrideOptions(SmallVectorImpl<const char *> &Args, |
| 7394 | const char *OverrideStr, |
| 7395 | llvm::StringSet<> &SavedStrings, |
| 7396 | StringRef EnvVar, raw_ostream *OS) { |
| 7397 | if (!OS) |
| 7398 | OS = &llvm::nulls(); |
| 7399 | |
| 7400 | if (OverrideStr[0] == '#') { |
| 7401 | ++OverrideStr; |
| 7402 | OS = &llvm::nulls(); |
| 7403 | } |
| 7404 | |
| 7405 | *OS << "### " << EnvVar << ": " << OverrideStr << "\n" ; |
| 7406 | |
| 7407 | // This does not need to be efficient. |
| 7408 | |
| 7409 | const char *S = OverrideStr; |
| 7410 | while (*S) { |
| 7411 | const char *End = ::strchr(s: S, c: ' '); |
| 7412 | if (!End) |
| 7413 | End = S + strlen(s: S); |
| 7414 | if (End != S) |
| 7415 | applyOneOverrideOption(OS&: *OS, Args, Edit: std::string(S, End), SavedStrings); |
| 7416 | S = End; |
| 7417 | if (*S != '\0') |
| 7418 | ++S; |
| 7419 | } |
| 7420 | } |
| 7421 | |