| 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/AVR.h" |
| 13 | #include "ToolChains/Arch/RISCV.h" |
| 14 | #include "ToolChains/BareMetal.h" |
| 15 | #include "ToolChains/CSKYToolChain.h" |
| 16 | #include "ToolChains/Clang.h" |
| 17 | #include "ToolChains/CrossWindows.h" |
| 18 | #include "ToolChains/Cuda.h" |
| 19 | #include "ToolChains/Cygwin.h" |
| 20 | #include "ToolChains/Darwin.h" |
| 21 | #include "ToolChains/DragonFly.h" |
| 22 | #include "ToolChains/FreeBSD.h" |
| 23 | #include "ToolChains/Fuchsia.h" |
| 24 | #include "ToolChains/Gnu.h" |
| 25 | #include "ToolChains/HIPAMD.h" |
| 26 | #include "ToolChains/HIPSPV.h" |
| 27 | #include "ToolChains/HLSL.h" |
| 28 | #include "ToolChains/Haiku.h" |
| 29 | #include "ToolChains/Hexagon.h" |
| 30 | #include "ToolChains/Hurd.h" |
| 31 | #include "ToolChains/LFILinux.h" |
| 32 | #include "ToolChains/Lanai.h" |
| 33 | #include "ToolChains/Linux.h" |
| 34 | #include "ToolChains/MSP430.h" |
| 35 | #include "ToolChains/MSVC.h" |
| 36 | #include "ToolChains/Managarm.h" |
| 37 | #include "ToolChains/MinGW.h" |
| 38 | #include "ToolChains/MipsLinux.h" |
| 39 | #include "ToolChains/NetBSD.h" |
| 40 | #include "ToolChains/OHOS.h" |
| 41 | #include "ToolChains/OpenBSD.h" |
| 42 | #include "ToolChains/PPCFreeBSD.h" |
| 43 | #include "ToolChains/PPCLinux.h" |
| 44 | #include "ToolChains/PS4CPU.h" |
| 45 | #include "ToolChains/SPIRV.h" |
| 46 | #include "ToolChains/SPIRVOpenMP.h" |
| 47 | #include "ToolChains/SYCL.h" |
| 48 | #include "ToolChains/Serenity.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/CommonArgs.h" |
| 62 | #include "clang/Driver/Compilation.h" |
| 63 | #include "clang/Driver/InputInfo.h" |
| 64 | #include "clang/Driver/Job.h" |
| 65 | #include "clang/Driver/ModulesDriver.h" |
| 66 | #include "clang/Driver/Phases.h" |
| 67 | #include "clang/Driver/SanitizerArgs.h" |
| 68 | #include "clang/Driver/Tool.h" |
| 69 | #include "clang/Driver/ToolChain.h" |
| 70 | #include "clang/Driver/Types.h" |
| 71 | #include "clang/Options/OptionUtils.h" |
| 72 | #include "clang/Options/Options.h" |
| 73 | #include "clang/ScalableStaticAnalysis/Core/Serialization/SerializationFormatRegistry.h" |
| 74 | #include "clang/ScalableStaticAnalysis/Core/TUSummary/ExtractorRegistry.h" |
| 75 | #include "clang/ScalableStaticAnalysis/SSAFForceLinker.h" // IWYU pragma: keep |
| 76 | #include "llvm/ADT/ArrayRef.h" |
| 77 | #include "llvm/ADT/STLExtras.h" |
| 78 | #include "llvm/ADT/ScopeExit.h" |
| 79 | #include "llvm/ADT/SmallSet.h" |
| 80 | #include "llvm/ADT/SmallVector.h" |
| 81 | #include "llvm/ADT/StringExtras.h" |
| 82 | #include "llvm/ADT/StringRef.h" |
| 83 | #include "llvm/ADT/StringSet.h" |
| 84 | #include "llvm/ADT/StringSwitch.h" |
| 85 | #include "llvm/Config/llvm-config.h" |
| 86 | #include "llvm/MC/TargetRegistry.h" |
| 87 | #include "llvm/Option/Arg.h" |
| 88 | #include "llvm/Option/ArgList.h" |
| 89 | #include "llvm/Option/OptSpecifier.h" |
| 90 | #include "llvm/Option/OptTable.h" |
| 91 | #include "llvm/Option/Option.h" |
| 92 | #include "llvm/Support/CommandLine.h" |
| 93 | #include "llvm/Support/ErrorHandling.h" |
| 94 | #include "llvm/Support/ExitCodes.h" |
| 95 | #include "llvm/Support/FileSystem.h" |
| 96 | #include "llvm/Support/FileUtilities.h" |
| 97 | #include "llvm/Support/FormatVariadic.h" |
| 98 | #include "llvm/Support/IOSandbox.h" |
| 99 | #include "llvm/Support/JSON.h" |
| 100 | #include "llvm/Support/MD5.h" |
| 101 | #include "llvm/Support/MemoryBuffer.h" |
| 102 | #include "llvm/Support/Path.h" |
| 103 | #include "llvm/Support/PrettyStackTrace.h" |
| 104 | #include "llvm/Support/Process.h" |
| 105 | #include "llvm/Support/Program.h" |
| 106 | #include "llvm/Support/Regex.h" |
| 107 | #include "llvm/Support/StringSaver.h" |
| 108 | #include "llvm/Support/TarWriter.h" |
| 109 | #include "llvm/Support/VirtualFileSystem.h" |
| 110 | #include "llvm/Support/raw_ostream.h" |
| 111 | #include "llvm/TargetParser/Host.h" |
| 112 | #include "llvm/TargetParser/RISCVISAInfo.h" |
| 113 | #include <cstdlib> // ::getenv |
| 114 | #include <map> |
| 115 | #include <memory> |
| 116 | #include <optional> |
| 117 | #include <set> |
| 118 | #include <string> |
| 119 | #include <utility> |
| 120 | #if LLVM_ON_UNIX |
| 121 | #include <unistd.h> // getpid |
| 122 | #endif |
| 123 | |
| 124 | using namespace clang::driver; |
| 125 | using namespace clang; |
| 126 | using namespace llvm::opt; |
| 127 | |
| 128 | template <typename F> static bool usesInput(const ArgList &Args, F &&Fn) { |
| 129 | return llvm::any_of(Args, [&](Arg *A) { |
| 130 | return (A->getOption().matches(ID: options::OPT_x) && |
| 131 | Fn(types::lookupTypeForTypeSpecifier(Name: A->getValue()))) || |
| 132 | (A->getOption().getKind() == Option::InputClass && |
| 133 | StringRef(A->getValue()).rfind(C: '.') != StringRef::npos && |
| 134 | Fn(types::lookupTypeForExtension( |
| 135 | Ext: &A->getValue()[StringRef(A->getValue()).rfind(C: '.') + 1]))); |
| 136 | }); |
| 137 | } |
| 138 | |
| 139 | static bool isIncludeDirArg(StringRef Arg) { |
| 140 | return Arg == "-internal-isystem" || Arg == "-internal-externc-isystem" || |
| 141 | Arg == "-isystem" || Arg == "-cxx-isystem" || Arg == "-idirafter" ; |
| 142 | } |
| 143 | |
| 144 | static void printCXXStdlibIncludeDirs(const ToolChain &TC, |
| 145 | const ArgList &Args) { |
| 146 | ArgStringList CC1Args; |
| 147 | if (Args.hasArg(Ids: options::OPT_stdlibxx_isystem)) |
| 148 | TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args); |
| 149 | else |
| 150 | TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args); |
| 151 | |
| 152 | for (size_t I = 0; I < CC1Args.size(); ++I) { |
| 153 | StringRef Arg(CC1Args[I]); |
| 154 | if (isIncludeDirArg(Arg) && I + 1 < CC1Args.size()) |
| 155 | llvm::outs() << CC1Args[++I] << '\n'; |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | CUIDOptions::CUIDOptions(llvm::opt::DerivedArgList &Args, const Driver &D) |
| 160 | : UseCUID(Kind::Hash) { |
| 161 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fuse_cuid_EQ)) { |
| 162 | StringRef UseCUIDStr = A->getValue(); |
| 163 | UseCUID = llvm::StringSwitch<Kind>(UseCUIDStr) |
| 164 | .Case(S: "hash" , Value: Kind::Hash) |
| 165 | .Case(S: "random" , Value: Kind::Random) |
| 166 | .Case(S: "none" , Value: Kind::None) |
| 167 | .Default(Value: Kind::Invalid); |
| 168 | if (UseCUID == Kind::Invalid) |
| 169 | D.Diag(DiagID: clang::diag::err_drv_invalid_value) |
| 170 | << A->getAsString(Args) << UseCUIDStr; |
| 171 | } |
| 172 | |
| 173 | FixedCUID = Args.getLastArgValue(Id: options::OPT_cuid_EQ); |
| 174 | if (!FixedCUID.empty()) |
| 175 | UseCUID = Kind::Fixed; |
| 176 | } |
| 177 | |
| 178 | std::string CUIDOptions::getCUID(StringRef InputFile, |
| 179 | llvm::opt::DerivedArgList &Args) const { |
| 180 | std::string CUID = FixedCUID.str(); |
| 181 | if (CUID.empty()) { |
| 182 | if (UseCUID == Kind::Random) |
| 183 | CUID = llvm::utohexstr(X: llvm::sys::Process::GetRandomNumber(), |
| 184 | /*LowerCase=*/true); |
| 185 | else if (UseCUID == Kind::Hash) { |
| 186 | llvm::MD5 Hasher; |
| 187 | llvm::MD5::MD5Result Hash; |
| 188 | Hasher.update(Str: InputFile); |
| 189 | for (auto *A : Args) { |
| 190 | if (A->getOption().matches(ID: options::OPT_INPUT)) |
| 191 | continue; |
| 192 | Hasher.update(Str: A->getAsString(Args)); |
| 193 | } |
| 194 | Hasher.final(Result&: Hash); |
| 195 | CUID = llvm::utohexstr(X: Hash.low(), /*LowerCase=*/true); |
| 196 | } |
| 197 | } |
| 198 | return CUID; |
| 199 | } |
| 200 | Driver::Driver(StringRef DriverExecutable, StringRef TargetTriple, |
| 201 | DiagnosticsEngine &Diags, std::string Title, |
| 202 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) |
| 203 | : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode), |
| 204 | SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), |
| 205 | Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None), |
| 206 | ModulesModeCXX20(false), DriverExecutable(DriverExecutable), |
| 207 | SysRoot(DEFAULT_SYSROOT), DriverTitle(Title), CCCPrintBindings(false), |
| 208 | CCPrintOptions(false), CCLogDiagnostics(false), CCGenDiagnostics(false), |
| 209 | CCPrintProcessStats(false), CCPrintInternalStats(false), |
| 210 | TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr), |
| 211 | PreferredLinker(CLANG_DEFAULT_LINKER), CheckInputsExist(true), |
| 212 | ProbePrecompiled(true), SuppressMissingInputWarning(false) { |
| 213 | // Provide a sane fallback if no VFS is specified. |
| 214 | if (!this->VFS) |
| 215 | this->VFS = llvm::vfs::getRealFileSystem(); |
| 216 | |
| 217 | Name = std::string(llvm::sys::path::filename(path: DriverExecutable)); |
| 218 | Dir = std::string(llvm::sys::path::parent_path(path: DriverExecutable)); |
| 219 | |
| 220 | if ((!SysRoot.empty()) && llvm::sys::path::is_relative(path: SysRoot)) { |
| 221 | // Prepend InstalledDir if SysRoot is relative |
| 222 | SmallString<128> P(Dir); |
| 223 | llvm::sys::path::append(path&: P, a: SysRoot); |
| 224 | SysRoot = std::string(P); |
| 225 | } |
| 226 | |
| 227 | #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR) |
| 228 | if (llvm::sys::path::is_absolute(CLANG_CONFIG_FILE_SYSTEM_DIR)) { |
| 229 | SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR; |
| 230 | } else { |
| 231 | SmallString<128> configFileDir(Dir); |
| 232 | llvm::sys::path::append(configFileDir, CLANG_CONFIG_FILE_SYSTEM_DIR); |
| 233 | llvm::sys::path::remove_dots(configFileDir, true); |
| 234 | SystemConfigDir = static_cast<std::string>(configFileDir); |
| 235 | } |
| 236 | #endif |
| 237 | #if defined(CLANG_CONFIG_FILE_USER_DIR) |
| 238 | { |
| 239 | SmallString<128> P; |
| 240 | llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR, P); |
| 241 | UserConfigDir = static_cast<std::string>(P); |
| 242 | } |
| 243 | #endif |
| 244 | |
| 245 | // Compute the path to the resource directory. |
| 246 | ResourceDir = GetResourcesPath(BinaryPath: DriverExecutable); |
| 247 | } |
| 248 | |
| 249 | void Driver::setDriverMode(StringRef Value) { |
| 250 | static StringRef OptName = |
| 251 | getOpts().getOption(Opt: options::OPT_driver_mode).getPrefixedName(); |
| 252 | if (auto M = llvm::StringSwitch<std::optional<DriverMode>>(Value) |
| 253 | .Case(S: "gcc" , Value: GCCMode) |
| 254 | .Case(S: "g++" , Value: GXXMode) |
| 255 | .Case(S: "cpp" , Value: CPPMode) |
| 256 | .Case(S: "cl" , Value: CLMode) |
| 257 | .Case(S: "flang" , Value: FlangMode) |
| 258 | .Case(S: "dxc" , Value: DXCMode) |
| 259 | .Default(Value: std::nullopt)) |
| 260 | Mode = *M; |
| 261 | else |
| 262 | Diag(DiagID: diag::err_drv_unsupported_option_argument) << OptName << Value; |
| 263 | } |
| 264 | |
| 265 | InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings, |
| 266 | bool UseDriverMode, |
| 267 | bool &ContainsError) const { |
| 268 | llvm::PrettyStackTraceString CrashInfo("Command line argument parsing" ); |
| 269 | ContainsError = false; |
| 270 | |
| 271 | llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(UseDriverMode); |
| 272 | unsigned MissingArgIndex, MissingArgCount; |
| 273 | InputArgList Args = getOpts().ParseArgs(Args: ArgStrings, MissingArgIndex, |
| 274 | MissingArgCount, VisibilityMask); |
| 275 | |
| 276 | // Check for missing argument error. |
| 277 | if (MissingArgCount) { |
| 278 | Diag(DiagID: diag::err_drv_missing_argument) |
| 279 | << Args.getArgString(Index: MissingArgIndex) << MissingArgCount; |
| 280 | ContainsError |= |
| 281 | Diags.getDiagnosticLevel(DiagID: diag::err_drv_missing_argument, |
| 282 | Loc: SourceLocation()) > DiagnosticsEngine::Warning; |
| 283 | } |
| 284 | |
| 285 | // Check for unsupported options. |
| 286 | for (const Arg *A : Args) { |
| 287 | if (A->getOption().hasFlag(Val: options::Unsupported)) { |
| 288 | Diag(DiagID: diag::err_drv_unsupported_opt) << A->getAsString(Args); |
| 289 | ContainsError |= Diags.getDiagnosticLevel(DiagID: diag::err_drv_unsupported_opt, |
| 290 | Loc: SourceLocation()) > |
| 291 | DiagnosticsEngine::Warning; |
| 292 | continue; |
| 293 | } |
| 294 | |
| 295 | // Warn about -mcpu= without an argument. |
| 296 | if (A->getOption().matches(ID: options::OPT_mcpu_EQ) && A->containsValue(Value: "" )) { |
| 297 | Diag(DiagID: diag::warn_drv_empty_joined_argument) << A->getAsString(Args); |
| 298 | ContainsError |= Diags.getDiagnosticLevel( |
| 299 | DiagID: diag::warn_drv_empty_joined_argument, |
| 300 | Loc: SourceLocation()) > DiagnosticsEngine::Warning; |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | for (const Arg *A : Args.filtered(Ids: options::OPT_UNKNOWN)) { |
| 305 | unsigned DiagID; |
| 306 | auto ArgString = A->getAsString(Args); |
| 307 | std::string Nearest; |
| 308 | if (getOpts().findNearest(Option: ArgString, NearestString&: Nearest, VisibilityMask) > 1) { |
| 309 | if (IsFlangMode()) { |
| 310 | if (getOpts().findExact(Option: ArgString, ExactString&: Nearest, |
| 311 | VisibilityMask: llvm::opt::Visibility(options::FC1Option))) { |
| 312 | DiagID = diag::err_drv_unknown_argument_with_suggestion; |
| 313 | Diags.Report(DiagID) << ArgString << "-Xflang " + Nearest; |
| 314 | } else { |
| 315 | DiagID = diag::err_drv_unknown_argument; |
| 316 | Diags.Report(DiagID) << ArgString; |
| 317 | } |
| 318 | } else if (!IsCLMode() && getOpts().findExact(Option: ArgString, ExactString&: Nearest, |
| 319 | VisibilityMask: llvm::opt::Visibility( |
| 320 | options::CC1Option))) { |
| 321 | DiagID = diag::err_drv_unknown_argument_with_suggestion; |
| 322 | Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest; |
| 323 | } else { |
| 324 | DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl |
| 325 | : diag::err_drv_unknown_argument; |
| 326 | Diags.Report(DiagID) << ArgString; |
| 327 | } |
| 328 | } else { |
| 329 | DiagID = IsCLMode() |
| 330 | ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion |
| 331 | : diag::err_drv_unknown_argument_with_suggestion; |
| 332 | Diags.Report(DiagID) << ArgString << Nearest; |
| 333 | } |
| 334 | ContainsError |= Diags.getDiagnosticLevel(DiagID, Loc: SourceLocation()) > |
| 335 | DiagnosticsEngine::Warning; |
| 336 | } |
| 337 | |
| 338 | for (const Arg *A : Args.filtered(Ids: options::OPT_o)) { |
| 339 | if (ArgStrings[A->getIndex()] == A->getSpelling()) |
| 340 | continue; |
| 341 | |
| 342 | // Warn on joined arguments that are similar to a long argument. |
| 343 | std::string ArgString = ArgStrings[A->getIndex()]; |
| 344 | std::string Nearest; |
| 345 | if (getOpts().findExact(Option: "-" + ArgString, ExactString&: Nearest, VisibilityMask)) |
| 346 | Diags.Report(DiagID: diag::warn_drv_potentially_misspelled_joined_argument) |
| 347 | << A->getAsString(Args) << Nearest; |
| 348 | } |
| 349 | |
| 350 | return Args; |
| 351 | } |
| 352 | |
| 353 | // Determine which compilation mode we are in. We look for options which |
| 354 | // affect the phase, starting with the earliest phases, and record which |
| 355 | // option we used to determine the final phase. In absence of any explicit |
| 356 | // action command line option, derive the compilation mode from the inputs. |
| 357 | phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, |
| 358 | llvm::ArrayRef<InputTy> Inputs, |
| 359 | Arg **FinalPhaseArg) const { |
| 360 | Arg *PhaseArg = nullptr; |
| 361 | phases::ID FinalPhase; |
| 362 | |
| 363 | // -{E,EP,P,M,MM} only run the preprocessor. |
| 364 | if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(Ids: options::OPT_E)) || |
| 365 | (PhaseArg = DAL.getLastArg(Ids: options::OPT__SLASH_EP)) || |
| 366 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_M, Ids: options::OPT_MM)) || |
| 367 | (PhaseArg = DAL.getLastArg(Ids: options::OPT__SLASH_P)) || |
| 368 | CCGenDiagnostics) { |
| 369 | FinalPhase = phases::Preprocess; |
| 370 | |
| 371 | // --precompile only runs up to precompilation. |
| 372 | // Options that cause the output of C++20 compiled module interfaces or |
| 373 | // header units have the same effect. |
| 374 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT__precompile)) || |
| 375 | (PhaseArg = |
| 376 | DAL.getLastArg(Ids: options::OPT__precompile_reduced_bmi)) || |
| 377 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_extract_api)) || |
| 378 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_fmodule_header, |
| 379 | Ids: options::OPT_fmodule_header_EQ))) { |
| 380 | FinalPhase = phases::Precompile; |
| 381 | // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler. |
| 382 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_fsyntax_only)) || |
| 383 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_print_supported_cpus)) || |
| 384 | (PhaseArg = |
| 385 | DAL.getLastArg(Ids: options::OPT_print_enabled_extensions)) || |
| 386 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_module_file_info)) || |
| 387 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_verify_pch)) || |
| 388 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_rewrite_objc)) || |
| 389 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_rewrite_legacy_objc)) || |
| 390 | (PhaseArg = DAL.getLastArg(Ids: options::OPT__analyze)) || |
| 391 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_emit_cir)) || |
| 392 | (PhaseArg = DAL.getLastArg(Ids: options::OPT_emit_ast))) { |
| 393 | FinalPhase = phases::Compile; |
| 394 | |
| 395 | // -S only runs up to the backend. |
| 396 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_S))) { |
| 397 | FinalPhase = phases::Backend; |
| 398 | |
| 399 | // -c compilation only runs up to the assembler. |
| 400 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_c))) { |
| 401 | FinalPhase = phases::Assemble; |
| 402 | |
| 403 | } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_emit_interface_stubs))) { |
| 404 | FinalPhase = phases::IfsMerge; |
| 405 | |
| 406 | // Otherwise autodetect from last phase triggered by input file. |
| 407 | } else { |
| 408 | FinalPhase = phases::Preprocess; |
| 409 | bool AnyPhase = false; |
| 410 | for (auto &I : Inputs) { |
| 411 | types::ID InputType = I.first; |
| 412 | const Arg *InputArg = I.second; |
| 413 | |
| 414 | // Linker options should not trigger more phases. |
| 415 | if (InputArg->getOption().hasFlag(Val: options::LinkerInput)) |
| 416 | continue; |
| 417 | |
| 418 | // Relies on the compilation phases being ordered. |
| 419 | auto PL = types::getCompilationPhases(Id: InputType); |
| 420 | if (PL.empty()) |
| 421 | continue; |
| 422 | |
| 423 | phases::ID LastPL = PL.back(); |
| 424 | if (LastPL > FinalPhase) |
| 425 | FinalPhase = LastPL; |
| 426 | AnyPhase = true; |
| 427 | } |
| 428 | |
| 429 | // Fall back to "do everything" when consistency check fails. |
| 430 | if (!AnyPhase || FinalPhase > phases::Link) |
| 431 | FinalPhase = phases::Link; |
| 432 | } |
| 433 | |
| 434 | if (FinalPhaseArg) |
| 435 | *FinalPhaseArg = PhaseArg; |
| 436 | |
| 437 | return FinalPhase; |
| 438 | } |
| 439 | |
| 440 | llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> |
| 441 | Driver::executeProgram(llvm::ArrayRef<llvm::StringRef> Args) const { |
| 442 | llvm::SmallString<64> OutputFile; |
| 443 | llvm::sys::fs::createTemporaryFile(Prefix: "driver-program" , Suffix: "txt" , ResultPath&: OutputFile, |
| 444 | Flags: llvm::sys::fs::OF_Text); |
| 445 | llvm::FileRemover OutputRemover(OutputFile.c_str()); |
| 446 | std::optional<llvm::StringRef> Redirects[] = { |
| 447 | {"" }, |
| 448 | OutputFile.str(), |
| 449 | {"" }, |
| 450 | }; |
| 451 | |
| 452 | std::string ErrorMessage; |
| 453 | int SecondsToWait = 60; |
| 454 | if (std::optional<std::string> Str = |
| 455 | llvm::sys::Process::GetEnv(name: "CLANG_TOOLCHAIN_PROGRAM_TIMEOUT" )) { |
| 456 | if (!llvm::to_integer(S: *Str, Num&: SecondsToWait)) |
| 457 | return llvm::createStringError(EC: std::error_code(), |
| 458 | S: "CLANG_TOOLCHAIN_PROGRAM_TIMEOUT expected " |
| 459 | "an integer, got '" + |
| 460 | *Str + "'" ); |
| 461 | SecondsToWait = std::max(a: SecondsToWait, b: 0); // infinite |
| 462 | } |
| 463 | StringRef Executable = Args[0]; |
| 464 | if (llvm::sys::ExecuteAndWait(Program: Executable, Args, Env: {}, Redirects, SecondsToWait, |
| 465 | /*MemoryLimit=*/0, ErrMsg: &ErrorMessage)) |
| 466 | return llvm::createStringError(EC: std::error_code(), |
| 467 | S: Executable + ": " + ErrorMessage); |
| 468 | |
| 469 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> OutputBuf = |
| 470 | llvm::MemoryBuffer::getFile(Filename: OutputFile.c_str()); |
| 471 | if (!OutputBuf) |
| 472 | return llvm::createStringError(EC: OutputBuf.getError(), |
| 473 | S: "Failed to read stdout of " + Executable + |
| 474 | ": " + OutputBuf.getError().message()); |
| 475 | return std::move(*OutputBuf); |
| 476 | } |
| 477 | |
| 478 | Arg *clang::driver::makeInputArg(DerivedArgList &Args, const OptTable &Opts, |
| 479 | StringRef Value, bool Claim) { |
| 480 | Arg *A = new Arg(Opts.getOption(Opt: options::OPT_INPUT), Value, |
| 481 | Args.getBaseArgs().MakeIndex(String0: Value), Value.data()); |
| 482 | Args.AddSynthesizedArg(A); |
| 483 | if (Claim) |
| 484 | A->claim(); |
| 485 | return A; |
| 486 | } |
| 487 | |
| 488 | DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { |
| 489 | const llvm::opt::OptTable &Opts = getOpts(); |
| 490 | DerivedArgList *DAL = new DerivedArgList(Args); |
| 491 | |
| 492 | bool HasNostdlib = Args.hasArg(Ids: options::OPT_nostdlib); |
| 493 | bool HasNostdlibxx = Args.hasArg(Ids: options::OPT_nostdlibxx); |
| 494 | bool HasNodefaultlib = Args.hasArg(Ids: options::OPT_nodefaultlibs); |
| 495 | bool IgnoreUnused = false; |
| 496 | for (Arg *A : Args) { |
| 497 | if (IgnoreUnused) |
| 498 | A->claim(); |
| 499 | |
| 500 | if (A->getOption().matches(ID: options::OPT_start_no_unused_arguments)) { |
| 501 | IgnoreUnused = true; |
| 502 | continue; |
| 503 | } |
| 504 | if (A->getOption().matches(ID: options::OPT_end_no_unused_arguments)) { |
| 505 | IgnoreUnused = false; |
| 506 | continue; |
| 507 | } |
| 508 | |
| 509 | // Unfortunately, we have to parse some forwarding options (-Xassembler, |
| 510 | // -Xlinker, -Xpreprocessor) because we either integrate their functionality |
| 511 | // (assembler and preprocessor), or bypass a previous driver ('collect2'). |
| 512 | |
| 513 | // Rewrite linker options, to replace --no-demangle with a custom internal |
| 514 | // option. |
| 515 | if ((A->getOption().matches(ID: options::OPT_Wl_COMMA) || |
| 516 | A->getOption().matches(ID: options::OPT_Xlinker)) && |
| 517 | A->containsValue(Value: "--no-demangle" )) { |
| 518 | // Add the rewritten no-demangle argument. |
| 519 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Z_Xlinker__no_demangle)); |
| 520 | |
| 521 | // Add the remaining values as Xlinker arguments. |
| 522 | for (StringRef Val : A->getValues()) |
| 523 | if (Val != "--no-demangle" ) |
| 524 | DAL->AddSeparateArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Xlinker), Value: Val); |
| 525 | |
| 526 | continue; |
| 527 | } |
| 528 | |
| 529 | // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by |
| 530 | // some build systems. We don't try to be complete here because we don't |
| 531 | // care to encourage this usage model. |
| 532 | if (A->getOption().matches(ID: options::OPT_Wp_COMMA) && |
| 533 | A->getNumValues() > 0 && |
| 534 | (A->getValue(N: 0) == StringRef("-MD" ) || |
| 535 | A->getValue(N: 0) == StringRef("-MMD" ))) { |
| 536 | // Rewrite to -MD/-MMD along with -MF. |
| 537 | if (A->getValue(N: 0) == StringRef("-MD" )) |
| 538 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MD)); |
| 539 | else |
| 540 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MMD)); |
| 541 | if (A->getNumValues() == 2) |
| 542 | DAL->AddSeparateArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MF), Value: A->getValue(N: 1)); |
| 543 | continue; |
| 544 | } |
| 545 | |
| 546 | // Rewrite reserved library names. |
| 547 | if (A->getOption().matches(ID: options::OPT_l)) { |
| 548 | StringRef Value = A->getValue(); |
| 549 | |
| 550 | // Rewrite unless -nostdlib is present. |
| 551 | if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx && |
| 552 | Value == "stdc++" ) { |
| 553 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Z_reserved_lib_stdcxx)); |
| 554 | continue; |
| 555 | } |
| 556 | |
| 557 | // Rewrite unconditionally. |
| 558 | if (Value == "cc_kext" ) { |
| 559 | DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Z_reserved_lib_cckext)); |
| 560 | continue; |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | // Pick up inputs via the -- option. |
| 565 | if (A->getOption().matches(ID: options::OPT__DASH_DASH)) { |
| 566 | A->claim(); |
| 567 | for (StringRef Val : A->getValues()) |
| 568 | DAL->append(A: makeInputArg(Args&: *DAL, Opts, Value: Val, Claim: false)); |
| 569 | continue; |
| 570 | } |
| 571 | |
| 572 | DAL->append(A); |
| 573 | } |
| 574 | |
| 575 | // DXC mode quits before assembly if an output object file isn't specified. |
| 576 | if (IsDXCMode() && !Args.hasArg(Ids: options::OPT_dxc_Fo)) |
| 577 | DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_S)); |
| 578 | |
| 579 | // Enforce -static if -miamcu is present. |
| 580 | if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) |
| 581 | DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_static)); |
| 582 | |
| 583 | // Add a default value of -mlinker-version=, if one was given and the user |
| 584 | // didn't specify one. |
| 585 | #if defined(HOST_LINK_VERSION) |
| 586 | if (!Args.hasArg(options::OPT_mlinker_version_EQ) && |
| 587 | strlen(HOST_LINK_VERSION) > 0) { |
| 588 | DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ), |
| 589 | HOST_LINK_VERSION); |
| 590 | DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); |
| 591 | } |
| 592 | #endif |
| 593 | |
| 594 | return DAL; |
| 595 | } |
| 596 | |
| 597 | static void setZosTargetVersion(const Driver &D, llvm::Triple &Target, |
| 598 | StringRef ArgTarget) { |
| 599 | |
| 600 | static bool BeSilent = false; |
| 601 | auto IsTooOldToBeSupported = [](int v, int r) -> bool { return v < 3; }; |
| 602 | |
| 603 | /* expect CURRENT, zOSVnRn, or 0xnnnnnnnn */ |
| 604 | if (ArgTarget.equals_insensitive(RHS: "CURRENT" )) { |
| 605 | /* If the user gives CURRENT, then we rely on the LE to set */ |
| 606 | /* __TARGET_LIB__. There's nothing more we need to do. */ |
| 607 | } else { |
| 608 | unsigned int Version = 0; |
| 609 | unsigned int Release = 0; |
| 610 | unsigned int Modification = 0; |
| 611 | bool IsOk = true; |
| 612 | llvm::Regex ZOsvRegex("[zZ][oO][sS][vV]([0-9])[rR]([0-9])" ); |
| 613 | llvm::Regex HexRegex( |
| 614 | "0x4" /* product */ |
| 615 | "([0-9a-fA-F])" /* version */ |
| 616 | "([0-9a-fA-F][0-9a-fA-F])" /* release */ |
| 617 | "([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])" /* modification */); |
| 618 | SmallVector<StringRef> Matches; |
| 619 | |
| 620 | if (ZOsvRegex.match(String: ArgTarget, Matches: &Matches)) { |
| 621 | Matches[1].getAsInteger(Radix: 10, Result&: Version); |
| 622 | Matches[2].getAsInteger(Radix: 10, Result&: Release); |
| 623 | Modification = 0; |
| 624 | if (IsTooOldToBeSupported(Version, Release)) { |
| 625 | if (!BeSilent) |
| 626 | D.Diag(DiagID: diag::err_zos_target_release_discontinued) << ArgTarget; |
| 627 | IsOk = false; |
| 628 | } |
| 629 | } else if (HexRegex.match(String: ArgTarget, Matches: &Matches)) { |
| 630 | Matches[1].getAsInteger(Radix: 16, Result&: Version); |
| 631 | Matches[2].getAsInteger(Radix: 16, Result&: Release); |
| 632 | Matches[3].getAsInteger(Radix: 16, Result&: Modification); |
| 633 | if (IsTooOldToBeSupported(Version, Release)) { |
| 634 | if (!BeSilent) |
| 635 | D.Diag(DiagID: diag::err_zos_target_release_discontinued) << ArgTarget; |
| 636 | IsOk = false; |
| 637 | } |
| 638 | } else { |
| 639 | /* something else: need to report an error */ |
| 640 | if (!BeSilent) |
| 641 | D.Diag(DiagID: diag::err_zos_target_unrecognized_release) << ArgTarget; |
| 642 | IsOk = false; |
| 643 | } |
| 644 | |
| 645 | if (IsOk) { |
| 646 | llvm::VersionTuple V(Version, Release, Modification); |
| 647 | llvm::VersionTuple TV = Target.getOSVersion(); |
| 648 | // The goal is to pick the minimally supported version of |
| 649 | // the OS. Pick the lesser as the target. |
| 650 | if (TV.empty() || V < TV) { |
| 651 | SmallString<16> Str; |
| 652 | Str = llvm::Triple::getOSTypeName(Kind: Target.getOS()); |
| 653 | Str += V.getAsString(); |
| 654 | Target.setOSName(Str); |
| 655 | } |
| 656 | } |
| 657 | } |
| 658 | BeSilent = true; |
| 659 | } |
| 660 | |
| 661 | /// Compute target triple from args. |
| 662 | /// |
| 663 | /// This routine provides the logic to compute a target triple from various |
| 664 | /// args passed to the driver and the default triple string. |
| 665 | static llvm::Triple computeTargetTriple(const Driver &D, StringRef TargetTriple, |
| 666 | const ArgList &Args, |
| 667 | StringRef ArchName = "" ) { |
| 668 | // FIXME: Already done in Compilation *Driver::BuildCompilation |
| 669 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_target)) |
| 670 | TargetTriple = A->getValue(); |
| 671 | |
| 672 | llvm::Triple Target(llvm::Triple::normalize(Str: TargetTriple)); |
| 673 | |
| 674 | // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made |
| 675 | // -gnu* only, and we can not change this, so we have to detect that case as |
| 676 | // being the Hurd OS. |
| 677 | if (TargetTriple.contains(Other: "-unknown-gnu" ) || TargetTriple.contains(Other: "-pc-gnu" )) |
| 678 | Target.setOSName("hurd" ); |
| 679 | |
| 680 | // Handle Apple-specific options available here. |
| 681 | if (Target.isOSBinFormatMachO()) { |
| 682 | // If an explicit Darwin arch name is given, that trumps all. |
| 683 | if (!ArchName.empty()) { |
| 684 | tools::darwin::setTripleTypeForMachOArchName(T&: Target, Str: ArchName, Args); |
| 685 | return llvm::Triple(Target.normalize()); |
| 686 | } |
| 687 | |
| 688 | // Handle the Darwin '-arch' flag. |
| 689 | if (Arg *A = Args.getLastArg(Ids: options::OPT_arch)) { |
| 690 | StringRef ArchName = A->getValue(); |
| 691 | tools::darwin::setTripleTypeForMachOArchName(T&: Target, Str: ArchName, Args); |
| 692 | } |
| 693 | } else if (!ArchName.empty()) { |
| 694 | Target.setArchName(ArchName); |
| 695 | return Target; |
| 696 | } |
| 697 | |
| 698 | // Handle pseudo-target flags '-mlittle-endian'/'-EL' and |
| 699 | // '-mbig-endian'/'-EB'. |
| 700 | if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_mlittle_endian, |
| 701 | Ids: options::OPT_mbig_endian)) { |
| 702 | llvm::Triple T = A->getOption().matches(ID: options::OPT_mlittle_endian) |
| 703 | ? Target.getLittleEndianArchVariant() |
| 704 | : Target.getBigEndianArchVariant(); |
| 705 | if (T.getArch() != llvm::Triple::UnknownArch) { |
| 706 | Target = llvm::Triple(T.normalize()); |
| 707 | Args.claimAllArgs(Ids: options::OPT_mlittle_endian, Ids: options::OPT_mbig_endian); |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | // Skip further flag support on OSes which don't support '-m32' or '-m64'. |
| 712 | if (Target.getArch() == llvm::Triple::tce) |
| 713 | return Target; |
| 714 | |
| 715 | // On AIX, the env OBJECT_MODE may affect the resulting arch variant. |
| 716 | // However, if --target was explicitly specified, it takes precedence. |
| 717 | #ifdef _AIX |
| 718 | if (!Args.hasArg(options::OPT_target)) { |
| 719 | if (std::optional<std::string> ObjectModeValue = |
| 720 | llvm::sys::Process::GetEnv("OBJECT_MODE" )) { |
| 721 | StringRef ObjectMode = *ObjectModeValue; |
| 722 | llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; |
| 723 | |
| 724 | if (D.IsFlangMode()) { |
| 725 | if (ObjectMode == "64" ) { |
| 726 | AT = Target.get64BitArchVariant().getArch(); |
| 727 | } else if (ObjectMode == "32" || ObjectMode == "32_64" || |
| 728 | ObjectMode == "any" ) { |
| 729 | // OBJECT_MODE setting can be overridden by -maix64/-m64 |
| 730 | if (Args.hasArg(options::OPT_maix64, options::OPT_m64)) |
| 731 | AT = Target.get64BitArchVariant().getArch(); |
| 732 | else |
| 733 | D.Diag(diag::err_drv_compile_mode_unsupported_aix); |
| 734 | } else { |
| 735 | D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode; |
| 736 | } |
| 737 | } else { |
| 738 | // Silently accept '32_64' and 'any' |
| 739 | const bool OtherAllowedMode = |
| 740 | ObjectMode == "32_64" || ObjectMode == "any" ; |
| 741 | if (ObjectMode == "64" ) |
| 742 | AT = Target.get64BitArchVariant().getArch(); |
| 743 | else if (ObjectMode == "32" ) |
| 744 | AT = Target.get32BitArchVariant().getArch(); |
| 745 | else if (!OtherAllowedMode) |
| 746 | D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode; |
| 747 | } |
| 748 | |
| 749 | if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) { |
| 750 | Target.setArch(AT); |
| 751 | Target = llvm::Triple(Target.normalize()); |
| 752 | } |
| 753 | } else if (D.IsFlangMode() && |
| 754 | !Args.hasArg(options::OPT_maix64, options::OPT_m64)) { |
| 755 | // For flang on AIX, if OBJECT_MODE is unset and neither |
| 756 | // -maix64 nor -m64 is specified, issue an error. |
| 757 | D.Diag(diag::err_drv_compile_mode_unsupported_aix); |
| 758 | } |
| 759 | } |
| 760 | #endif |
| 761 | |
| 762 | // Currently the only architecture supported by *-uefi triples are x86_64. |
| 763 | if (Target.isUEFI() && Target.getArch() != llvm::Triple::x86_64) |
| 764 | D.Diag(DiagID: diag::err_target_unknown_triple) << Target.str(); |
| 765 | |
| 766 | // The `-maix[32|64]` flags are only valid for AIX targets. |
| 767 | if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_maix32, Ids: options::OPT_maix64); |
| 768 | A && !Target.isOSAIX()) |
| 769 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 770 | << A->getAsString(Args) << Target.str(); |
| 771 | |
| 772 | // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'. |
| 773 | Arg *A = Args.getLastArg(Ids: options::OPT_m64, Ids: options::OPT_mx32, |
| 774 | Ids: options::OPT_m32, Ids: options::OPT_m16, |
| 775 | Ids: options::OPT_maix32, Ids: options::OPT_maix64); |
| 776 | if (A) { |
| 777 | llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; |
| 778 | |
| 779 | if (A->getOption().matches(ID: options::OPT_m64) || |
| 780 | A->getOption().matches(ID: options::OPT_maix64)) { |
| 781 | AT = Target.get64BitArchVariant().getArch(); |
| 782 | if (Target.getEnvironment() == llvm::Triple::GNUX32 || |
| 783 | Target.getEnvironment() == llvm::Triple::GNUT64) |
| 784 | Target.setEnvironment(llvm::Triple::GNU); |
| 785 | else if (Target.getEnvironment() == llvm::Triple::MuslX32) |
| 786 | Target.setEnvironment(llvm::Triple::Musl); |
| 787 | } else if (A->getOption().matches(ID: options::OPT_mx32) && |
| 788 | Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) { |
| 789 | AT = llvm::Triple::x86_64; |
| 790 | if (Target.getEnvironment() == llvm::Triple::Musl) |
| 791 | Target.setEnvironment(llvm::Triple::MuslX32); |
| 792 | else |
| 793 | Target.setEnvironment(llvm::Triple::GNUX32); |
| 794 | } else if (A->getOption().matches(ID: options::OPT_m32) || |
| 795 | A->getOption().matches(ID: options::OPT_maix32)) { |
| 796 | if (D.IsFlangMode()) { |
| 797 | if (Target.isOSAIX()) { |
| 798 | D.Diag(DiagID: diag::err_drv_compile_mode_unsupported_aix); |
| 799 | } else { |
| 800 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 801 | << A->getAsString(Args) << Target.str(); |
| 802 | } |
| 803 | } else { |
| 804 | AT = Target.get32BitArchVariant().getArch(); |
| 805 | if (Target.getEnvironment() == llvm::Triple::GNUX32) |
| 806 | Target.setEnvironment(llvm::Triple::GNU); |
| 807 | else if (Target.getEnvironment() == llvm::Triple::MuslX32) |
| 808 | Target.setEnvironment(llvm::Triple::Musl); |
| 809 | } |
| 810 | } else if (A->getOption().matches(ID: options::OPT_m16) && |
| 811 | Target.get32BitArchVariant().getArch() == llvm::Triple::x86) { |
| 812 | AT = llvm::Triple::x86; |
| 813 | Target.setEnvironment(llvm::Triple::CODE16); |
| 814 | } |
| 815 | |
| 816 | if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) { |
| 817 | Target.setArch(Kind: AT); |
| 818 | if (Target.isWindowsGNUEnvironment()) |
| 819 | toolchains::MinGW::fixTripleArch(D, Triple&: Target, Args); |
| 820 | } |
| 821 | |
| 822 | Target = llvm::Triple(Target.normalize()); |
| 823 | } |
| 824 | |
| 825 | if (Target.isOSzOS()) { |
| 826 | if ((A = Args.getLastArg(Ids: options::OPT_mzos_target_EQ))) { |
| 827 | setZosTargetVersion(D, Target, ArgTarget: A->getValue()); |
| 828 | } |
| 829 | } |
| 830 | |
| 831 | // Handle -miamcu flag. |
| 832 | if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) { |
| 833 | if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86) |
| 834 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) << "-miamcu" |
| 835 | << Target.str(); |
| 836 | |
| 837 | if (A && !A->getOption().matches(ID: options::OPT_m32)) |
| 838 | D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) |
| 839 | << "-miamcu" << A->getBaseArg().getAsString(Args); |
| 840 | |
| 841 | Target.setArch(Kind: llvm::Triple::x86); |
| 842 | Target.setArchName("i586" ); |
| 843 | Target.setEnvironmentName("" ); |
| 844 | Target.setOS(llvm::Triple::ELFIAMCU); |
| 845 | Target.setVendor(llvm::Triple::Intel); |
| 846 | } |
| 847 | |
| 848 | // If target is MIPS adjust the target triple |
| 849 | // accordingly to provided ABI name. |
| 850 | if (Target.isMIPS()) { |
| 851 | if ((A = Args.getLastArg(Ids: options::OPT_mabi_EQ))) { |
| 852 | StringRef ABIName = A->getValue(); |
| 853 | if (ABIName == "32" ) { |
| 854 | Target = Target.get32BitArchVariant(); |
| 855 | if (Target.getEnvironment() == llvm::Triple::GNUABI64 || |
| 856 | Target.getEnvironment() == llvm::Triple::GNUABIN32) |
| 857 | Target.setEnvironment(llvm::Triple::GNU); |
| 858 | } else if (ABIName == "n32" ) { |
| 859 | Target = Target.get64BitArchVariant(); |
| 860 | if (Target.getEnvironment() == llvm::Triple::GNU || |
| 861 | Target.getEnvironment() == llvm::Triple::GNUT64 || |
| 862 | Target.getEnvironment() == llvm::Triple::GNUABI64) |
| 863 | Target.setEnvironment(llvm::Triple::GNUABIN32); |
| 864 | else if (Target.getEnvironment() == llvm::Triple::Musl || |
| 865 | Target.getEnvironment() == llvm::Triple::MuslABI64) |
| 866 | Target.setEnvironment(llvm::Triple::MuslABIN32); |
| 867 | } else if (ABIName == "64" ) { |
| 868 | Target = Target.get64BitArchVariant(); |
| 869 | if (Target.getEnvironment() == llvm::Triple::GNU || |
| 870 | Target.getEnvironment() == llvm::Triple::GNUT64 || |
| 871 | Target.getEnvironment() == llvm::Triple::GNUABIN32) |
| 872 | Target.setEnvironment(llvm::Triple::GNUABI64); |
| 873 | else if (Target.getEnvironment() == llvm::Triple::Musl || |
| 874 | Target.getEnvironment() == llvm::Triple::MuslABIN32) |
| 875 | Target.setEnvironment(llvm::Triple::MuslABI64); |
| 876 | } |
| 877 | |
| 878 | Target = llvm::Triple(Target.normalize()); |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | // If target is RISC-V adjust the target triple according to |
| 883 | // provided architecture name |
| 884 | if (Target.isRISCV()) { |
| 885 | if (Args.hasArg(Ids: options::OPT_march_EQ) || |
| 886 | Args.hasArg(Ids: options::OPT_mcpu_EQ)) { |
| 887 | std::string ArchName = tools::riscv::getRISCVArch(Args, Triple: Target); |
| 888 | auto ISAInfo = llvm::RISCVISAInfo::parseArchString( |
| 889 | Arch: ArchName, /*EnableExperimentalExtensions=*/EnableExperimentalExtension: true); |
| 890 | if (!llvm::errorToBool(Err: ISAInfo.takeError())) { |
| 891 | unsigned XLen = (*ISAInfo)->getXLen(); |
| 892 | if (XLen == 32) { |
| 893 | if (Target.isLittleEndian()) |
| 894 | Target.setArch(Kind: llvm::Triple::riscv32); |
| 895 | else |
| 896 | Target.setArch(Kind: llvm::Triple::riscv32be); |
| 897 | Target = llvm::Triple(Target.normalize()); |
| 898 | } else if (XLen == 64) { |
| 899 | if (Target.isLittleEndian()) |
| 900 | Target.setArch(Kind: llvm::Triple::riscv64); |
| 901 | else |
| 902 | Target.setArch(Kind: llvm::Triple::riscv64be); |
| 903 | Target = llvm::Triple(Target.normalize()); |
| 904 | } |
| 905 | } |
| 906 | } |
| 907 | } |
| 908 | |
| 909 | if (Target.getArch() == llvm::Triple::riscv32be || |
| 910 | Target.getArch() == llvm::Triple::riscv64be) { |
| 911 | static bool WarnedRISCVBE = false; |
| 912 | if (!WarnedRISCVBE) { |
| 913 | D.Diag(DiagID: diag::warn_drv_riscv_be_experimental); |
| 914 | WarnedRISCVBE = true; |
| 915 | } |
| 916 | } |
| 917 | |
| 918 | return Target; |
| 919 | } |
| 920 | |
| 921 | /// Compute the desired OpenMP runtime from the flags provided. |
| 922 | Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const { |
| 923 | StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME); |
| 924 | |
| 925 | const Arg *A = Args.getLastArg(Ids: options::OPT_fopenmp_EQ); |
| 926 | if (A) |
| 927 | RuntimeName = A->getValue(); |
| 928 | |
| 929 | auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName) |
| 930 | .Case(S: "libomp" , Value: OMPRT_OMP) |
| 931 | .Case(S: "libgomp" , Value: OMPRT_GOMP) |
| 932 | .Case(S: "libiomp5" , Value: OMPRT_IOMP5) |
| 933 | .Default(Value: OMPRT_Unknown); |
| 934 | |
| 935 | if (RT == OMPRT_Unknown) { |
| 936 | if (A) |
| 937 | Diag(DiagID: diag::err_drv_unsupported_option_argument) |
| 938 | << A->getSpelling() << A->getValue(); |
| 939 | else |
| 940 | // FIXME: We could use a nicer diagnostic here. |
| 941 | Diag(DiagID: diag::err_drv_unsupported_opt) << "-fopenmp" ; |
| 942 | } |
| 943 | |
| 944 | return RT; |
| 945 | } |
| 946 | |
| 947 | // Handles `native` offload architectures by using the 'offload-arch' utility. |
| 948 | static llvm::SmallVector<std::string> |
| 949 | getSystemOffloadArchs(Compilation &C, Action::OffloadKind Kind) { |
| 950 | StringRef Program = C.getArgs().getLastArgValue( |
| 951 | Id: options::OPT_offload_arch_tool_EQ, Default: "offload-arch" ); |
| 952 | |
| 953 | SmallVector<std::string> GPUArchs; |
| 954 | if (llvm::ErrorOr<std::string> Executable = |
| 955 | llvm::sys::findProgramByName(Name: Program, Paths: {C.getDriver().Dir})) { |
| 956 | llvm::SmallVector<StringRef> Args{*Executable}; |
| 957 | bool UsesLLVMOffloading = |
| 958 | C.getArgs().hasFlag(Pos: options::OPT_foffload_via_llvm, |
| 959 | Neg: options::OPT_fno_offload_via_llvm, Default: false); |
| 960 | if (!UsesLLVMOffloading) { |
| 961 | if (Kind == Action::OFK_HIP) |
| 962 | Args.push_back(Elt: "--only=amdgpu" ); |
| 963 | else if (Kind == Action::OFK_Cuda) |
| 964 | Args.push_back(Elt: "--only=nvptx" ); |
| 965 | } |
| 966 | auto StdoutOrErr = C.getDriver().executeProgram(Args); |
| 967 | |
| 968 | if (!StdoutOrErr) { |
| 969 | C.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch) |
| 970 | << Action::GetOffloadKindName(Kind) << StdoutOrErr.takeError() |
| 971 | << "--offload-arch" ; |
| 972 | return GPUArchs; |
| 973 | } |
| 974 | if ((*StdoutOrErr)->getBuffer().empty()) { |
| 975 | C.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch) |
| 976 | << Action::GetOffloadKindName(Kind) << "No GPU detected in the system" |
| 977 | << "--offload-arch" ; |
| 978 | return GPUArchs; |
| 979 | } |
| 980 | |
| 981 | for (StringRef Arch : llvm::split(Str: (*StdoutOrErr)->getBuffer(), Separator: "\n" )) |
| 982 | if (!Arch.empty()) |
| 983 | GPUArchs.push_back(Elt: Arch.str()); |
| 984 | } else { |
| 985 | C.getDriver().Diag(DiagID: diag::err_drv_command_failure) << "offload-arch" ; |
| 986 | } |
| 987 | return GPUArchs; |
| 988 | } |
| 989 | |
| 990 | using TripleSet = std::multiset<llvm::Triple>; |
| 991 | |
| 992 | // Attempts to infer the correct offloading toolchain triple by looking at the |
| 993 | // requested offloading kind and architectures. |
| 994 | static TripleSet inferOffloadToolchains(Compilation &C, |
| 995 | Action::OffloadKind Kind) { |
| 996 | std::set<std::string> Archs; |
| 997 | for (Arg *A : C.getInputArgs()) { |
| 998 | for (StringRef Arch : A->getValues()) { |
| 999 | if (A->getOption().matches(ID: options::OPT_offload_arch_EQ)) { |
| 1000 | if (Arch == "native" ) { |
| 1001 | for (StringRef Str : getSystemOffloadArchs(C, Kind)) |
| 1002 | Archs.insert(x: Str.str()); |
| 1003 | } else { |
| 1004 | Archs.insert(x: Arch.str()); |
| 1005 | } |
| 1006 | } else if (A->getOption().matches(ID: options::OPT_no_offload_arch_EQ)) { |
| 1007 | if (Arch == "all" ) |
| 1008 | Archs.clear(); |
| 1009 | else |
| 1010 | Archs.erase(x: Arch.str()); |
| 1011 | } |
| 1012 | } |
| 1013 | } |
| 1014 | |
| 1015 | TripleSet Triples; |
| 1016 | for (llvm::StringRef Arch : Archs) { |
| 1017 | OffloadArch ID = StringToOffloadArch(S: Arch); |
| 1018 | if (ID.isUnknown()) { |
| 1019 | llvm::Triple AMDGPUTriple(llvm::Triple::amdgpu, llvm::Triple::NoSubArch, |
| 1020 | llvm::Triple::AMD, llvm::Triple::AMDHSA); |
| 1021 | ID = StringToOffloadArch(S: getProcessorFromTargetID(T: AMDGPUTriple, OffloadArch: Arch)); |
| 1022 | } |
| 1023 | |
| 1024 | bool UsesLLVMOffloading = |
| 1025 | C.getArgs().hasFlag(Pos: options::OPT_foffload_via_llvm, |
| 1026 | Neg: options::OPT_fno_offload_via_llvm, Default: false); |
| 1027 | if (!UsesLLVMOffloading) { |
| 1028 | if (Kind == Action::OFK_HIP && !ID.isAMDGPU() && !ID.isAMDGCNSPIRV()) { |
| 1029 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 1030 | << "HIP" << Arch; |
| 1031 | return {}; |
| 1032 | } |
| 1033 | if (Kind == Action::OFK_Cuda && !ID.isNVPTX()) { |
| 1034 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 1035 | << "CUDA" << Arch; |
| 1036 | return {}; |
| 1037 | } |
| 1038 | } |
| 1039 | if (Kind == Action::OFK_OpenMP && (ID.isUnknown() || ID.isUnused())) { |
| 1040 | C.getDriver().Diag(DiagID: clang::diag::err_drv_failed_to_deduce_target_from_arch) |
| 1041 | << Arch; |
| 1042 | return {}; |
| 1043 | } |
| 1044 | if (ID.isUnknown() || ID.isUnused()) { |
| 1045 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 1046 | << "offload" << Arch; |
| 1047 | return {}; |
| 1048 | } |
| 1049 | |
| 1050 | llvm::Triple Triple = |
| 1051 | OffloadArchToTriple(DefaultToolchainTriple: C.getDefaultToolChain().getTriple(), ID); |
| 1052 | if (UsesLLVMOffloading) |
| 1053 | Triple.setEnvironment(llvm::Triple::LLVM); |
| 1054 | |
| 1055 | // Make a new argument that dispatches this argument to the appropriate |
| 1056 | // toolchain. This is required when we infer it and create potentially |
| 1057 | // incompatible toolchains from the global option. |
| 1058 | Option Opt = C.getDriver().getOpts().getOption(Opt: options::OPT_Xarch__); |
| 1059 | unsigned Index = C.getArgs().getBaseArgs().MakeIndex(String0: "-Xarch_" ); |
| 1060 | Arg *A = new Arg(Opt, C.getArgs().getArgString(Index), Index, |
| 1061 | C.getArgs().MakeArgString(Str: Triple.getArchName()), |
| 1062 | C.getArgs().MakeArgString(Str: "--offload-arch=" + Arch)); |
| 1063 | A->claim(); |
| 1064 | C.getArgs().append(A); |
| 1065 | C.getArgs().AddSynthesizedArg(A); |
| 1066 | |
| 1067 | auto It = Triples.lower_bound(x: Triple); |
| 1068 | if (It == Triples.end() || *It != Triple) |
| 1069 | Triples.insert(position: It, x: Triple); |
| 1070 | } |
| 1071 | |
| 1072 | // Infer the default target triple if no specific architectures are given. |
| 1073 | if (Archs.empty() && Kind == Action::OFK_HIP) { |
| 1074 | Triples.insert(x: llvm::Triple(llvm::Triple::amdgpu, llvm::Triple::NoSubArch, |
| 1075 | llvm::Triple::AMD, llvm::Triple::AMDHSA)); |
| 1076 | } else if (Archs.empty() && Kind == Action::OFK_Cuda) { |
| 1077 | llvm::Triple::ArchType Arch = |
| 1078 | C.getDefaultToolChain().getTriple().isArch64Bit() |
| 1079 | ? llvm::Triple::nvptx64 |
| 1080 | : llvm::Triple::nvptx; |
| 1081 | Triples.insert(x: llvm::Triple(Arch, llvm::Triple::NoSubArch, |
| 1082 | llvm::Triple::NVIDIA, llvm::Triple::CUDA)); |
| 1083 | } else if (Archs.empty() && Kind == Action::OFK_SYCL) |
| 1084 | Triples.insert( |
| 1085 | x: llvm::Triple(C.getDefaultToolChain().getTriple().isArch64Bit() |
| 1086 | ? llvm::Triple::spirv64 |
| 1087 | : llvm::Triple::spirv32)); |
| 1088 | |
| 1089 | // We need to dispatch these to the appropriate toolchain now. |
| 1090 | C.getArgs().eraseArg(Id: options::OPT_offload_arch_EQ); |
| 1091 | C.getArgs().eraseArg(Id: options::OPT_no_offload_arch_EQ); |
| 1092 | |
| 1093 | return Triples; |
| 1094 | } |
| 1095 | |
| 1096 | void Driver::CreateOffloadingDeviceToolChains(Compilation &C, |
| 1097 | InputList &Inputs) { |
| 1098 | bool IsCuda = |
| 1099 | llvm::any_of(Range&: Inputs, P: [](std::pair<types::ID, const llvm::opt::Arg *> &I) { |
| 1100 | return types::isCuda(Id: I.first); |
| 1101 | }); |
| 1102 | bool IsHIP = |
| 1103 | (llvm::any_of(Range&: Inputs, |
| 1104 | P: [](std::pair<types::ID, const llvm::opt::Arg *> &I) { |
| 1105 | return types::isHIP(Id: I.first); |
| 1106 | }) || |
| 1107 | C.getInputArgs().hasArg(Ids: options::OPT_hip_link) || |
| 1108 | C.getInputArgs().hasArg(Ids: options::OPT_hipstdpar)); |
| 1109 | bool IsSYCL = C.getInputArgs().hasFlag(Pos: options::OPT_fsycl, |
| 1110 | Neg: options::OPT_fno_sycl, Default: false); |
| 1111 | bool IsOpenMPOffloading = |
| 1112 | (C.getInputArgs().hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ, |
| 1113 | Neg: options::OPT_fno_openmp, Default: false) && |
| 1114 | (C.getInputArgs().hasArg(Ids: options::OPT_offload_targets_EQ) || |
| 1115 | (C.getInputArgs().hasArg(Ids: options::OPT_offload_arch_EQ) && |
| 1116 | !(IsCuda || IsHIP)))); |
| 1117 | |
| 1118 | llvm::SmallSet<Action::OffloadKind, 4> Kinds; |
| 1119 | const std::pair<bool, Action::OffloadKind> ActiveKinds[] = { |
| 1120 | {IsCuda, Action::OFK_Cuda}, |
| 1121 | {IsHIP, Action::OFK_HIP}, |
| 1122 | {IsOpenMPOffloading, Action::OFK_OpenMP}, |
| 1123 | {IsSYCL, Action::OFK_SYCL}}; |
| 1124 | for (const auto &[Active, Kind] : ActiveKinds) |
| 1125 | if (Active) |
| 1126 | Kinds.insert(V: Kind); |
| 1127 | |
| 1128 | // We currently don't support any kind of mixed offloading. |
| 1129 | if (Kinds.size() > 1) { |
| 1130 | Diag(DiagID: clang::diag::err_drv_mix_offload) |
| 1131 | << Action::GetOffloadKindName(Kind: *Kinds.begin()).upper() |
| 1132 | << Action::GetOffloadKindName(Kind: *(++Kinds.begin())).upper(); |
| 1133 | return; |
| 1134 | } |
| 1135 | |
| 1136 | // Initialize the compilation identifier used for unique CUDA / HIP names. |
| 1137 | if (IsCuda || IsHIP) |
| 1138 | CUIDOpts = CUIDOptions(C.getArgs(), *this); |
| 1139 | |
| 1140 | // Get the list of requested offloading toolchains. If they were not |
| 1141 | // explicitly specified we will infer them based on the offloading language |
| 1142 | // and requested architectures. |
| 1143 | TripleSet Triples; |
| 1144 | if (C.getInputArgs().hasArg(Ids: options::OPT_offload_targets_EQ)) { |
| 1145 | std::vector<std::string> ArgValues = |
| 1146 | C.getInputArgs().getAllArgValues(Id: options::OPT_offload_targets_EQ); |
| 1147 | for (llvm::StringRef Target : ArgValues) { |
| 1148 | Triples.insert(x: ToolChain::normalizeOffloadTriple(OrigTT: Target)); |
| 1149 | } |
| 1150 | |
| 1151 | if (ArgValues.empty()) |
| 1152 | Diag(DiagID: clang::diag::warn_drv_empty_joined_argument) |
| 1153 | << C.getInputArgs() |
| 1154 | .getLastArg(Ids: options::OPT_offload_targets_EQ) |
| 1155 | ->getAsString(Args: C.getInputArgs()); |
| 1156 | } else { |
| 1157 | for (Action::OffloadKind Kind : Kinds) |
| 1158 | Triples = inferOffloadToolchains(C, Kind); |
| 1159 | } |
| 1160 | |
| 1161 | // Build an offloading toolchain for every requested target and kind. |
| 1162 | llvm::StringMap<StringRef> FoundNormalizedTriples; |
| 1163 | for (const llvm::Triple &Target : Triples) { |
| 1164 | // OpenMP offloading requires a compatible libomp. |
| 1165 | if (Kinds.contains(V: Action::OFK_OpenMP)) { |
| 1166 | OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(Args: C.getInputArgs()); |
| 1167 | if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) { |
| 1168 | Diag(DiagID: clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets); |
| 1169 | return; |
| 1170 | } |
| 1171 | } |
| 1172 | |
| 1173 | // Certain options are not allowed when combined with SYCL compilation. |
| 1174 | if (Kinds.contains(V: Action::OFK_SYCL)) { |
| 1175 | for (auto ID : |
| 1176 | {options::OPT_static_libstdcxx, options::OPT_ffreestanding}) |
| 1177 | if (Arg *IncompatArg = C.getInputArgs().getLastArg(Ids: ID)) |
| 1178 | Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with) |
| 1179 | << IncompatArg->getSpelling() << "-fsycl" ; |
| 1180 | } |
| 1181 | |
| 1182 | // Create a device toolchain for every specified kind and triple. |
| 1183 | for (Action::OffloadKind Kind : Kinds) { |
| 1184 | if (Target.getArch() == llvm::Triple::ArchType::UnknownArch) { |
| 1185 | Diag(DiagID: diag::err_drv_invalid_or_unsupported_offload_target) |
| 1186 | << Target.str(); |
| 1187 | continue; |
| 1188 | } |
| 1189 | |
| 1190 | std::string NormalizedName = Target.normalize(); |
| 1191 | auto [TripleIt, Inserted] = |
| 1192 | FoundNormalizedTriples.try_emplace(Key: NormalizedName, Args: Target.str()); |
| 1193 | if (!Inserted) { |
| 1194 | Diag(DiagID: clang::diag::warn_drv_omp_offload_target_duplicate) |
| 1195 | << Target.str() << TripleIt->second; |
| 1196 | continue; |
| 1197 | } |
| 1198 | |
| 1199 | auto &TC = getOffloadToolChain(Args: C.getInputArgs(), Kind, Target, |
| 1200 | AuxTarget: C.getDefaultToolChain().getTriple()); |
| 1201 | |
| 1202 | // Emit a warning if the detected CUDA version is too new. |
| 1203 | if (Kind == Action::OFK_Cuda && Target.getOS() == llvm::Triple::CUDA) { |
| 1204 | auto &CudaInstallation = |
| 1205 | static_cast<const toolchains::CudaToolChain &>(TC).CudaInstallation; |
| 1206 | if (CudaInstallation.isValid()) |
| 1207 | CudaInstallation.WarnIfUnsupportedVersion(); |
| 1208 | } |
| 1209 | |
| 1210 | C.addOffloadDeviceToolChain(DeviceToolChain: &TC, OffloadKind: Kind); |
| 1211 | } |
| 1212 | } |
| 1213 | |
| 1214 | // Non-RDC SYCL device code is finalized by a clang-linker-wrapper job |
| 1215 | // bound to one device toolchain, so only one SYCL target can be requested |
| 1216 | // for now. This restriction might be relaxed in future updates. |
| 1217 | if (Kinds.contains(V: Action::OFK_SYCL)) { |
| 1218 | const Arg *RDCArg = C.getInputArgs().getLastArg(Ids: options::OPT_fgpu_rdc, |
| 1219 | Ids: options::OPT_fno_gpu_rdc); |
| 1220 | if (RDCArg && RDCArg->getOption().matches(ID: options::OPT_fno_gpu_rdc)) { |
| 1221 | auto TCRange = C.getOffloadToolChains<Action::OFK_SYCL>(); |
| 1222 | if (std::distance(first: TCRange.first, last: TCRange.second) > 1) |
| 1223 | Diag(DiagID: clang::diag::err_drv_sycl_no_rdc_multiple_targets) |
| 1224 | << RDCArg->getAsString(Args: C.getInputArgs()); |
| 1225 | } |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | bool Driver::loadZOSCustomizationFile(llvm::cl::ExpansionContext &ExpCtx) { |
| 1230 | if (IsCLMode() || IsDXCMode() || IsFlangMode()) |
| 1231 | return false; |
| 1232 | |
| 1233 | SmallString<128> CustomizationFile; |
| 1234 | StringRef PathLIBEnv = StringRef(getenv(name: "CLANG_CONFIG_PATH" )).trim(); |
| 1235 | // If the env var is a directory then append "/clang.cfg" and treat |
| 1236 | // that as the config file. Otherwise treat the env var as the |
| 1237 | // config file. |
| 1238 | if (!PathLIBEnv.empty()) { |
| 1239 | llvm::sys::path::append(path&: CustomizationFile, a: PathLIBEnv); |
| 1240 | if (llvm::sys::fs::is_directory(Path: PathLIBEnv)) |
| 1241 | llvm::sys::path::append(path&: CustomizationFile, a: "/clang.cfg" ); |
| 1242 | if (llvm::sys::fs::is_regular_file(Path: CustomizationFile)) |
| 1243 | return readConfigFile(FileName: CustomizationFile, ExpCtx); |
| 1244 | Diag(DiagID: diag::err_drv_config_file_not_found) << CustomizationFile; |
| 1245 | return true; |
| 1246 | } |
| 1247 | |
| 1248 | SmallString<128> BaseDir(llvm::sys::path::parent_path(path: Dir)); |
| 1249 | llvm::sys::path::append(path&: CustomizationFile, a: BaseDir + "/etc/clang.cfg" ); |
| 1250 | if (llvm::sys::fs::is_regular_file(Path: CustomizationFile)) |
| 1251 | return readConfigFile(FileName: CustomizationFile, ExpCtx); |
| 1252 | |
| 1253 | // If no customization file, just return |
| 1254 | return false; |
| 1255 | } |
| 1256 | |
| 1257 | static void appendOneArg(InputArgList &Args, const Arg *Opt) { |
| 1258 | // The args for config files or /clang: flags belong to different InputArgList |
| 1259 | // objects than Args. This copies an Arg from one of those other InputArgLists |
| 1260 | // to the ownership of Args. |
| 1261 | unsigned Index = Args.MakeIndex(String0: Opt->getSpelling()); |
| 1262 | Arg *Copy = new Arg(Opt->getOption(), Args.getArgString(Index), Index); |
| 1263 | Copy->getValues() = Opt->getValues(); |
| 1264 | if (Opt->isClaimed()) |
| 1265 | Copy->claim(); |
| 1266 | Copy->setOwnsValues(Opt->getOwnsValues()); |
| 1267 | Opt->setOwnsValues(false); |
| 1268 | Args.append(A: Copy); |
| 1269 | if (Opt->getAlias()) { |
| 1270 | const Arg *Alias = Opt->getAlias(); |
| 1271 | unsigned Index = Args.MakeIndex(String0: Alias->getSpelling()); |
| 1272 | auto AliasCopy = std::make_unique<Arg>(args: Alias->getOption(), |
| 1273 | args: Args.getArgString(Index), args&: Index); |
| 1274 | AliasCopy->getValues() = Alias->getValues(); |
| 1275 | AliasCopy->setOwnsValues(false); |
| 1276 | if (Alias->isClaimed()) |
| 1277 | AliasCopy->claim(); |
| 1278 | Copy->setAlias(std::move(AliasCopy)); |
| 1279 | } |
| 1280 | } |
| 1281 | |
| 1282 | bool Driver::readConfigFile(StringRef FileName, |
| 1283 | llvm::cl::ExpansionContext &ExpCtx) { |
| 1284 | // Try opening the given file. |
| 1285 | auto Status = getVFS().status(Path: FileName); |
| 1286 | if (!Status) { |
| 1287 | Diag(DiagID: diag::err_drv_cannot_open_config_file) |
| 1288 | << FileName << Status.getError().message(); |
| 1289 | return true; |
| 1290 | } |
| 1291 | if (Status->getType() != llvm::sys::fs::file_type::regular_file) { |
| 1292 | Diag(DiagID: diag::err_drv_cannot_open_config_file) |
| 1293 | << FileName << "not a regular file" ; |
| 1294 | return true; |
| 1295 | } |
| 1296 | |
| 1297 | // Try reading the given file. |
| 1298 | SmallVector<const char *, 32> NewCfgFileArgs; |
| 1299 | if (llvm::Error Err = ExpCtx.readConfigFile(CfgFile: FileName, Argv&: NewCfgFileArgs)) { |
| 1300 | Diag(DiagID: diag::err_drv_cannot_read_config_file) |
| 1301 | << FileName << toString(E: std::move(Err)); |
| 1302 | return true; |
| 1303 | } |
| 1304 | |
| 1305 | // Populate head and tail lists. The tail list is used only when linking. |
| 1306 | SmallVector<const char *, 32> NewCfgHeadArgs, NewCfgTailArgs; |
| 1307 | for (const char *Opt : NewCfgFileArgs) { |
| 1308 | // An $-prefixed option should go to the tail list. |
| 1309 | if (Opt[0] == '$' && Opt[1]) |
| 1310 | NewCfgTailArgs.push_back(Elt: Opt + 1); |
| 1311 | else |
| 1312 | NewCfgHeadArgs.push_back(Elt: Opt); |
| 1313 | } |
| 1314 | |
| 1315 | // Read options from config file. |
| 1316 | llvm::SmallString<128> CfgFileName(FileName); |
| 1317 | llvm::sys::path::native(path&: CfgFileName); |
| 1318 | bool ContainErrors = false; |
| 1319 | auto NewHeadOptions = std::make_unique<InputArgList>( |
| 1320 | args: ParseArgStrings(ArgStrings: NewCfgHeadArgs, /*UseDriverMode=*/true, ContainsError&: ContainErrors)); |
| 1321 | if (ContainErrors) |
| 1322 | return true; |
| 1323 | auto NewTailOptions = std::make_unique<InputArgList>( |
| 1324 | args: ParseArgStrings(ArgStrings: NewCfgTailArgs, /*UseDriverMode=*/true, ContainsError&: ContainErrors)); |
| 1325 | if (ContainErrors) |
| 1326 | return true; |
| 1327 | |
| 1328 | // Claim all arguments that come from a configuration file so that the driver |
| 1329 | // does not warn on any that is unused. |
| 1330 | for (Arg *A : *NewHeadOptions) |
| 1331 | A->claim(); |
| 1332 | for (Arg *A : *NewTailOptions) |
| 1333 | A->claim(); |
| 1334 | |
| 1335 | if (!CfgOptionsHead) |
| 1336 | CfgOptionsHead = std::move(NewHeadOptions); |
| 1337 | else { |
| 1338 | // If this is a subsequent config file, append options to the previous one. |
| 1339 | for (auto *Opt : *NewHeadOptions) |
| 1340 | appendOneArg(Args&: *CfgOptionsHead, Opt); |
| 1341 | } |
| 1342 | |
| 1343 | if (!CfgOptionsTail) |
| 1344 | CfgOptionsTail = std::move(NewTailOptions); |
| 1345 | else { |
| 1346 | // If this is a subsequent config file, append options to the previous one. |
| 1347 | for (auto *Opt : *NewTailOptions) |
| 1348 | appendOneArg(Args&: *CfgOptionsTail, Opt); |
| 1349 | } |
| 1350 | |
| 1351 | ConfigFiles.push_back(x: std::string(CfgFileName)); |
| 1352 | return false; |
| 1353 | } |
| 1354 | |
| 1355 | bool Driver::loadConfigFiles() { |
| 1356 | llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(), |
| 1357 | llvm::cl::tokenizeConfigFile, &getVFS()); |
| 1358 | |
| 1359 | // Process options that change search path for config files. |
| 1360 | if (CLOptions) { |
| 1361 | if (CLOptions->hasArg(Ids: options::OPT_config_system_dir_EQ)) { |
| 1362 | SmallString<128> CfgDir; |
| 1363 | CfgDir.append( |
| 1364 | RHS: CLOptions->getLastArgValue(Id: options::OPT_config_system_dir_EQ)); |
| 1365 | if (CfgDir.empty() || getVFS().makeAbsolute(Path&: CfgDir)) |
| 1366 | SystemConfigDir.clear(); |
| 1367 | else |
| 1368 | SystemConfigDir = static_cast<std::string>(CfgDir); |
| 1369 | } |
| 1370 | if (CLOptions->hasArg(Ids: options::OPT_config_user_dir_EQ)) { |
| 1371 | SmallString<128> CfgDir; |
| 1372 | llvm::sys::fs::expand_tilde( |
| 1373 | path: CLOptions->getLastArgValue(Id: options::OPT_config_user_dir_EQ), output&: CfgDir); |
| 1374 | if (CfgDir.empty() || getVFS().makeAbsolute(Path&: CfgDir)) |
| 1375 | UserConfigDir.clear(); |
| 1376 | else |
| 1377 | UserConfigDir = static_cast<std::string>(CfgDir); |
| 1378 | } |
| 1379 | } |
| 1380 | |
| 1381 | // Prepare list of directories where config file is searched for. |
| 1382 | StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir}; |
| 1383 | ExpCtx.setSearchDirs(CfgFileSearchDirs); |
| 1384 | |
| 1385 | // First try to load configuration from the default files, return on error. |
| 1386 | if (loadDefaultConfigFiles(ExpCtx)) |
| 1387 | return true; |
| 1388 | |
| 1389 | // Then load configuration files specified explicitly. |
| 1390 | SmallString<128> CfgFilePath; |
| 1391 | if (CLOptions) { |
| 1392 | for (auto CfgFileName : CLOptions->getAllArgValues(Id: options::OPT_config)) { |
| 1393 | // If argument contains directory separator, treat it as a path to |
| 1394 | // configuration file. |
| 1395 | if (llvm::sys::path::has_parent_path(path: CfgFileName)) { |
| 1396 | CfgFilePath.assign(RHS: CfgFileName); |
| 1397 | if (llvm::sys::path::is_relative(path: CfgFilePath)) { |
| 1398 | if (getVFS().makeAbsolute(Path&: CfgFilePath)) { |
| 1399 | Diag(DiagID: diag::err_drv_cannot_open_config_file) |
| 1400 | << CfgFilePath << "cannot get absolute path" ; |
| 1401 | return true; |
| 1402 | } |
| 1403 | } |
| 1404 | } else if (!ExpCtx.findConfigFile(FileName: CfgFileName, FilePath&: CfgFilePath)) { |
| 1405 | // Report an error that the config file could not be found. |
| 1406 | Diag(DiagID: diag::err_drv_config_file_not_found) << CfgFileName; |
| 1407 | for (const StringRef &SearchDir : CfgFileSearchDirs) |
| 1408 | if (!SearchDir.empty()) |
| 1409 | Diag(DiagID: diag::note_drv_config_file_searched_in) << SearchDir; |
| 1410 | return true; |
| 1411 | } |
| 1412 | |
| 1413 | // Try to read the config file, return on error. |
| 1414 | if (readConfigFile(FileName: CfgFilePath, ExpCtx)) |
| 1415 | return true; |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | // No error occurred. |
| 1420 | return false; |
| 1421 | } |
| 1422 | |
| 1423 | static bool findTripleConfigFile(llvm::cl::ExpansionContext &ExpCtx, |
| 1424 | SmallString<128> &ConfigFilePath, |
| 1425 | llvm::Triple Triple, std::string Suffix) { |
| 1426 | // First, try the full unmodified triple. |
| 1427 | if (ExpCtx.findConfigFile(FileName: Triple.str() + Suffix, FilePath&: ConfigFilePath)) |
| 1428 | return true; |
| 1429 | |
| 1430 | // Don't continue if we didn't find a parsable version in the triple. |
| 1431 | VersionTuple OSVersion = Triple.getOSVersion(); |
| 1432 | if (!OSVersion.getMinor().has_value()) |
| 1433 | return false; |
| 1434 | |
| 1435 | std::string BaseOSName = Triple.getOSTypeName(Kind: Triple.getOS()).str(); |
| 1436 | |
| 1437 | // Next try strip the version to only include the major component. |
| 1438 | // e.g. arm64-apple-darwin23.6.0 -> arm64-apple-darwin23 |
| 1439 | if (OSVersion.getMajor() != 0) { |
| 1440 | Triple.setOSName(BaseOSName + llvm::utostr(X: OSVersion.getMajor())); |
| 1441 | if (ExpCtx.findConfigFile(FileName: Triple.str() + Suffix, FilePath&: ConfigFilePath)) |
| 1442 | return true; |
| 1443 | } |
| 1444 | |
| 1445 | // Finally, try without any version suffix at all. |
| 1446 | // e.g. arm64-apple-darwin23.6.0 -> arm64-apple-darwin |
| 1447 | Triple.setOSName(BaseOSName); |
| 1448 | return ExpCtx.findConfigFile(FileName: Triple.str() + Suffix, FilePath&: ConfigFilePath); |
| 1449 | } |
| 1450 | |
| 1451 | bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) { |
| 1452 | // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty |
| 1453 | // value. |
| 1454 | if (const char *NoConfigEnv = ::getenv(name: "CLANG_NO_DEFAULT_CONFIG" )) { |
| 1455 | if (*NoConfigEnv) |
| 1456 | return false; |
| 1457 | } |
| 1458 | if (CLOptions && CLOptions->hasArg(Ids: options::OPT_no_default_config)) |
| 1459 | return false; |
| 1460 | |
| 1461 | std::string RealMode = getExecutableForDriverMode(Mode); |
| 1462 | llvm::Triple Triple; |
| 1463 | |
| 1464 | // If name prefix is present, no --target= override was passed via CLOptions |
| 1465 | // and the name prefix is not a valid triple, force it for backwards |
| 1466 | // compatibility. |
| 1467 | if (!ClangNameParts.TargetPrefix.empty() && |
| 1468 | computeTargetTriple(D: *this, TargetTriple: "/invalid/" , Args: *CLOptions).str() == |
| 1469 | "/invalid/" ) { |
| 1470 | llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix}; |
| 1471 | if (PrefixTriple.getArch() == llvm::Triple::UnknownArch || |
| 1472 | PrefixTriple.isOSUnknown()) |
| 1473 | Triple = std::move(PrefixTriple); |
| 1474 | } |
| 1475 | |
| 1476 | // Otherwise, use the real triple as used by the driver. |
| 1477 | llvm::Triple RealTriple = |
| 1478 | computeTargetTriple(D: *this, TargetTriple, Args: *CLOptions); |
| 1479 | if (Triple.str().empty()) { |
| 1480 | Triple = RealTriple; |
| 1481 | assert(!Triple.str().empty()); |
| 1482 | } |
| 1483 | |
| 1484 | // On z/OS, start by loading the customization file before loading |
| 1485 | // the usual default config file(s). |
| 1486 | if (RealTriple.isOSzOS() && loadZOSCustomizationFile(ExpCtx)) |
| 1487 | return true; |
| 1488 | |
| 1489 | // Search for config files in the following order: |
| 1490 | // 1. <triple>-<mode>.cfg using real driver mode |
| 1491 | // (e.g. i386-pc-linux-gnu-clang++.cfg). |
| 1492 | // 2. <triple>-<mode>.cfg using executable suffix |
| 1493 | // (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++). |
| 1494 | // 3. <triple>.cfg + <mode>.cfg using real driver mode |
| 1495 | // (e.g. i386-pc-linux-gnu.cfg + clang++.cfg). |
| 1496 | // 4. <triple>.cfg + <mode>.cfg using executable suffix |
| 1497 | // (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++). |
| 1498 | |
| 1499 | // Try loading <triple>-<mode>.cfg, and return if we find a match. |
| 1500 | SmallString<128> CfgFilePath; |
| 1501 | if (findTripleConfigFile(ExpCtx, ConfigFilePath&: CfgFilePath, Triple, |
| 1502 | Suffix: "-" + RealMode + ".cfg" )) |
| 1503 | return readConfigFile(FileName: CfgFilePath, ExpCtx); |
| 1504 | |
| 1505 | bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() && |
| 1506 | ClangNameParts.ModeSuffix != RealMode; |
| 1507 | if (TryModeSuffix) { |
| 1508 | if (findTripleConfigFile(ExpCtx, ConfigFilePath&: CfgFilePath, Triple, |
| 1509 | Suffix: "-" + ClangNameParts.ModeSuffix + ".cfg" )) |
| 1510 | return readConfigFile(FileName: CfgFilePath, ExpCtx); |
| 1511 | } |
| 1512 | |
| 1513 | // Try loading <mode>.cfg, and return if loading failed. If a matching file |
| 1514 | // was not found, still proceed on to try <triple>.cfg. |
| 1515 | std::string CfgFileName = RealMode + ".cfg" ; |
| 1516 | if (ExpCtx.findConfigFile(FileName: CfgFileName, FilePath&: CfgFilePath)) { |
| 1517 | if (readConfigFile(FileName: CfgFilePath, ExpCtx)) |
| 1518 | return true; |
| 1519 | } else if (TryModeSuffix) { |
| 1520 | CfgFileName = ClangNameParts.ModeSuffix + ".cfg" ; |
| 1521 | if (ExpCtx.findConfigFile(FileName: CfgFileName, FilePath&: CfgFilePath) && |
| 1522 | readConfigFile(FileName: CfgFilePath, ExpCtx)) |
| 1523 | return true; |
| 1524 | } |
| 1525 | |
| 1526 | // Try loading <triple>.cfg and return if we find a match. |
| 1527 | if (findTripleConfigFile(ExpCtx, ConfigFilePath&: CfgFilePath, Triple, Suffix: ".cfg" )) |
| 1528 | return readConfigFile(FileName: CfgFilePath, ExpCtx); |
| 1529 | |
| 1530 | // If we were unable to find a config file deduced from executable name, |
| 1531 | // that is not an error. |
| 1532 | return false; |
| 1533 | } |
| 1534 | |
| 1535 | Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { |
| 1536 | llvm::PrettyStackTraceString CrashInfo("Compilation construction" ); |
| 1537 | |
| 1538 | // FIXME: Handle environment options which affect driver behavior, somewhere |
| 1539 | // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. |
| 1540 | |
| 1541 | // We look for the driver mode option early, because the mode can affect |
| 1542 | // how other options are parsed. |
| 1543 | |
| 1544 | auto DriverMode = getDriverMode(ProgName: DriverExecutable, Args: ArgList.slice(N: 1)); |
| 1545 | if (!DriverMode.empty()) |
| 1546 | setDriverMode(DriverMode); |
| 1547 | |
| 1548 | // FIXME: What are we going to do with -V and -b? |
| 1549 | |
| 1550 | // Arguments specified in command line. |
| 1551 | bool ContainsError; |
| 1552 | CLOptions = std::make_unique<InputArgList>( |
| 1553 | args: ParseArgStrings(ArgStrings: ArgList.slice(N: 1), /*UseDriverMode=*/true, ContainsError)); |
| 1554 | |
| 1555 | // Try parsing configuration file. |
| 1556 | if (!ContainsError) |
| 1557 | ContainsError = loadConfigFiles(); |
| 1558 | bool HasConfigFileHead = !ContainsError && CfgOptionsHead; |
| 1559 | bool HasConfigFileTail = !ContainsError && CfgOptionsTail; |
| 1560 | |
| 1561 | // All arguments, from both config file and command line. |
| 1562 | InputArgList Args = |
| 1563 | HasConfigFileHead ? std::move(*CfgOptionsHead) : std::move(*CLOptions); |
| 1564 | |
| 1565 | if (HasConfigFileHead) |
| 1566 | for (auto *Opt : *CLOptions) |
| 1567 | if (!Opt->getOption().matches(ID: options::OPT_config)) |
| 1568 | appendOneArg(Args, Opt); |
| 1569 | |
| 1570 | // In CL mode, look for any pass-through arguments |
| 1571 | if (IsCLMode() && !ContainsError) { |
| 1572 | SmallVector<const char *, 16> CLModePassThroughArgList; |
| 1573 | for (const auto *A : Args.filtered(Ids: options::OPT__SLASH_clang)) { |
| 1574 | A->claim(); |
| 1575 | CLModePassThroughArgList.push_back(Elt: A->getValue()); |
| 1576 | } |
| 1577 | |
| 1578 | if (!CLModePassThroughArgList.empty()) { |
| 1579 | // Parse any pass through args using default clang processing rather |
| 1580 | // than clang-cl processing. |
| 1581 | auto CLModePassThroughOptions = std::make_unique<InputArgList>( |
| 1582 | args: ParseArgStrings(ArgStrings: CLModePassThroughArgList, /*UseDriverMode=*/false, |
| 1583 | ContainsError)); |
| 1584 | |
| 1585 | if (!ContainsError) |
| 1586 | for (auto *Opt : *CLModePassThroughOptions) |
| 1587 | appendOneArg(Args, Opt); |
| 1588 | } |
| 1589 | } |
| 1590 | |
| 1591 | // Check for working directory option before accessing any files |
| 1592 | if (Arg *WD = Args.getLastArg(Ids: options::OPT_working_directory)) |
| 1593 | if (VFS->setCurrentWorkingDirectory(WD->getValue())) |
| 1594 | Diag(DiagID: diag::err_drv_unable_to_set_working_directory) << WD->getValue(); |
| 1595 | |
| 1596 | // Check for missing include directories. |
| 1597 | if (!Diags.isIgnored(DiagID: diag::warn_missing_include_dirs, Loc: SourceLocation())) { |
| 1598 | for (auto IncludeDir : Args.getAllArgValues(Id: options::OPT_I_Group)) { |
| 1599 | if (!VFS->exists(Path: IncludeDir)) |
| 1600 | Diag(DiagID: diag::warn_missing_include_dirs) << IncludeDir; |
| 1601 | } |
| 1602 | } |
| 1603 | |
| 1604 | // FIXME: This stuff needs to go into the Compilation, not the driver. |
| 1605 | bool CCCPrintPhases; |
| 1606 | |
| 1607 | // -canonical-prefixes, -no-canonical-prefixes are used very early in main. |
| 1608 | Args.ClaimAllArgs(Id0: options::OPT_canonical_prefixes); |
| 1609 | Args.ClaimAllArgs(Id0: options::OPT_no_canonical_prefixes); |
| 1610 | |
| 1611 | // f(no-)integated-cc1 is also used very early in main. |
| 1612 | Args.ClaimAllArgs(Id0: options::OPT_fintegrated_cc1); |
| 1613 | Args.ClaimAllArgs(Id0: options::OPT_fno_integrated_cc1); |
| 1614 | |
| 1615 | // Ignore -pipe. |
| 1616 | Args.ClaimAllArgs(Id0: options::OPT_pipe); |
| 1617 | |
| 1618 | // Extract -ccc args. |
| 1619 | // |
| 1620 | // FIXME: We need to figure out where this behavior should live. Most of it |
| 1621 | // should be outside in the client; the parts that aren't should have proper |
| 1622 | // options, either by introducing new ones or by overloading gcc ones like -V |
| 1623 | // or -b. |
| 1624 | CCCPrintPhases = Args.hasArg(Ids: options::OPT_ccc_print_phases); |
| 1625 | CCCPrintBindings = Args.hasArg(Ids: options::OPT_ccc_print_bindings); |
| 1626 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_ccc_gcc_name)) |
| 1627 | CCCGenericGCCName = A->getValue(); |
| 1628 | |
| 1629 | // Process -fproc-stat-report options. |
| 1630 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_fproc_stat_report_EQ)) { |
| 1631 | CCPrintProcessStats = true; |
| 1632 | CCPrintStatReportFilename = A->getValue(); |
| 1633 | } |
| 1634 | if (Args.hasArg(Ids: options::OPT_fproc_stat_report)) |
| 1635 | CCPrintProcessStats = true; |
| 1636 | |
| 1637 | // FIXME: TargetTriple is used by the target-prefixed calls to as/ld |
| 1638 | // and getToolChain is const. |
| 1639 | if (IsCLMode()) { |
| 1640 | // clang-cl targets MSVC-style Win32. |
| 1641 | llvm::Triple T(TargetTriple); |
| 1642 | T.setOS(llvm::Triple::Win32); |
| 1643 | T.setVendor(llvm::Triple::PC); |
| 1644 | T.setEnvironment(llvm::Triple::MSVC); |
| 1645 | T.setObjectFormat(llvm::Triple::COFF); |
| 1646 | if (Args.hasArg(Ids: options::OPT__SLASH_arm64EC)) |
| 1647 | T.setArch(Kind: llvm::Triple::aarch64, SubArch: llvm::Triple::AArch64SubArch_arm64ec); |
| 1648 | TargetTriple = T.str(); |
| 1649 | } else if (IsDXCMode()) { |
| 1650 | // Build TargetTriple from target_profile option for clang-dxc. |
| 1651 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_target_profile)) { |
| 1652 | StringRef TargetProfile = A->getValue(); |
| 1653 | if (auto Triple = |
| 1654 | toolchains::HLSLToolChain::parseTargetProfile(TargetProfile)) |
| 1655 | TargetTriple = *Triple; |
| 1656 | else |
| 1657 | Diag(DiagID: diag::err_drv_invalid_directx_shader_module) << TargetProfile; |
| 1658 | |
| 1659 | A->claim(); |
| 1660 | |
| 1661 | if (Args.hasArg(Ids: options::OPT_spirv)) { |
| 1662 | const llvm::StringMap<llvm::Triple::SubArchType> ValidTargets = { |
| 1663 | {"vulkan1.2" , llvm::Triple::SPIRVSubArch_v15}, |
| 1664 | {"vulkan1.3" , llvm::Triple::SPIRVSubArch_v16}}; |
| 1665 | llvm::Triple T(TargetTriple); |
| 1666 | |
| 1667 | // Set specific Vulkan version. Default to vulkan1.3. |
| 1668 | auto TargetInfo = ValidTargets.find(Key: "vulkan1.3" ); |
| 1669 | assert(TargetInfo != ValidTargets.end()); |
| 1670 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_fspv_target_env_EQ)) { |
| 1671 | TargetInfo = ValidTargets.find(Key: A->getValue()); |
| 1672 | if (TargetInfo == ValidTargets.end()) { |
| 1673 | Diag(DiagID: diag::err_drv_invalid_value) |
| 1674 | << A->getAsString(Args) << A->getValue(); |
| 1675 | } |
| 1676 | A->claim(); |
| 1677 | } |
| 1678 | if (TargetInfo != ValidTargets.end()) { |
| 1679 | T.setOSName(TargetInfo->getKey()); |
| 1680 | T.setArch(Kind: llvm::Triple::spirv, SubArch: TargetInfo->getValue()); |
| 1681 | TargetTriple = T.str(); |
| 1682 | } |
| 1683 | } |
| 1684 | } else { |
| 1685 | Diag(DiagID: diag::err_drv_dxc_missing_target_profile); |
| 1686 | } |
| 1687 | } |
| 1688 | |
| 1689 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_target)) |
| 1690 | TargetTriple = A->getValue(); |
| 1691 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_ccc_install_dir)) |
| 1692 | Dir = A->getValue(); |
| 1693 | for (const Arg *A : Args.filtered(Ids: options::OPT_B)) { |
| 1694 | A->claim(); |
| 1695 | PrefixDirs.push_back(Elt: A->getValue(N: 0)); |
| 1696 | } |
| 1697 | if (std::optional<std::string> CompilerPathValue = |
| 1698 | llvm::sys::Process::GetEnv(name: "COMPILER_PATH" )) { |
| 1699 | StringRef CompilerPath = *CompilerPathValue; |
| 1700 | while (!CompilerPath.empty()) { |
| 1701 | std::pair<StringRef, StringRef> Split = |
| 1702 | CompilerPath.split(Separator: llvm::sys::EnvPathSeparator); |
| 1703 | PrefixDirs.push_back(Elt: std::string(Split.first)); |
| 1704 | CompilerPath = Split.second; |
| 1705 | } |
| 1706 | } |
| 1707 | if (const Arg *A = Args.getLastArg(Ids: options::OPT__sysroot_EQ)) |
| 1708 | SysRoot = A->getValue(); |
| 1709 | if (const Arg *A = Args.getLastArg(Ids: options::OPT__dyld_prefix_EQ)) |
| 1710 | DyldPrefix = A->getValue(); |
| 1711 | |
| 1712 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_resource_dir)) |
| 1713 | ResourceDir = A->getValue(); |
| 1714 | |
| 1715 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_save_temps_EQ)) { |
| 1716 | SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue()) |
| 1717 | .Case(S: "cwd" , Value: SaveTempsCwd) |
| 1718 | .Case(S: "obj" , Value: SaveTempsObj) |
| 1719 | .Default(Value: SaveTempsCwd); |
| 1720 | } |
| 1721 | |
| 1722 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_offload_host_only, |
| 1723 | Ids: options::OPT_offload_device_only, |
| 1724 | Ids: options::OPT_offload_host_device)) { |
| 1725 | if (A->getOption().matches(ID: options::OPT_offload_host_only)) |
| 1726 | Offload = OffloadHost; |
| 1727 | else if (A->getOption().matches(ID: options::OPT_offload_device_only)) |
| 1728 | Offload = OffloadDevice; |
| 1729 | else |
| 1730 | Offload = OffloadHostDevice; |
| 1731 | } |
| 1732 | |
| 1733 | // Process -fembed-bitcode= flags. |
| 1734 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fembed_bitcode_EQ)) { |
| 1735 | StringRef Name = A->getValue(); |
| 1736 | unsigned Model = llvm::StringSwitch<unsigned>(Name) |
| 1737 | .Case(S: "off" , Value: EmbedNone) |
| 1738 | .Case(S: "all" , Value: EmbedBitcode) |
| 1739 | .Case(S: "bitcode" , Value: EmbedBitcode) |
| 1740 | .Case(S: "marker" , Value: EmbedMarker) |
| 1741 | .Default(Value: ~0U); |
| 1742 | if (Model == ~0U) { |
| 1743 | Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) |
| 1744 | << Name; |
| 1745 | } else |
| 1746 | BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model); |
| 1747 | } |
| 1748 | |
| 1749 | // Remove existing compilation database so that each job can append to it. |
| 1750 | if (Arg *A = Args.getLastArg(Ids: options::OPT_MJ)) |
| 1751 | llvm::sys::fs::remove(path: A->getValue()); |
| 1752 | |
| 1753 | // Setting up the jobs for some precompile cases depends on whether we are |
| 1754 | // treating them as PCH, implicit modules or C++20 ones. |
| 1755 | // TODO: inferring the mode like this seems fragile (it meets the objective |
| 1756 | // of not requiring anything new for operation, however). |
| 1757 | const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ); |
| 1758 | ModulesModeCXX20 = |
| 1759 | !Args.hasArg(Ids: options::OPT_fmodules) && Std && |
| 1760 | (Std->containsValue(Value: "c++20" ) || Std->containsValue(Value: "c++2a" ) || |
| 1761 | Std->containsValue(Value: "c++23" ) || Std->containsValue(Value: "c++2b" ) || |
| 1762 | Std->containsValue(Value: "c++26" ) || Std->containsValue(Value: "c++2c" ) || |
| 1763 | Std->containsValue(Value: "c++2d" ) || Std->containsValue(Value: "c++latest" )); |
| 1764 | |
| 1765 | // Process -fmodule-header{=} flags. |
| 1766 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_header_EQ, |
| 1767 | Ids: options::OPT_fmodule_header)) { |
| 1768 | // These flags force C++20 handling of headers. |
| 1769 | ModulesModeCXX20 = true; |
| 1770 | if (A->getOption().matches(ID: options::OPT_fmodule_header)) |
| 1771 | CXX20HeaderType = HeaderMode_Default; |
| 1772 | else { |
| 1773 | StringRef ArgName = A->getValue(); |
| 1774 | unsigned Kind = llvm::StringSwitch<unsigned>(ArgName) |
| 1775 | .Case(S: "user" , Value: HeaderMode_User) |
| 1776 | .Case(S: "system" , Value: HeaderMode_System) |
| 1777 | .Default(Value: ~0U); |
| 1778 | if (Kind == ~0U) { |
| 1779 | Diags.Report(DiagID: diag::err_drv_invalid_value) |
| 1780 | << A->getAsString(Args) << ArgName; |
| 1781 | } else |
| 1782 | CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind); |
| 1783 | } |
| 1784 | } |
| 1785 | |
| 1786 | std::unique_ptr<llvm::opt::InputArgList> UArgs = |
| 1787 | std::make_unique<InputArgList>(args: std::move(Args)); |
| 1788 | |
| 1789 | // Owned by the host. |
| 1790 | const ToolChain &TC = |
| 1791 | getToolChain(Args: *UArgs, Target: computeTargetTriple(D: *this, TargetTriple, Args: *UArgs)); |
| 1792 | |
| 1793 | { |
| 1794 | SmallVector<std::string> MultilibMacroDefinesStr = |
| 1795 | TC.getMultilibMacroDefinesStr(Args&: *UArgs); |
| 1796 | SmallVector<const char *> MLMacroDefinesChar( |
| 1797 | llvm::map_range(C&: MultilibMacroDefinesStr, F: [&UArgs](const auto &S) { |
| 1798 | return UArgs->MakeArgString(Str: Twine("-D" ) + Twine(S)); |
| 1799 | })); |
| 1800 | bool MLContainsError; |
| 1801 | auto MultilibMacroDefineList = |
| 1802 | std::make_unique<InputArgList>(args: ParseArgStrings( |
| 1803 | ArgStrings: MLMacroDefinesChar, /*UseDriverMode=*/false, ContainsError&: MLContainsError)); |
| 1804 | if (!MLContainsError) { |
| 1805 | for (auto *Opt : *MultilibMacroDefineList) { |
| 1806 | appendOneArg(Args&: *UArgs, Opt); |
| 1807 | } |
| 1808 | } |
| 1809 | } |
| 1810 | |
| 1811 | // Perform the default argument translations. |
| 1812 | DerivedArgList *TranslatedArgs = TranslateInputArgs(Args: *UArgs); |
| 1813 | |
| 1814 | // Check if the environment version is valid except wasm case. |
| 1815 | llvm::Triple Triple = TC.getTriple(); |
| 1816 | if (!Triple.isWasm()) { |
| 1817 | StringRef TripleVersionName = Triple.getEnvironmentVersionString(); |
| 1818 | StringRef TripleObjectFormat = |
| 1819 | Triple.getObjectFormatTypeName(ObjectFormat: Triple.getObjectFormat()); |
| 1820 | if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "" && |
| 1821 | TripleVersionName != TripleObjectFormat) { |
| 1822 | Diags.Report(DiagID: diag::err_drv_triple_version_invalid) |
| 1823 | << TripleVersionName << TC.getTripleString(); |
| 1824 | ContainsError = true; |
| 1825 | } |
| 1826 | } |
| 1827 | |
| 1828 | // Report warning when arm64EC option is overridden by specified target |
| 1829 | if ((TC.getTriple().getArch() != llvm::Triple::aarch64 || |
| 1830 | TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) && |
| 1831 | UArgs->hasArg(Ids: options::OPT__SLASH_arm64EC)) { |
| 1832 | getDiags().Report(DiagID: clang::diag::warn_target_override_arm64ec) |
| 1833 | << TC.getTripleString(); |
| 1834 | } |
| 1835 | |
| 1836 | // A common user mistake is specifying a target of aarch64-none-eabi or |
| 1837 | // arm-none-elf whereas the correct names are aarch64-none-elf & |
| 1838 | // arm-none-eabi. Detect these cases and issue a warning. |
| 1839 | if (TC.getTriple().getOS() == llvm::Triple::UnknownOS && |
| 1840 | TC.getTriple().getVendor() == llvm::Triple::UnknownVendor) { |
| 1841 | switch (TC.getTriple().getArch()) { |
| 1842 | case llvm::Triple::arm: |
| 1843 | case llvm::Triple::armeb: |
| 1844 | case llvm::Triple::thumb: |
| 1845 | case llvm::Triple::thumbeb: |
| 1846 | if (TC.getTriple().getEnvironmentName() == "elf" ) { |
| 1847 | Diag(DiagID: diag::warn_target_unrecognized_env) |
| 1848 | << TargetTriple |
| 1849 | << (TC.getTriple().getArchName().str() + "-none-eabi" ); |
| 1850 | } |
| 1851 | break; |
| 1852 | case llvm::Triple::aarch64: |
| 1853 | case llvm::Triple::aarch64_be: |
| 1854 | case llvm::Triple::aarch64_32: |
| 1855 | if (TC.getTriple().getEnvironmentName().starts_with(Prefix: "eabi" )) { |
| 1856 | Diag(DiagID: diag::warn_target_unrecognized_env) |
| 1857 | << TargetTriple |
| 1858 | << (TC.getTriple().getArchName().str() + "-none-elf" ); |
| 1859 | } |
| 1860 | break; |
| 1861 | default: |
| 1862 | break; |
| 1863 | } |
| 1864 | } |
| 1865 | |
| 1866 | // The compilation takes ownership of Args. |
| 1867 | Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs, |
| 1868 | ContainsError); |
| 1869 | |
| 1870 | if (!HandleImmediateArgs(C&: *C)) |
| 1871 | return C; |
| 1872 | |
| 1873 | // Construct the list of inputs. |
| 1874 | InputList Inputs; |
| 1875 | BuildInputs(TC: C->getDefaultToolChain(), Args&: *TranslatedArgs, Inputs); |
| 1876 | if (HasConfigFileTail && Inputs.size()) { |
| 1877 | Arg *FinalPhaseArg; |
| 1878 | if (getFinalPhase(DAL: *TranslatedArgs, Inputs, FinalPhaseArg: &FinalPhaseArg) == |
| 1879 | phases::Link) { |
| 1880 | DerivedArgList TranslatedLinkerIns(*CfgOptionsTail); |
| 1881 | for (Arg *A : *CfgOptionsTail) |
| 1882 | TranslatedLinkerIns.append(A); |
| 1883 | BuildInputs(TC: C->getDefaultToolChain(), Args&: TranslatedLinkerIns, Inputs); |
| 1884 | } |
| 1885 | } |
| 1886 | |
| 1887 | // Populate the tool chains for the offloading devices, if any. |
| 1888 | CreateOffloadingDeviceToolChains(C&: *C, Inputs); |
| 1889 | |
| 1890 | bool UseModulesDriver = C->getArgs().hasFlag( |
| 1891 | Pos: options::OPT_fmodules_driver, Neg: options::OPT_fno_modules_driver, Default: false); |
| 1892 | modules::StdModuleManifest ModulesManifest; |
| 1893 | if (UseModulesDriver) { |
| 1894 | Diags.Report(DiagID: diag::remark_performing_driver_managed_module_build); |
| 1895 | |
| 1896 | modules::diagnoseModulesDriverArgs(DAL&: C->getArgs(), Diags); |
| 1897 | |
| 1898 | // Read the Standard library module manifest and, if available, add all |
| 1899 | // discovered modules to this Compilation. Jobs for modules specified in |
| 1900 | // the manifest that are not required by any command-line input are pruned |
| 1901 | // later. |
| 1902 | const auto StdModuleManifestPath = |
| 1903 | GetStdModuleManifestPath(C: *C, TC: C->getDefaultToolChain()); |
| 1904 | |
| 1905 | if (!llvm::sys::fs::exists(Path: StdModuleManifestPath)) |
| 1906 | Diags.Report(DiagID: diag::remark_modules_manifest_not_found); |
| 1907 | else { |
| 1908 | Diags.Report(DiagID: diag::remark_using_modules_manifest) |
| 1909 | << StdModuleManifestPath; |
| 1910 | if (auto ManifestOrErr = |
| 1911 | modules::readStdModuleManifest(ManifestPath: StdModuleManifestPath, VFS&: getVFS())) { |
| 1912 | ModulesManifest = std::move(*ManifestOrErr); |
| 1913 | // Only allow on-demand imports of standard library modules for now. |
| 1914 | llvm::erase_if(C&: ModulesManifest.Modules, P: [](const auto &ModuleEntry) { |
| 1915 | return !ModuleEntry.IsStdlib; |
| 1916 | }); |
| 1917 | modules::buildStdModuleManifestInputs(ManifestEntries: ModulesManifest.Modules, C&: *C, |
| 1918 | Inputs); |
| 1919 | } else { |
| 1920 | llvm::handleAllErrors( |
| 1921 | E: ManifestOrErr.takeError(), |
| 1922 | Handlers: [&](llvm::json::ParseError &Err) { |
| 1923 | Diags.Report(DiagID: diag::err_modules_manifest_failed_parse) |
| 1924 | << Err.message(); |
| 1925 | }, |
| 1926 | Handlers: [&](llvm::FileError &Err) { |
| 1927 | Diags.Report(DiagID: diag::err_cannot_open_file) |
| 1928 | << Err.getFileName() << Err.messageWithoutFileInfo(); |
| 1929 | }); |
| 1930 | } |
| 1931 | } |
| 1932 | } |
| 1933 | |
| 1934 | // Construct the list of abstract actions to perform for this compilation. On |
| 1935 | // MachO targets this uses the driver-driver and universal actions. |
| 1936 | if (TC.getTriple().isOSBinFormatMachO()) |
| 1937 | BuildUniversalActions(C&: *C, TC: C->getDefaultToolChain(), BAInputs: Inputs); |
| 1938 | else |
| 1939 | BuildActions(C&: *C, Args&: C->getArgs(), Inputs, Actions&: C->getActions()); |
| 1940 | |
| 1941 | if (CCCPrintPhases) { |
| 1942 | PrintActions(C: *C); |
| 1943 | return C; |
| 1944 | } |
| 1945 | |
| 1946 | BuildJobs(C&: *C); |
| 1947 | |
| 1948 | if (UseModulesDriver) |
| 1949 | modules::runModulesDriver(C&: *C, ManifestEntries: ModulesManifest.Modules); |
| 1950 | |
| 1951 | return C; |
| 1952 | } |
| 1953 | |
| 1954 | static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) { |
| 1955 | llvm::opt::ArgStringList ASL; |
| 1956 | for (const auto *A : Args) { |
| 1957 | // Use user's original spelling of flags. For example, use |
| 1958 | // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user |
| 1959 | // wrote the former. |
| 1960 | while (A->getAlias()) |
| 1961 | A = A->getAlias(); |
| 1962 | A->render(Args, Output&: ASL); |
| 1963 | } |
| 1964 | |
| 1965 | for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) { |
| 1966 | if (I != ASL.begin()) |
| 1967 | OS << ' '; |
| 1968 | llvm::sys::printArg(OS, Arg: *I, Quote: true); |
| 1969 | } |
| 1970 | OS << '\n'; |
| 1971 | } |
| 1972 | |
| 1973 | bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename, |
| 1974 | SmallString<128> &CrashDiagDir) { |
| 1975 | using namespace llvm::sys; |
| 1976 | assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() && |
| 1977 | "Only knows about .crash files on Darwin" ); |
| 1978 | // This is not a formal output of the compiler, let's bypass the sandbox. |
| 1979 | auto BypassSandbox = sandbox::scopedDisable(); |
| 1980 | |
| 1981 | // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/ |
| 1982 | // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern |
| 1983 | // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash. |
| 1984 | path::home_directory(result&: CrashDiagDir); |
| 1985 | if (CrashDiagDir.starts_with(Prefix: "/var/root" )) |
| 1986 | CrashDiagDir = "/" ; |
| 1987 | path::append(path&: CrashDiagDir, a: "Library/Logs/DiagnosticReports" ); |
| 1988 | int PID = |
| 1989 | #if LLVM_ON_UNIX |
| 1990 | getpid(); |
| 1991 | #else |
| 1992 | 0; |
| 1993 | #endif |
| 1994 | std::error_code EC; |
| 1995 | fs::file_status FileStatus; |
| 1996 | TimePoint<> LastAccessTime; |
| 1997 | SmallString<128> CrashFilePath; |
| 1998 | // Lookup the .crash files and get the one generated by a subprocess spawned |
| 1999 | // by this driver invocation. |
| 2000 | for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd; |
| 2001 | File != FileEnd && !EC; File.increment(ec&: EC)) { |
| 2002 | StringRef FileName = path::filename(path: File->path()); |
| 2003 | if (!FileName.starts_with(Prefix: Name)) |
| 2004 | continue; |
| 2005 | if (fs::status(path: File->path(), result&: FileStatus)) |
| 2006 | continue; |
| 2007 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile = |
| 2008 | llvm::MemoryBuffer::getFile(Filename: File->path()); |
| 2009 | if (!CrashFile) |
| 2010 | continue; |
| 2011 | // The first line should start with "Process:", otherwise this isn't a real |
| 2012 | // .crash file. |
| 2013 | StringRef Data = CrashFile.get()->getBuffer(); |
| 2014 | if (!Data.starts_with(Prefix: "Process:" )) |
| 2015 | continue; |
| 2016 | // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]" |
| 2017 | size_t ParentProcPos = Data.find(Str: "Parent Process:" ); |
| 2018 | if (ParentProcPos == StringRef::npos) |
| 2019 | continue; |
| 2020 | size_t LineEnd = Data.find_first_of(Chars: "\n" , From: ParentProcPos); |
| 2021 | if (LineEnd == StringRef::npos) |
| 2022 | continue; |
| 2023 | StringRef ParentProcess = Data.slice(Start: ParentProcPos+15, End: LineEnd).trim(); |
| 2024 | int OpenBracket = -1, CloseBracket = -1; |
| 2025 | for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) { |
| 2026 | if (ParentProcess[i] == '[') |
| 2027 | OpenBracket = i; |
| 2028 | if (ParentProcess[i] == ']') |
| 2029 | CloseBracket = i; |
| 2030 | } |
| 2031 | // Extract the parent process PID from the .crash file and check whether |
| 2032 | // it matches this driver invocation pid. |
| 2033 | int CrashPID; |
| 2034 | if (OpenBracket < 0 || CloseBracket < 0 || |
| 2035 | ParentProcess.slice(Start: OpenBracket + 1, End: CloseBracket) |
| 2036 | .getAsInteger(Radix: 10, Result&: CrashPID) || CrashPID != PID) { |
| 2037 | continue; |
| 2038 | } |
| 2039 | |
| 2040 | // Found a .crash file matching the driver pid. To avoid getting an older |
| 2041 | // and misleading crash file, continue looking for the most recent. |
| 2042 | // FIXME: the driver can dispatch multiple cc1 invocations, leading to |
| 2043 | // multiple crashes poiting to the same parent process. Since the driver |
| 2044 | // does not collect pid information for the dispatched invocation there's |
| 2045 | // currently no way to distinguish among them. |
| 2046 | const auto FileAccessTime = FileStatus.getLastModificationTime(); |
| 2047 | if (FileAccessTime > LastAccessTime) { |
| 2048 | CrashFilePath.assign(RHS: File->path()); |
| 2049 | LastAccessTime = FileAccessTime; |
| 2050 | } |
| 2051 | } |
| 2052 | |
| 2053 | // If found, copy it over to the location of other reproducer files. |
| 2054 | if (!CrashFilePath.empty()) { |
| 2055 | EC = fs::copy_file(From: CrashFilePath, To: ReproCrashFilename); |
| 2056 | if (EC) |
| 2057 | return false; |
| 2058 | return true; |
| 2059 | } |
| 2060 | |
| 2061 | return false; |
| 2062 | } |
| 2063 | |
| 2064 | static const char BugReportMsg[] = |
| 2065 | "\n********************\n\n" |
| 2066 | "PLEASE ATTACH THE FOLLOWING CRASH REPRODUCER FILES TO THE BUG REPORT:" ; |
| 2067 | |
| 2068 | // When clang crashes, produce diagnostic information including the fully |
| 2069 | // preprocessed source file(s). Request that the developer attach the |
| 2070 | // diagnostic information to a bug report. |
| 2071 | void Driver::generateCompilationDiagnostics( |
| 2072 | Compilation &C, const Command &FailingCommand, |
| 2073 | StringRef AdditionalInformation, CompilationDiagnosticReport *Report) { |
| 2074 | if (C.getArgs().hasArg(Ids: options::OPT_fno_crash_diagnostics)) |
| 2075 | return; |
| 2076 | |
| 2077 | bool HasCrashTar = C.getArgs().hasArg(Ids: options::OPT_fcrash_diagnostics_tar); |
| 2078 | |
| 2079 | unsigned Level = 1; |
| 2080 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_fcrash_diagnostics_EQ)) { |
| 2081 | Level = llvm::StringSwitch<unsigned>(A->getValue()) |
| 2082 | .Case(S: "off" , Value: 0) |
| 2083 | .Case(S: "compiler" , Value: 1) |
| 2084 | .Case(S: "all" , Value: 2) |
| 2085 | .Default(Value: 1); |
| 2086 | } |
| 2087 | if (!Level) |
| 2088 | return; |
| 2089 | |
| 2090 | // Don't try to generate diagnostics for dsymutil jobs. |
| 2091 | if (FailingCommand.getCreator().isDsymutilJob()) |
| 2092 | return; |
| 2093 | |
| 2094 | bool IsLLD = false; |
| 2095 | ArgStringList SavedTemps; |
| 2096 | if (FailingCommand.getCreator().isLinkJob()) { |
| 2097 | C.getDefaultToolChain().GetLinkerPath(LinkerIsLLD: &IsLLD); |
| 2098 | if (!IsLLD || Level < 2) |
| 2099 | return; |
| 2100 | |
| 2101 | // If lld crashed, we will re-run the same command with the input it used |
| 2102 | // to have. In that case we should not remove temp files in |
| 2103 | // initCompilationForDiagnostics yet. They will be added back and removed |
| 2104 | // later. |
| 2105 | SavedTemps = std::move(C.getTempFiles()); |
| 2106 | assert(!C.getTempFiles().size()); |
| 2107 | } |
| 2108 | |
| 2109 | // Print the version of the compiler. |
| 2110 | PrintVersion(C, OS&: llvm::errs()); |
| 2111 | |
| 2112 | // Suppress driver output and emit preprocessor output to temp file. |
| 2113 | CCGenDiagnostics = true; |
| 2114 | |
| 2115 | // Save the original job command(s). |
| 2116 | Command Cmd = FailingCommand; |
| 2117 | |
| 2118 | // Keep track of whether we produce any errors while trying to produce |
| 2119 | // preprocessed sources. |
| 2120 | DiagnosticErrorTrap Trap(Diags); |
| 2121 | |
| 2122 | // Suppress tool output. |
| 2123 | C.initCompilationForDiagnostics(); |
| 2124 | |
| 2125 | // If lld failed, rerun it again with --reproduce. |
| 2126 | if (IsLLD) { |
| 2127 | const char *TmpName = CreateTempFile(C, Prefix: "linker-crash" , Suffix: "tar" ); |
| 2128 | Command NewLLDInvocation = Cmd; |
| 2129 | llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments(); |
| 2130 | StringRef ReproduceOption = |
| 2131 | C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() |
| 2132 | ? "/reproduce:" |
| 2133 | : "--reproduce=" ; |
| 2134 | ArgList.push_back(Elt: Saver.save(S: Twine(ReproduceOption) + TmpName).data()); |
| 2135 | NewLLDInvocation.replaceArguments(List: std::move(ArgList)); |
| 2136 | |
| 2137 | // Redirect stdout/stderr to /dev/null. |
| 2138 | NewLLDInvocation.Execute(Redirects: {std::nullopt, {"" }, {"" }}, ErrMsg: nullptr, ExecutionFailed: nullptr); |
| 2139 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << BugReportMsg; |
| 2140 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << TmpName; |
| 2141 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2142 | << "\n\n********************" ; |
| 2143 | if (Report) |
| 2144 | Report->TemporaryFiles.push_back(Elt: TmpName); |
| 2145 | return; |
| 2146 | } |
| 2147 | |
| 2148 | // Construct the list of inputs. |
| 2149 | InputList Inputs; |
| 2150 | BuildInputs(TC: C.getDefaultToolChain(), Args&: C.getArgs(), Inputs); |
| 2151 | |
| 2152 | ArgStringList IRInputs; |
| 2153 | for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { |
| 2154 | bool IgnoreInput = false; |
| 2155 | |
| 2156 | // Save IR inputs separately, ignore input from stdin or any other inputs |
| 2157 | // that cannot be preprocessed. Check type first as not all linker inputs |
| 2158 | // have a value. |
| 2159 | if (types::isLLVMIR(Id: it->first)) { |
| 2160 | IRInputs.push_back(Elt: it->second->getValue()); |
| 2161 | IgnoreInput = true; |
| 2162 | } else if (types::getPreprocessedType(Id: it->first) == types::TY_INVALID) { |
| 2163 | IgnoreInput = true; |
| 2164 | } else if (!strcmp(s1: it->second->getValue(), s2: "-" )) { |
| 2165 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2166 | << "Error generating preprocessed source(s) - " |
| 2167 | "ignoring input from stdin." ; |
| 2168 | IgnoreInput = true; |
| 2169 | } |
| 2170 | |
| 2171 | if (IgnoreInput) { |
| 2172 | it = Inputs.erase(CI: it); |
| 2173 | ie = Inputs.end(); |
| 2174 | } else { |
| 2175 | ++it; |
| 2176 | } |
| 2177 | } |
| 2178 | |
| 2179 | if (Inputs.empty() && IRInputs.empty()) { |
| 2180 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2181 | << "Error generating preprocessed source(s) - " |
| 2182 | "no preprocessable inputs." ; |
| 2183 | return; |
| 2184 | } |
| 2185 | |
| 2186 | // If there are multiple -arch options, build a reproducer only for the bound |
| 2187 | // arch that crashed. |
| 2188 | llvm::StringSet<> ArchNames; |
| 2189 | for (const Arg *A : C.getArgs()) { |
| 2190 | if (A->getOption().matches(ID: options::OPT_arch)) { |
| 2191 | StringRef ArchName = A->getValue(); |
| 2192 | ArchNames.insert(key: ArchName); |
| 2193 | } |
| 2194 | } |
| 2195 | if (ArchNames.size() > 1) { |
| 2196 | // Build a reproducer only for the bound arch that crashed. |
| 2197 | StringRef FailingArch = Cmd.getBoundArch().ArchName; |
| 2198 | if (FailingArch.empty()) { |
| 2199 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2200 | << "Error generating preprocessed source(s) - cannot generate " |
| 2201 | "preprocessed source with multiple -arch options." ; |
| 2202 | return; |
| 2203 | } |
| 2204 | C.getArgs().eraseArg(Id: options::OPT_arch); |
| 2205 | C.getArgs().AddJoinedArg(BaseArg: nullptr, Opt: getOpts().getOption(Opt: options::OPT_arch), |
| 2206 | Value: FailingArch); |
| 2207 | } |
| 2208 | |
| 2209 | // If we only have IR inputs there's no need for preprocessing. |
| 2210 | if (!Inputs.empty()) { |
| 2211 | // Construct the list of abstract actions to perform for this compilation. |
| 2212 | // On Darwin OSes this uses the driver-driver and builds universal actions. |
| 2213 | const ToolChain &TC = C.getDefaultToolChain(); |
| 2214 | if (TC.getTriple().isOSBinFormatMachO()) |
| 2215 | BuildUniversalActions(C, TC, BAInputs: Inputs); |
| 2216 | else |
| 2217 | BuildActions(C, Args&: C.getArgs(), Inputs, Actions&: C.getActions()); |
| 2218 | |
| 2219 | BuildJobs(C); |
| 2220 | |
| 2221 | // If there were errors building the compilation, quit now. |
| 2222 | if (Trap.hasErrorOccurred()) { |
| 2223 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2224 | << "Error generating preprocessed source(s)." ; |
| 2225 | return; |
| 2226 | } |
| 2227 | // Generate preprocessed output. |
| 2228 | SmallVector<std::pair<int, const Command *>, 4> FailingCommands; |
| 2229 | C.ExecuteJobs(Jobs: C.getJobs(), FailingCommands); |
| 2230 | |
| 2231 | // If any of the preprocessing commands failed, clean up and exit. |
| 2232 | if (!FailingCommands.empty()) { |
| 2233 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2234 | << "Error generating preprocessed source(s)." ; |
| 2235 | return; |
| 2236 | } |
| 2237 | |
| 2238 | const ArgStringList &TempFiles = C.getTempFiles(); |
| 2239 | if (TempFiles.empty()) { |
| 2240 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2241 | << "Error generating preprocessed source(s)." ; |
| 2242 | return; |
| 2243 | } |
| 2244 | } |
| 2245 | |
| 2246 | // Copying filenames due to ownership. |
| 2247 | const ArgStringList &Files = C.getTempFiles(); |
| 2248 | SmallVector<std::string> TempFiles(Files.begin(), Files.end()); |
| 2249 | |
| 2250 | // We'd like to copy the IR input file into our own temp file |
| 2251 | // because the build system might try to clean-up after itself. |
| 2252 | for (auto const *Input : IRInputs) { |
| 2253 | int FD; |
| 2254 | llvm::SmallVector<char, 64> Path; |
| 2255 | |
| 2256 | StringRef extension = llvm::sys::path::extension(path: Input); |
| 2257 | if (!extension.empty()) |
| 2258 | extension = extension.drop_front(); |
| 2259 | |
| 2260 | std::error_code EC = llvm::sys::fs::createTemporaryFile( |
| 2261 | Prefix: llvm::sys::path::stem(path: Input), Suffix: extension, ResultFD&: FD, ResultPath&: Path); |
| 2262 | if (EC) { |
| 2263 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2264 | << "Error generating run script: " << "Failed copying IR input files" |
| 2265 | << " " << EC.message(); |
| 2266 | return; |
| 2267 | } |
| 2268 | |
| 2269 | EC = llvm::sys::fs::copy_file(From: Input, ToFD: FD); |
| 2270 | if (EC) { |
| 2271 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2272 | << "Error generating run script: " << "Failed copying IR input files" |
| 2273 | << " " << EC.message(); |
| 2274 | return; |
| 2275 | } |
| 2276 | |
| 2277 | TempFiles.push_back(Elt: std::string(Path.begin(), Path.end())); |
| 2278 | } |
| 2279 | |
| 2280 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << BugReportMsg; |
| 2281 | |
| 2282 | SmallString<128> VFS; |
| 2283 | SmallString<128> ReproCrashFilename; |
| 2284 | for (std::string &TempFile : TempFiles) { |
| 2285 | if (!HasCrashTar) |
| 2286 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << TempFile; |
| 2287 | if (Report) |
| 2288 | Report->TemporaryFiles.push_back(Elt: TempFile); |
| 2289 | if (ReproCrashFilename.empty()) { |
| 2290 | ReproCrashFilename = TempFile; |
| 2291 | llvm::sys::path::replace_extension(path&: ReproCrashFilename, extension: ".crash" ); |
| 2292 | } |
| 2293 | if (StringRef(TempFile).ends_with(Suffix: ".cache" )) { |
| 2294 | // In some cases (modules) we'll dump extra data to help with reproducing |
| 2295 | // the crash into a directory next to the output. |
| 2296 | VFS = llvm::sys::path::filename(path: TempFile); |
| 2297 | llvm::sys::path::append(path&: VFS, a: "vfs" , b: "vfs.yaml" ); |
| 2298 | } |
| 2299 | } |
| 2300 | |
| 2301 | for (const char *TempFile : SavedTemps) |
| 2302 | TempFiles.push_back(Elt: TempFile); |
| 2303 | |
| 2304 | // Assume associated files are based off of the first temporary file. |
| 2305 | CrashReportInfo CrashInfo(TempFiles[0], VFS); |
| 2306 | |
| 2307 | llvm::SmallString<128> Script(CrashInfo.Filename); |
| 2308 | llvm::sys::path::replace_extension(path&: Script, extension: "sh" ); |
| 2309 | std::error_code EC; |
| 2310 | llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew, |
| 2311 | llvm::sys::fs::FA_Write, |
| 2312 | llvm::sys::fs::OF_Text); |
| 2313 | if (EC) { |
| 2314 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2315 | << "Error generating run script: " << Script << " " << EC.message(); |
| 2316 | } else { |
| 2317 | ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n" |
| 2318 | << "# Driver args: " ; |
| 2319 | printArgList(OS&: ScriptOS, Args: C.getInputArgs()); |
| 2320 | ScriptOS << "# Original command: " ; |
| 2321 | Cmd.Print(OS&: ScriptOS, Terminator: "\n" , /*Quote=*/true); |
| 2322 | Cmd.Print(OS&: ScriptOS, Terminator: "\n" , /*Quote=*/true, CrashInfo: &CrashInfo); |
| 2323 | if (!AdditionalInformation.empty()) |
| 2324 | ScriptOS << "\n# Additional information: " << AdditionalInformation |
| 2325 | << "\n" ; |
| 2326 | if (Report) |
| 2327 | Report->TemporaryFiles.push_back(Elt: std::string(Script)); |
| 2328 | TempFiles.push_back(Elt: std::string(Script)); |
| 2329 | ScriptOS.close(); |
| 2330 | if (!HasCrashTar) |
| 2331 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << Script; |
| 2332 | } |
| 2333 | |
| 2334 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_fcrash_diagnostics_tar)) { |
| 2335 | StringRef CrashDiagnosticsTar = A->getValue(); |
| 2336 | Expected<std::unique_ptr<llvm::TarWriter>> TarOrErr = |
| 2337 | llvm::TarWriter::create(OutputPath: CrashDiagnosticsTar, |
| 2338 | BaseDir: llvm::sys::path::stem(path: CrashDiagnosticsTar)); |
| 2339 | if (!TarOrErr) { |
| 2340 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2341 | << (std::string("Error creating reproducer tarball: " ) + |
| 2342 | llvm::toString(E: TarOrErr.takeError())); |
| 2343 | } else { |
| 2344 | std::unique_ptr<llvm::TarWriter> &Tar = *TarOrErr; |
| 2345 | for (const std::string &TempFile : TempFiles) { |
| 2346 | if (llvm::sys::fs::is_directory(Path: TempFile)) { |
| 2347 | std::error_code EC; |
| 2348 | for (llvm::sys::fs::recursive_directory_iterator I(TempFile, EC), E; |
| 2349 | I != E && !EC; I.increment(ec&: EC)) { |
| 2350 | if (llvm::sys::fs::is_regular_file(Path: I->path())) { |
| 2351 | auto BufferOrErr = llvm::MemoryBuffer::getFile(Filename: I->path()); |
| 2352 | if (BufferOrErr) { |
| 2353 | // Construct path of file relative to TempFile. |
| 2354 | llvm::SmallString<128> PathInTar = |
| 2355 | llvm::sys::path::filename(path: TempFile); |
| 2356 | StringRef SubPath = I->path(); |
| 2357 | if (SubPath.consume_front(Prefix: TempFile)) { |
| 2358 | if (!SubPath.empty() && |
| 2359 | llvm::sys::path::is_separator(value: SubPath.front())) { |
| 2360 | SubPath = SubPath.drop_front(); |
| 2361 | } |
| 2362 | llvm::sys::path::append(path&: PathInTar, a: SubPath); |
| 2363 | Tar->append(Path: PathInTar, Data: (*BufferOrErr)->getBuffer()); |
| 2364 | } |
| 2365 | } else { |
| 2366 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2367 | << (std::string("Error reading file for tarball: " ) + |
| 2368 | I->path()); |
| 2369 | } |
| 2370 | } |
| 2371 | } |
| 2372 | if (EC) { |
| 2373 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2374 | << (std::string("Error iterating directory for tarball: " ) + |
| 2375 | TempFile + " " + EC.message()); |
| 2376 | } |
| 2377 | } else { |
| 2378 | auto BufferOrErr = llvm::MemoryBuffer::getFile(Filename: TempFile); |
| 2379 | if (BufferOrErr) { |
| 2380 | Tar->append(Path: llvm::sys::path::filename(path: TempFile), |
| 2381 | Data: (*BufferOrErr)->getBuffer()); |
| 2382 | } else { |
| 2383 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2384 | << (std::string("Error reading file for tarball: " ) + TempFile); |
| 2385 | } |
| 2386 | } |
| 2387 | } |
| 2388 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2389 | << CrashDiagnosticsTar; |
| 2390 | } |
| 2391 | } |
| 2392 | |
| 2393 | // On darwin, provide information about the .crash diagnostic report. |
| 2394 | if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) { |
| 2395 | SmallString<128> CrashDiagDir; |
| 2396 | if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) { |
| 2397 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2398 | << ReproCrashFilename.str(); |
| 2399 | } else { // Suggest a directory for the user to look for .crash files. |
| 2400 | llvm::sys::path::append(path&: CrashDiagDir, a: Name); |
| 2401 | CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash" ; |
| 2402 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2403 | << "Crash backtrace is located in" ; |
| 2404 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2405 | << CrashDiagDir.str(); |
| 2406 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2407 | << "(choose the .crash file that corresponds to your crash)" ; |
| 2408 | } |
| 2409 | } |
| 2410 | |
| 2411 | Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) |
| 2412 | << "\n\n********************" ; |
| 2413 | } |
| 2414 | |
| 2415 | void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) { |
| 2416 | // Since commandLineFitsWithinSystemLimits() may underestimate system's |
| 2417 | // capacity if the tool does not support response files, there is a chance/ |
| 2418 | // that things will just work without a response file, so we silently just |
| 2419 | // skip it. |
| 2420 | if (Cmd.getResponseFileSupport().ResponseKind == |
| 2421 | ResponseFileSupport::RF_None || |
| 2422 | llvm::sys::commandLineFitsWithinSystemLimits(Program: Cmd.getExecutable(), |
| 2423 | Args: Cmd.getArguments())) |
| 2424 | return; |
| 2425 | |
| 2426 | std::string TmpName = GetTemporaryPath(Prefix: "response" , Suffix: "txt" ); |
| 2427 | Cmd.setResponseFile(C.addTempFile(Name: C.getArgs().MakeArgString(Str: TmpName))); |
| 2428 | } |
| 2429 | |
| 2430 | int Driver::ExecuteCompilation( |
| 2431 | Compilation &C, |
| 2432 | SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) { |
| 2433 | if (C.getArgs().hasArg(Ids: options::OPT_fdriver_only)) { |
| 2434 | if (C.getArgs().hasArg(Ids: options::OPT_v)) |
| 2435 | C.getJobs().Print(OS&: llvm::errs(), Terminator: "\n" , Quote: true); |
| 2436 | |
| 2437 | C.ExecuteJobs(Jobs: C.getJobs(), FailingCommands, /*LogOnly=*/true); |
| 2438 | |
| 2439 | // If there were errors building the compilation, quit now. |
| 2440 | if (!FailingCommands.empty() || Diags.hasErrorOccurred()) |
| 2441 | return 1; |
| 2442 | |
| 2443 | return 0; |
| 2444 | } |
| 2445 | |
| 2446 | // Just print if -### was present. |
| 2447 | if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH)) { |
| 2448 | C.getJobs().Print(OS&: llvm::errs(), Terminator: "\n" , Quote: true); |
| 2449 | return Diags.hasErrorOccurred() ? 1 : 0; |
| 2450 | } |
| 2451 | |
| 2452 | // If there were errors building the compilation, quit now. |
| 2453 | if (Diags.hasErrorOccurred()) |
| 2454 | return 1; |
| 2455 | |
| 2456 | // Set up response file names for each command, if necessary. |
| 2457 | for (auto &Job : C.getJobs()) |
| 2458 | setUpResponseFiles(C, Cmd&: Job); |
| 2459 | |
| 2460 | C.ExecuteJobs(Jobs: C.getJobs(), FailingCommands); |
| 2461 | |
| 2462 | // If the command succeeded, we are done. |
| 2463 | if (FailingCommands.empty()) |
| 2464 | return 0; |
| 2465 | |
| 2466 | // Otherwise, remove result files and print extra information about abnormal |
| 2467 | // failures. |
| 2468 | int Res = 0; |
| 2469 | for (const auto &CmdPair : FailingCommands) { |
| 2470 | int CommandRes = CmdPair.first; |
| 2471 | const Command *FailingCommand = CmdPair.second; |
| 2472 | |
| 2473 | // Remove result files if we're not saving temps. |
| 2474 | if (!isSaveTempsEnabled()) { |
| 2475 | const JobAction *JA = cast<JobAction>(Val: &FailingCommand->getSource()); |
| 2476 | C.CleanupFileMap(Files: C.getResultFiles(), JA, IssueErrors: true); |
| 2477 | |
| 2478 | // Failure result files are valid unless we crashed. |
| 2479 | if (CommandRes < 0) |
| 2480 | C.CleanupFileMap(Files: C.getFailureResultFiles(), JA, IssueErrors: true); |
| 2481 | } |
| 2482 | |
| 2483 | // llvm/lib/Support/*/Signals.inc will exit with a special return code |
| 2484 | // for SIGPIPE. Do not print diagnostics for this case. |
| 2485 | if (CommandRes == EX_IOERR) { |
| 2486 | Res = CommandRes; |
| 2487 | continue; |
| 2488 | } |
| 2489 | |
| 2490 | // Print extra information about abnormal failures, if possible. |
| 2491 | // |
| 2492 | // This is ad-hoc, but we don't want to be excessively noisy. If the result |
| 2493 | // status was 1, assume the command failed normally. In particular, if it |
| 2494 | // was the compiler then assume it gave a reasonable error code. Failures |
| 2495 | // in other tools are less common, and they generally have worse |
| 2496 | // diagnostics, so always print the diagnostic there. |
| 2497 | const Tool &FailingTool = FailingCommand->getCreator(); |
| 2498 | |
| 2499 | if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) { |
| 2500 | // FIXME: See FIXME above regarding result code interpretation. |
| 2501 | #if LLVM_ON_UNIX |
| 2502 | // On Unix, signals are represented by return codes of 128 plus the |
| 2503 | // signal number. Return code 255 is excluded because some tools, |
| 2504 | // such as llvm-ifs, exit with code 255 (-1) on failure. |
| 2505 | if (CommandRes > 128 && CommandRes != 255) |
| 2506 | #else |
| 2507 | if (CommandRes < 0) |
| 2508 | #endif |
| 2509 | Diag(DiagID: clang::diag::err_drv_command_signalled) |
| 2510 | << FailingTool.getShortName(); |
| 2511 | else |
| 2512 | Diag(DiagID: clang::diag::err_drv_command_failed) |
| 2513 | << FailingTool.getShortName() << CommandRes; |
| 2514 | } |
| 2515 | } |
| 2516 | return Res; |
| 2517 | } |
| 2518 | |
| 2519 | void Driver::PrintHelp(bool ShowHidden) const { |
| 2520 | llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(); |
| 2521 | |
| 2522 | std::string Usage = llvm::formatv(Fmt: "{0} [options] file..." , Vals: Name).str(); |
| 2523 | getOpts().printHelp(OS&: llvm::outs(), Usage: Usage.c_str(), Title: DriverTitle.c_str(), |
| 2524 | ShowHidden, /*ShowAllAliases=*/false, |
| 2525 | VisibilityMask); |
| 2526 | } |
| 2527 | |
| 2528 | void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { |
| 2529 | if (IsFlangMode()) { |
| 2530 | OS << getClangToolFullVersion(ToolName: "flang" ) << '\n'; |
| 2531 | } else { |
| 2532 | // FIXME: The following handlers should use a callback mechanism, we don't |
| 2533 | // know what the client would like to do. |
| 2534 | OS << getClangFullVersion() << '\n'; |
| 2535 | } |
| 2536 | const ToolChain &TC = C.getDefaultToolChain(); |
| 2537 | OS << "Target: " << TC.getTripleString() << '\n'; |
| 2538 | |
| 2539 | // Print the threading model. |
| 2540 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_mthread_model)) { |
| 2541 | // Don't print if the ToolChain would have barfed on it already |
| 2542 | if (TC.isThreadModelSupported(Model: A->getValue())) |
| 2543 | OS << "Thread model: " << A->getValue(); |
| 2544 | } else |
| 2545 | OS << "Thread model: " << TC.getThreadModel(); |
| 2546 | OS << '\n'; |
| 2547 | |
| 2548 | // Print out the install directory. |
| 2549 | OS << "InstalledDir: " << Dir << '\n'; |
| 2550 | |
| 2551 | // Print the build config if it's non-default. |
| 2552 | // Intended to help LLVM developers understand the configs of compilers |
| 2553 | // they're investigating. |
| 2554 | if (!llvm::cl::getCompilerBuildConfig().empty()) |
| 2555 | llvm::cl::printBuildConfig(OS); |
| 2556 | |
| 2557 | // If configuration files were used, print their paths. |
| 2558 | for (auto ConfigFile : ConfigFiles) |
| 2559 | OS << "Configuration file: " << ConfigFile << '\n'; |
| 2560 | } |
| 2561 | |
| 2562 | /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories |
| 2563 | /// option. |
| 2564 | static void PrintDiagnosticCategories(raw_ostream &OS) { |
| 2565 | // Skip the empty category. |
| 2566 | for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max; |
| 2567 | ++i) |
| 2568 | OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(CategoryID: i) << '\n'; |
| 2569 | } |
| 2570 | |
| 2571 | void Driver::HandleAutocompletions(StringRef PassedFlags) const { |
| 2572 | if (PassedFlags == "" ) |
| 2573 | return; |
| 2574 | // Print out all options that start with a given argument. This is used for |
| 2575 | // shell autocompletion. |
| 2576 | std::vector<std::string> SuggestedCompletions; |
| 2577 | std::vector<std::string> Flags; |
| 2578 | |
| 2579 | llvm::opt::Visibility VisibilityMask(options::ClangOption); |
| 2580 | |
| 2581 | // Make sure that Flang-only options don't pollute the Clang output |
| 2582 | // TODO: Make sure that Clang-only options don't pollute Flang output |
| 2583 | if (IsFlangMode()) |
| 2584 | VisibilityMask = llvm::opt::Visibility(options::FlangOption); |
| 2585 | |
| 2586 | // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag," |
| 2587 | // because the latter indicates that the user put space before pushing tab |
| 2588 | // which should end up in a file completion. |
| 2589 | const bool HasSpace = PassedFlags.ends_with(Suffix: "," ); |
| 2590 | |
| 2591 | // Parse PassedFlags by "," as all the command-line flags are passed to this |
| 2592 | // function separated by "," |
| 2593 | StringRef TargetFlags = PassedFlags; |
| 2594 | while (TargetFlags != "" ) { |
| 2595 | StringRef CurFlag; |
| 2596 | std::tie(args&: CurFlag, args&: TargetFlags) = TargetFlags.split(Separator: "," ); |
| 2597 | Flags.push_back(x: std::string(CurFlag)); |
| 2598 | } |
| 2599 | |
| 2600 | // We want to show cc1-only options only when clang is invoked with -cc1 or |
| 2601 | // -Xclang. |
| 2602 | if (llvm::is_contained(Range&: Flags, Element: "-Xclang" ) || llvm::is_contained(Range&: Flags, Element: "-cc1" )) |
| 2603 | VisibilityMask = llvm::opt::Visibility(options::CC1Option); |
| 2604 | |
| 2605 | const llvm::opt::OptTable &Opts = getOpts(); |
| 2606 | StringRef Cur; |
| 2607 | Cur = Flags.at(n: Flags.size() - 1); |
| 2608 | StringRef Prev; |
| 2609 | if (Flags.size() >= 2) { |
| 2610 | Prev = Flags.at(n: Flags.size() - 2); |
| 2611 | SuggestedCompletions = Opts.suggestValueCompletions(Option: Prev, Arg: Cur); |
| 2612 | } |
| 2613 | |
| 2614 | if (SuggestedCompletions.empty()) |
| 2615 | SuggestedCompletions = Opts.suggestValueCompletions(Option: Cur, Arg: "" ); |
| 2616 | |
| 2617 | // If Flags were empty, it means the user typed `clang [tab]` where we should |
| 2618 | // list all possible flags. If there was no value completion and the user |
| 2619 | // pressed tab after a space, we should fall back to a file completion. |
| 2620 | // We're printing a newline to be consistent with what we print at the end of |
| 2621 | // this function. |
| 2622 | if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) { |
| 2623 | llvm::outs() << '\n'; |
| 2624 | return; |
| 2625 | } |
| 2626 | |
| 2627 | // When flag ends with '=' and there was no value completion, return empty |
| 2628 | // string and fall back to the file autocompletion. |
| 2629 | if (SuggestedCompletions.empty() && !Cur.ends_with(Suffix: "=" )) { |
| 2630 | // If the flag is in the form of "--autocomplete=-foo", |
| 2631 | // we were requested to print out all option names that start with "-foo". |
| 2632 | // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only". |
| 2633 | SuggestedCompletions = Opts.findByPrefix( |
| 2634 | Cur, VisibilityMask, |
| 2635 | /*DisableFlags=*/options::Unsupported | options::Ignored); |
| 2636 | |
| 2637 | // We have to query the -W flags manually as they're not in the OptTable. |
| 2638 | // TODO: Find a good way to add them to OptTable instead and them remove |
| 2639 | // this code. |
| 2640 | for (StringRef S : DiagnosticIDs::getDiagnosticFlags()) |
| 2641 | if (S.starts_with(Prefix: Cur)) |
| 2642 | SuggestedCompletions.push_back(x: std::string(S)); |
| 2643 | } |
| 2644 | |
| 2645 | // Sort the autocomplete candidates so that shells print them out in a |
| 2646 | // deterministic order. We could sort in any way, but we chose |
| 2647 | // case-insensitive sorting for consistency with the -help option |
| 2648 | // which prints out options in the case-insensitive alphabetical order. |
| 2649 | llvm::sort(C&: SuggestedCompletions, Comp: [](StringRef A, StringRef B) { |
| 2650 | if (int X = A.compare_insensitive(RHS: B)) |
| 2651 | return X < 0; |
| 2652 | return A.compare(RHS: B) > 0; |
| 2653 | }); |
| 2654 | |
| 2655 | llvm::outs() << llvm::join(R&: SuggestedCompletions, Separator: "\n" ) << '\n'; |
| 2656 | } |
| 2657 | |
| 2658 | bool Driver::HandleImmediateArgs(Compilation &C) { |
| 2659 | // The order these options are handled in gcc is all over the place, but we |
| 2660 | // don't expect inconsistencies w.r.t. that to matter in practice. |
| 2661 | |
| 2662 | if (C.getArgs().hasArg(Ids: options::OPT_dumpmachine)) { |
| 2663 | llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; |
| 2664 | return false; |
| 2665 | } |
| 2666 | |
| 2667 | if (C.getArgs().hasArg(Ids: options::OPT_dumpversion)) { |
| 2668 | // Since -dumpversion is only implemented for pedantic GCC compatibility, we |
| 2669 | // return an answer which matches our definition of __VERSION__. |
| 2670 | llvm::outs() << CLANG_VERSION_STRING << "\n" ; |
| 2671 | return false; |
| 2672 | } |
| 2673 | |
| 2674 | if (C.getArgs().hasArg(Ids: options::OPT__print_diagnostic_categories)) { |
| 2675 | PrintDiagnosticCategories(OS&: llvm::outs()); |
| 2676 | return false; |
| 2677 | } |
| 2678 | |
| 2679 | if (C.getArgs().hasArg(Ids: options::OPT_help) || |
| 2680 | C.getArgs().hasArg(Ids: options::OPT__help_hidden)) { |
| 2681 | PrintHelp(ShowHidden: C.getArgs().hasArg(Ids: options::OPT__help_hidden)); |
| 2682 | return false; |
| 2683 | } |
| 2684 | |
| 2685 | if (C.getArgs().hasArg(Ids: options::OPT__version)) { |
| 2686 | // Follow gcc behavior and use stdout for --version and stderr for -v. |
| 2687 | PrintVersion(C, OS&: llvm::outs()); |
| 2688 | return false; |
| 2689 | } |
| 2690 | |
| 2691 | // Honor --ssaf-list-extractors, --ssaf-list-formats and their combinations. |
| 2692 | bool = C.getArgs().hasArg(Ids: options::OPT__ssaf_list_extractors); |
| 2693 | bool ListFormats = C.getArgs().hasArg(Ids: options::OPT__ssaf_list_formats); |
| 2694 | if (ListExtractors || ListFormats) { |
| 2695 | if (ListExtractors) |
| 2696 | ssaf::printAvailableTUSummaryExtractors(OS&: llvm::outs()); |
| 2697 | if (ListFormats) |
| 2698 | ssaf::printAvailableFormats(OS&: llvm::outs()); |
| 2699 | return false; |
| 2700 | } |
| 2701 | |
| 2702 | if (C.getArgs().hasArg(Ids: options::OPT__ssaf_list_formats)) { |
| 2703 | ssaf::printAvailableFormats(OS&: llvm::outs()); |
| 2704 | return false; |
| 2705 | } |
| 2706 | |
| 2707 | if (C.getArgs().hasArg(Ids: options::OPT_v) || |
| 2708 | C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH) || |
| 2709 | C.getArgs().hasArg(Ids: options::OPT_print_supported_cpus) || |
| 2710 | C.getArgs().hasArg(Ids: options::OPT_print_supported_extensions) || |
| 2711 | C.getArgs().hasArg(Ids: options::OPT_print_enabled_extensions)) { |
| 2712 | PrintVersion(C, OS&: llvm::errs()); |
| 2713 | SuppressMissingInputWarning = true; |
| 2714 | } |
| 2715 | |
| 2716 | if (C.getArgs().hasArg(Ids: options::OPT_v)) { |
| 2717 | if (!SystemConfigDir.empty()) |
| 2718 | llvm::errs() << "System configuration file directory: " |
| 2719 | << SystemConfigDir << "\n" ; |
| 2720 | if (!UserConfigDir.empty()) |
| 2721 | llvm::errs() << "User configuration file directory: " |
| 2722 | << UserConfigDir << "\n" ; |
| 2723 | } |
| 2724 | |
| 2725 | const ToolChain &TC = C.getDefaultToolChain(); |
| 2726 | |
| 2727 | if (C.getArgs().hasArg(Ids: options::OPT_v)) |
| 2728 | TC.printVerboseInfo(OS&: llvm::errs()); |
| 2729 | |
| 2730 | if (C.getArgs().hasArg(Ids: options::OPT_print_resource_dir)) { |
| 2731 | llvm::outs() << ResourceDir << '\n'; |
| 2732 | return false; |
| 2733 | } |
| 2734 | |
| 2735 | if (C.getArgs().hasArg(Ids: options::OPT_print_search_dirs)) { |
| 2736 | llvm::outs() << "programs: =" ; |
| 2737 | bool separator = false; |
| 2738 | // Print -B and COMPILER_PATH. |
| 2739 | for (const std::string &Path : PrefixDirs) { |
| 2740 | if (separator) |
| 2741 | llvm::outs() << llvm::sys::EnvPathSeparator; |
| 2742 | llvm::outs() << Path; |
| 2743 | separator = true; |
| 2744 | } |
| 2745 | for (const std::string &Path : TC.getProgramPaths()) { |
| 2746 | if (separator) |
| 2747 | llvm::outs() << llvm::sys::EnvPathSeparator; |
| 2748 | llvm::outs() << Path; |
| 2749 | separator = true; |
| 2750 | } |
| 2751 | llvm::outs() << "\n" ; |
| 2752 | llvm::outs() << "libraries: =" << ResourceDir; |
| 2753 | |
| 2754 | StringRef sysroot = C.getSysRoot(); |
| 2755 | |
| 2756 | for (const std::string &Path : TC.getFilePaths()) { |
| 2757 | // Always print a separator. ResourceDir was the first item shown. |
| 2758 | llvm::outs() << llvm::sys::EnvPathSeparator; |
| 2759 | // Interpretation of leading '=' is needed only for NetBSD. |
| 2760 | if (Path[0] == '=') |
| 2761 | llvm::outs() << sysroot << Path.substr(pos: 1); |
| 2762 | else |
| 2763 | llvm::outs() << Path; |
| 2764 | } |
| 2765 | llvm::outs() << "\n" ; |
| 2766 | return false; |
| 2767 | } |
| 2768 | |
| 2769 | if (C.getArgs().hasArg(Ids: options::OPT_print_cxx_stdlib)) { |
| 2770 | llvm::outs() << TC.GetCXXStdlibName(Args: C.getArgs()) << '\n'; |
| 2771 | return false; |
| 2772 | } |
| 2773 | |
| 2774 | if (C.getArgs().hasArg(Ids: options::OPT_print_cxx_stdlib_include_dirs)) { |
| 2775 | printCXXStdlibIncludeDirs(TC, Args: C.getArgs()); |
| 2776 | return false; |
| 2777 | } |
| 2778 | |
| 2779 | if (C.getArgs().hasArg(Ids: options::OPT_print_std_module_manifest_path)) { |
| 2780 | llvm::outs() << GetStdModuleManifestPath(C, TC: C.getDefaultToolChain()) |
| 2781 | << '\n'; |
| 2782 | return false; |
| 2783 | } |
| 2784 | |
| 2785 | if (C.getArgs().hasArg(Ids: options::OPT_print_runtime_dir)) { |
| 2786 | for (auto RuntimePath : |
| 2787 | {TC.getRuntimePath(), std::make_optional(t: TC.getCompilerRTPath())}) { |
| 2788 | if (RuntimePath && getVFS().exists(Path: *RuntimePath)) { |
| 2789 | llvm::outs() << *RuntimePath << '\n'; |
| 2790 | return false; |
| 2791 | } |
| 2792 | } |
| 2793 | llvm::outs() << "(runtime dir is not present)" << '\n'; |
| 2794 | return false; |
| 2795 | } |
| 2796 | |
| 2797 | if (C.getArgs().hasArg(Ids: options::OPT_print_diagnostic_options)) { |
| 2798 | std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags(); |
| 2799 | for (std::size_t I = 0; I != Flags.size(); I += 2) |
| 2800 | llvm::outs() << " " << Flags[I] << "\n " << Flags[I + 1] << "\n\n" ; |
| 2801 | return false; |
| 2802 | } |
| 2803 | |
| 2804 | // FIXME: The following handlers should use a callback mechanism, we don't |
| 2805 | // know what the client would like to do. |
| 2806 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_print_file_name_EQ)) { |
| 2807 | llvm::outs() << GetFilePath(Name: A->getValue(), TC) << "\n" ; |
| 2808 | return false; |
| 2809 | } |
| 2810 | |
| 2811 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_print_prog_name_EQ)) { |
| 2812 | StringRef ProgName = A->getValue(); |
| 2813 | |
| 2814 | // Null program name cannot have a path. |
| 2815 | if (! ProgName.empty()) |
| 2816 | llvm::outs() << GetProgramPath(Name: ProgName, TC); |
| 2817 | |
| 2818 | llvm::outs() << "\n" ; |
| 2819 | return false; |
| 2820 | } |
| 2821 | |
| 2822 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_autocomplete)) { |
| 2823 | StringRef PassedFlags = A->getValue(); |
| 2824 | HandleAutocompletions(PassedFlags); |
| 2825 | return false; |
| 2826 | } |
| 2827 | |
| 2828 | if (C.getArgs().hasArg(Ids: options::OPT_print_libgcc_file_name)) { |
| 2829 | ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args: C.getArgs()); |
| 2830 | const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args: C.getArgs())); |
| 2831 | // The 'Darwin' toolchain is initialized only when its arguments are |
| 2832 | // computed. Get the default arguments for OFK_None to ensure that |
| 2833 | // initialization is performed before trying to access properties of |
| 2834 | // the toolchain in the functions below. |
| 2835 | // FIXME: Remove when darwin's toolchain is initialized during construction. |
| 2836 | // FIXME: For some more esoteric targets the default toolchain is not the |
| 2837 | // correct one. |
| 2838 | C.getArgsForToolChain(TC: &TC, BA: BoundArch(Triple.getArchName()), |
| 2839 | DeviceOffloadKind: Action::OFK_Host); |
| 2840 | RegisterEffectiveTriple TripleRAII(TC, Triple); |
| 2841 | switch (RLT) { |
| 2842 | case ToolChain::RLT_CompilerRT: |
| 2843 | llvm::outs() << TC.getCompilerRT(Args: C.getArgs(), Component: "builtins" ) << "\n" ; |
| 2844 | break; |
| 2845 | case ToolChain::RLT_Libgcc: |
| 2846 | llvm::outs() << GetFilePath(Name: "libgcc.a" , TC) << "\n" ; |
| 2847 | break; |
| 2848 | } |
| 2849 | return false; |
| 2850 | } |
| 2851 | |
| 2852 | if (C.getArgs().hasArg(Ids: options::OPT_print_multi_lib)) { |
| 2853 | for (const Multilib &Multilib : TC.getMultilibs()) |
| 2854 | if (!Multilib.isError()) |
| 2855 | llvm::outs() << Multilib << "\n" ; |
| 2856 | return false; |
| 2857 | } |
| 2858 | |
| 2859 | if (C.getArgs().hasArg(Ids: options::OPT_print_multi_flags)) { |
| 2860 | Multilib::flags_list ArgFlags = TC.getMultilibFlags(C.getArgs()); |
| 2861 | llvm::StringSet<> ExpandedFlags = TC.getMultilibs().expandFlags(ArgFlags); |
| 2862 | std::set<llvm::StringRef> SortedFlags; |
| 2863 | for (const auto &FlagEntry : ExpandedFlags) |
| 2864 | SortedFlags.insert(x: FlagEntry.getKey()); |
| 2865 | for (auto Flag : SortedFlags) |
| 2866 | llvm::outs() << Flag << '\n'; |
| 2867 | return false; |
| 2868 | } |
| 2869 | |
| 2870 | if (C.getArgs().hasArg(Ids: options::OPT_print_multi_directory)) { |
| 2871 | for (const Multilib &Multilib : TC.getSelectedMultilibs()) { |
| 2872 | if (Multilib.gccSuffix().empty()) |
| 2873 | llvm::outs() << ".\n" ; |
| 2874 | else { |
| 2875 | StringRef Suffix(Multilib.gccSuffix()); |
| 2876 | assert(Suffix.front() == '/'); |
| 2877 | llvm::outs() << Suffix.substr(Start: 1) << "\n" ; |
| 2878 | } |
| 2879 | } |
| 2880 | return false; |
| 2881 | } |
| 2882 | |
| 2883 | if (C.getArgs().hasArg(Ids: options::OPT_print_target_triple)) { |
| 2884 | llvm::outs() << TC.getTripleString() << "\n" ; |
| 2885 | return false; |
| 2886 | } |
| 2887 | |
| 2888 | if (C.getArgs().hasArg(Ids: options::OPT_print_effective_triple)) { |
| 2889 | const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args: C.getArgs())); |
| 2890 | llvm::outs() << Triple.getTriple() << "\n" ; |
| 2891 | return false; |
| 2892 | } |
| 2893 | |
| 2894 | if (C.getArgs().hasArg(Ids: options::OPT_print_targets)) { |
| 2895 | llvm::TargetRegistry::printRegisteredTargetsForVersion(OS&: llvm::outs()); |
| 2896 | return false; |
| 2897 | } |
| 2898 | |
| 2899 | return true; |
| 2900 | } |
| 2901 | |
| 2902 | enum { |
| 2903 | TopLevelAction = 0, |
| 2904 | HeadSibAction = 1, |
| 2905 | OtherSibAction = 2, |
| 2906 | }; |
| 2907 | |
| 2908 | // Display an action graph human-readably. Action A is the "sink" node |
| 2909 | // and latest-occuring action. Traversal is in pre-order, visiting the |
| 2910 | // inputs to each action before printing the action itself. |
| 2911 | static unsigned PrintActions1(const Compilation &C, Action *A, |
| 2912 | std::map<Action *, unsigned> &Ids, |
| 2913 | Twine Indent = {}, int Kind = TopLevelAction) { |
| 2914 | if (auto It = Ids.find(x: A); It != Ids.end()) // A was already visited. |
| 2915 | return It->second; |
| 2916 | |
| 2917 | std::string str; |
| 2918 | llvm::raw_string_ostream os(str); |
| 2919 | |
| 2920 | auto getSibIndent = [](int K) -> Twine { |
| 2921 | return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "" ; |
| 2922 | }; |
| 2923 | |
| 2924 | Twine SibIndent = Indent + getSibIndent(Kind); |
| 2925 | int SibKind = HeadSibAction; |
| 2926 | os << Action::getClassName(AC: A->getKind()) << ", " ; |
| 2927 | if (InputAction *IA = dyn_cast<InputAction>(Val: A)) { |
| 2928 | os << "\"" << IA->getInputArg().getValue() << "\"" ; |
| 2929 | } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(Val: A)) { |
| 2930 | os << '"' << BIA->getArch().ArchName << '"' << ", {" |
| 2931 | << PrintActions1(C, A: *BIA->input_begin(), Ids, Indent: SibIndent, Kind: SibKind) << "}" ; |
| 2932 | } else if (OffloadAction *OA = dyn_cast<OffloadAction>(Val: A)) { |
| 2933 | bool IsFirst = true; |
| 2934 | OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, BoundArch BA) { |
| 2935 | assert(TC && "Unknown host toolchain" ); |
| 2936 | // E.g. for two CUDA device dependences whose bound arch is sm_20 and |
| 2937 | // sm_35 this will generate: |
| 2938 | // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device" |
| 2939 | // (nvptx64-nvidia-cuda:sm_35) {#ID} |
| 2940 | if (!IsFirst) |
| 2941 | os << ", " ; |
| 2942 | os << '"'; |
| 2943 | os << A->getOffloadingKindPrefix(); |
| 2944 | os << " (" ; |
| 2945 | os << TC->getTripleString(); |
| 2946 | if (!BA.empty()) |
| 2947 | os << ":" << BA.ArchName; |
| 2948 | os << ")" ; |
| 2949 | os << '"'; |
| 2950 | os << " {" << PrintActions1(C, A, Ids, Indent: SibIndent, Kind: SibKind) << "}" ; |
| 2951 | IsFirst = false; |
| 2952 | SibKind = OtherSibAction; |
| 2953 | }); |
| 2954 | } else { |
| 2955 | const ActionList *AL = &A->getInputs(); |
| 2956 | |
| 2957 | if (AL->size()) { |
| 2958 | const char *Prefix = "{" ; |
| 2959 | for (Action *PreRequisite : *AL) { |
| 2960 | os << Prefix << PrintActions1(C, A: PreRequisite, Ids, Indent: SibIndent, Kind: SibKind); |
| 2961 | Prefix = ", " ; |
| 2962 | SibKind = OtherSibAction; |
| 2963 | } |
| 2964 | os << "}" ; |
| 2965 | } else |
| 2966 | os << "{}" ; |
| 2967 | } |
| 2968 | |
| 2969 | // Append offload info for all options other than the offloading action |
| 2970 | // itself (e.g. (cuda-device, sm_20) or (cuda-host)). |
| 2971 | std::string offload_str; |
| 2972 | llvm::raw_string_ostream offload_os(offload_str); |
| 2973 | if (!isa<OffloadAction>(Val: A)) { |
| 2974 | auto S = A->getOffloadingKindPrefix(); |
| 2975 | if (!S.empty()) { |
| 2976 | offload_os << ", (" << S; |
| 2977 | if (!A->getOffloadingArch().empty()) |
| 2978 | offload_os << ", " << A->getOffloadingArch().ArchName; |
| 2979 | offload_os << ")" ; |
| 2980 | } |
| 2981 | } |
| 2982 | |
| 2983 | auto getSelfIndent = [](int K) -> Twine { |
| 2984 | return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "" ; |
| 2985 | }; |
| 2986 | |
| 2987 | unsigned Id = Ids.size(); |
| 2988 | Ids[A] = Id; |
| 2989 | llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", " |
| 2990 | << types::getTypeName(Id: A->getType()) << offload_os.str() << "\n" ; |
| 2991 | |
| 2992 | return Id; |
| 2993 | } |
| 2994 | |
| 2995 | // Print the action graphs in a compilation C. |
| 2996 | // For example "clang -c file1.c file2.c" is composed of two subgraphs. |
| 2997 | void Driver::PrintActions(const Compilation &C) const { |
| 2998 | std::map<Action *, unsigned> Ids; |
| 2999 | for (Action *A : C.getActions()) |
| 3000 | PrintActions1(C, A, Ids); |
| 3001 | } |
| 3002 | |
| 3003 | /// Check whether the given input tree contains any compilation or |
| 3004 | /// assembly actions. |
| 3005 | static bool ContainsCompileOrAssembleAction(const Action *A) { |
| 3006 | if (isa<CompileJobAction>(Val: A) || isa<BackendJobAction>(Val: A) || |
| 3007 | isa<AssembleJobAction>(Val: A)) |
| 3008 | return true; |
| 3009 | |
| 3010 | return llvm::any_of(Range: A->inputs(), P: ContainsCompileOrAssembleAction); |
| 3011 | } |
| 3012 | |
| 3013 | void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC, |
| 3014 | const InputList &BAInputs) const { |
| 3015 | DerivedArgList &Args = C.getArgs(); |
| 3016 | ActionList &Actions = C.getActions(); |
| 3017 | llvm::PrettyStackTraceString CrashInfo("Building universal build actions" ); |
| 3018 | // Collect the list of architectures. Duplicates are allowed, but should only |
| 3019 | // be handled once (in the order seen). |
| 3020 | llvm::StringSet<> ArchNames; |
| 3021 | SmallVector<const char *, 4> Archs; |
| 3022 | for (Arg *A : Args) { |
| 3023 | if (A->getOption().matches(ID: options::OPT_arch)) { |
| 3024 | // Validate the option here; we don't save the type here because its |
| 3025 | // particular spelling may participate in other driver choices. |
| 3026 | llvm::Triple::ArchType Arch = |
| 3027 | tools::darwin::getArchTypeForMachOArchName(Str: A->getValue()); |
| 3028 | if (Arch == llvm::Triple::UnknownArch) { |
| 3029 | Diag(DiagID: clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args); |
| 3030 | continue; |
| 3031 | } |
| 3032 | |
| 3033 | A->claim(); |
| 3034 | if (ArchNames.insert(key: A->getValue()).second) |
| 3035 | Archs.push_back(Elt: A->getValue()); |
| 3036 | } |
| 3037 | } |
| 3038 | |
| 3039 | // When there is no explicit arch for this platform, make sure we still bind |
| 3040 | // the architecture (to the default) so that -Xarch_ is handled correctly. |
| 3041 | if (!Archs.size()) |
| 3042 | Archs.push_back(Elt: Args.MakeArgString(Str: TC.getDefaultUniversalArchName())); |
| 3043 | |
| 3044 | ActionList SingleActions; |
| 3045 | BuildActions(C, Args, Inputs: BAInputs, Actions&: SingleActions); |
| 3046 | |
| 3047 | // Add in arch bindings for every top level action, as well as lipo and |
| 3048 | // dsymutil steps if needed. |
| 3049 | for (Action* Act : SingleActions) { |
| 3050 | // Make sure we can lipo this kind of output. If not (and it is an actual |
| 3051 | // output) then we disallow, since we can't create an output file with the |
| 3052 | // right name without overwriting it. We could remove this oddity by just |
| 3053 | // changing the output names to include the arch, which would also fix |
| 3054 | // -save-temps. Compatibility wins for now. |
| 3055 | |
| 3056 | if (Archs.size() > 1 && !types::canLipoType(Id: Act->getType())) |
| 3057 | Diag(DiagID: clang::diag::err_drv_invalid_output_with_multiple_archs) |
| 3058 | << types::getTypeName(Id: Act->getType()); |
| 3059 | |
| 3060 | ActionList Inputs; |
| 3061 | for (unsigned i = 0, e = Archs.size(); i != e; ++i) |
| 3062 | Inputs.push_back(Elt: C.MakeAction<BindArchAction>(Arg&: Act, Arg: BoundArch(Archs[i]))); |
| 3063 | |
| 3064 | // Lipo if necessary, we do it this way because we need to set the arch flag |
| 3065 | // so that -Xarch_ gets overwritten. |
| 3066 | if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) |
| 3067 | Actions.append(in_start: Inputs.begin(), in_end: Inputs.end()); |
| 3068 | else |
| 3069 | Actions.push_back(Elt: C.MakeAction<LipoJobAction>(Arg&: Inputs, Arg: Act->getType())); |
| 3070 | |
| 3071 | // Handle debug info queries. |
| 3072 | Arg *A = Args.getLastArg(Ids: options::OPT_g_Group); |
| 3073 | bool enablesDebugInfo = A && !A->getOption().matches(ID: options::OPT_g0) && |
| 3074 | !A->getOption().matches(ID: options::OPT_gstabs); |
| 3075 | bool enablesPseudoProbe = |
| 3076 | Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling, |
| 3077 | Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false); |
| 3078 | bool enablesDebugInfoForProfiling = |
| 3079 | Args.hasFlag(Pos: options::OPT_fdebug_info_for_profiling, |
| 3080 | Neg: options::OPT_fno_debug_info_for_profiling, Default: false); |
| 3081 | if ((enablesDebugInfo || willEmitRemarks(Args) || enablesPseudoProbe || |
| 3082 | enablesDebugInfoForProfiling) && |
| 3083 | ContainsCompileOrAssembleAction(A: Actions.back())) { |
| 3084 | |
| 3085 | // Add a 'dsymutil' step if necessary, when debug info, remarks, or |
| 3086 | // pseudo probes are enabled and we have a compile input. We need to run |
| 3087 | // 'dsymutil' ourselves in such cases because the debug info will refer |
| 3088 | // to a temporary object file which will be removed at the end of the |
| 3089 | // compilation process. |
| 3090 | if (Act->getType() == types::TY_Image) { |
| 3091 | ActionList Inputs; |
| 3092 | Inputs.push_back(Elt: Actions.back()); |
| 3093 | Actions.pop_back(); |
| 3094 | Actions.push_back( |
| 3095 | Elt: C.MakeAction<DsymutilJobAction>(Arg&: Inputs, Arg: types::TY_dSYM)); |
| 3096 | } |
| 3097 | |
| 3098 | // Verify the debug info output. |
| 3099 | if (Args.hasArg(Ids: options::OPT_verify_debug_info)) { |
| 3100 | Action *LastAction = Actions.pop_back_val(); |
| 3101 | Actions.push_back(Elt: C.MakeAction<VerifyDebugInfoJobAction>( |
| 3102 | Arg&: LastAction, Arg: types::TY_Nothing)); |
| 3103 | } |
| 3104 | } |
| 3105 | } |
| 3106 | } |
| 3107 | |
| 3108 | bool Driver::DiagnoseInputExistence(StringRef Value, types::ID Ty, |
| 3109 | bool TypoCorrect) const { |
| 3110 | if (!getCheckInputsExist()) |
| 3111 | return true; |
| 3112 | |
| 3113 | // stdin always exists. |
| 3114 | if (Value == "-" ) |
| 3115 | return true; |
| 3116 | |
| 3117 | // If it's a header to be found in the system or user search path, then defer |
| 3118 | // complaints about its absence until those searches can be done. When we |
| 3119 | // are definitely processing headers for C++20 header units, extend this to |
| 3120 | // allow the user to put "-fmodule-header -xc++-header vector" for example. |
| 3121 | if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader || |
| 3122 | (ModulesModeCXX20 && Ty == types::TY_CXXHeader)) |
| 3123 | return true; |
| 3124 | |
| 3125 | if (getVFS().exists(Path: Value)) |
| 3126 | return true; |
| 3127 | |
| 3128 | if (TypoCorrect) { |
| 3129 | // Check if the filename is a typo for an option flag. OptTable thinks |
| 3130 | // that all args that are not known options and that start with / are |
| 3131 | // filenames, but e.g. `/diagnostic:caret` is more likely a typo for |
| 3132 | // the option `/diagnostics:caret` than a reference to a file in the root |
| 3133 | // directory. |
| 3134 | std::string Nearest; |
| 3135 | if (getOpts().findNearest(Option: Value, NearestString&: Nearest, VisibilityMask: getOptionVisibilityMask()) <= 1) { |
| 3136 | Diag(DiagID: clang::diag::err_drv_no_such_file_with_suggestion) |
| 3137 | << Value << Nearest; |
| 3138 | return false; |
| 3139 | } |
| 3140 | } |
| 3141 | |
| 3142 | // In CL mode, don't error on apparently non-existent linker inputs, because |
| 3143 | // they can be influenced by linker flags the clang driver might not |
| 3144 | // understand. |
| 3145 | // Examples: |
| 3146 | // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver |
| 3147 | // module look for an MSVC installation in the registry. (We could ask |
| 3148 | // the MSVCToolChain object if it can find `ole32.lib`, but the logic to |
| 3149 | // look in the registry might move into lld-link in the future so that |
| 3150 | // lld-link invocations in non-MSVC shells just work too.) |
| 3151 | // - `clang-cl ... /link ...` can pass arbitrary flags to the linker, |
| 3152 | // including /libpath:, which is used to find .lib and .obj files. |
| 3153 | // So do not diagnose this on the driver level. Rely on the linker diagnosing |
| 3154 | // it. (If we don't end up invoking the linker, this means we'll emit a |
| 3155 | // "'linker' input unused [-Wunused-command-line-argument]" warning instead |
| 3156 | // of an error.) |
| 3157 | // |
| 3158 | // Only do this skip after the typo correction step above. `/Brepo` is treated |
| 3159 | // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit |
| 3160 | // an error if we have a flag that's within an edit distance of 1 from a |
| 3161 | // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the |
| 3162 | // driver in the unlikely case they run into this.) |
| 3163 | // |
| 3164 | // Don't do this for inputs that start with a '/', else we'd pass options |
| 3165 | // like /libpath: through to the linker silently. |
| 3166 | // |
| 3167 | // Emitting an error for linker inputs can also cause incorrect diagnostics |
| 3168 | // with the gcc driver. The command |
| 3169 | // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o |
| 3170 | // will make lld look for some/dir/file.o, while we will diagnose here that |
| 3171 | // `/file.o` does not exist. However, configure scripts check if |
| 3172 | // `clang /GR-` compiles without error to see if the compiler is cl.exe, |
| 3173 | // so we can't downgrade diagnostics for `/GR-` from an error to a warning |
| 3174 | // in cc mode. (We can in cl mode because cl.exe itself only warns on |
| 3175 | // unknown flags.) |
| 3176 | if (IsCLMode() && Ty == types::TY_Object && !Value.starts_with(Prefix: "/" )) |
| 3177 | return true; |
| 3178 | |
| 3179 | Diag(DiagID: clang::diag::err_drv_no_such_file) << Value; |
| 3180 | return false; |
| 3181 | } |
| 3182 | |
| 3183 | // Get the C++20 Header Unit type corresponding to the input type. |
| 3184 | static types::ID (ModuleHeaderMode HM) { |
| 3185 | switch (HM) { |
| 3186 | case HeaderMode_User: |
| 3187 | return types::TY_CXXUHeader; |
| 3188 | case HeaderMode_System: |
| 3189 | return types::TY_CXXSHeader; |
| 3190 | case HeaderMode_Default: |
| 3191 | break; |
| 3192 | case HeaderMode_None: |
| 3193 | llvm_unreachable("should not be called in this case" ); |
| 3194 | } |
| 3195 | return types::TY_CXXHUHeader; |
| 3196 | } |
| 3197 | |
| 3198 | // Construct a the list of inputs and their types. |
| 3199 | void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, |
| 3200 | InputList &Inputs) const { |
| 3201 | const llvm::opt::OptTable &Opts = getOpts(); |
| 3202 | // Track the current user specified (-x) input. We also explicitly track the |
| 3203 | // argument used to set the type; we only want to claim the type when we |
| 3204 | // actually use it, so we warn about unused -x arguments. |
| 3205 | types::ID InputType = types::TY_Nothing; |
| 3206 | Arg *InputTypeArg = nullptr; |
| 3207 | |
| 3208 | // The last /TC or /TP option sets the input type to C or C++ globally. |
| 3209 | if (Arg *TCTP = Args.getLastArgNoClaim(Ids: options::OPT__SLASH_TC, |
| 3210 | Ids: options::OPT__SLASH_TP)) { |
| 3211 | InputTypeArg = TCTP; |
| 3212 | InputType = TCTP->getOption().matches(ID: options::OPT__SLASH_TC) |
| 3213 | ? types::TY_C |
| 3214 | : types::TY_CXX; |
| 3215 | |
| 3216 | Arg *Previous = nullptr; |
| 3217 | bool ShowNote = false; |
| 3218 | for (Arg *A : |
| 3219 | Args.filtered(Ids: options::OPT__SLASH_TC, Ids: options::OPT__SLASH_TP)) { |
| 3220 | if (Previous) { |
| 3221 | Diag(DiagID: clang::diag::warn_drv_overriding_option) |
| 3222 | << Previous->getSpelling() << A->getSpelling(); |
| 3223 | ShowNote = true; |
| 3224 | } |
| 3225 | Previous = A; |
| 3226 | } |
| 3227 | if (ShowNote) |
| 3228 | Diag(DiagID: clang::diag::note_drv_t_option_is_global); |
| 3229 | } |
| 3230 | |
| 3231 | // Warn -x after last input file has no effect |
| 3232 | { |
| 3233 | Arg *LastXArg = Args.getLastArgNoClaim(Ids: options::OPT_x); |
| 3234 | Arg *LastInputArg = Args.getLastArgNoClaim(Ids: options::OPT_INPUT); |
| 3235 | if (LastXArg && LastInputArg && |
| 3236 | LastInputArg->getIndex() < LastXArg->getIndex()) |
| 3237 | Diag(DiagID: clang::diag::warn_drv_unused_x) << LastXArg->getValue(); |
| 3238 | } |
| 3239 | |
| 3240 | bool IsSYCL = Args.hasFlag(Pos: options::OPT_fsycl, Neg: options::OPT_fno_sycl, Default: false); |
| 3241 | |
| 3242 | for (Arg *A : Args) { |
| 3243 | if (A->getOption().getKind() == Option::InputClass) { |
| 3244 | const char *Value = A->getValue(); |
| 3245 | types::ID Ty = types::TY_INVALID; |
| 3246 | |
| 3247 | // Infer the input type if necessary. |
| 3248 | if (InputType == types::TY_Nothing) { |
| 3249 | // If there was an explicit arg for this, claim it. |
| 3250 | if (InputTypeArg) |
| 3251 | InputTypeArg->claim(); |
| 3252 | |
| 3253 | // stdin must be handled specially. |
| 3254 | if (strcmp(s1: Value, s2: "-" ) == 0) { |
| 3255 | if (IsFlangMode()) { |
| 3256 | Ty = types::TY_Fortran; |
| 3257 | } else if (IsDXCMode()) { |
| 3258 | Ty = types::TY_HLSL; |
| 3259 | } else if (IsSYCL) { |
| 3260 | Ty = types::TY_CXX; |
| 3261 | } else { |
| 3262 | // If running with -E, treat as a C input (this changes the |
| 3263 | // builtin macros, for example). This may be overridden by -ObjC |
| 3264 | // below. |
| 3265 | // |
| 3266 | // Otherwise emit an error but still use a valid type to avoid |
| 3267 | // spurious errors (e.g., no inputs). |
| 3268 | assert(!CCGenDiagnostics && "stdin produces no crash reproducer" ); |
| 3269 | if (!Args.hasArgNoClaim(Ids: options::OPT_E) && !CCCIsCPP()) |
| 3270 | Diag(DiagID: IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl |
| 3271 | : clang::diag::err_drv_unknown_stdin_type); |
| 3272 | Ty = types::TY_C; |
| 3273 | } |
| 3274 | } else { |
| 3275 | // Otherwise lookup by extension. |
| 3276 | // Fallback is C if invoked as C preprocessor, C++ if invoked with |
| 3277 | // clang-cl /E, or Object otherwise. |
| 3278 | // We use a host hook here because Darwin at least has its own |
| 3279 | // idea of what .s is. |
| 3280 | if (const char *Ext = strrchr(s: Value, c: '.')) |
| 3281 | Ty = TC.LookupTypeForExtension(Ext: Ext + 1); |
| 3282 | |
| 3283 | if (Ty == types::TY_INVALID) { |
| 3284 | if (IsCLMode() && (Args.hasArgNoClaim(Ids: options::OPT_E) || CCGenDiagnostics)) |
| 3285 | Ty = types::TY_CXX; |
| 3286 | else if (CCCIsCPP() || CCGenDiagnostics) |
| 3287 | Ty = types::TY_C; |
| 3288 | else if (IsDXCMode()) |
| 3289 | Ty = types::TY_HLSL; |
| 3290 | else |
| 3291 | Ty = types::TY_Object; |
| 3292 | } |
| 3293 | |
| 3294 | // If the driver is invoked as C++ compiler (like clang++ or c++) it |
| 3295 | // should autodetect some input files as C++ for g++ compatibility. |
| 3296 | if (CCCIsCXX()) { |
| 3297 | types::ID OldTy = Ty; |
| 3298 | Ty = types::lookupCXXTypeForCType(Id: Ty); |
| 3299 | |
| 3300 | // Do not complain about foo.h, when we are known to be processing |
| 3301 | // it as a C++20 header unit. |
| 3302 | if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode())) |
| 3303 | Diag(DiagID: clang::diag::warn_drv_treating_input_as_cxx) |
| 3304 | << getTypeName(Id: OldTy) << getTypeName(Id: Ty); |
| 3305 | } |
| 3306 | |
| 3307 | // If running with -fthinlto-index=, extensions that normally identify |
| 3308 | // native object files actually identify LLVM bitcode files. |
| 3309 | if (Args.hasArgNoClaim(Ids: options::OPT_fthinlto_index_EQ) && |
| 3310 | Ty == types::TY_Object) |
| 3311 | Ty = types::TY_LLVM_BC; |
| 3312 | } |
| 3313 | |
| 3314 | // -ObjC and -ObjC++ override the default language, but only for "source |
| 3315 | // files". We just treat everything that isn't a linker input as a |
| 3316 | // source file. |
| 3317 | // |
| 3318 | // FIXME: Clean this up if we move the phase sequence into the type. |
| 3319 | if (Ty != types::TY_Object) { |
| 3320 | if (Args.hasArg(Ids: options::OPT_ObjC)) |
| 3321 | Ty = types::TY_ObjC; |
| 3322 | else if (Args.hasArg(Ids: options::OPT_ObjCXX)) |
| 3323 | Ty = types::TY_ObjCXX; |
| 3324 | } |
| 3325 | |
| 3326 | // Disambiguate headers that are meant to be header units from those |
| 3327 | // intended to be PCH. Avoid missing '.h' cases that are counted as |
| 3328 | // C headers by default - we know we are in C++ mode and we do not |
| 3329 | // want to issue a complaint about compiling things in the wrong mode. |
| 3330 | if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) && |
| 3331 | hasHeaderMode()) |
| 3332 | Ty = CXXHeaderUnitType(HM: CXX20HeaderType); |
| 3333 | } else { |
| 3334 | assert(InputTypeArg && "InputType set w/o InputTypeArg" ); |
| 3335 | if (!InputTypeArg->getOption().matches(ID: options::OPT_x)) { |
| 3336 | // If emulating cl.exe, make sure that /TC and /TP don't affect input |
| 3337 | // object files. |
| 3338 | const char *Ext = strrchr(s: Value, c: '.'); |
| 3339 | if (Ext && TC.LookupTypeForExtension(Ext: Ext + 1) == types::TY_Object) |
| 3340 | Ty = types::TY_Object; |
| 3341 | } |
| 3342 | if (Ty == types::TY_INVALID) { |
| 3343 | Ty = InputType; |
| 3344 | InputTypeArg->claim(); |
| 3345 | } |
| 3346 | } |
| 3347 | |
| 3348 | if ((Ty == types::TY_C || Ty == types::TY_CXX) && |
| 3349 | Args.hasArgNoClaim(Ids: options::OPT_hipstdpar)) |
| 3350 | Ty = types::TY_HIP; |
| 3351 | |
| 3352 | if (DiagnoseInputExistence(Value, Ty, /*TypoCorrect=*/true)) |
| 3353 | Inputs.push_back(Elt: std::make_pair(x&: Ty, y&: A)); |
| 3354 | |
| 3355 | } else if (A->getOption().matches(ID: options::OPT__SLASH_Tc)) { |
| 3356 | StringRef Value = A->getValue(); |
| 3357 | if (DiagnoseInputExistence(Value, Ty: types::TY_C, |
| 3358 | /*TypoCorrect=*/false)) { |
| 3359 | Arg *InputArg = makeInputArg(Args, Opts, Value: A->getValue()); |
| 3360 | Inputs.push_back(Elt: std::make_pair(x: types::TY_C, y&: InputArg)); |
| 3361 | } |
| 3362 | A->claim(); |
| 3363 | } else if (A->getOption().matches(ID: options::OPT__SLASH_Tp)) { |
| 3364 | StringRef Value = A->getValue(); |
| 3365 | if (DiagnoseInputExistence(Value, Ty: types::TY_CXX, |
| 3366 | /*TypoCorrect=*/false)) { |
| 3367 | Arg *InputArg = makeInputArg(Args, Opts, Value: A->getValue()); |
| 3368 | Inputs.push_back(Elt: std::make_pair(x: types::TY_CXX, y&: InputArg)); |
| 3369 | } |
| 3370 | A->claim(); |
| 3371 | } else if (A->getOption().hasFlag(Val: options::LinkerInput)) { |
| 3372 | // Just treat as object type, we could make a special type for this if |
| 3373 | // necessary. |
| 3374 | Inputs.push_back(Elt: std::make_pair(x: types::TY_Object, y&: A)); |
| 3375 | |
| 3376 | } else if (A->getOption().matches(ID: options::OPT_x)) { |
| 3377 | InputTypeArg = A; |
| 3378 | InputType = types::lookupTypeForTypeSpecifier(Name: A->getValue()); |
| 3379 | A->claim(); |
| 3380 | |
| 3381 | // Follow gcc behavior and treat as linker input for invalid -x |
| 3382 | // options. Its not clear why we shouldn't just revert to unknown; but |
| 3383 | // this isn't very important, we might as well be bug compatible. |
| 3384 | if (!InputType) { |
| 3385 | Diag(DiagID: clang::diag::err_drv_unknown_language) << A->getValue(); |
| 3386 | InputType = types::TY_Object; |
| 3387 | } |
| 3388 | |
| 3389 | // If the user has put -fmodule-header{,=} then we treat C++ headers as |
| 3390 | // header unit inputs. So we 'promote' -xc++-header appropriately. |
| 3391 | if (InputType == types::TY_CXXHeader && hasHeaderMode()) |
| 3392 | InputType = CXXHeaderUnitType(HM: CXX20HeaderType); |
| 3393 | } else if (A->getOption().getID() == options::OPT_U) { |
| 3394 | assert(A->getNumValues() == 1 && "The /U option has one value." ); |
| 3395 | StringRef Val = A->getValue(N: 0); |
| 3396 | if (Val.find_first_of(Chars: "/\\" ) != StringRef::npos) { |
| 3397 | // Warn about e.g. "/Users/me/myfile.c". |
| 3398 | Diag(DiagID: diag::warn_slash_u_filename) << Val; |
| 3399 | Diag(DiagID: diag::note_use_dashdash); |
| 3400 | } |
| 3401 | } |
| 3402 | } |
| 3403 | if (CCCIsCPP() && Inputs.empty()) { |
| 3404 | // If called as standalone preprocessor, stdin is processed |
| 3405 | // if no other input is present. |
| 3406 | Arg *A = makeInputArg(Args, Opts, Value: "-" ); |
| 3407 | Inputs.push_back(Elt: std::make_pair(x: types::TY_C, y&: A)); |
| 3408 | } |
| 3409 | } |
| 3410 | |
| 3411 | void Driver::handleArguments(Compilation &C, DerivedArgList &Args, |
| 3412 | const InputList &Inputs, |
| 3413 | ActionList &Actions) const { |
| 3414 | |
| 3415 | // Diagnose misuse of /Fo. |
| 3416 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_Fo)) { |
| 3417 | StringRef V = A->getValue(); |
| 3418 | if (Inputs.size() > 1 && !V.empty() && |
| 3419 | !llvm::sys::path::is_separator(value: V.back())) { |
| 3420 | // Check whether /Fo tries to name an output file for multiple inputs. |
| 3421 | Diag(DiagID: clang::diag::err_drv_out_file_argument_with_multiple_sources) |
| 3422 | << A->getSpelling() << V; |
| 3423 | Args.eraseArg(Id: options::OPT__SLASH_Fo); |
| 3424 | } |
| 3425 | } |
| 3426 | |
| 3427 | // Diagnose misuse of /Fa. |
| 3428 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_Fa)) { |
| 3429 | StringRef V = A->getValue(); |
| 3430 | if (Inputs.size() > 1 && !V.empty() && |
| 3431 | !llvm::sys::path::is_separator(value: V.back())) { |
| 3432 | // Check whether /Fa tries to name an asm file for multiple inputs. |
| 3433 | Diag(DiagID: clang::diag::err_drv_out_file_argument_with_multiple_sources) |
| 3434 | << A->getSpelling() << V; |
| 3435 | Args.eraseArg(Id: options::OPT__SLASH_Fa); |
| 3436 | } |
| 3437 | } |
| 3438 | |
| 3439 | // Diagnose misuse of /o. |
| 3440 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_o)) { |
| 3441 | if (A->getValue()[0] == '\0') { |
| 3442 | // It has to have a value. |
| 3443 | Diag(DiagID: clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; |
| 3444 | Args.eraseArg(Id: options::OPT__SLASH_o); |
| 3445 | } |
| 3446 | } |
| 3447 | |
| 3448 | // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames. |
| 3449 | Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc); |
| 3450 | Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu); |
| 3451 | if (YcArg && YuArg && strcmp(s1: YcArg->getValue(), s2: YuArg->getValue()) != 0) { |
| 3452 | Diag(DiagID: clang::diag::warn_drv_ycyu_different_arg_clang_cl); |
| 3453 | Args.eraseArg(Id: options::OPT__SLASH_Yc); |
| 3454 | Args.eraseArg(Id: options::OPT__SLASH_Yu); |
| 3455 | YcArg = YuArg = nullptr; |
| 3456 | } |
| 3457 | if (YcArg && Inputs.size() > 1) { |
| 3458 | Diag(DiagID: clang::diag::warn_drv_yc_multiple_inputs_clang_cl); |
| 3459 | Args.eraseArg(Id: options::OPT__SLASH_Yc); |
| 3460 | YcArg = nullptr; |
| 3461 | } |
| 3462 | |
| 3463 | Arg *FinalPhaseArg; |
| 3464 | phases::ID FinalPhase = getFinalPhase(DAL: Args, Inputs, FinalPhaseArg: &FinalPhaseArg); |
| 3465 | |
| 3466 | if (FinalPhase == phases::Link) { |
| 3467 | if (Args.hasArgNoClaim(Ids: options::OPT_hipstdpar)) { |
| 3468 | Args.AddFlagArg(BaseArg: nullptr, Opt: getOpts().getOption(Opt: options::OPT_hip_link)); |
| 3469 | Args.AddFlagArg(BaseArg: nullptr, |
| 3470 | Opt: getOpts().getOption(Opt: options::OPT_frtlib_add_rpath)); |
| 3471 | } |
| 3472 | // Emitting LLVM while linking disabled except in the HIPAMD or SPIR-V |
| 3473 | // Toolchains |
| 3474 | if (Args.hasArg(Ids: options::OPT_emit_llvm) && |
| 3475 | !Args.hasArg(Ids: options::OPT_hip_link) && |
| 3476 | !C.getDefaultToolChain().getTriple().isSPIRV()) |
| 3477 | Diag(DiagID: clang::diag::err_drv_emit_llvm_link); |
| 3478 | if (C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() && |
| 3479 | C.getDefaultToolChain().isUsingLTO(Args) && |
| 3480 | !Args.getLastArgValue(Id: options::OPT_fuse_ld_EQ) |
| 3481 | .starts_with_insensitive(Prefix: "lld" )) |
| 3482 | Diag(DiagID: clang::diag::err_drv_lto_without_lld); |
| 3483 | |
| 3484 | // If -dumpdir is not specified, give a default prefix derived from the link |
| 3485 | // output filename. For example, `clang -g -gsplit-dwarf a.c -o x` passes |
| 3486 | // `-dumpdir x-` to cc1. If -o is unspecified, use |
| 3487 | // stem(getDefaultImageName()) (usually stem("a.out") = "a"). |
| 3488 | if (!Args.hasArg(Ids: options::OPT_dumpdir)) { |
| 3489 | Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_o); |
| 3490 | Arg *Arg = Args.MakeSeparateArg( |
| 3491 | BaseArg: nullptr, Opt: getOpts().getOption(Opt: options::OPT_dumpdir), |
| 3492 | Value: Args.MakeArgString( |
| 3493 | Str: (FinalOutput ? FinalOutput->getValue() |
| 3494 | : llvm::sys::path::stem(path: getDefaultImageName())) + |
| 3495 | "-" )); |
| 3496 | Arg->claim(); |
| 3497 | Args.append(A: Arg); |
| 3498 | } |
| 3499 | } |
| 3500 | |
| 3501 | if (FinalPhase == phases::Preprocess || Args.hasArg(Ids: options::OPT__SLASH_Y_)) { |
| 3502 | // If only preprocessing or /Y- is used, all pch handling is disabled. |
| 3503 | // Rather than check for it everywhere, just remove clang-cl pch-related |
| 3504 | // flags here. |
| 3505 | Args.eraseArg(Id: options::OPT__SLASH_Fp); |
| 3506 | Args.eraseArg(Id: options::OPT__SLASH_Yc); |
| 3507 | Args.eraseArg(Id: options::OPT__SLASH_Yu); |
| 3508 | YcArg = YuArg = nullptr; |
| 3509 | } |
| 3510 | |
| 3511 | if (Args.hasArg(Ids: options::OPT_include_pch) && |
| 3512 | Args.hasArg(Ids: options::OPT_ignore_pch)) { |
| 3513 | // If -ignore-pch is used, -include-pch is disabled. Since -emit-pch is |
| 3514 | // CC1option, it will not be added to command argments if -ignore-pch is |
| 3515 | // used. |
| 3516 | Args.eraseArg(Id: options::OPT_include_pch); |
| 3517 | } |
| 3518 | |
| 3519 | bool LinkOnly = phases::Link == FinalPhase && Inputs.size() > 0; |
| 3520 | for (auto &I : Inputs) { |
| 3521 | types::ID InputType = I.first; |
| 3522 | const Arg *InputArg = I.second; |
| 3523 | |
| 3524 | auto PL = types::getCompilationPhases(Id: InputType); |
| 3525 | |
| 3526 | phases::ID InitialPhase = PL[0]; |
| 3527 | LinkOnly = LinkOnly && phases::Link == InitialPhase && PL.size() == 1; |
| 3528 | |
| 3529 | // If the first step comes after the final phase we are doing as part of |
| 3530 | // this compilation, warn the user about it. |
| 3531 | if (InitialPhase > FinalPhase) { |
| 3532 | if (InputArg->isClaimed()) |
| 3533 | continue; |
| 3534 | |
| 3535 | // Claim here to avoid the more general unused warning. |
| 3536 | InputArg->claim(); |
| 3537 | |
| 3538 | // Suppress all unused style warnings with -Qunused-arguments |
| 3539 | if (Args.hasArg(Ids: options::OPT_Qunused_arguments)) |
| 3540 | continue; |
| 3541 | |
| 3542 | // Special case when final phase determined by binary name, rather than |
| 3543 | // by a command-line argument with a corresponding Arg. |
| 3544 | if (CCCIsCPP()) |
| 3545 | Diag(DiagID: clang::diag::warn_drv_input_file_unused_by_cpp) |
| 3546 | << InputArg->getAsString(Args) << getPhaseName(Id: InitialPhase); |
| 3547 | // Special case '-E' warning on a previously preprocessed file to make |
| 3548 | // more sense. |
| 3549 | else if (InitialPhase == phases::Compile && |
| 3550 | (Args.getLastArg(Ids: options::OPT__SLASH_EP, |
| 3551 | Ids: options::OPT__SLASH_P) || |
| 3552 | Args.getLastArg(Ids: options::OPT_E) || |
| 3553 | Args.getLastArg(Ids: options::OPT_M, Ids: options::OPT_MM)) && |
| 3554 | getPreprocessedType(Id: InputType) == types::TY_INVALID) |
| 3555 | Diag(DiagID: clang::diag::warn_drv_preprocessed_input_file_unused) |
| 3556 | << InputArg->getAsString(Args) << !!FinalPhaseArg |
| 3557 | << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "" ); |
| 3558 | else |
| 3559 | Diag(DiagID: clang::diag::warn_drv_input_file_unused) |
| 3560 | << InputArg->getAsString(Args) << getPhaseName(Id: InitialPhase) |
| 3561 | << !FinalPhaseArg |
| 3562 | << (FinalPhaseArg ? FinalPhaseArg->getSpelling() : "" ); |
| 3563 | continue; |
| 3564 | } |
| 3565 | |
| 3566 | if (YcArg) { |
| 3567 | // Add a separate precompile phase for the compile phase. |
| 3568 | if (FinalPhase >= phases::Compile) { |
| 3569 | const types::ID = lookupHeaderTypeForSourceType(Id: InputType); |
| 3570 | // Build the pipeline for the pch file. |
| 3571 | Action *ClangClPch = C.MakeAction<InputAction>(Arg: *InputArg, Arg: HeaderType); |
| 3572 | auto HostLTO = C.getDefaultToolChain().getLTOMode(Args); |
| 3573 | for (phases::ID Phase : types::getCompilationPhases(Id: HeaderType)) |
| 3574 | ClangClPch = ConstructPhaseAction(C, Args, Phase, Input: ClangClPch, |
| 3575 | TargetDeviceOffloadKind: Action::OFK_None, TargetLTOMode: HostLTO); |
| 3576 | assert(ClangClPch); |
| 3577 | Actions.push_back(Elt: ClangClPch); |
| 3578 | // The driver currently exits after the first failed command. This |
| 3579 | // relies on that behavior, to make sure if the pch generation fails, |
| 3580 | // the main compilation won't run. |
| 3581 | // FIXME: If the main compilation fails, the PCH generation should |
| 3582 | // probably not be considered successful either. |
| 3583 | } |
| 3584 | } |
| 3585 | } |
| 3586 | |
| 3587 | // Claim any options which are obviously only used for compilation. |
| 3588 | if (LinkOnly) { |
| 3589 | Args.ClaimAllArgs(Id0: options::OPT_CompileOnly_Group); |
| 3590 | Args.ClaimAllArgs(Id0: options::OPT_cl_compile_Group); |
| 3591 | } |
| 3592 | } |
| 3593 | |
| 3594 | /// HIP non-RDC \c -S for AMDGCN: emit host and device assembly separately and |
| 3595 | /// bundle with \c clang-offload-bundler, instead of \c llvm-offload-binary / |
| 3596 | /// \c clang-linker-wrapper fatbin embedding. |
| 3597 | static bool shouldBundleHIPAsm(const Compilation &C, |
| 3598 | const llvm::opt::DerivedArgList &Args, |
| 3599 | const Driver &D) { |
| 3600 | if (!C.isOffloadingHostKind(Kind: Action::OFK_HIP) || |
| 3601 | !Args.hasArg(Ids: options::OPT_S) || Args.hasArg(Ids: options::OPT_emit_llvm) || |
| 3602 | D.offloadDeviceOnly() || |
| 3603 | Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false)) |
| 3604 | return false; |
| 3605 | |
| 3606 | bool HasAMDGCNHIPDevice = false; |
| 3607 | auto HIPTCs = C.getOffloadToolChains(Kind: Action::OFK_HIP); |
| 3608 | for (auto It = HIPTCs.first; It != HIPTCs.second; ++It) { |
| 3609 | const ToolChain *TC = It->second; |
| 3610 | const llvm::Triple &Tr = TC->getTriple(); |
| 3611 | if (!Tr.isAMDGPU()) |
| 3612 | return false; |
| 3613 | HasAMDGCNHIPDevice = true; |
| 3614 | } |
| 3615 | return HasAMDGCNHIPDevice; |
| 3616 | } |
| 3617 | |
| 3618 | void Driver::BuildActions(Compilation &C, DerivedArgList &Args, |
| 3619 | const InputList &Inputs, ActionList &Actions) const { |
| 3620 | llvm::PrettyStackTraceString CrashInfo("Building compilation actions" ); |
| 3621 | |
| 3622 | if (!SuppressMissingInputWarning && Inputs.empty()) { |
| 3623 | Diag(DiagID: clang::diag::err_drv_no_input_files); |
| 3624 | return; |
| 3625 | } |
| 3626 | |
| 3627 | handleArguments(C, Args, Inputs, Actions); |
| 3628 | |
| 3629 | // The legacy offloading driver has been removed; the new driver is always |
| 3630 | // used. Accept the old toggles as no-ops, but warn that disabling it no |
| 3631 | // longer has any effect. |
| 3632 | if (Arg *A = Args.getLastArg(Ids: options::OPT_no_offload_new_driver)) |
| 3633 | Diag(DiagID: clang::diag::warn_drv_deprecated_custom) |
| 3634 | << A->getAsString(Args) |
| 3635 | << "the legacy offloading driver has been removed" ; |
| 3636 | Args.ClaimAllArgs(Id0: options::OPT_no_offload_new_driver); |
| 3637 | Args.ClaimAllArgs(Id0: options::OPT_offload_new_driver); |
| 3638 | |
| 3639 | bool HIPRDCDeviceOnlyFatBin = |
| 3640 | C.isOffloadingHostKind(Kind: Action::OFK_HIP) && offloadDeviceOnly() && |
| 3641 | Args.hasArg(Ids: options::OPT_hip_link) && |
| 3642 | Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false) && |
| 3643 | getFinalPhase(DAL: Args, Inputs) == phases::Link && |
| 3644 | !Args.hasArg(Ids: options::OPT_emit_llvm) && |
| 3645 | Args.hasFlag(Pos: options::OPT_gpu_bundle_output, |
| 3646 | Neg: options::OPT_no_gpu_bundle_output, Default: true); |
| 3647 | |
| 3648 | // Construct the actions to perform. |
| 3649 | ExtractAPIJobAction * = nullptr; |
| 3650 | ActionList LinkerInputs; |
| 3651 | ActionList MergerInputs; |
| 3652 | |
| 3653 | for (auto &I : Inputs) { |
| 3654 | types::ID InputType = I.first; |
| 3655 | const Arg *InputArg = I.second; |
| 3656 | |
| 3657 | auto PL = types::getCompilationPhases(Driver: *this, DAL&: Args, Inputs, Id: InputType); |
| 3658 | if (PL.empty()) |
| 3659 | continue; |
| 3660 | |
| 3661 | auto FullPL = types::getCompilationPhases(Id: InputType); |
| 3662 | |
| 3663 | // Build the pipeline for this file. |
| 3664 | Action *Current = C.MakeAction<InputAction>(Arg: *InputArg, Arg&: InputType); |
| 3665 | |
| 3666 | // Device-only HIP links consume packaged offload bitcode directly. |
| 3667 | if (HIPRDCDeviceOnlyFatBin && InputType == types::TY_LLVM_BC) { |
| 3668 | LinkerInputs.push_back(Elt: Current); |
| 3669 | continue; |
| 3670 | } |
| 3671 | |
| 3672 | std::string CUID; |
| 3673 | if (CUIDOpts.isEnabled() && types::isSrcFile(Id: InputType)) { |
| 3674 | CUID = CUIDOpts.getCUID(InputFile: InputArg->getValue(), Args); |
| 3675 | cast<InputAction>(Val: Current)->setId(CUID); |
| 3676 | } |
| 3677 | |
| 3678 | ActionList HIPAsmDeviceActions; |
| 3679 | |
| 3680 | for (phases::ID Phase : PL) { |
| 3681 | if (!Current) |
| 3682 | break; |
| 3683 | |
| 3684 | // Queue linker inputs. |
| 3685 | if (Phase == phases::Link) { |
| 3686 | assert(Phase == PL.back() && "linking must be final compilation step." ); |
| 3687 | // We don't need to generate additional link commands if emitting AMD |
| 3688 | // bitcode or compiling only for the offload device |
| 3689 | if (!(C.getInputArgs().hasArg(Ids: options::OPT_hip_link) && |
| 3690 | (C.getInputArgs().hasArg(Ids: options::OPT_emit_llvm))) && |
| 3691 | !offloadDeviceOnly()) |
| 3692 | LinkerInputs.push_back(Elt: Current); |
| 3693 | Current = nullptr; |
| 3694 | break; |
| 3695 | } |
| 3696 | |
| 3697 | // TODO: Consider removing this because the merged may not end up being |
| 3698 | // the final Phase in the pipeline. Perhaps the merged could just merge |
| 3699 | // and then pass an artifact of some sort to the Link Phase. |
| 3700 | // Queue merger inputs. |
| 3701 | if (Phase == phases::IfsMerge) { |
| 3702 | assert(Phase == PL.back() && "merging must be final compilation step." ); |
| 3703 | MergerInputs.push_back(Elt: Current); |
| 3704 | Current = nullptr; |
| 3705 | break; |
| 3706 | } |
| 3707 | |
| 3708 | if (Phase == phases::Precompile && ExtractAPIAction) { |
| 3709 | ExtractAPIAction->addHeaderInput(Input: Current); |
| 3710 | Current = nullptr; |
| 3711 | break; |
| 3712 | } |
| 3713 | |
| 3714 | // FIXME: Should we include any prior module file outputs as inputs of |
| 3715 | // later actions in the same command line? |
| 3716 | |
| 3717 | // Otherwise construct the appropriate action. |
| 3718 | Action *NewCurrent = |
| 3719 | ConstructPhaseAction(C, Args, Phase, Input: Current, TargetDeviceOffloadKind: Action::OFK_None, |
| 3720 | TargetLTOMode: C.getDefaultToolChain().getLTOMode(Args)); |
| 3721 | |
| 3722 | // We didn't create a new action, so we will just move to the next phase. |
| 3723 | if (NewCurrent == Current) |
| 3724 | continue; |
| 3725 | |
| 3726 | if (auto *EAA = dyn_cast<ExtractAPIJobAction>(Val: NewCurrent)) |
| 3727 | ExtractAPIAction = EAA; |
| 3728 | |
| 3729 | Current = NewCurrent; |
| 3730 | |
| 3731 | // Try to build the offloading actions and add the result as a dependency |
| 3732 | // to the host. |
| 3733 | Current = BuildOffloadingActions(C, Args, Input: I, CUID, HostAction: Current, |
| 3734 | HIPAsmBundleDeviceOut: &HIPAsmDeviceActions); |
| 3735 | |
| 3736 | if (Current->getType() == types::TY_Nothing) |
| 3737 | break; |
| 3738 | } |
| 3739 | |
| 3740 | // HIP non-RDC -S (AMDGCN): bundle host and device assembly instead of |
| 3741 | // embedding a fat binary in host asm. |
| 3742 | if (Current && !HIPAsmDeviceActions.empty()) { |
| 3743 | ActionList BundleInputs; |
| 3744 | BundleInputs.append(RHS: HIPAsmDeviceActions); |
| 3745 | BundleInputs.push_back(Elt: Current); |
| 3746 | Current = C.MakeAction<OffloadBundlingJobAction>(Arg&: BundleInputs); |
| 3747 | } |
| 3748 | |
| 3749 | // If we ended with something, add to the output list. |
| 3750 | if (Current) { |
| 3751 | Actions.push_back(Elt: Current); |
| 3752 | Current->propagateHostOffloadInfo(OKinds: C.getActiveOffloadKinds(), |
| 3753 | /*BA=*/OArch: {}); |
| 3754 | } |
| 3755 | } |
| 3756 | |
| 3757 | // Add a link action if necessary. |
| 3758 | if (!LinkerInputs.empty()) { |
| 3759 | Action *LA; |
| 3760 | // Check if this Linker Job should emit a static library. |
| 3761 | if (ShouldEmitStaticLibrary(Args)) { |
| 3762 | LA = C.MakeAction<StaticLibJobAction>(Arg&: LinkerInputs, Arg: types::TY_Image); |
| 3763 | } else if (C.getActiveOffloadKinds() != Action::OFK_None || |
| 3764 | Args.hasArg(Ids: options::OPT_offload_link)) { |
| 3765 | LA = C.MakeAction<LinkerWrapperJobAction>( |
| 3766 | Arg&: LinkerInputs, |
| 3767 | Arg: HIPRDCDeviceOnlyFatBin ? types::TY_HIP_FATBIN : types::TY_Image); |
| 3768 | LA->propagateHostOffloadInfo(OKinds: C.getActiveOffloadKinds(), |
| 3769 | /*BA=*/OArch: {}); |
| 3770 | } else { |
| 3771 | // If we are linking but were passed -emit-llvm, we will be calling |
| 3772 | // llvm-link, so set the output type accordingly. This is only allowed in |
| 3773 | // rare cases, so make sure we aren't going to error about it. |
| 3774 | bool LinkingIR = Args.hasArg(Ids: options::OPT_emit_llvm) && |
| 3775 | C.getDefaultToolChain().getTriple().isSPIRV(); |
| 3776 | types::ID LT = LinkingIR && !Diags.hasErrorOccurred() ? types::TY_LLVM_BC |
| 3777 | : types::TY_Image; |
| 3778 | LA = C.MakeAction<LinkJobAction>(Arg&: LinkerInputs, Arg&: LT); |
| 3779 | } |
| 3780 | Actions.push_back(Elt: LA); |
| 3781 | } |
| 3782 | |
| 3783 | // Add an interface stubs merge action if necessary. |
| 3784 | if (!MergerInputs.empty()) |
| 3785 | Actions.push_back( |
| 3786 | Elt: C.MakeAction<IfsMergeJobAction>(Arg&: MergerInputs, Arg: types::TY_Image)); |
| 3787 | |
| 3788 | if (Args.hasArg(Ids: options::OPT_emit_interface_stubs)) { |
| 3789 | auto PhaseList = types::getCompilationPhases( |
| 3790 | Id: types::TY_IFS_CPP, |
| 3791 | LastPhase: Args.hasArg(Ids: options::OPT_c) ? phases::Compile : phases::IfsMerge); |
| 3792 | |
| 3793 | ActionList MergerInputs; |
| 3794 | |
| 3795 | for (auto &I : Inputs) { |
| 3796 | types::ID InputType = I.first; |
| 3797 | const Arg *InputArg = I.second; |
| 3798 | |
| 3799 | // Currently clang and the llvm assembler do not support generating symbol |
| 3800 | // stubs from assembly, so we skip the input on asm files. For ifs files |
| 3801 | // we rely on the normal pipeline setup in the pipeline setup code above. |
| 3802 | if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm || |
| 3803 | InputType == types::TY_Asm) |
| 3804 | continue; |
| 3805 | |
| 3806 | Action *Current = C.MakeAction<InputAction>(Arg: *InputArg, Arg&: InputType); |
| 3807 | |
| 3808 | for (auto Phase : PhaseList) { |
| 3809 | switch (Phase) { |
| 3810 | default: |
| 3811 | llvm_unreachable( |
| 3812 | "IFS Pipeline can only consist of Compile followed by IfsMerge." ); |
| 3813 | case phases::Compile: { |
| 3814 | // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs |
| 3815 | // files where the .o file is located. The compile action can not |
| 3816 | // handle this. |
| 3817 | if (InputType == types::TY_Object) |
| 3818 | break; |
| 3819 | |
| 3820 | Current = C.MakeAction<CompileJobAction>(Arg&: Current, Arg: types::TY_IFS_CPP); |
| 3821 | break; |
| 3822 | } |
| 3823 | case phases::IfsMerge: { |
| 3824 | assert(Phase == PhaseList.back() && |
| 3825 | "merging must be final compilation step." ); |
| 3826 | MergerInputs.push_back(Elt: Current); |
| 3827 | Current = nullptr; |
| 3828 | break; |
| 3829 | } |
| 3830 | } |
| 3831 | } |
| 3832 | |
| 3833 | // If we ended with something, add to the output list. |
| 3834 | if (Current) |
| 3835 | Actions.push_back(Elt: Current); |
| 3836 | } |
| 3837 | |
| 3838 | // Add an interface stubs merge action if necessary. |
| 3839 | if (!MergerInputs.empty()) |
| 3840 | Actions.push_back( |
| 3841 | Elt: C.MakeAction<IfsMergeJobAction>(Arg&: MergerInputs, Arg: types::TY_Image)); |
| 3842 | } |
| 3843 | |
| 3844 | for (auto Opt : {options::OPT_print_supported_cpus, |
| 3845 | options::OPT_print_supported_extensions, |
| 3846 | options::OPT_print_enabled_extensions}) { |
| 3847 | // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a |
| 3848 | // custom Compile phase that prints out supported cpu models and quits. |
| 3849 | // |
| 3850 | // If either --print-supported-extensions or --print-enabled-extensions is |
| 3851 | // specified, call the corresponding helper function that prints out the |
| 3852 | // supported/enabled extensions and quits. |
| 3853 | if (Arg *A = Args.getLastArg(Ids: Opt)) { |
| 3854 | if (Opt == options::OPT_print_supported_extensions && |
| 3855 | !C.getDefaultToolChain().getTriple().isRISCV() && |
| 3856 | !C.getDefaultToolChain().getTriple().isAArch64() && |
| 3857 | !C.getDefaultToolChain().getTriple().isARM()) { |
| 3858 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_on_target) |
| 3859 | << "--print-supported-extensions" ; |
| 3860 | return; |
| 3861 | } |
| 3862 | if (Opt == options::OPT_print_enabled_extensions && |
| 3863 | !C.getDefaultToolChain().getTriple().isRISCV() && |
| 3864 | !C.getDefaultToolChain().getTriple().isAArch64()) { |
| 3865 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_on_target) |
| 3866 | << "--print-enabled-extensions" ; |
| 3867 | return; |
| 3868 | } |
| 3869 | |
| 3870 | // Use the -mcpu=? flag as the dummy input to cc1. |
| 3871 | Actions.clear(); |
| 3872 | Action *InputAc = C.MakeAction<InputAction>( |
| 3873 | Arg&: *A, Arg: IsFlangMode() ? types::TY_Fortran : types::TY_C); |
| 3874 | Actions.push_back( |
| 3875 | Elt: C.MakeAction<PrecompileJobAction>(Arg&: InputAc, Arg: types::TY_Nothing)); |
| 3876 | for (auto &I : Inputs) |
| 3877 | I.second->claim(); |
| 3878 | } |
| 3879 | } |
| 3880 | |
| 3881 | llvm::Triple TargetTriple(C.getDriver().getTargetTriple()); |
| 3882 | if (TargetTriple.getOS() == llvm::Triple::Vulkan || |
| 3883 | TargetTriple.getOS() == llvm::Triple::ShaderModel) { |
| 3884 | const auto &TC = |
| 3885 | static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain()); |
| 3886 | |
| 3887 | // Call objcopy for manipulation of the unvalidated DXContainer when an |
| 3888 | // option in Args requires it. |
| 3889 | if (TC.requiresObjcopy(Args)) { |
| 3890 | Action *LastAction = Actions.back(); |
| 3891 | // llvm-objcopy expects an unvalidated DXIL container (TY_OBJECT). |
| 3892 | if (LastAction->getType() == types::TY_Object) { |
| 3893 | ActionList ObjcopyActions({LastAction}); |
| 3894 | Actions.push_back( |
| 3895 | Elt: C.MakeAction<ObjcopyJobAction>(Arg&: ObjcopyActions, Arg: types::TY_Object)); |
| 3896 | } |
| 3897 | } |
| 3898 | |
| 3899 | // Call validator when -Vd not in Args. |
| 3900 | auto ValInfo = TC.getValidationInfo(Args); |
| 3901 | if (ValInfo.NeedsValidation) { |
| 3902 | Action *LastAction = Actions.back(); |
| 3903 | if (LastAction->getType() == types::TY_Object) { |
| 3904 | types::ID OutType = |
| 3905 | ValInfo.ProducesOutput ? types::TY_DX_CONTAINER : types::TY_Object; |
| 3906 | Actions.push_back( |
| 3907 | Elt: C.MakeAction<BinaryAnalyzeJobAction>(Arg&: LastAction, Arg&: OutType)); |
| 3908 | } |
| 3909 | } |
| 3910 | |
| 3911 | // Call metal-shaderconverter when targeting metal. |
| 3912 | if (TC.requiresBinaryTranslation(Args)) { |
| 3913 | Action *LastAction = Actions.back(); |
| 3914 | // Metal shader converter runs on DXIL containers, which can either be |
| 3915 | // validated (in which case they are TY_DX_CONTAINER), or unvalidated |
| 3916 | // (TY_OBJECT). |
| 3917 | if (LastAction->getType() == types::TY_DX_CONTAINER || |
| 3918 | LastAction->getType() == types::TY_Object) |
| 3919 | Actions.push_back(Elt: C.MakeAction<BinaryTranslatorJobAction>( |
| 3920 | Arg&: LastAction, Arg: types::TY_DX_CONTAINER)); |
| 3921 | } |
| 3922 | } |
| 3923 | |
| 3924 | // Claim ignored clang-cl options. |
| 3925 | Args.ClaimAllArgs(Id0: options::OPT_cl_ignored_Group); |
| 3926 | } |
| 3927 | |
| 3928 | /// Returns the canonical name for the offloading architecture when using a HIP |
| 3929 | /// or CUDA architecture. |
| 3930 | static StringRef getCanonicalArchString(Compilation &C, |
| 3931 | const llvm::opt::DerivedArgList &Args, |
| 3932 | StringRef ArchStr, |
| 3933 | const llvm::Triple &Triple) { |
| 3934 | // Lookup the CUDA / HIP architecture string. Only report an error if we were |
| 3935 | // expecting the triple to be only NVPTX / AMDGPU. |
| 3936 | OffloadArch Arch = |
| 3937 | StringToOffloadArch(S: getProcessorFromTargetID(T: Triple, OffloadArch: ArchStr)); |
| 3938 | if (Triple.isNVPTX() && (Arch.isUnknown() || !Arch.isNVPTX())) { |
| 3939 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 3940 | << "CUDA" << ArchStr; |
| 3941 | return StringRef(); |
| 3942 | } else if (Triple.isAMDGPU()) { |
| 3943 | if (Arch.isUnknown() || (!Arch.isAMDGPU() && !Arch.isAMDGCNSPIRV())) { |
| 3944 | C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch) |
| 3945 | << "HIP" << ArchStr; |
| 3946 | return StringRef(); |
| 3947 | } |
| 3948 | |
| 3949 | if (Triple.getSubArch() != llvm::Triple::NoSubArch) { |
| 3950 | llvm::Triple::SubArchType ArchSubArch = getOffloadArchSubArch(ID: Arch); |
| 3951 | if (ArchSubArch != Triple.getSubArch() && |
| 3952 | llvm::AMDGPU::getMajorSubArch(SubArch: ArchSubArch) != Triple.getSubArch()) { |
| 3953 | C.getDriver().Diag(DiagID: clang::diag::err_target_unsupported_arch) |
| 3954 | << ArchStr << Triple.getArchName(); |
| 3955 | return StringRef(); |
| 3956 | } |
| 3957 | } |
| 3958 | } |
| 3959 | |
| 3960 | if (Arch.isNVPTX()) |
| 3961 | return Args.MakeArgStringRef(Str: OffloadArchToString(A: Arch)); |
| 3962 | |
| 3963 | if (Arch.isAMDGPU() || Arch.isAMDGCNSPIRV()) { |
| 3964 | llvm::StringMap<bool> Features; |
| 3965 | std::optional<StringRef> Arch = parseTargetID(T: Triple, OffloadArch: ArchStr, FeatureMap: &Features); |
| 3966 | if (!Arch) { |
| 3967 | C.getDriver().Diag(DiagID: clang::diag::err_drv_bad_target_id) << ArchStr; |
| 3968 | return StringRef(); |
| 3969 | } |
| 3970 | return Args.MakeArgStringRef(Str: getCanonicalTargetID(Processor: *Arch, Features)); |
| 3971 | } |
| 3972 | |
| 3973 | // If the input isn't CUDA or HIP just return the architecture. |
| 3974 | return ArchStr; |
| 3975 | } |
| 3976 | |
| 3977 | /// Checks if the set offloading architectures does not conflict. Returns the |
| 3978 | /// incompatible pair if a conflict occurs. |
| 3979 | static std::optional<std::pair<llvm::StringRef, llvm::StringRef>> |
| 3980 | getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs, |
| 3981 | llvm::Triple Triple) { |
| 3982 | if (!Triple.isAMDGPU()) |
| 3983 | return std::nullopt; |
| 3984 | |
| 3985 | std::set<StringRef> ArchSet; |
| 3986 | llvm::copy(Range: Archs, Out: std::inserter(x&: ArchSet, i: ArchSet.begin())); |
| 3987 | return getConflictTargetIDCombination(TargetIDs: ArchSet); |
| 3988 | } |
| 3989 | |
| 3990 | llvm::SmallVector<BoundArch> |
| 3991 | Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, |
| 3992 | Action::OffloadKind Kind, const ToolChain &TC) const { |
| 3993 | // --offload and --offload-arch options are mutually exclusive. |
| 3994 | if (Args.hasArgNoClaim(Ids: options::OPT_offload_EQ) && |
| 3995 | Args.hasArgNoClaim(Ids: options::OPT_offload_arch_EQ, |
| 3996 | Ids: options::OPT_no_offload_arch_EQ)) { |
| 3997 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_with_opt) |
| 3998 | << "--offload" |
| 3999 | << (Args.hasArgNoClaim(Ids: options::OPT_offload_arch_EQ) |
| 4000 | ? "--offload-arch" |
| 4001 | : "--no-offload-arch" ); |
| 4002 | } |
| 4003 | |
| 4004 | llvm::DenseSet<StringRef> Archs; |
| 4005 | for (auto *Arg : C.getArgsForToolChain(TC: &TC, /*BA=*/{}, DeviceOffloadKind: Kind)) { |
| 4006 | // Add or remove the seen architectures in order of appearance. If an |
| 4007 | // invalid architecture is given we simply exit. |
| 4008 | if (Arg->getOption().matches(ID: options::OPT_offload_arch_EQ)) { |
| 4009 | for (StringRef Arch : Arg->getValues()) { |
| 4010 | if (Arch == "native" || Arch.empty()) { |
| 4011 | auto GPUsOrErr = TC.getSystemGPUArchs(Args); |
| 4012 | if (!GPUsOrErr) { |
| 4013 | TC.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch) |
| 4014 | << TC.getTriple().getArchName() |
| 4015 | << llvm::toString(E: GPUsOrErr.takeError()) << "--offload-arch" ; |
| 4016 | continue; |
| 4017 | } |
| 4018 | |
| 4019 | for (auto ArchStr : *GPUsOrErr) { |
| 4020 | StringRef CanonicalStr = getCanonicalArchString( |
| 4021 | C, Args, ArchStr: Args.MakeArgString(Str: ArchStr), Triple: TC.getTriple()); |
| 4022 | if (!CanonicalStr.empty()) |
| 4023 | Archs.insert(V: CanonicalStr); |
| 4024 | else |
| 4025 | return {}; |
| 4026 | } |
| 4027 | } else { |
| 4028 | StringRef CanonicalStr = |
| 4029 | getCanonicalArchString(C, Args, ArchStr: Arch, Triple: TC.getTriple()); |
| 4030 | if (!CanonicalStr.empty()) |
| 4031 | Archs.insert(V: CanonicalStr); |
| 4032 | else |
| 4033 | return {}; |
| 4034 | } |
| 4035 | } |
| 4036 | } else if (Arg->getOption().matches(ID: options::OPT_no_offload_arch_EQ)) { |
| 4037 | for (StringRef Arch : Arg->getValues()) { |
| 4038 | if (Arch == "all" ) { |
| 4039 | Archs.clear(); |
| 4040 | } else { |
| 4041 | StringRef ArchStr = |
| 4042 | getCanonicalArchString(C, Args, ArchStr: Arch, Triple: TC.getTriple()); |
| 4043 | Archs.erase(V: ArchStr); |
| 4044 | } |
| 4045 | } |
| 4046 | } |
| 4047 | } |
| 4048 | |
| 4049 | if (auto ConflictingArchs = |
| 4050 | getConflictOffloadArchCombination(Archs, Triple: TC.getTriple())) |
| 4051 | C.getDriver().Diag(DiagID: clang::diag::err_drv_bad_offload_arch_combo) |
| 4052 | << ConflictingArchs->first << ConflictingArchs->second; |
| 4053 | |
| 4054 | // Fill in the default architectures if not provided explicitly. |
| 4055 | bool HasSubArch = TC.getTriple().isAMDGCN() && |
| 4056 | TC.getTriple().getSubArch() != llvm::Triple::NoSubArch; |
| 4057 | if (Archs.empty() && !HasSubArch) { |
| 4058 | if (Kind == Action::OFK_Cuda) { |
| 4059 | Archs.insert(V: OffloadArchToString(A: TC.getTriple().isSPIRV() |
| 4060 | ? OffloadArch::getUnused() |
| 4061 | : OffloadArch::CudaDefault())); |
| 4062 | } else if (Kind == Action::OFK_HIP) { |
| 4063 | Archs.insert(V: OffloadArchToString(A: TC.getTriple().isSPIRV() |
| 4064 | ? OffloadArch::getGeneric() |
| 4065 | : OffloadArch::HIPDefault())); |
| 4066 | } else if (Kind == Action::OFK_SYCL) { |
| 4067 | Archs.insert(V: StringRef()); |
| 4068 | } else if (Kind == Action::OFK_OpenMP) { |
| 4069 | // Accept legacy `-march` device arguments for OpenMP. |
| 4070 | if (auto *Arg = C.getArgsForToolChain(TC: &TC, /*BA=*/{}, DeviceOffloadKind: Kind) |
| 4071 | .getLastArg(Ids: options::OPT_march_EQ)) { |
| 4072 | Archs.insert(V: Arg->getValue()); |
| 4073 | } else { |
| 4074 | auto ArchsOrErr = TC.getSystemGPUArchs(Args); |
| 4075 | if (!ArchsOrErr) { |
| 4076 | TC.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch) |
| 4077 | << TC.getArchName() << llvm::toString(E: ArchsOrErr.takeError()) |
| 4078 | << "--offload-arch" ; |
| 4079 | } else if (!ArchsOrErr->empty()) { |
| 4080 | for (auto Arch : *ArchsOrErr) |
| 4081 | Archs.insert(V: Args.MakeArgStringRef(Str: Arch)); |
| 4082 | } else { |
| 4083 | Archs.insert(V: StringRef()); |
| 4084 | } |
| 4085 | } |
| 4086 | } |
| 4087 | } else if (Archs.empty() && HasSubArch) { |
| 4088 | // Use default CPU if we have a subarch in the triple. |
| 4089 | // |
| 4090 | // TODO: We ought to be able to get away with the empty string here, but |
| 4091 | // many tests require removal of redundant -target-cpu arguments |
| 4092 | OffloadArch TripleOffloadArch = |
| 4093 | getSubArchOffloadArch(SubArch: TC.getTriple().getSubArch()); |
| 4094 | llvm::StringRef ArchStr = TripleOffloadArch.isUnknown() |
| 4095 | ? "" |
| 4096 | : OffloadArchToString(A: TripleOffloadArch); |
| 4097 | StringRef CanonicalStr = |
| 4098 | getCanonicalArchString(C, Args, ArchStr, Triple: TC.getTriple()); |
| 4099 | if (!CanonicalStr.empty()) |
| 4100 | Archs.insert(V: CanonicalStr); |
| 4101 | } |
| 4102 | |
| 4103 | Args.ClaimAllArgs(Id0: options::OPT_offload_arch_EQ); |
| 4104 | Args.ClaimAllArgs(Id0: options::OPT_no_offload_arch_EQ); |
| 4105 | |
| 4106 | SmallVector<StringRef> Sorted(Archs.begin(), Archs.end()); |
| 4107 | llvm::sort(C&: Sorted); |
| 4108 | |
| 4109 | // Convert to BoundArch, parsing each architecture string once |
| 4110 | SmallVector<BoundArch> Result; |
| 4111 | Result.reserve(N: Sorted.size()); |
| 4112 | for (StringRef Arch : Sorted) |
| 4113 | Result.push_back(Elt: BoundArch(Arch)); |
| 4114 | return Result; |
| 4115 | } |
| 4116 | |
| 4117 | Action * |
| 4118 | Driver::BuildOffloadingActions(Compilation &C, llvm::opt::DerivedArgList &Args, |
| 4119 | const InputTy &Input, StringRef CUID, |
| 4120 | Action *HostAction, |
| 4121 | ActionList *HIPAsmBundleDeviceOut) const { |
| 4122 | // Don't build offloading actions if explicitly disabled or we do not have a |
| 4123 | // valid source input. |
| 4124 | if (offloadHostOnly() || !types::isSrcFile(Id: Input.first)) |
| 4125 | return HostAction; |
| 4126 | |
| 4127 | bool HIPNoRDC = |
| 4128 | C.isOffloadingHostKind(Kind: Action::OFK_HIP) && |
| 4129 | !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false); |
| 4130 | |
| 4131 | // SYCL defaults to relocatable device code. |
| 4132 | bool SYCLNoRDC = |
| 4133 | C.isOffloadingHostKind(Kind: Action::OFK_SYCL) && |
| 4134 | !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, |
| 4135 | /*Default=*/true); |
| 4136 | |
| 4137 | bool HIPRelocatableObj = |
| 4138 | C.isOffloadingHostKind(Kind: Action::OFK_HIP) && |
| 4139 | Args.hasFlag(Pos: options::OPT_fhip_emit_relocatable, |
| 4140 | Neg: options::OPT_fno_hip_emit_relocatable, Default: false); |
| 4141 | |
| 4142 | if (!HIPNoRDC && HIPRelocatableObj) |
| 4143 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_with_opt) |
| 4144 | << "-fhip-emit-relocatable" |
| 4145 | << "-fgpu-rdc" ; |
| 4146 | |
| 4147 | if (!offloadDeviceOnly() && HIPRelocatableObj) |
| 4148 | C.getDriver().Diag(DiagID: diag::err_opt_not_valid_without_opt) |
| 4149 | << "-fhip-emit-relocatable" |
| 4150 | << "--offload-device-only" ; |
| 4151 | |
| 4152 | // Don't build offloading actions if we do not have a compile action. If |
| 4153 | // preprocessing only ignore embedding. |
| 4154 | if (!(isa<CompileJobAction>(Val: HostAction) || |
| 4155 | getFinalPhase(DAL: Args, Inputs: {Input}) == phases::Preprocess)) |
| 4156 | return HostAction; |
| 4157 | |
| 4158 | bool UsesLLVMOffloading = Args.hasArg( |
| 4159 | Ids: options::OPT_foffload_via_llvm, Ids: options::OPT_fno_offload_via_llvm, Ids: false); |
| 4160 | |
| 4161 | ActionList OffloadActions; |
| 4162 | OffloadAction::DeviceDependences DDeps; |
| 4163 | |
| 4164 | const Action::OffloadKind OffloadKinds[] = { |
| 4165 | Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP, Action::OFK_SYCL}; |
| 4166 | |
| 4167 | for (Action::OffloadKind Kind : OffloadKinds) { |
| 4168 | SmallVector<const ToolChain *, 2> ToolChains; |
| 4169 | ActionList DeviceActions; |
| 4170 | |
| 4171 | auto TCRange = C.getOffloadToolChains(Kind); |
| 4172 | for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI) |
| 4173 | ToolChains.push_back(Elt: TI->second); |
| 4174 | |
| 4175 | if (ToolChains.empty()) |
| 4176 | continue; |
| 4177 | |
| 4178 | types::ID InputType = Input.first; |
| 4179 | const Arg *InputArg = Input.second; |
| 4180 | |
| 4181 | // The toolchain can be active for unsupported file types. |
| 4182 | if ((Kind == Action::OFK_Cuda && !types::isCuda(Id: InputType)) || |
| 4183 | (Kind == Action::OFK_HIP && !types::isHIP(Id: InputType))) |
| 4184 | continue; |
| 4185 | |
| 4186 | // Get the product of all bound architectures and toolchains. |
| 4187 | SmallVector<std::pair<const ToolChain *, BoundArch>> TCAndArchs; |
| 4188 | for (const ToolChain *TC : ToolChains) { |
| 4189 | for (BoundArch Arch : getOffloadArchs(C, Args: C.getArgs(), Kind, TC: *TC)) { |
| 4190 | TCAndArchs.push_back(Elt: std::make_pair(x&: TC, y&: Arch)); |
| 4191 | DeviceActions.push_back( |
| 4192 | Elt: C.MakeAction<InputAction>(Arg: *InputArg, Arg&: InputType, Arg&: CUID)); |
| 4193 | } |
| 4194 | } |
| 4195 | |
| 4196 | if (DeviceActions.empty()) |
| 4197 | return HostAction; |
| 4198 | |
| 4199 | // FIXME: Do not collapse the host side for Darwin targets with SYCL offload |
| 4200 | // compilations. The toolchain is not properly initialized for the target. |
| 4201 | if (isa<CompileJobAction>(Val: HostAction) && Kind == Action::OFK_SYCL && |
| 4202 | HostAction->getType() != types::TY_Nothing && |
| 4203 | C.getSingleOffloadToolChain<Action::OFK_Host>() |
| 4204 | ->getTriple() |
| 4205 | .isOSDarwin()) |
| 4206 | HostAction->setCannotBeCollapsedWithNextDependentAction(); |
| 4207 | |
| 4208 | auto PL = types::getCompilationPhases(Driver: *this, DAL&: Args, Inputs: {Input}, Id: InputType); |
| 4209 | |
| 4210 | for (phases::ID Phase : PL) { |
| 4211 | if (Phase == phases::Link) { |
| 4212 | assert(Phase == PL.back() && "linking must be final compilation step." ); |
| 4213 | break; |
| 4214 | } |
| 4215 | |
| 4216 | // Assemble actions are not used for the SYCL device side. Both compile |
| 4217 | // and backend actions are used to generate IR and textual IR if needed. |
| 4218 | if (Kind == Action::OFK_SYCL && Phase == phases::Assemble) |
| 4219 | continue; |
| 4220 | |
| 4221 | auto *TCAndArch = TCAndArchs.begin(); |
| 4222 | for (Action *&A : DeviceActions) { |
| 4223 | if (A->getType() == types::TY_Nothing) |
| 4224 | continue; |
| 4225 | |
| 4226 | // Propagate the ToolChain so we can use it in ConstructPhaseAction. |
| 4227 | A->propagateDeviceOffloadInfo(OKind: Kind, OArch: TCAndArch->second, |
| 4228 | OToolChain: TCAndArch->first); |
| 4229 | A = ConstructPhaseAction(C, Args, Phase, Input: A, TargetDeviceOffloadKind: Kind, |
| 4230 | TargetLTOMode: TCAndArch->first->getLTOMode(Args, Kind)); |
| 4231 | |
| 4232 | if (isa<CompileJobAction>(Val: A) && isa<CompileJobAction>(Val: HostAction) && |
| 4233 | Kind == Action::OFK_OpenMP && |
| 4234 | HostAction->getType() != types::TY_Nothing) { |
| 4235 | // OpenMP offloading has a dependency on the host compile action to |
| 4236 | // identify which declarations need to be emitted. This shouldn't be |
| 4237 | // collapsed with any other actions so we can use it in the device. |
| 4238 | HostAction->setCannotBeCollapsedWithNextDependentAction(); |
| 4239 | OffloadAction::HostDependence HDep( |
| 4240 | *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), |
| 4241 | TCAndArch->second, Kind); |
| 4242 | OffloadAction::DeviceDependences DDep; |
| 4243 | DDep.add(A&: *A, TC: *TCAndArch->first, BA: TCAndArch->second, OKind: Kind); |
| 4244 | A = C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: DDep); |
| 4245 | } |
| 4246 | |
| 4247 | ++TCAndArch; |
| 4248 | } |
| 4249 | } |
| 4250 | |
| 4251 | // Compiling HIP in device-only non-RDC mode requires linking each action |
| 4252 | // individually. |
| 4253 | for (Action *&A : DeviceActions) { |
| 4254 | auto *OffloadTriple = A->getOffloadingToolChain() |
| 4255 | ? &A->getOffloadingToolChain()->getTriple() |
| 4256 | : nullptr; |
| 4257 | bool IsHIPSPV = |
| 4258 | OffloadTriple && OffloadTriple->isSPIRV() && |
| 4259 | (OffloadTriple->getOS() == llvm::Triple::OSType::AMDHSA || |
| 4260 | OffloadTriple->getOS() == llvm::Triple::OSType::ChipStar); |
| 4261 | |
| 4262 | if ((A->getType() != types::TY_Object && !IsHIPSPV && |
| 4263 | A->getType() != types::TY_LTO_BC) || |
| 4264 | HIPRelocatableObj || !HIPNoRDC || !offloadDeviceOnly()) |
| 4265 | continue; |
| 4266 | ActionList LinkerInput = {A}; |
| 4267 | A = C.MakeAction<LinkJobAction>(Arg&: LinkerInput, Arg: types::TY_Image); |
| 4268 | } |
| 4269 | |
| 4270 | auto *TCAndArch = TCAndArchs.begin(); |
| 4271 | for (Action *A : DeviceActions) { |
| 4272 | DDeps.add(A&: *A, TC: *TCAndArch->first, BA: TCAndArch->second, OKind: Kind); |
| 4273 | OffloadAction::DeviceDependences DDep; |
| 4274 | DDep.add(A&: *A, TC: *TCAndArch->first, BA: TCAndArch->second, OKind: Kind); |
| 4275 | |
| 4276 | // The CUDA fatbinary path can include PTX alongside the cubin. |
| 4277 | // The LLVM offload wrapper path feeds these images through a device |
| 4278 | // linker first, and clang-nvlink-wrapper does not accept PTX as input. |
| 4279 | for (Action *Input : A->getInputs()) |
| 4280 | if (!UsesLLVMOffloading && Kind == Action::OFK_Cuda && |
| 4281 | A->getType() == types::TY_Object && |
| 4282 | !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, |
| 4283 | Default: false)) |
| 4284 | DDep.add(A&: *Input, TC: *TCAndArch->first, BA: TCAndArch->second, OKind: Kind); |
| 4285 | OffloadActions.push_back(Elt: C.MakeAction<OffloadAction>(Arg&: DDep, Arg: A->getType())); |
| 4286 | |
| 4287 | ++TCAndArch; |
| 4288 | } |
| 4289 | } |
| 4290 | |
| 4291 | // HIP code in device-only non-RDC mode will bundle the output if it invoked |
| 4292 | // the linker or if the user explicitly requested it. |
| 4293 | bool ShouldBundleHIP = |
| 4294 | Args.hasFlag(Pos: options::OPT_gpu_bundle_output, |
| 4295 | Neg: options::OPT_no_gpu_bundle_output, Default: false) || |
| 4296 | (!Args.getLastArg(Ids: options::OPT_no_gpu_bundle_output) && HIPNoRDC && |
| 4297 | offloadDeviceOnly() && llvm::none_of(Range&: OffloadActions, P: [](Action *A) { |
| 4298 | return A->getType() != types::TY_Image; |
| 4299 | })); |
| 4300 | |
| 4301 | // All kinds exit now in device-only mode except for non-RDC mode HIP. If no |
| 4302 | // device dependences were produced (e.g. an invalid offload architecture was |
| 4303 | // diagnosed) fall back to the host action instead of an empty offload action. |
| 4304 | if (offloadDeviceOnly() && !ShouldBundleHIP) |
| 4305 | return DDeps.getActions().empty() |
| 4306 | ? HostAction |
| 4307 | : C.MakeAction<OffloadAction>(Arg&: DDeps, Arg: types::TY_Nothing); |
| 4308 | |
| 4309 | if (OffloadActions.empty()) |
| 4310 | return HostAction; |
| 4311 | |
| 4312 | OffloadAction::DeviceDependences DDep; |
| 4313 | if (!UsesLLVMOffloading && C.isOffloadingHostKind(Kind: Action::OFK_Cuda) && |
| 4314 | (!Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false) || |
| 4315 | Args.hasArg(Ids: options::OPT_cuda_emit_nvcc_abi))) { |
| 4316 | // If we are not in RDC-mode or are targeting the NVCC ABI we just emit the |
| 4317 | // final CUDA fatbinary for each translation unit without any linking. |
| 4318 | Action *FatbinAction = |
| 4319 | C.MakeAction<LinkJobAction>(Arg&: OffloadActions, Arg: types::TY_CUDA_FATBIN); |
| 4320 | DDep.add(A&: *FatbinAction, TC: *C.getSingleOffloadToolChain<Action::OFK_Cuda>(), |
| 4321 | /*BA=*/{}, OKind: Action::OFK_Cuda); |
| 4322 | } else if (!UsesLLVMOffloading && HIPNoRDC && offloadDeviceOnly()) { |
| 4323 | // If we are in device-only non-RDC-mode we just emit the final HIP |
| 4324 | // fatbinary for each translation unit, linking each input individually. |
| 4325 | Action *FatbinAction = |
| 4326 | C.MakeAction<LinkJobAction>(Arg&: OffloadActions, Arg: types::TY_HIP_FATBIN); |
| 4327 | DDep.add(A&: *FatbinAction, |
| 4328 | TC: *C.getOffloadToolChains<Action::OFK_HIP>().first->second, |
| 4329 | /*BA=*/{}, OKind: Action::OFK_HIP); |
| 4330 | } else if ((!UsesLLVMOffloading && HIPNoRDC) || SYCLNoRDC) { |
| 4331 | // Host + device assembly: defer to clang-offload-bundler (see |
| 4332 | // BuildActions). |
| 4333 | if (HIPNoRDC && HIPAsmBundleDeviceOut && |
| 4334 | shouldBundleHIPAsm(C, Args, D: C.getDriver())) { |
| 4335 | for (Action *OA : OffloadActions) |
| 4336 | HIPAsmBundleDeviceOut->push_back(Elt: OA); |
| 4337 | return HostAction; |
| 4338 | } |
| 4339 | // Package all the offloading actions into a single output that can be |
| 4340 | // embedded in the host and linked. |
| 4341 | Action *PackagerAction = |
| 4342 | C.MakeAction<OffloadPackagerJobAction>(Arg&: OffloadActions, Arg: types::TY_Image); |
| 4343 | |
| 4344 | // For non-RDC compilation, wrap the device binary with linker wrapper |
| 4345 | // before bundling with host code. Do not bind a specific arch here, as the |
| 4346 | // packaged binary may contain entries for multiple archs. |
| 4347 | Action::OffloadKind Kind = SYCLNoRDC ? Action::OFK_SYCL : Action::OFK_HIP; |
| 4348 | types::ID FatbinType = |
| 4349 | SYCLNoRDC ? types::TY_SYCL_FATBIN : types::TY_HIP_FATBIN; |
| 4350 | ActionList AL{PackagerAction}; |
| 4351 | PackagerAction = C.MakeAction<LinkerWrapperJobAction>(Arg&: AL, Arg&: FatbinType); |
| 4352 | DDep.add(A&: *PackagerAction, TC: *C.getOffloadToolChains(Kind).first->second, |
| 4353 | /*BA=*/{}, OKind: Kind); |
| 4354 | } else { |
| 4355 | // Package all the offloading actions into a single output that can be |
| 4356 | // embedded in the host and linked. |
| 4357 | Action *PackagerAction = |
| 4358 | C.MakeAction<OffloadPackagerJobAction>(Arg&: OffloadActions, Arg: types::TY_Image); |
| 4359 | DDep.add(A&: *PackagerAction, TC: *C.getSingleOffloadToolChain<Action::OFK_Host>(), |
| 4360 | /*BA=*/{}, OffloadKindMask: C.getActiveOffloadKinds()); |
| 4361 | } |
| 4362 | |
| 4363 | // HIP wants '--offload-device-only' to create a fatbinary by default. |
| 4364 | if (offloadDeviceOnly()) |
| 4365 | return C.MakeAction<OffloadAction>(Arg&: DDep, Arg: types::TY_Nothing); |
| 4366 | |
| 4367 | // If we are unable to embed a single device output into the host, we need to |
| 4368 | // add each device output as a host dependency to ensure they are still built. |
| 4369 | bool SingleDeviceOutput = !llvm::any_of(Range&: OffloadActions, P: [](Action *A) { |
| 4370 | return A->getType() == types::TY_Nothing; |
| 4371 | }) && isa<CompileJobAction>(Val: HostAction); |
| 4372 | OffloadAction::HostDependence HDep( |
| 4373 | *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), |
| 4374 | /*BA=*/{}, SingleDeviceOutput ? DDep : DDeps); |
| 4375 | return C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: SingleDeviceOutput ? DDep : DDeps); |
| 4376 | } |
| 4377 | |
| 4378 | Action *Driver::ConstructPhaseAction( |
| 4379 | Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input, |
| 4380 | Action::OffloadKind TargetDeviceOffloadKind, LTOKind TargetLTOMode) const { |
| 4381 | llvm::PrettyStackTraceString CrashInfo("Constructing phase actions" ); |
| 4382 | |
| 4383 | // Some types skip the assembler phase (e.g., llvm-bc), but we can't |
| 4384 | // encode this in the steps because the intermediate type depends on |
| 4385 | // arguments. Just special case here. |
| 4386 | if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm) |
| 4387 | return Input; |
| 4388 | |
| 4389 | // Use of --sycl-link will only allow for the link phase to occur. This is |
| 4390 | // for all input files. |
| 4391 | if (Args.hasArg(Ids: options::OPT_sycl_link) && Phase != phases::Link) |
| 4392 | return Input; |
| 4393 | |
| 4394 | // Build the appropriate action. |
| 4395 | switch (Phase) { |
| 4396 | case phases::Link: |
| 4397 | llvm_unreachable("link action invalid here." ); |
| 4398 | case phases::IfsMerge: |
| 4399 | llvm_unreachable("ifsmerge action invalid here." ); |
| 4400 | case phases::Preprocess: { |
| 4401 | types::ID OutputTy; |
| 4402 | // -M and -MM specify the dependency file name by altering the output type, |
| 4403 | // -if -MD and -MMD are not specified. |
| 4404 | if (Args.hasArg(Ids: options::OPT_M, Ids: options::OPT_MM) && |
| 4405 | !Args.hasArg(Ids: options::OPT_MD, Ids: options::OPT_MMD)) { |
| 4406 | OutputTy = types::TY_Dependencies; |
| 4407 | } else { |
| 4408 | OutputTy = Input->getType(); |
| 4409 | // For these cases, the preprocessor is only translating forms, the Output |
| 4410 | // still needs preprocessing. |
| 4411 | if (!Args.hasFlag(Pos: options::OPT_frewrite_includes, |
| 4412 | Neg: options::OPT_fno_rewrite_includes, Default: false) && |
| 4413 | !Args.hasFlag(Pos: options::OPT_frewrite_imports, |
| 4414 | Neg: options::OPT_fno_rewrite_imports, Default: false) && |
| 4415 | !Args.hasFlag(Pos: options::OPT_fdirectives_only, |
| 4416 | Neg: options::OPT_fno_directives_only, Default: false) && |
| 4417 | !CCGenDiagnostics) |
| 4418 | OutputTy = types::getPreprocessedType(Id: OutputTy); |
| 4419 | assert(OutputTy != types::TY_INVALID && |
| 4420 | "Cannot preprocess this input type!" ); |
| 4421 | } |
| 4422 | return C.MakeAction<PreprocessJobAction>(Arg&: Input, Arg&: OutputTy); |
| 4423 | } |
| 4424 | case phases::Precompile: { |
| 4425 | // API extraction should not generate an actual precompilation action. |
| 4426 | if (Args.hasArg(Ids: options::OPT_extract_api)) |
| 4427 | return C.MakeAction<ExtractAPIJobAction>(Arg&: Input, Arg: types::TY_API_INFO); |
| 4428 | |
| 4429 | // Standard library modules always precompile in -fmodules-driver mode, |
| 4430 | // even when -fsyntax-only is specified. |
| 4431 | if (Input->getType() == types::TY_CXXStdModule || |
| 4432 | Input->getType() == types::TY_PP_CXXStdModule) |
| 4433 | return C.MakeAction<PrecompileJobAction>( |
| 4434 | Arg&: Input, Arg: getPrecompiledType(Id: Input->getType())); |
| 4435 | |
| 4436 | // With 'fmodules-reduced-bmi', we don't want to run the |
| 4437 | // precompile phase unless the user specified '--precompile' or |
| 4438 | // '--precompile-reduced-bmi'. If '--precompile' is specified, we will try |
| 4439 | // to emit the reduced BMI as a by product in |
| 4440 | // GenerateModuleInterfaceAction. If '--precompile-reduced-bmi' is |
| 4441 | // specified, we will generate the reduced BMI directly. |
| 4442 | if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi) && |
| 4443 | (Input->getType() == driver::types::TY_CXXModule || |
| 4444 | Input->getType() == driver::types::TY_PP_CXXModule) && |
| 4445 | !Args.getLastArg(Ids: options::OPT__precompile) && |
| 4446 | !Args.getLastArg(Ids: options::OPT__precompile_reduced_bmi)) |
| 4447 | return Input; |
| 4448 | |
| 4449 | types::ID OutputTy = getPrecompiledType(Id: Input->getType()); |
| 4450 | assert(OutputTy != types::TY_INVALID && |
| 4451 | "Cannot precompile this input type!" ); |
| 4452 | |
| 4453 | // If we're given a module name, precompile header file inputs as a |
| 4454 | // module, not as a precompiled header. |
| 4455 | const char *ModName = nullptr; |
| 4456 | if (OutputTy == types::TY_PCH) { |
| 4457 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_name_EQ)) |
| 4458 | ModName = A->getValue(); |
| 4459 | if (ModName) |
| 4460 | OutputTy = types::TY_ModuleFile; |
| 4461 | } |
| 4462 | |
| 4463 | if (Args.hasArg(Ids: options::OPT_fsyntax_only)) { |
| 4464 | // Syntax checks should not emit a PCH file |
| 4465 | OutputTy = types::TY_Nothing; |
| 4466 | } |
| 4467 | |
| 4468 | return C.MakeAction<PrecompileJobAction>(Arg&: Input, Arg&: OutputTy); |
| 4469 | } |
| 4470 | case phases::Compile: { |
| 4471 | if (Args.hasArg(Ids: options::OPT_fsyntax_only)) |
| 4472 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_Nothing); |
| 4473 | if (Args.hasArg(Ids: options::OPT_rewrite_objc)) |
| 4474 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_RewrittenObjC); |
| 4475 | if (Args.hasArg(Ids: options::OPT_rewrite_legacy_objc)) |
| 4476 | return C.MakeAction<CompileJobAction>(Arg&: Input, |
| 4477 | Arg: types::TY_RewrittenLegacyObjC); |
| 4478 | if (Args.hasArg(Ids: options::OPT__analyze)) |
| 4479 | return C.MakeAction<AnalyzeJobAction>(Arg&: Input, Arg: types::TY_Plist); |
| 4480 | if (Args.hasArg(Ids: options::OPT_emit_ast)) |
| 4481 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_AST); |
| 4482 | if (Args.hasArg(Ids: options::OPT_emit_cir)) |
| 4483 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_CIR); |
| 4484 | if (Args.hasArg(Ids: options::OPT_module_file_info)) |
| 4485 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_ModuleFile); |
| 4486 | if (Args.hasArg(Ids: options::OPT_verify_pch)) |
| 4487 | return C.MakeAction<VerifyPCHJobAction>(Arg&: Input, Arg: types::TY_Nothing); |
| 4488 | if (Args.hasArg(Ids: options::OPT_extract_api)) |
| 4489 | return C.MakeAction<ExtractAPIJobAction>(Arg&: Input, Arg: types::TY_API_INFO); |
| 4490 | return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_LLVM_BC); |
| 4491 | } |
| 4492 | case phases::Backend: { |
| 4493 | if (TargetLTOMode != LTOK_None) { |
| 4494 | bool IsDeviceOffload = TargetDeviceOffloadKind != Action::OFK_None; |
| 4495 | if (!IsDeviceOffload) { |
| 4496 | types::ID Output; |
| 4497 | if (Args.hasArg(Ids: options::OPT_ffat_lto_objects) && |
| 4498 | !Args.hasArg(Ids: options::OPT_emit_llvm)) |
| 4499 | Output = types::TY_PP_Asm; |
| 4500 | else if (Args.hasArg(Ids: options::OPT_S)) |
| 4501 | Output = types::TY_LTO_IR; |
| 4502 | else |
| 4503 | Output = types::TY_LTO_BC; |
| 4504 | return C.MakeAction<BackendJobAction>(Arg&: Input, Arg&: Output); |
| 4505 | } |
| 4506 | types::ID Output; |
| 4507 | if (Args.hasArg(Ids: options::OPT_emit_llvm)) { |
| 4508 | Output = |
| 4509 | Args.hasArg(Ids: options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; |
| 4510 | } else if (Args.hasArg(Ids: options::OPT_S) && offloadDeviceOnly() && |
| 4511 | !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, |
| 4512 | Default: false)) { |
| 4513 | // For non-RDC device-only compilations with -S, produce real assembly |
| 4514 | // since the user explicitly requested assembly output. |
| 4515 | Output = types::TY_PP_Asm; |
| 4516 | } else if (Args.hasArg(Ids: options::OPT_S)) { |
| 4517 | Output = types::TY_LTO_IR; |
| 4518 | } else { |
| 4519 | Output = types::TY_LTO_BC; |
| 4520 | } |
| 4521 | return C.MakeAction<BackendJobAction>(Arg&: Input, Arg&: Output); |
| 4522 | } |
| 4523 | if (Args.hasArg(Ids: options::OPT_emit_llvm) || |
| 4524 | TargetDeviceOffloadKind == Action::OFK_SYCL) { |
| 4525 | types::ID Output = |
| 4526 | Args.hasArg(Ids: options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; |
| 4527 | return C.MakeAction<BackendJobAction>(Arg&: Input, Arg&: Output); |
| 4528 | } |
| 4529 | |
| 4530 | return C.MakeAction<BackendJobAction>(Arg&: Input, Arg: types::TY_PP_Asm); |
| 4531 | } |
| 4532 | case phases::Assemble: |
| 4533 | // When -marm64x is used, construct jobs for the EC and native targets and |
| 4534 | // merge them into an archive with llvm-objcopy. |
| 4535 | const llvm::Triple Target(llvm::Triple::normalize(Str: TargetTriple)); |
| 4536 | if (Target.isOSWindows() && Args.hasArg(Ids: options::OPT_marm64x)) { |
| 4537 | Action *Act = |
| 4538 | C.MakeAction<AssembleJobAction>(Arg: std::move(Input), Arg: types::TY_Object); |
| 4539 | ActionList Inputs; |
| 4540 | Inputs.push_back(Elt: C.MakeAction<BindArchAction>(Arg&: Act, Arg: BoundArch("aarch64" ))); |
| 4541 | Inputs.push_back(Elt: C.MakeAction<BindArchAction>(Arg&: Act, Arg: BoundArch("arm64ec" ))); |
| 4542 | return C.MakeAction<ObjcopyJobAction>(Arg&: Inputs, Arg: types::TY_Object); |
| 4543 | } |
| 4544 | return C.MakeAction<AssembleJobAction>(Arg: std::move(Input), Arg: types::TY_Object); |
| 4545 | } |
| 4546 | |
| 4547 | llvm_unreachable("invalid phase in ConstructPhaseAction" ); |
| 4548 | } |
| 4549 | |
| 4550 | static bool isOffloadDeviceCC1JobCandidate(Command &Job) { |
| 4551 | const Action &Source = Job.getSource(); |
| 4552 | if (!isa<CompileJobAction>(Val: Source) && !isa<BackendJobAction>(Val: Source)) |
| 4553 | return false; |
| 4554 | |
| 4555 | if (Job.getBoundArch().empty() && !Source.getOffloadingArch().empty()) |
| 4556 | Job.setBoundArch(Source.getOffloadingArch()); |
| 4557 | |
| 4558 | if (Job.getBoundArch().empty()) |
| 4559 | return false; |
| 4560 | |
| 4561 | if (StringRef(Job.getCreator().getName()) != "clang" ) |
| 4562 | return false; |
| 4563 | |
| 4564 | Action::OffloadKind OKind = Source.getOffloadingDeviceKind(); |
| 4565 | if (OKind != Action::OFK_None && OKind != Action::OFK_Host) |
| 4566 | return true; |
| 4567 | |
| 4568 | const llvm::Triple &Triple = Job.getCreator().getToolChain().getTriple(); |
| 4569 | return Triple.isAMDGPU() || Triple.isNVPTX() || Triple.isSPIROrSPIRV(); |
| 4570 | } |
| 4571 | |
| 4572 | static std::string getOffloadDeviceCC1ParallelJobGroup(const Command &Job) { |
| 4573 | const Action &Source = Job.getSource(); |
| 4574 | // This key groups device cc1 jobs that can run in parallel. Jobs may differ |
| 4575 | // by offload arch, but must have the same offload kind, target triple, |
| 4576 | // action kind, and output type. For example, HIP compile jobs for gfx900 and |
| 4577 | // gfx906 can share a group, but HIP and OpenMP jobs cannot. |
| 4578 | return (Twine(Action::GetOffloadKindName(Kind: Source.getOffloadingDeviceKind())) + |
| 4579 | ":" + Job.getCreator().getToolChain().getTripleString() + ":" + |
| 4580 | Source.getClassName() + ":" + types::getTypeName(Id: Source.getType())) |
| 4581 | .str(); |
| 4582 | } |
| 4583 | |
| 4584 | static void claimAndDiagnoseOffloadJobs(const Driver &D, const ArgList &Args) { |
| 4585 | auto OffloadJobs = tools::parseOffloadJobs(Args); |
| 4586 | if (!OffloadJobs.A) |
| 4587 | return; |
| 4588 | |
| 4589 | if (!OffloadJobs.isValid()) |
| 4590 | D.Diag(DiagID: diag::err_drv_invalid_int_value) |
| 4591 | << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value; |
| 4592 | |
| 4593 | OffloadJobs.A->claim(); |
| 4594 | } |
| 4595 | |
| 4596 | static void markOffloadDeviceCC1JobsForParallelExecution(Compilation &C) { |
| 4597 | for (auto &Job : C.getJobs()) { |
| 4598 | if (!isOffloadDeviceCC1JobCandidate(Job)) |
| 4599 | continue; |
| 4600 | |
| 4601 | Job.setOffloadDeviceParallelJobGroup( |
| 4602 | getOffloadDeviceCC1ParallelJobGroup(Job)); |
| 4603 | } |
| 4604 | } |
| 4605 | |
| 4606 | void Driver::BuildJobs(Compilation &C) const { |
| 4607 | llvm::PrettyStackTraceString CrashInfo("Building compilation jobs" ); |
| 4608 | |
| 4609 | Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o); |
| 4610 | |
| 4611 | // It is an error to provide a -o option if we are making multiple output |
| 4612 | // files. There are exceptions: |
| 4613 | // |
| 4614 | // IfsMergeJob: when generating interface stubs enabled we want to be able to |
| 4615 | // generate the stub file at the same time that we generate the real |
| 4616 | // library/a.out. So when a .o, .so, etc are the output, with clang interface |
| 4617 | // stubs there will also be a .ifs and .ifso at the same location. |
| 4618 | // |
| 4619 | // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled |
| 4620 | // and -c is passed, we still want to be able to generate a .ifs file while |
| 4621 | // we are also generating .o files. So we allow more than one output file in |
| 4622 | // this case as well. |
| 4623 | // |
| 4624 | // OffloadClass of type TY_Nothing: device-only output will place many outputs |
| 4625 | // into a single offloading action. We should count all inputs to the action |
| 4626 | // as outputs. Also ignore device-only outputs if we're compiling with |
| 4627 | // -fsyntax-only. |
| 4628 | if (FinalOutput) { |
| 4629 | unsigned NumOutputs = 0; |
| 4630 | unsigned NumIfsOutputs = 0; |
| 4631 | for (const Action *A : C.getActions()) { |
| 4632 | // The actions below do not increase the number of outputs. |
| 4633 | if (A->getKind() == clang::driver::Action::BinaryAnalyzeJobClass || |
| 4634 | A->getKind() == clang::driver::Action::BinaryTranslatorJobClass) |
| 4635 | continue; |
| 4636 | |
| 4637 | // With -fmodules-driver, Standard library modules should not count toward |
| 4638 | // the number of outputs, since they are implicitly added to the input |
| 4639 | // list. |
| 4640 | if (isa<PrecompileJobAction>(Val: A) && !A->getInputs().empty() && |
| 4641 | (A->getInputs().front()->getType() == types::TY_CXXStdModule || |
| 4642 | A->getInputs().front()->getType() == types::TY_PP_CXXStdModule)) |
| 4643 | continue; |
| 4644 | |
| 4645 | if (A->getType() != types::TY_Nothing && |
| 4646 | !(A->getKind() == Action::IfsMergeJobClass || |
| 4647 | (A->getType() == clang::driver::types::TY_IFS_CPP && |
| 4648 | A->getKind() == clang::driver::Action::CompileJobClass && |
| 4649 | 0 == NumIfsOutputs++) || |
| 4650 | (A->getKind() == Action::BindArchClass && A->getInputs().size() && |
| 4651 | A->getInputs().front()->getKind() == Action::IfsMergeJobClass))) |
| 4652 | ++NumOutputs; |
| 4653 | else if (A->getKind() == Action::OffloadClass && |
| 4654 | A->getType() == types::TY_Nothing && |
| 4655 | !C.getArgs().hasArg(Ids: options::OPT_fsyntax_only)) |
| 4656 | NumOutputs += A->size(); |
| 4657 | } |
| 4658 | |
| 4659 | if (NumOutputs > 1) { |
| 4660 | Diag(DiagID: clang::diag::err_drv_output_argument_with_multiple_files); |
| 4661 | FinalOutput = nullptr; |
| 4662 | } |
| 4663 | } |
| 4664 | |
| 4665 | const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple(); |
| 4666 | |
| 4667 | // Collect the list of architectures. |
| 4668 | llvm::StringSet<> ArchNames; |
| 4669 | if (RawTriple.isOSBinFormatMachO()) |
| 4670 | for (const Arg *A : C.getArgs()) |
| 4671 | if (A->getOption().matches(ID: options::OPT_arch)) |
| 4672 | ArchNames.insert(key: A->getValue()); |
| 4673 | |
| 4674 | // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. |
| 4675 | std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults; |
| 4676 | for (Action *A : C.getActions()) { |
| 4677 | // If we are linking an image for multiple archs then the linker wants |
| 4678 | // -arch_multiple and -final_output <final image name>. Unfortunately, this |
| 4679 | // doesn't fit in cleanly because we have to pass this information down. |
| 4680 | // |
| 4681 | // FIXME: This is a hack; find a cleaner way to integrate this into the |
| 4682 | // process. |
| 4683 | const char *LinkingOutput = nullptr; |
| 4684 | if (isa<LipoJobAction>(Val: A)) { |
| 4685 | if (FinalOutput) |
| 4686 | LinkingOutput = FinalOutput->getValue(); |
| 4687 | else |
| 4688 | LinkingOutput = getDefaultImageName(); |
| 4689 | } |
| 4690 | |
| 4691 | BuildJobsForAction(C, A, TC: &C.getDefaultToolChain(), |
| 4692 | /*BA=*/{}, |
| 4693 | /*AtTopLevel*/ true, |
| 4694 | /*MultipleArchs*/ ArchNames.size() > 1 || |
| 4695 | C.getArgs().hasArgNoClaim(Ids: options::OPT_marm64x), |
| 4696 | /*LinkingOutput*/ LinkingOutput, CachedResults, |
| 4697 | /*TargetDeviceOffloadKind*/ Action::OFK_None); |
| 4698 | } |
| 4699 | |
| 4700 | // If we have more than one job, then disable integrated-cc1 for now. Do this |
| 4701 | // also when we need to report process execution statistics. |
| 4702 | if (C.getJobs().size() > 1 || CCPrintProcessStats) |
| 4703 | for (auto &J : C.getJobs()) |
| 4704 | J.InProcess = false; |
| 4705 | |
| 4706 | markOffloadDeviceCC1JobsForParallelExecution(C); |
| 4707 | if (C.getActiveOffloadKinds() != Action::OFK_None) |
| 4708 | claimAndDiagnoseOffloadJobs(D: *this, Args: C.getArgs()); |
| 4709 | |
| 4710 | if (CCPrintProcessStats) { |
| 4711 | C.setPostCallback([=](const Command &Cmd, int Res) { |
| 4712 | std::optional<llvm::sys::ProcessStatistics> ProcStat = |
| 4713 | Cmd.getProcessStatistics(); |
| 4714 | if (!ProcStat) |
| 4715 | return; |
| 4716 | |
| 4717 | const char *LinkingOutput = nullptr; |
| 4718 | if (FinalOutput) |
| 4719 | LinkingOutput = FinalOutput->getValue(); |
| 4720 | else if (!Cmd.getOutputFilenames().empty()) |
| 4721 | LinkingOutput = Cmd.getOutputFilenames().front().c_str(); |
| 4722 | else |
| 4723 | LinkingOutput = getDefaultImageName(); |
| 4724 | |
| 4725 | if (CCPrintStatReportFilename.empty()) { |
| 4726 | using namespace llvm; |
| 4727 | // Human readable output. |
| 4728 | outs() << sys::path::filename(path: Cmd.getExecutable()) << ": " |
| 4729 | << "output=" << LinkingOutput; |
| 4730 | outs() << ", total=" |
| 4731 | << format(Fmt: "%.3f" , Vals: ProcStat->TotalTime.count() / 1000.) << " ms" |
| 4732 | << ", user=" |
| 4733 | << format(Fmt: "%.3f" , Vals: ProcStat->UserTime.count() / 1000.) << " ms" |
| 4734 | << ", mem=" << ProcStat->PeakMemory << " Kb\n" ; |
| 4735 | } else { |
| 4736 | // CSV format. |
| 4737 | std::string Buffer; |
| 4738 | llvm::raw_string_ostream Out(Buffer); |
| 4739 | llvm::sys::printArg(OS&: Out, Arg: llvm::sys::path::filename(path: Cmd.getExecutable()), |
| 4740 | /*Quote*/ true); |
| 4741 | Out << ','; |
| 4742 | llvm::sys::printArg(OS&: Out, Arg: LinkingOutput, Quote: true); |
| 4743 | Out << ',' << ProcStat->TotalTime.count() << ',' |
| 4744 | << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory |
| 4745 | << '\n'; |
| 4746 | Out.flush(); |
| 4747 | std::error_code EC; |
| 4748 | llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC, |
| 4749 | llvm::sys::fs::OF_Append | |
| 4750 | llvm::sys::fs::OF_Text); |
| 4751 | if (EC) |
| 4752 | return; |
| 4753 | auto L = OS.lock(); |
| 4754 | if (!L) { |
| 4755 | llvm::errs() << "ERROR: Cannot lock file " |
| 4756 | << CCPrintStatReportFilename << ": " |
| 4757 | << toString(E: L.takeError()) << "\n" ; |
| 4758 | return; |
| 4759 | } |
| 4760 | OS << Buffer; |
| 4761 | OS.flush(); |
| 4762 | } |
| 4763 | }); |
| 4764 | } |
| 4765 | |
| 4766 | // If the user passed -Qunused-arguments or there were errors, don't |
| 4767 | // warn about any unused arguments. |
| 4768 | bool ReportUnusedArguments = |
| 4769 | !Diags.hasErrorOccurred() && |
| 4770 | !C.getArgs().hasArg(Ids: options::OPT_Qunused_arguments); |
| 4771 | |
| 4772 | // Claim -fdriver-only here. |
| 4773 | (void)C.getArgs().hasArg(Ids: options::OPT_fdriver_only); |
| 4774 | // Claim -### here. |
| 4775 | (void)C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH); |
| 4776 | |
| 4777 | // Claim --driver-mode, --rsp-quoting, it was handled earlier. |
| 4778 | (void)C.getArgs().hasArg(Ids: options::OPT_driver_mode); |
| 4779 | (void)C.getArgs().hasArg(Ids: options::OPT_rsp_quoting); |
| 4780 | |
| 4781 | bool HasAssembleJob = llvm::any_of(Range&: C.getJobs(), P: [](auto &J) { |
| 4782 | // Match ClangAs and other derived assemblers of Tool. ClangAs uses a |
| 4783 | // longer ShortName "clang integrated assembler" while other assemblers just |
| 4784 | // use "assembler". |
| 4785 | return strstr(J.getCreator().getShortName(), "assembler" ); |
| 4786 | }); |
| 4787 | for (Arg *A : C.getArgs()) { |
| 4788 | // FIXME: It would be nice to be able to send the argument to the |
| 4789 | // DiagnosticsEngine, so that extra values, position, and so on could be |
| 4790 | // printed. |
| 4791 | if (!A->isClaimed()) { |
| 4792 | if (A->getOption().hasFlag(Val: options::NoArgumentUnused)) |
| 4793 | continue; |
| 4794 | |
| 4795 | // Suppress the warning automatically if this is just a flag, and it is an |
| 4796 | // instance of an argument we already claimed. |
| 4797 | const Option &Opt = A->getOption(); |
| 4798 | if (Opt.getKind() == Option::FlagClass) { |
| 4799 | bool DuplicateClaimed = false; |
| 4800 | |
| 4801 | for (const Arg *AA : C.getArgs().filtered(Ids: &Opt)) { |
| 4802 | if (AA->isClaimed()) { |
| 4803 | DuplicateClaimed = true; |
| 4804 | break; |
| 4805 | } |
| 4806 | } |
| 4807 | |
| 4808 | if (DuplicateClaimed) |
| 4809 | continue; |
| 4810 | } |
| 4811 | |
| 4812 | // In clang-cl, don't mention unknown arguments here since they have |
| 4813 | // already been warned about. |
| 4814 | if (!IsCLMode() || !A->getOption().matches(ID: options::OPT_UNKNOWN)) { |
| 4815 | if (A->getOption().hasFlag(Val: options::TargetSpecific) && |
| 4816 | !A->isIgnoredTargetSpecific() && !HasAssembleJob && |
| 4817 | // When for example -### or -v is used |
| 4818 | // without a file, target specific options are not |
| 4819 | // consumed/validated. |
| 4820 | // Instead emitting an error emit a warning instead. |
| 4821 | !C.getActions().empty()) { |
| 4822 | Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 4823 | << A->getSpelling() << getTargetTriple(); |
| 4824 | } else if (ReportUnusedArguments) { |
| 4825 | Diag(DiagID: clang::diag::warn_drv_unused_argument) |
| 4826 | << A->getAsString(Args: C.getArgs()); |
| 4827 | } |
| 4828 | } |
| 4829 | } |
| 4830 | } |
| 4831 | } |
| 4832 | |
| 4833 | namespace { |
| 4834 | /// Utility class to control the collapse of dependent actions and select the |
| 4835 | /// tools accordingly. |
| 4836 | class ToolSelector final { |
| 4837 | /// The tool chain this selector refers to. |
| 4838 | const ToolChain &TC; |
| 4839 | |
| 4840 | /// The compilation this selector refers to. |
| 4841 | const Compilation &C; |
| 4842 | |
| 4843 | /// The base action this selector refers to. |
| 4844 | const JobAction *BaseAction; |
| 4845 | |
| 4846 | /// Set to true if the current toolchain refers to host actions. |
| 4847 | bool IsHostSelector; |
| 4848 | |
| 4849 | /// Set to true if save-temps and embed-bitcode functionalities are active. |
| 4850 | bool SaveTemps; |
| 4851 | bool EmbedBitcode; |
| 4852 | |
| 4853 | /// Get previous dependent action or null if that does not exist. If |
| 4854 | /// \a CanBeCollapsed is false, that action must be legal to collapse or |
| 4855 | /// null will be returned. |
| 4856 | const JobAction *getPrevDependentAction(const ActionList &Inputs, |
| 4857 | ActionList &SavedOffloadAction, |
| 4858 | bool CanBeCollapsed = true) { |
| 4859 | // An option can be collapsed only if it has a single input. |
| 4860 | if (Inputs.size() != 1) |
| 4861 | return nullptr; |
| 4862 | |
| 4863 | Action *CurAction = *Inputs.begin(); |
| 4864 | if (CanBeCollapsed && |
| 4865 | !CurAction->isCollapsingWithNextDependentActionLegal()) |
| 4866 | return nullptr; |
| 4867 | |
| 4868 | // If the input action is an offload action. Look through it and save any |
| 4869 | // offload action that can be dropped in the event of a collapse. |
| 4870 | if (auto *OA = dyn_cast<OffloadAction>(Val: CurAction)) { |
| 4871 | // If the dependent action is a device action, we will attempt to collapse |
| 4872 | // only with other device actions. Otherwise, we would do the same but |
| 4873 | // with host actions only. |
| 4874 | if (!IsHostSelector) { |
| 4875 | if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) { |
| 4876 | CurAction = |
| 4877 | OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true); |
| 4878 | if (CanBeCollapsed && |
| 4879 | !CurAction->isCollapsingWithNextDependentActionLegal()) |
| 4880 | return nullptr; |
| 4881 | SavedOffloadAction.push_back(Elt: OA); |
| 4882 | return dyn_cast<JobAction>(Val: CurAction); |
| 4883 | } |
| 4884 | } else if (OA->hasHostDependence()) { |
| 4885 | CurAction = OA->getHostDependence(); |
| 4886 | if (CanBeCollapsed && |
| 4887 | !CurAction->isCollapsingWithNextDependentActionLegal()) |
| 4888 | return nullptr; |
| 4889 | SavedOffloadAction.push_back(Elt: OA); |
| 4890 | return dyn_cast<JobAction>(Val: CurAction); |
| 4891 | } |
| 4892 | return nullptr; |
| 4893 | } |
| 4894 | |
| 4895 | return dyn_cast<JobAction>(Val: CurAction); |
| 4896 | } |
| 4897 | |
| 4898 | /// Return true if an assemble action can be collapsed. |
| 4899 | bool canCollapseAssembleAction() const { |
| 4900 | return TC.useIntegratedAs() && !SaveTemps && |
| 4901 | !C.getArgs().hasArg(Ids: options::OPT_via_file_asm) && |
| 4902 | !C.getArgs().hasArg(Ids: options::OPT__SLASH_FA) && |
| 4903 | !C.getArgs().hasArg(Ids: options::OPT__SLASH_Fa) && |
| 4904 | !C.getArgs().hasArg(Ids: options::OPT_dxc_Fc); |
| 4905 | } |
| 4906 | |
| 4907 | /// Return true if a preprocessor action can be collapsed. |
| 4908 | bool canCollapsePreprocessorAction() const { |
| 4909 | return !C.getArgs().hasArg(Ids: options::OPT_no_integrated_cpp) && |
| 4910 | !C.getArgs().hasArg(Ids: options::OPT_traditional_cpp) && !SaveTemps && |
| 4911 | !C.getArgs().hasArg(Ids: options::OPT_rewrite_objc); |
| 4912 | } |
| 4913 | |
| 4914 | /// Struct that relates an action with the offload actions that would be |
| 4915 | /// collapsed with it. |
| 4916 | struct JobActionInfo final { |
| 4917 | /// The action this info refers to. |
| 4918 | const JobAction *JA = nullptr; |
| 4919 | /// The offload actions we need to take care off if this action is |
| 4920 | /// collapsed. |
| 4921 | ActionList SavedOffloadAction; |
| 4922 | }; |
| 4923 | |
| 4924 | /// Append collapsed offload actions from the give number of elements in the |
| 4925 | /// action info array. |
| 4926 | static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction, |
| 4927 | ArrayRef<JobActionInfo> &ActionInfo, |
| 4928 | unsigned ElementNum) { |
| 4929 | assert(ElementNum <= ActionInfo.size() && "Invalid number of elements." ); |
| 4930 | for (unsigned I = 0; I < ElementNum; ++I) |
| 4931 | CollapsedOffloadAction.append(in_start: ActionInfo[I].SavedOffloadAction.begin(), |
| 4932 | in_end: ActionInfo[I].SavedOffloadAction.end()); |
| 4933 | } |
| 4934 | |
| 4935 | /// Functions that attempt to perform the combining. They detect if that is |
| 4936 | /// legal, and if so they update the inputs \a Inputs and the offload action |
| 4937 | /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with |
| 4938 | /// the combined action is returned. If the combining is not legal or if the |
| 4939 | /// tool does not exist, null is returned. |
| 4940 | /// Currently three kinds of collapsing are supported: |
| 4941 | /// - Assemble + Backend + Compile; |
| 4942 | /// - Assemble + Backend ; |
| 4943 | /// - Backend + Compile. |
| 4944 | const Tool * |
| 4945 | combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo, |
| 4946 | ActionList &Inputs, |
| 4947 | ActionList &CollapsedOffloadAction) { |
| 4948 | if (ActionInfo.size() < 3 || !canCollapseAssembleAction()) |
| 4949 | return nullptr; |
| 4950 | auto *AJ = dyn_cast<AssembleJobAction>(Val: ActionInfo[0].JA); |
| 4951 | auto *BJ = dyn_cast<BackendJobAction>(Val: ActionInfo[1].JA); |
| 4952 | auto *CJ = dyn_cast<CompileJobAction>(Val: ActionInfo[2].JA); |
| 4953 | if (!AJ || !BJ || !CJ) |
| 4954 | return nullptr; |
| 4955 | |
| 4956 | // Get compiler tool. |
| 4957 | const Tool *T = TC.SelectTool(JA: *CJ); |
| 4958 | if (!T) |
| 4959 | return nullptr; |
| 4960 | |
| 4961 | // Can't collapse if we don't have codegen support unless we are |
| 4962 | // emitting LLVM IR. |
| 4963 | bool OutputIsLLVM = types::isLLVMIR(Id: ActionInfo[0].JA->getType()); |
| 4964 | if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) |
| 4965 | return nullptr; |
| 4966 | |
| 4967 | // When using -fembed-bitcode, it is required to have the same tool (clang) |
| 4968 | // for both CompilerJA and BackendJA. Otherwise, combine two stages. |
| 4969 | if (EmbedBitcode) { |
| 4970 | const Tool *BT = TC.SelectTool(JA: *BJ); |
| 4971 | if (BT == T) |
| 4972 | return nullptr; |
| 4973 | } |
| 4974 | |
| 4975 | if (!T->hasIntegratedAssembler()) |
| 4976 | return nullptr; |
| 4977 | |
| 4978 | Inputs = CJ->getInputs(); |
| 4979 | AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, |
| 4980 | /*NumElements=*/ElementNum: 3); |
| 4981 | return T; |
| 4982 | } |
| 4983 | const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo, |
| 4984 | ActionList &Inputs, |
| 4985 | ActionList &CollapsedOffloadAction) { |
| 4986 | if (ActionInfo.size() < 2 || !canCollapseAssembleAction()) |
| 4987 | return nullptr; |
| 4988 | auto *AJ = dyn_cast<AssembleJobAction>(Val: ActionInfo[0].JA); |
| 4989 | auto *BJ = dyn_cast<BackendJobAction>(Val: ActionInfo[1].JA); |
| 4990 | if (!AJ || !BJ) |
| 4991 | return nullptr; |
| 4992 | |
| 4993 | // Get backend tool. |
| 4994 | const Tool *T = TC.SelectTool(JA: *BJ); |
| 4995 | if (!T) |
| 4996 | return nullptr; |
| 4997 | |
| 4998 | if (!T->hasIntegratedAssembler()) |
| 4999 | return nullptr; |
| 5000 | |
| 5001 | Inputs = BJ->getInputs(); |
| 5002 | AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, |
| 5003 | /*NumElements=*/ElementNum: 2); |
| 5004 | return T; |
| 5005 | } |
| 5006 | const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo, |
| 5007 | ActionList &Inputs, |
| 5008 | ActionList &CollapsedOffloadAction) { |
| 5009 | if (ActionInfo.size() < 2) |
| 5010 | return nullptr; |
| 5011 | auto *BJ = dyn_cast<BackendJobAction>(Val: ActionInfo[0].JA); |
| 5012 | auto *CJ = dyn_cast<CompileJobAction>(Val: ActionInfo[1].JA); |
| 5013 | if (!BJ || !CJ) |
| 5014 | return nullptr; |
| 5015 | |
| 5016 | auto HasBitcodeInput = [](const JobActionInfo &AI) { |
| 5017 | for (auto &Input : AI.JA->getInputs()) |
| 5018 | if (!types::isLLVMIR(Id: Input->getType())) |
| 5019 | return false; |
| 5020 | return true; |
| 5021 | }; |
| 5022 | |
| 5023 | // Check if the initial input (to the compile job or its predessor if one |
| 5024 | // exists) is LLVM bitcode. In that case, no preprocessor step is required |
| 5025 | // and we can still collapse the compile and backend jobs when we have |
| 5026 | // -save-temps. I.e. there is no need for a separate compile job just to |
| 5027 | // emit unoptimized bitcode. |
| 5028 | bool InputIsBitcode = all_of(Range&: ActionInfo, P: HasBitcodeInput); |
| 5029 | if (SaveTemps && !InputIsBitcode) |
| 5030 | return nullptr; |
| 5031 | |
| 5032 | // Get compiler tool. |
| 5033 | const Tool *T = TC.SelectTool(JA: *CJ); |
| 5034 | if (!T) |
| 5035 | return nullptr; |
| 5036 | |
| 5037 | // Can't collapse if we don't have codegen support unless we are |
| 5038 | // emitting LLVM IR. |
| 5039 | bool OutputIsLLVM = types::isLLVMIR(Id: ActionInfo[0].JA->getType()); |
| 5040 | if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) |
| 5041 | return nullptr; |
| 5042 | |
| 5043 | if (T->canEmitIR() && EmbedBitcode) |
| 5044 | return nullptr; |
| 5045 | |
| 5046 | Inputs = CJ->getInputs(); |
| 5047 | AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, |
| 5048 | /*NumElements=*/ElementNum: 2); |
| 5049 | return T; |
| 5050 | } |
| 5051 | |
| 5052 | /// Updates the inputs if the obtained tool supports combining with |
| 5053 | /// preprocessor action, and the current input is indeed a preprocessor |
| 5054 | /// action. If combining results in the collapse of offloading actions, those |
| 5055 | /// are appended to \a CollapsedOffloadAction. |
| 5056 | void combineWithPreprocessor(const Tool *T, ActionList &Inputs, |
| 5057 | ActionList &CollapsedOffloadAction) { |
| 5058 | if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP()) |
| 5059 | return; |
| 5060 | |
| 5061 | // Attempt to get a preprocessor action dependence. |
| 5062 | ActionList PreprocessJobOffloadActions; |
| 5063 | ActionList NewInputs; |
| 5064 | for (Action *A : Inputs) { |
| 5065 | auto *PJ = getPrevDependentAction(Inputs: {A}, SavedOffloadAction&: PreprocessJobOffloadActions); |
| 5066 | if (!PJ || !isa<PreprocessJobAction>(Val: PJ)) { |
| 5067 | NewInputs.push_back(Elt: A); |
| 5068 | continue; |
| 5069 | } |
| 5070 | |
| 5071 | // This is legal to combine. Append any offload action we found and add the |
| 5072 | // current input to preprocessor inputs. |
| 5073 | CollapsedOffloadAction.append(in_start: PreprocessJobOffloadActions.begin(), |
| 5074 | in_end: PreprocessJobOffloadActions.end()); |
| 5075 | NewInputs.append(in_start: PJ->input_begin(), in_end: PJ->input_end()); |
| 5076 | } |
| 5077 | Inputs = NewInputs; |
| 5078 | } |
| 5079 | |
| 5080 | public: |
| 5081 | ToolSelector(const JobAction *BaseAction, const ToolChain &TC, |
| 5082 | const Compilation &C, bool SaveTemps, bool EmbedBitcode) |
| 5083 | : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps), |
| 5084 | EmbedBitcode(EmbedBitcode) { |
| 5085 | assert(BaseAction && "Invalid base action." ); |
| 5086 | IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None; |
| 5087 | } |
| 5088 | |
| 5089 | /// Check if a chain of actions can be combined and return the tool that can |
| 5090 | /// handle the combination of actions. The pointer to the current inputs \a |
| 5091 | /// Inputs and the list of offload actions \a CollapsedOffloadActions |
| 5092 | /// connected to collapsed actions are updated accordingly. The latter enables |
| 5093 | /// the caller of the selector to process them afterwards instead of just |
| 5094 | /// dropping them. If no suitable tool is found, null will be returned. |
| 5095 | const Tool *getTool(ActionList &Inputs, |
| 5096 | ActionList &CollapsedOffloadAction) { |
| 5097 | // |
| 5098 | // Get the largest chain of actions that we could combine. |
| 5099 | // |
| 5100 | |
| 5101 | SmallVector<JobActionInfo, 5> ActionChain(1); |
| 5102 | ActionChain.back().JA = BaseAction; |
| 5103 | while (ActionChain.back().JA) { |
| 5104 | const Action *CurAction = ActionChain.back().JA; |
| 5105 | |
| 5106 | // Grow the chain by one element. |
| 5107 | ActionChain.resize(N: ActionChain.size() + 1); |
| 5108 | JobActionInfo &AI = ActionChain.back(); |
| 5109 | |
| 5110 | // Attempt to fill it with the |
| 5111 | AI.JA = |
| 5112 | getPrevDependentAction(Inputs: CurAction->getInputs(), SavedOffloadAction&: AI.SavedOffloadAction); |
| 5113 | } |
| 5114 | |
| 5115 | // Pop the last action info as it could not be filled. |
| 5116 | ActionChain.pop_back(); |
| 5117 | |
| 5118 | // |
| 5119 | // Attempt to combine actions. If all combining attempts failed, just return |
| 5120 | // the tool of the provided action. At the end we attempt to combine the |
| 5121 | // action with any preprocessor action it may depend on. |
| 5122 | // |
| 5123 | |
| 5124 | const Tool *T = combineAssembleBackendCompile(ActionInfo: ActionChain, Inputs, |
| 5125 | CollapsedOffloadAction); |
| 5126 | if (!T) |
| 5127 | T = combineAssembleBackend(ActionInfo: ActionChain, Inputs, CollapsedOffloadAction); |
| 5128 | if (!T) |
| 5129 | T = combineBackendCompile(ActionInfo: ActionChain, Inputs, CollapsedOffloadAction); |
| 5130 | if (!T) { |
| 5131 | Inputs = BaseAction->getInputs(); |
| 5132 | T = TC.SelectTool(JA: *BaseAction); |
| 5133 | } |
| 5134 | |
| 5135 | combineWithPreprocessor(T, Inputs, CollapsedOffloadAction); |
| 5136 | return T; |
| 5137 | } |
| 5138 | }; |
| 5139 | } |
| 5140 | |
| 5141 | /// Return a string that uniquely identifies the result of a job. The bound arch |
| 5142 | /// is not necessarily represented in the toolchain's triple -- for example, |
| 5143 | /// armv7 and armv7s both map to the same triple -- so we need both in our map. |
| 5144 | /// Also, we need to add the offloading device kind, as the same tool chain can |
| 5145 | /// be used for host and device for some programming models, e.g. OpenMP. |
| 5146 | static std::string GetTriplePlusArchString(const ToolChain *TC, BoundArch BA, |
| 5147 | Action::OffloadKind OffloadKind) { |
| 5148 | std::string TriplePlusArch = TC->getTriple().normalize(); |
| 5149 | if (!BA.empty()) { |
| 5150 | TriplePlusArch += "-" ; |
| 5151 | TriplePlusArch += BA.ArchName; |
| 5152 | } |
| 5153 | TriplePlusArch += "-" ; |
| 5154 | TriplePlusArch += Action::GetOffloadKindName(Kind: OffloadKind); |
| 5155 | return TriplePlusArch; |
| 5156 | } |
| 5157 | |
| 5158 | InputInfoList Driver::BuildJobsForAction( |
| 5159 | Compilation &C, const Action *A, const ToolChain *TC, BoundArch BA, |
| 5160 | bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, |
| 5161 | std::map<std::pair<const Action *, std::string>, InputInfoList> |
| 5162 | &CachedResults, |
| 5163 | Action::OffloadKind TargetDeviceOffloadKind) const { |
| 5164 | std::pair<const Action *, std::string> ActionTC = { |
| 5165 | A, GetTriplePlusArchString(TC, BA, OffloadKind: TargetDeviceOffloadKind)}; |
| 5166 | auto CachedResult = CachedResults.find(x: ActionTC); |
| 5167 | if (CachedResult != CachedResults.end()) { |
| 5168 | return CachedResult->second; |
| 5169 | } |
| 5170 | InputInfoList Result = BuildJobsForActionNoCache( |
| 5171 | C, A, TC, BA, AtTopLevel, MultipleArchs, LinkingOutput, CachedResults, |
| 5172 | TargetDeviceOffloadKind); |
| 5173 | CachedResults[ActionTC] = Result; |
| 5174 | return Result; |
| 5175 | } |
| 5176 | |
| 5177 | static void handleTimeTrace(Compilation &C, const ArgList &Args, |
| 5178 | const JobAction *JA, const char *BaseInput, |
| 5179 | const InputInfo &Result) { |
| 5180 | Arg *A = |
| 5181 | Args.getLastArg(Ids: options::OPT_ftime_trace, Ids: options::OPT_ftime_trace_EQ); |
| 5182 | if (!A) |
| 5183 | return; |
| 5184 | |
| 5185 | SmallString<64> OffloadingPrefix; |
| 5186 | if (JA->getOffloadingDeviceKind() != Action::OFK_None) { |
| 5187 | const ToolChain *TC = JA->getOffloadingToolChain(); |
| 5188 | OffloadingPrefix = Action::GetOffloadingFileNamePrefix( |
| 5189 | Kind: JA->getOffloadingDeviceKind(), NormalizedTriple: TC ? TC->getEffectiveTriple().str() : "" , |
| 5190 | /*CreatePrefixForHost=*/false); |
| 5191 | BoundArch Arch = JA->getOffloadingArch(); |
| 5192 | if (!Arch.empty()) { |
| 5193 | OffloadingPrefix += "-" ; |
| 5194 | OffloadingPrefix += Arch.ArchName; |
| 5195 | } |
| 5196 | } else if (JA->getOffloadingHostActiveKinds() != Action::OFK_None && |
| 5197 | C.getDriver().isSaveTempsEnabled()) { |
| 5198 | OffloadingPrefix = Action::GetOffloadingFileNamePrefix( |
| 5199 | Kind: Action::OFK_None, NormalizedTriple: C.getDefaultToolChain().getTripleString(), |
| 5200 | /*CreatePrefixForHost=*/true); |
| 5201 | } |
| 5202 | |
| 5203 | SmallString<128> Path; |
| 5204 | if (A->getOption().matches(ID: options::OPT_ftime_trace_EQ)) { |
| 5205 | Path = A->getValue(); |
| 5206 | if (llvm::sys::fs::is_directory(Path)) { |
| 5207 | SmallString<128> Tmp(OffloadingPrefix.empty() |
| 5208 | ? llvm::sys::path::stem(path: Result.getFilename()) |
| 5209 | : llvm::sys::path::stem(path: BaseInput)); |
| 5210 | Tmp += OffloadingPrefix; |
| 5211 | Tmp += ".json" ; |
| 5212 | llvm::sys::path::append(path&: Path, a: Tmp); |
| 5213 | } |
| 5214 | } else { |
| 5215 | if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) { |
| 5216 | // The trace file is ${dumpdir}${basename}${offloadprefix}.json. Note |
| 5217 | // that dumpdir may not end with a path separator. |
| 5218 | Path = DumpDir->getValue(); |
| 5219 | Path += llvm::sys::path::stem(path: BaseInput); |
| 5220 | Path += OffloadingPrefix; |
| 5221 | Path += ".json" ; |
| 5222 | } else if (!OffloadingPrefix.empty()) { |
| 5223 | // For offloading, derive path from -o output directory combined with |
| 5224 | // the input filename and offload prefix. |
| 5225 | SmallString<128> TraceName(llvm::sys::path::stem(path: BaseInput)); |
| 5226 | TraceName += OffloadingPrefix; |
| 5227 | if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o)) |
| 5228 | Path = llvm::sys::path::parent_path(path: FinalOutput->getValue()); |
| 5229 | llvm::sys::path::append(path&: Path, a: TraceName); |
| 5230 | Path += ".json" ; |
| 5231 | } else { |
| 5232 | Path = Result.getFilename(); |
| 5233 | llvm::sys::path::replace_extension(path&: Path, extension: "json" ); |
| 5234 | } |
| 5235 | } |
| 5236 | const char *ResultFile = C.getArgs().MakeArgString(Str: Path); |
| 5237 | C.addTimeTraceFile(Name: ResultFile, JA); |
| 5238 | C.addResultFile(Name: ResultFile, JA); |
| 5239 | } |
| 5240 | |
| 5241 | InputInfoList Driver::BuildJobsForActionNoCache( |
| 5242 | Compilation &C, const Action *A, const ToolChain *TC, BoundArch BA, |
| 5243 | bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, |
| 5244 | std::map<std::pair<const Action *, std::string>, InputInfoList> |
| 5245 | &CachedResults, |
| 5246 | Action::OffloadKind TargetDeviceOffloadKind) const { |
| 5247 | llvm::PrettyStackTraceString CrashInfo("Building compilation jobs" ); |
| 5248 | |
| 5249 | // Track the bound arch for commands constructed in this scope so |
| 5250 | // generateCompilationDiagnostics can identify the crashing arch. |
| 5251 | BoundArch SavedBoundArch = C.getCurrentBoundArch(); |
| 5252 | C.setCurrentBoundArch(BA); |
| 5253 | auto RestoreBoundArch = |
| 5254 | llvm::scope_exit([&] { C.setCurrentBoundArch(SavedBoundArch); }); |
| 5255 | |
| 5256 | InputInfoList OffloadDependencesInputInfo; |
| 5257 | bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None; |
| 5258 | if (const OffloadAction *OA = dyn_cast<OffloadAction>(Val: A)) { |
| 5259 | // The 'Darwin' toolchain is initialized only when its arguments are |
| 5260 | // computed. Get the default arguments for OFK_None to ensure that |
| 5261 | // initialization is performed before processing the offload action. |
| 5262 | // FIXME: Remove when darwin's toolchain is initialized during construction. |
| 5263 | C.getArgsForToolChain(TC, BA, DeviceOffloadKind: Action::OFK_Host); |
| 5264 | |
| 5265 | // The offload action is expected to be used in four different situations. |
| 5266 | // |
| 5267 | // a) Set a toolchain/architecture/kind for a host action: |
| 5268 | // Host Action 1 -> OffloadAction -> Host Action 2 |
| 5269 | // |
| 5270 | // b) Set a toolchain/architecture/kind for a device action; |
| 5271 | // Device Action 1 -> OffloadAction -> Device Action 2 |
| 5272 | // |
| 5273 | // c) Specify a device dependence to a host action; |
| 5274 | // Device Action 1 _ |
| 5275 | // \ |
| 5276 | // Host Action 1 ---> OffloadAction -> Host Action 2 |
| 5277 | // |
| 5278 | // d) Specify a host dependence to a device action. |
| 5279 | // Host Action 1 _ |
| 5280 | // \ |
| 5281 | // Device Action 1 ---> OffloadAction -> Device Action 2 |
| 5282 | // |
| 5283 | // For a) and b), we just return the job generated for the dependences. For |
| 5284 | // c) and d) we override the current action with the host/device dependence |
| 5285 | // if the current toolchain is host/device and set the offload dependences |
| 5286 | // info with the jobs obtained from the device/host dependence(s). |
| 5287 | |
| 5288 | // If there is a single device option or has no host action, just generate |
| 5289 | // the job for it. |
| 5290 | if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) { |
| 5291 | InputInfoList DevA; |
| 5292 | OA->doOnEachDeviceDependence(Work: [&](Action *DepA, const ToolChain *DepTC, |
| 5293 | BoundArch DepBoundArch) { |
| 5294 | DevA.append(RHS: BuildJobsForAction(C, A: DepA, TC: DepTC, BA: DepBoundArch, AtTopLevel, |
| 5295 | /*MultipleArchs=*/!DepBoundArch.empty(), |
| 5296 | LinkingOutput, CachedResults, |
| 5297 | TargetDeviceOffloadKind: DepA->getOffloadingDeviceKind())); |
| 5298 | }); |
| 5299 | return DevA; |
| 5300 | } |
| 5301 | |
| 5302 | // If 'Action 2' is host, we generate jobs for the device dependences and |
| 5303 | // override the current action with the host dependence. Otherwise, we |
| 5304 | // generate the host dependences and override the action with the device |
| 5305 | // dependence. The dependences can't therefore be a top-level action. |
| 5306 | OA->doOnEachDependence( |
| 5307 | /*IsHostDependence=*/BuildingForOffloadDevice, |
| 5308 | Work: [&](Action *DepA, const ToolChain *DepTC, BoundArch DepBoundArch) { |
| 5309 | OffloadDependencesInputInfo.append(RHS: BuildJobsForAction( |
| 5310 | C, A: DepA, TC: DepTC, BA: DepBoundArch, /*AtTopLevel=*/false, |
| 5311 | /*MultipleArchs=*/!DepBoundArch.empty(), LinkingOutput, |
| 5312 | CachedResults, TargetDeviceOffloadKind: DepA->getOffloadingDeviceKind())); |
| 5313 | }); |
| 5314 | |
| 5315 | A = BuildingForOffloadDevice |
| 5316 | ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) |
| 5317 | : OA->getHostDependence(); |
| 5318 | |
| 5319 | // We may have already built this action as a part of the offloading |
| 5320 | // toolchain, return the cached input if so. |
| 5321 | std::pair<const Action *, std::string> ActionTC = { |
| 5322 | OA->getHostDependence(), |
| 5323 | GetTriplePlusArchString(TC, BA, OffloadKind: TargetDeviceOffloadKind)}; |
| 5324 | auto It = CachedResults.find(x: ActionTC); |
| 5325 | if (It != CachedResults.end()) { |
| 5326 | InputInfoList Inputs = It->second; |
| 5327 | Inputs.append(RHS: OffloadDependencesInputInfo); |
| 5328 | return Inputs; |
| 5329 | } |
| 5330 | } |
| 5331 | |
| 5332 | if (const InputAction *IA = dyn_cast<InputAction>(Val: A)) { |
| 5333 | // FIXME: It would be nice to not claim this here; maybe the old scheme of |
| 5334 | // just using Args was better? |
| 5335 | const Arg &Input = IA->getInputArg(); |
| 5336 | Input.claim(); |
| 5337 | if (Input.getOption().matches(ID: options::OPT_INPUT)) { |
| 5338 | const char *Name = Input.getValue(); |
| 5339 | return {InputInfo(A, Name, /* _BaseInput = */ Name)}; |
| 5340 | } |
| 5341 | return {InputInfo(A, &Input, /* _BaseInput = */ "" )}; |
| 5342 | } |
| 5343 | |
| 5344 | if (const BindArchAction *BAA = dyn_cast<BindArchAction>(Val: A)) { |
| 5345 | const ToolChain *TC; |
| 5346 | BoundArch ArchName = BAA->getArch(); |
| 5347 | |
| 5348 | if (!ArchName.empty()) |
| 5349 | TC = &getToolChain(Args: C.getArgs(), |
| 5350 | Target: computeTargetTriple(D: *this, TargetTriple, Args: C.getArgs(), |
| 5351 | ArchName: ArchName.ArchName)); |
| 5352 | else |
| 5353 | TC = &C.getDefaultToolChain(); |
| 5354 | |
| 5355 | return BuildJobsForAction(C, A: *BAA->input_begin(), TC, BA: ArchName, AtTopLevel, |
| 5356 | MultipleArchs, LinkingOutput, CachedResults, |
| 5357 | TargetDeviceOffloadKind); |
| 5358 | } |
| 5359 | |
| 5360 | |
| 5361 | ActionList Inputs = A->getInputs(); |
| 5362 | |
| 5363 | const JobAction *JA = cast<JobAction>(Val: A); |
| 5364 | ActionList CollapsedOffloadActions; |
| 5365 | |
| 5366 | ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), |
| 5367 | embedBitcodeInObject() && !TC->isUsingLTO(Args: C.getArgs())); |
| 5368 | const Tool *T = TS.getTool(Inputs, CollapsedOffloadAction&: CollapsedOffloadActions); |
| 5369 | |
| 5370 | if (!T) |
| 5371 | return {InputInfo()}; |
| 5372 | |
| 5373 | // If we've collapsed action list that contained OffloadAction we |
| 5374 | // need to build jobs for host/device-side inputs it may have held. |
| 5375 | for (const auto *OA : CollapsedOffloadActions) |
| 5376 | cast<OffloadAction>(Val: OA)->doOnEachDependence( |
| 5377 | /*IsHostDependence=*/BuildingForOffloadDevice, |
| 5378 | Work: [&](Action *DepA, const ToolChain *DepTC, BoundArch DepBoundArch) { |
| 5379 | OffloadDependencesInputInfo.append(RHS: BuildJobsForAction( |
| 5380 | C, A: DepA, TC: DepTC, BA: DepBoundArch, /*AtTopLevel=*/false, |
| 5381 | /*MultipleArchs=*/!DepBoundArch.empty(), LinkingOutput, |
| 5382 | CachedResults, TargetDeviceOffloadKind: DepA->getOffloadingDeviceKind())); |
| 5383 | }); |
| 5384 | |
| 5385 | // Only use pipes when there is exactly one input. |
| 5386 | InputInfoList InputInfos; |
| 5387 | for (const Action *Input : Inputs) { |
| 5388 | // Treat dsymutil and verify sub-jobs as being at the top-level too, they |
| 5389 | // shouldn't get temporary output names. |
| 5390 | // FIXME: Clean this up. |
| 5391 | bool SubJobAtTopLevel = |
| 5392 | AtTopLevel && (isa<DsymutilJobAction>(Val: A) || isa<VerifyJobAction>(Val: A)); |
| 5393 | InputInfos.append(RHS: BuildJobsForAction( |
| 5394 | C, A: Input, TC, BA, AtTopLevel: SubJobAtTopLevel, MultipleArchs, LinkingOutput, |
| 5395 | CachedResults, TargetDeviceOffloadKind: A->getOffloadingDeviceKind())); |
| 5396 | } |
| 5397 | |
| 5398 | // Always use the first file input as the base input. |
| 5399 | const char *BaseInput = InputInfos[0].getBaseInput(); |
| 5400 | for (auto &Info : InputInfos) { |
| 5401 | if (Info.isFilename()) { |
| 5402 | BaseInput = Info.getBaseInput(); |
| 5403 | break; |
| 5404 | } |
| 5405 | } |
| 5406 | |
| 5407 | // ... except dsymutil actions, which use their actual input as the base |
| 5408 | // input. |
| 5409 | if (JA->getType() == types::TY_dSYM) |
| 5410 | BaseInput = InputInfos[0].getFilename(); |
| 5411 | |
| 5412 | // Append outputs of offload device jobs to the input list |
| 5413 | if (!OffloadDependencesInputInfo.empty()) |
| 5414 | InputInfos.append(in_start: OffloadDependencesInputInfo.begin(), |
| 5415 | in_end: OffloadDependencesInputInfo.end()); |
| 5416 | |
| 5417 | // Set the effective triple of the toolchain for the duration of this job. |
| 5418 | llvm::Triple EffectiveTriple; |
| 5419 | const ToolChain &ToolTC = T->getToolChain(); |
| 5420 | const ArgList &Args = |
| 5421 | C.getArgsForToolChain(TC, BA, DeviceOffloadKind: A->getOffloadingDeviceKind()); |
| 5422 | if (InputInfos.size() != 1) { |
| 5423 | EffectiveTriple = |
| 5424 | llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args, BA)); |
| 5425 | } else { |
| 5426 | // Pass along the input type if it can be unambiguously determined. |
| 5427 | EffectiveTriple = llvm::Triple( |
| 5428 | ToolTC.ComputeEffectiveClangTriple(Args, BA, InputType: InputInfos[0].getType())); |
| 5429 | } |
| 5430 | RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple); |
| 5431 | |
| 5432 | // Determine the place to write output to, if any. |
| 5433 | InputInfo Result; |
| 5434 | if (JA->getType() == types::TY_Nothing) |
| 5435 | Result = {InputInfo(A, BaseInput)}; |
| 5436 | else { |
| 5437 | // We only have to generate a prefix for the host if this is not a top-level |
| 5438 | // action. |
| 5439 | std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( |
| 5440 | Kind: A->getOffloadingDeviceKind(), NormalizedTriple: EffectiveTriple.str(), |
| 5441 | /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(Val: A) || |
| 5442 | !(A->getOffloadingHostActiveKinds() == Action::OFK_None || |
| 5443 | AtTopLevel)); |
| 5444 | Result = InputInfo(A, |
| 5445 | GetNamedOutputPath(C, JA: *JA, BaseInput, BA, AtTopLevel, |
| 5446 | MultipleArchs, NormalizedTriple: OffloadingPrefix), |
| 5447 | BaseInput); |
| 5448 | if (T->canEmitIR()) |
| 5449 | handleTimeTrace(C, Args, JA, BaseInput, Result); |
| 5450 | } |
| 5451 | |
| 5452 | if (CCCPrintBindings && !CCGenDiagnostics) { |
| 5453 | llvm::errs() << "# \"" << T->getToolChain().getEffectiveTriple().str() |
| 5454 | << '"' << " - \"" << T->getName() << "\", inputs: [" ; |
| 5455 | for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { |
| 5456 | llvm::errs() << InputInfos[i].getAsString(); |
| 5457 | if (i + 1 != e) |
| 5458 | llvm::errs() << ", " ; |
| 5459 | } |
| 5460 | llvm::errs() << "], output: " << Result.getAsString() << "\n" ; |
| 5461 | } else { |
| 5462 | T->ConstructJob(C, JA: *JA, Output: Result, Inputs: InputInfos, TCArgs: Args, LinkingOutput); |
| 5463 | } |
| 5464 | return {Result}; |
| 5465 | } |
| 5466 | |
| 5467 | const char *Driver::getDefaultImageName() const { |
| 5468 | llvm::Triple Target(llvm::Triple::normalize(Str: TargetTriple)); |
| 5469 | return Target.isOSWindows() ? "a.exe" : "a.out" ; |
| 5470 | } |
| 5471 | |
| 5472 | /// Create output filename based on ArgValue, which could either be a |
| 5473 | /// full filename, filename without extension, or a directory. If ArgValue |
| 5474 | /// does not provide a filename, then use BaseName, and use the extension |
| 5475 | /// suitable for FileType. |
| 5476 | static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, |
| 5477 | StringRef BaseName, |
| 5478 | types::ID FileType) { |
| 5479 | SmallString<128> Filename = ArgValue; |
| 5480 | |
| 5481 | if (ArgValue.empty()) { |
| 5482 | // If the argument is empty, output to BaseName in the current dir. |
| 5483 | Filename = BaseName; |
| 5484 | } else if (llvm::sys::path::is_separator(value: Filename.back())) { |
| 5485 | // If the argument is a directory, output to BaseName in that dir. |
| 5486 | llvm::sys::path::append(path&: Filename, a: BaseName); |
| 5487 | } |
| 5488 | |
| 5489 | if (!llvm::sys::path::has_extension(path: ArgValue)) { |
| 5490 | // If the argument didn't provide an extension, then set it. |
| 5491 | const char *Extension = types::getTypeTempSuffix(Id: FileType, CLStyle: true); |
| 5492 | |
| 5493 | if (FileType == types::TY_Image && |
| 5494 | Args.hasArg(Ids: options::OPT__SLASH_LD, Ids: options::OPT__SLASH_LDd)) { |
| 5495 | // The output file is a dll. |
| 5496 | Extension = "dll" ; |
| 5497 | } |
| 5498 | |
| 5499 | llvm::sys::path::replace_extension(path&: Filename, extension: Extension); |
| 5500 | } |
| 5501 | |
| 5502 | return Args.MakeArgString(Str: Filename.c_str()); |
| 5503 | } |
| 5504 | |
| 5505 | static bool HasPreprocessOutput(const Action &JA) { |
| 5506 | if (isa<PreprocessJobAction>(Val: JA)) |
| 5507 | return true; |
| 5508 | if (isa<OffloadAction>(Val: JA) && isa<PreprocessJobAction>(Val: JA.getInputs()[0])) |
| 5509 | return true; |
| 5510 | if (isa<OffloadBundlingJobAction>(Val: JA) && |
| 5511 | HasPreprocessOutput(JA: *(JA.getInputs()[0]))) |
| 5512 | return true; |
| 5513 | return false; |
| 5514 | } |
| 5515 | |
| 5516 | const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix, |
| 5517 | StringRef Suffix, bool MultipleArchs, |
| 5518 | StringRef BoundArchStr, |
| 5519 | bool NeedUniqueDirectory) const { |
| 5520 | SmallString<128> TmpName; |
| 5521 | Arg *A = C.getArgs().getLastArg(Ids: options::OPT_fcrash_diagnostics_dir); |
| 5522 | std::optional<std::string> CrashDirectory = |
| 5523 | CCGenDiagnostics && A |
| 5524 | ? std::string(A->getValue()) |
| 5525 | : llvm::sys::Process::GetEnv(name: "CLANG_CRASH_DIAGNOSTICS_DIR" ); |
| 5526 | if (CrashDirectory) { |
| 5527 | if (!getVFS().exists(Path: *CrashDirectory)) |
| 5528 | llvm::sys::fs::create_directories(path: *CrashDirectory); |
| 5529 | SmallString<128> Path(*CrashDirectory); |
| 5530 | llvm::sys::path::append(path&: Path, a: Prefix); |
| 5531 | const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%" ; |
| 5532 | if (std::error_code EC = |
| 5533 | llvm::sys::fs::createUniqueFile(Model: Path + Middle + Suffix, ResultPath&: TmpName)) { |
| 5534 | Diag(DiagID: clang::diag::err_unable_to_make_temp) << EC.message(); |
| 5535 | return "" ; |
| 5536 | } |
| 5537 | } else { |
| 5538 | if (MultipleArchs && !BoundArchStr.empty()) { |
| 5539 | if (NeedUniqueDirectory) { |
| 5540 | TmpName = GetTemporaryDirectory(Prefix); |
| 5541 | llvm::sys::path::append(path&: TmpName, a: Twine(Prefix) + "-" + BoundArchStr + |
| 5542 | "." + Suffix); |
| 5543 | } else { |
| 5544 | TmpName = GetTemporaryPath(Prefix: (Twine(Prefix) + "-" + BoundArchStr).str(), |
| 5545 | Suffix); |
| 5546 | } |
| 5547 | |
| 5548 | } else { |
| 5549 | TmpName = GetTemporaryPath(Prefix, Suffix); |
| 5550 | } |
| 5551 | } |
| 5552 | return C.addTempFile(Name: C.getArgs().MakeArgString(Str: TmpName)); |
| 5553 | } |
| 5554 | |
| 5555 | // Calculate the output path of the module file when compiling a module unit |
| 5556 | // with the `-fmodule-output` option or `-fmodule-output=` option specified. |
| 5557 | // The behavior is: |
| 5558 | // - If `-fmodule-output=` is specfied, then the module file is |
| 5559 | // writing to the value. |
| 5560 | // - Otherwise if the output object file of the module unit is specified, the |
| 5561 | // output path |
| 5562 | // of the module file should be the same with the output object file except |
| 5563 | // the corresponding suffix. This requires both `-o` and `-c` are specified. |
| 5564 | // - Otherwise, the output path of the module file will be the same with the |
| 5565 | // input with the corresponding suffix. |
| 5566 | static const char *GetModuleOutputPath(Compilation &C, const JobAction &JA, |
| 5567 | const char *BaseInput) { |
| 5568 | assert(isa<PrecompileJobAction>(JA) && JA.getType() == types::TY_ModuleFile && |
| 5569 | (C.getArgs().hasArg(options::OPT_fmodule_output) || |
| 5570 | C.getArgs().hasArg(options::OPT_fmodule_output_EQ))); |
| 5571 | |
| 5572 | SmallString<256> OutputPath = |
| 5573 | tools::getCXX20NamedModuleOutputPath(Args: C.getArgs(), BaseInput); |
| 5574 | |
| 5575 | return C.addResultFile(Name: C.getArgs().MakeArgString(Str: OutputPath.c_str()), JA: &JA); |
| 5576 | } |
| 5577 | |
| 5578 | const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, |
| 5579 | const char *BaseInput, BoundArch BA, |
| 5580 | bool AtTopLevel, bool MultipleArchs, |
| 5581 | StringRef OffloadingPrefix) const { |
| 5582 | std::string BoundArchStr = sanitizeTargetIDInFileName(TargetID: BA.ArchName); |
| 5583 | |
| 5584 | llvm::PrettyStackTraceString CrashInfo("Computing output path" ); |
| 5585 | |
| 5586 | auto CreateTempOutputPath = [&](StringRef Prefix) { |
| 5587 | const char *Suffix = |
| 5588 | types::getTypeTempSuffix(Id: JA.getType(), CLStyle: IsCLMode() || IsDXCMode()); |
| 5589 | // The non-offloading toolchain on Darwin requires deterministic input |
| 5590 | // file name for binaries to be deterministic, therefore it needs unique |
| 5591 | // directory. |
| 5592 | const llvm::Triple Triple(C.getDriver().getTargetTriple()); |
| 5593 | const bool NeedUniqueDirectory = |
| 5594 | (JA.getOffloadingDeviceKind() == Action::OFK_None || |
| 5595 | JA.getOffloadingDeviceKind() == Action::OFK_Host) && |
| 5596 | Triple.isOSDarwin(); |
| 5597 | return CreateTempFile(C, Prefix, Suffix, MultipleArchs, BoundArchStr, |
| 5598 | NeedUniqueDirectory); |
| 5599 | }; |
| 5600 | |
| 5601 | // Standard library output in -fmodules-driver? |
| 5602 | if (isa<PrecompileJobAction>(Val: JA) && !JA.getInputs().empty() && |
| 5603 | (JA.getInputs().front()->getType() == types::TY_CXXStdModule || |
| 5604 | JA.getInputs().front()->getType() == types::TY_PP_CXXStdModule)) { |
| 5605 | StringRef Filename = llvm::sys::path::filename(path: BaseInput); |
| 5606 | StringRef Stem = llvm::sys::path::stem(path: Filename); |
| 5607 | return CreateTempOutputPath(Stem); |
| 5608 | } |
| 5609 | |
| 5610 | // Output to a user requested destination? |
| 5611 | if (AtTopLevel && !isa<DsymutilJobAction>(Val: JA) && !isa<VerifyJobAction>(Val: JA)) { |
| 5612 | if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) |
| 5613 | return C.addResultFile(Name: FinalOutput->getValue(), JA: &JA); |
| 5614 | } |
| 5615 | |
| 5616 | // For /P, preprocess to file named after BaseInput. |
| 5617 | if (C.getArgs().hasArg(Ids: options::OPT__SLASH_P)) { |
| 5618 | assert(AtTopLevel && isa<PreprocessJobAction>(JA)); |
| 5619 | StringRef BaseName = llvm::sys::path::filename(path: BaseInput); |
| 5620 | StringRef NameArg; |
| 5621 | if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fi)) |
| 5622 | NameArg = A->getValue(); |
| 5623 | return C.addResultFile( |
| 5624 | Name: MakeCLOutputFilename(Args: C.getArgs(), ArgValue: NameArg, BaseName, FileType: types::TY_PP_C), |
| 5625 | JA: &JA); |
| 5626 | } |
| 5627 | |
| 5628 | // Default to writing to stdout? |
| 5629 | if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) { |
| 5630 | return "-" ; |
| 5631 | } |
| 5632 | |
| 5633 | if (JA.getType() == types::TY_ModuleFile && |
| 5634 | C.getArgs().getLastArg(Ids: options::OPT_module_file_info)) { |
| 5635 | return "-" ; |
| 5636 | } |
| 5637 | |
| 5638 | if (JA.getType() == types::TY_PP_Asm && |
| 5639 | C.getArgs().hasArg(Ids: options::OPT_dxc_Fc)) { |
| 5640 | StringRef FcValue = C.getArgs().getLastArgValue(Id: options::OPT_dxc_Fc); |
| 5641 | // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably |
| 5642 | // handle this as part of the SLASH_Fa handling below. |
| 5643 | return C.addResultFile(Name: C.getArgs().MakeArgString(Str: FcValue), JA: &JA); |
| 5644 | } |
| 5645 | |
| 5646 | if ((JA.getType() == types::TY_Object && |
| 5647 | C.getArgs().hasArg(Ids: options::OPT_dxc_Fo)) || |
| 5648 | JA.getType() == types::TY_DX_CONTAINER) { |
| 5649 | StringRef FoValue = C.getArgs().getLastArgValue(Id: options::OPT_dxc_Fo); |
| 5650 | assert((C.getDefaultToolChain().getTriple().isDXIL() || |
| 5651 | C.getDefaultToolChain().getTriple().isSPIRV()) && |
| 5652 | "expected DXIL or SPIR-V triple for HLSL output path" ); |
| 5653 | const auto &TC = |
| 5654 | static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain()); |
| 5655 | // Fo can be empty here if the validator is running for a compiler flow |
| 5656 | // that is using Fc or just printing disassembly. |
| 5657 | if (TC.isLastOutputProducingJob(Args&: C.getArgs(), AC: JA.getKind()) && |
| 5658 | !FoValue.empty()) |
| 5659 | return C.addResultFile(Name: C.getArgs().MakeArgString(Str: FoValue), JA: &JA); |
| 5660 | StringRef Name = llvm::sys::path::filename(path: BaseInput); |
| 5661 | std::pair<StringRef, StringRef> Split = Name.split(Separator: '.'); |
| 5662 | const char *Suffix = types::getTypeTempSuffix(Id: JA.getType(), CLStyle: true); |
| 5663 | return CreateTempFile(C, Prefix: Split.first, Suffix, MultipleArchs: false); |
| 5664 | } |
| 5665 | |
| 5666 | // Is this the assembly listing for /FA? |
| 5667 | if (JA.getType() == types::TY_PP_Asm && |
| 5668 | (C.getArgs().hasArg(Ids: options::OPT__SLASH_FA) || |
| 5669 | C.getArgs().hasArg(Ids: options::OPT__SLASH_Fa))) { |
| 5670 | // Use /Fa and the input filename to determine the asm file name. |
| 5671 | StringRef BaseName = llvm::sys::path::filename(path: BaseInput); |
| 5672 | StringRef FaValue = C.getArgs().getLastArgValue(Id: options::OPT__SLASH_Fa); |
| 5673 | return C.addResultFile( |
| 5674 | Name: MakeCLOutputFilename(Args: C.getArgs(), ArgValue: FaValue, BaseName, FileType: JA.getType()), |
| 5675 | JA: &JA); |
| 5676 | } |
| 5677 | |
| 5678 | if (JA.getType() == types::TY_API_INFO && |
| 5679 | C.getArgs().hasArg(Ids: options::OPT_emit_extension_symbol_graphs) && |
| 5680 | C.getArgs().hasArg(Ids: options::OPT_o)) |
| 5681 | Diag(DiagID: clang::diag::err_drv_unexpected_symbol_graph_output) |
| 5682 | << C.getArgs().getLastArgValue(Id: options::OPT_o); |
| 5683 | |
| 5684 | // DXC defaults to standard out when generating assembly. We check this after |
| 5685 | // any DXC flags that might specify a file. |
| 5686 | if (AtTopLevel && JA.getType() == types::TY_PP_Asm && IsDXCMode()) |
| 5687 | return "-" ; |
| 5688 | |
| 5689 | bool SpecifiedModuleOutput = |
| 5690 | C.getArgs().hasArg(Ids: options::OPT_fmodule_output) || |
| 5691 | C.getArgs().hasArg(Ids: options::OPT_fmodule_output_EQ); |
| 5692 | if (MultipleArchs && SpecifiedModuleOutput) |
| 5693 | Diag(DiagID: clang::diag::err_drv_module_output_with_multiple_arch); |
| 5694 | |
| 5695 | // If we're emitting a module output with the specified option |
| 5696 | // `-fmodule-output`. |
| 5697 | if (!AtTopLevel && isa<PrecompileJobAction>(Val: JA) && |
| 5698 | JA.getType() == types::TY_ModuleFile && SpecifiedModuleOutput) { |
| 5699 | assert(C.getArgs().hasArg(options::OPT_fno_modules_reduced_bmi)); |
| 5700 | return GetModuleOutputPath(C, JA, BaseInput); |
| 5701 | } |
| 5702 | |
| 5703 | // Output to a temporary file? |
| 5704 | if ((!AtTopLevel && !isSaveTempsEnabled() && |
| 5705 | !C.getArgs().hasArg(Ids: options::OPT__SLASH_Fo)) || |
| 5706 | CCGenDiagnostics) { |
| 5707 | StringRef Name = llvm::sys::path::filename(path: BaseInput); |
| 5708 | return CreateTempOutputPath(Name.split(Separator: '.').first); |
| 5709 | } |
| 5710 | |
| 5711 | SmallString<128> BasePath(BaseInput); |
| 5712 | SmallString<128> ExternalPath("" ); |
| 5713 | StringRef BaseName; |
| 5714 | |
| 5715 | // Dsymutil actions should use the full path. |
| 5716 | if (isa<DsymutilJobAction>(Val: JA) && C.getArgs().hasArg(Ids: options::OPT_dsym_dir)) { |
| 5717 | ExternalPath += C.getArgs().getLastArg(Ids: options::OPT_dsym_dir)->getValue(); |
| 5718 | // We use posix style here because the tests (specifically |
| 5719 | // darwin-dsymutil.c) demonstrate that posix style paths are acceptable |
| 5720 | // even on Windows and if we don't then the similar test covering this |
| 5721 | // fails. |
| 5722 | llvm::sys::path::append(path&: ExternalPath, style: llvm::sys::path::Style::posix, |
| 5723 | a: llvm::sys::path::filename(path: BasePath)); |
| 5724 | BaseName = ExternalPath; |
| 5725 | } else if (isa<DsymutilJobAction>(Val: JA) || isa<VerifyJobAction>(Val: JA)) |
| 5726 | BaseName = BasePath; |
| 5727 | else |
| 5728 | BaseName = llvm::sys::path::filename(path: BasePath); |
| 5729 | |
| 5730 | // Determine what the derived output name should be. |
| 5731 | const char *NamedOutput; |
| 5732 | |
| 5733 | if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC || |
| 5734 | JA.getType() == types::TY_LLVM_BC || |
| 5735 | JA.getType() == types::TY_LLVM_IR) && |
| 5736 | C.getArgs().hasArg(Ids: options::OPT__SLASH_Fo, Ids: options::OPT__SLASH_o)) { |
| 5737 | // The /Fo or /o flag decides the object filename. |
| 5738 | StringRef Val = |
| 5739 | C.getArgs() |
| 5740 | .getLastArg(Ids: options::OPT__SLASH_Fo, Ids: options::OPT__SLASH_o) |
| 5741 | ->getValue(); |
| 5742 | NamedOutput = |
| 5743 | MakeCLOutputFilename(Args: C.getArgs(), ArgValue: Val, BaseName, FileType: JA.getType()); |
| 5744 | } else if (JA.getType() == types::TY_Image && |
| 5745 | C.getArgs().hasArg(Ids: options::OPT__SLASH_Fe, |
| 5746 | Ids: options::OPT__SLASH_o)) { |
| 5747 | // The /Fe or /o flag names the linked file. |
| 5748 | StringRef Val = |
| 5749 | C.getArgs() |
| 5750 | .getLastArg(Ids: options::OPT__SLASH_Fe, Ids: options::OPT__SLASH_o) |
| 5751 | ->getValue(); |
| 5752 | NamedOutput = |
| 5753 | MakeCLOutputFilename(Args: C.getArgs(), ArgValue: Val, BaseName, FileType: types::TY_Image); |
| 5754 | } else if (JA.getType() == types::TY_Image) { |
| 5755 | if (IsCLMode()) { |
| 5756 | // clang-cl uses BaseName for the executable name. |
| 5757 | NamedOutput = |
| 5758 | MakeCLOutputFilename(Args: C.getArgs(), ArgValue: "" , BaseName, FileType: types::TY_Image); |
| 5759 | } else { |
| 5760 | SmallString<128> Output(getDefaultImageName()); |
| 5761 | // HIP image for device compilation with -fno-gpu-rdc is per compilation |
| 5762 | // unit. |
| 5763 | bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP && |
| 5764 | !C.getArgs().hasFlag(Pos: options::OPT_fgpu_rdc, |
| 5765 | Neg: options::OPT_fno_gpu_rdc, Default: false); |
| 5766 | bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(Val: JA); |
| 5767 | if (UseOutExtension) { |
| 5768 | Output = BaseName; |
| 5769 | llvm::sys::path::replace_extension(path&: Output, extension: "" ); |
| 5770 | } |
| 5771 | Output += OffloadingPrefix; |
| 5772 | if (MultipleArchs && !BoundArchStr.empty()) { |
| 5773 | Output += "-" ; |
| 5774 | Output.append(RHS: BoundArchStr); |
| 5775 | } |
| 5776 | if (UseOutExtension) |
| 5777 | Output += ".out" ; |
| 5778 | NamedOutput = C.getArgs().MakeArgString(Str: Output.c_str()); |
| 5779 | } |
| 5780 | } else if (JA.getType() == types::TY_PCH && IsCLMode()) { |
| 5781 | NamedOutput = C.getArgs().MakeArgString(Str: GetClPchPath(C, BaseName)); |
| 5782 | } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) && |
| 5783 | C.getArgs().hasArg(Ids: options::OPT__SLASH_o)) { |
| 5784 | StringRef Val = |
| 5785 | C.getArgs() |
| 5786 | .getLastArg(Ids: options::OPT__SLASH_o) |
| 5787 | ->getValue(); |
| 5788 | NamedOutput = |
| 5789 | MakeCLOutputFilename(Args: C.getArgs(), ArgValue: Val, BaseName, FileType: types::TY_Object); |
| 5790 | } else { |
| 5791 | const char *Suffix = |
| 5792 | types::getTypeTempSuffix(Id: JA.getType(), CLStyle: IsCLMode() || IsDXCMode()); |
| 5793 | assert(Suffix && "All types used for output should have a suffix." ); |
| 5794 | |
| 5795 | std::string::size_type End = std::string::npos; |
| 5796 | if (!types::appendSuffixForType(Id: JA.getType())) |
| 5797 | End = BaseName.rfind(C: '.'); |
| 5798 | SmallString<128> Suffixed(BaseName.substr(Start: 0, N: End)); |
| 5799 | Suffixed += OffloadingPrefix; |
| 5800 | if (MultipleArchs && !BoundArchStr.empty()) { |
| 5801 | Suffixed += "-" ; |
| 5802 | Suffixed.append(RHS: BoundArchStr); |
| 5803 | } |
| 5804 | // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for |
| 5805 | // the unoptimized bitcode so that it does not get overwritten by the ".bc" |
| 5806 | // optimized bitcode output. |
| 5807 | auto IsAMDRDCInCompilePhase = [](const JobAction &JA, |
| 5808 | const llvm::opt::DerivedArgList &Args) { |
| 5809 | // The relocatable compilation in HIP and OpenMP implies -emit-llvm. |
| 5810 | // Similarly, use a ".tmp.bc" suffix for the unoptimized bitcode |
| 5811 | // (generated in the compile phase.) |
| 5812 | const ToolChain *TC = JA.getOffloadingToolChain(); |
| 5813 | return isa<CompileJobAction>(Val: JA) && |
| 5814 | (JA.getOffloadingDeviceKind() == Action::OFK_HIP || |
| 5815 | (JA.getOffloadingDeviceKind() == Action::OFK_OpenMP && TC && |
| 5816 | TC->getTriple().isAMDGPU())); |
| 5817 | }; |
| 5818 | |
| 5819 | // The linker wrapper may not support the input and output files to be the |
| 5820 | // same one, and without it -save-temps can fail. |
| 5821 | bool IsLinkerWrapper = |
| 5822 | JA.getType() == types::TY_Object && isa<LinkerWrapperJobAction>(Val: JA); |
| 5823 | bool IsEmitBitcode = JA.getType() == types::TY_LLVM_BC && |
| 5824 | (C.getArgs().hasArg(Ids: options::OPT_emit_llvm) || |
| 5825 | IsAMDRDCInCompilePhase(JA, C.getArgs())); |
| 5826 | |
| 5827 | if (!AtTopLevel && (IsLinkerWrapper || IsEmitBitcode)) |
| 5828 | Suffixed += ".tmp" ; |
| 5829 | Suffixed += '.'; |
| 5830 | Suffixed += Suffix; |
| 5831 | NamedOutput = C.getArgs().MakeArgString(Str: Suffixed.c_str()); |
| 5832 | } |
| 5833 | |
| 5834 | // Prepend object file path if -save-temps=obj |
| 5835 | if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(Ids: options::OPT_o) && |
| 5836 | JA.getType() != types::TY_PCH) { |
| 5837 | Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o); |
| 5838 | SmallString<128> TempPath(FinalOutput->getValue()); |
| 5839 | llvm::sys::path::remove_filename(path&: TempPath); |
| 5840 | StringRef OutputFileName = llvm::sys::path::filename(path: NamedOutput); |
| 5841 | llvm::sys::path::append(path&: TempPath, a: OutputFileName); |
| 5842 | NamedOutput = C.getArgs().MakeArgString(Str: TempPath.c_str()); |
| 5843 | } |
| 5844 | |
| 5845 | // If we're saving temps and the temp file conflicts with the input file, |
| 5846 | // then avoid overwriting input file. |
| 5847 | if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { |
| 5848 | bool SameFile = false; |
| 5849 | SmallString<256> Result; |
| 5850 | llvm::sys::fs::current_path(result&: Result); |
| 5851 | llvm::sys::path::append(path&: Result, a: BaseName); |
| 5852 | llvm::sys::fs::equivalent(A: BaseInput, B: Result.c_str(), result&: SameFile); |
| 5853 | // Must share the same path to conflict. |
| 5854 | if (SameFile) { |
| 5855 | StringRef Name = llvm::sys::path::filename(path: BaseInput); |
| 5856 | std::pair<StringRef, StringRef> Split = Name.split(Separator: '.'); |
| 5857 | std::string TmpName = GetTemporaryPath( |
| 5858 | Prefix: Split.first, |
| 5859 | Suffix: types::getTypeTempSuffix(Id: JA.getType(), CLStyle: IsCLMode() || IsDXCMode())); |
| 5860 | return C.addTempFile(Name: C.getArgs().MakeArgString(Str: TmpName)); |
| 5861 | } |
| 5862 | } |
| 5863 | |
| 5864 | // As an annoying special case, PCH generation doesn't strip the pathname. |
| 5865 | if (JA.getType() == types::TY_PCH && !IsCLMode()) { |
| 5866 | llvm::sys::path::remove_filename(path&: BasePath); |
| 5867 | if (BasePath.empty()) |
| 5868 | BasePath = NamedOutput; |
| 5869 | else |
| 5870 | llvm::sys::path::append(path&: BasePath, a: NamedOutput); |
| 5871 | return C.addResultFile(Name: C.getArgs().MakeArgString(Str: BasePath.c_str()), JA: &JA); |
| 5872 | } |
| 5873 | |
| 5874 | return C.addResultFile(Name: NamedOutput, JA: &JA); |
| 5875 | } |
| 5876 | |
| 5877 | std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const { |
| 5878 | // Search for Name in a list of paths. |
| 5879 | auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P) |
| 5880 | -> std::optional<std::string> { |
| 5881 | // Respect a limited subset of the '-Bprefix' functionality in GCC by |
| 5882 | // attempting to use this prefix when looking for file paths. |
| 5883 | for (const auto &Dir : P) { |
| 5884 | if (Dir.empty()) |
| 5885 | continue; |
| 5886 | SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(pos: 1) : Dir); |
| 5887 | llvm::sys::path::append(path&: P, a: Name); |
| 5888 | if (llvm::sys::fs::exists(Path: Twine(P))) |
| 5889 | return std::string(P); |
| 5890 | } |
| 5891 | return std::nullopt; |
| 5892 | }; |
| 5893 | |
| 5894 | if (auto P = SearchPaths(PrefixDirs)) |
| 5895 | return *P; |
| 5896 | |
| 5897 | SmallString<128> R(ResourceDir); |
| 5898 | llvm::sys::path::append(path&: R, a: Name); |
| 5899 | if (llvm::sys::fs::exists(Path: Twine(R))) |
| 5900 | return std::string(R); |
| 5901 | |
| 5902 | SmallString<128> P(TC.getCompilerRTPath()); |
| 5903 | llvm::sys::path::append(path&: P, a: Name); |
| 5904 | if (llvm::sys::fs::exists(Path: Twine(P))) |
| 5905 | return std::string(P); |
| 5906 | |
| 5907 | // With Flang, also look for intrinsic modules |
| 5908 | if (IsFlangMode()) { |
| 5909 | if (std::optional<std::string> IntrPath = |
| 5910 | TC.getDefaultIntrinsicModuleDir()) { |
| 5911 | SmallString<128> P(*IntrPath); |
| 5912 | llvm::sys::path::append(path&: P, a: Name); |
| 5913 | if (llvm::sys::fs::exists(Path: P)) |
| 5914 | return std::string(P); |
| 5915 | } |
| 5916 | } |
| 5917 | |
| 5918 | SmallString<128> D(Dir); |
| 5919 | llvm::sys::path::append(path&: D, a: ".." , b: Name); |
| 5920 | if (llvm::sys::fs::exists(Path: Twine(D))) |
| 5921 | return std::string(D); |
| 5922 | |
| 5923 | if (auto P = SearchPaths(TC.getLibraryPaths())) |
| 5924 | return *P; |
| 5925 | |
| 5926 | if (auto P = SearchPaths(TC.getFilePaths())) |
| 5927 | return *P; |
| 5928 | |
| 5929 | SmallString<128> R2(ResourceDir); |
| 5930 | llvm::sys::path::append(path&: R2, a: ".." , b: ".." , c: Name); |
| 5931 | if (llvm::sys::fs::exists(Path: Twine(R2))) |
| 5932 | return std::string(R2); |
| 5933 | |
| 5934 | return std::string(Name); |
| 5935 | } |
| 5936 | |
| 5937 | void Driver::generatePrefixedToolNames( |
| 5938 | StringRef Tool, const ToolChain &TC, |
| 5939 | SmallVectorImpl<std::string> &Names) const { |
| 5940 | // FIXME: Needs a better variable than TargetTriple |
| 5941 | Names.emplace_back(Args: (TargetTriple + "-" + Tool).str()); |
| 5942 | Names.emplace_back(Args&: Tool); |
| 5943 | } |
| 5944 | |
| 5945 | static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) { |
| 5946 | llvm::sys::path::append(path&: Dir, a: Name); |
| 5947 | if (llvm::sys::fs::can_execute(Path: Twine(Dir))) |
| 5948 | return true; |
| 5949 | llvm::sys::path::remove_filename(path&: Dir); |
| 5950 | return false; |
| 5951 | } |
| 5952 | |
| 5953 | std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const { |
| 5954 | SmallVector<std::string, 2> TargetSpecificExecutables; |
| 5955 | generatePrefixedToolNames(Tool: Name, TC, Names&: TargetSpecificExecutables); |
| 5956 | |
| 5957 | // Respect a limited subset of the '-Bprefix' functionality in GCC by |
| 5958 | // attempting to use this prefix when looking for program paths. |
| 5959 | for (const auto &PrefixDir : PrefixDirs) { |
| 5960 | if (llvm::sys::fs::is_directory(Path: PrefixDir)) { |
| 5961 | SmallString<128> P(PrefixDir); |
| 5962 | if (ScanDirForExecutable(Dir&: P, Name)) |
| 5963 | return std::string(P); |
| 5964 | } else { |
| 5965 | SmallString<128> P((PrefixDir + Name).str()); |
| 5966 | if (llvm::sys::fs::can_execute(Path: Twine(P))) |
| 5967 | return std::string(P); |
| 5968 | } |
| 5969 | } |
| 5970 | |
| 5971 | const ToolChain::path_list &List = TC.getProgramPaths(); |
| 5972 | for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) { |
| 5973 | // For each possible name of the tool look for it in |
| 5974 | // program paths first, then the path. |
| 5975 | // Higher priority names will be first, meaning that |
| 5976 | // a higher priority name in the path will be found |
| 5977 | // instead of a lower priority name in the program path. |
| 5978 | // E.g. <triple>-gcc on the path will be found instead |
| 5979 | // of gcc in the program path |
| 5980 | for (const auto &Path : List) { |
| 5981 | SmallString<128> P(Path); |
| 5982 | if (ScanDirForExecutable(Dir&: P, Name: TargetSpecificExecutable)) |
| 5983 | return std::string(P); |
| 5984 | } |
| 5985 | |
| 5986 | // Fall back to the path |
| 5987 | if (llvm::ErrorOr<std::string> P = |
| 5988 | llvm::sys::findProgramByName(Name: TargetSpecificExecutable)) |
| 5989 | return *P; |
| 5990 | } |
| 5991 | |
| 5992 | return std::string(Name); |
| 5993 | } |
| 5994 | |
| 5995 | std::string Driver::GetStdModuleManifestPath(const Compilation &C, |
| 5996 | const ToolChain &TC) const { |
| 5997 | std::string error = "<NOT PRESENT>" ; |
| 5998 | |
| 5999 | if (C.getArgs().hasArg(Ids: options::OPT_nostdlib)) |
| 6000 | return error; |
| 6001 | |
| 6002 | switch (TC.GetCXXStdlibType(Args: C.getArgs())) { |
| 6003 | case ToolChain::CST_Libcxx: { |
| 6004 | auto evaluate = [&](const char *library) -> std::optional<std::string> { |
| 6005 | std::string lib = GetFilePath(Name: library, TC); |
| 6006 | |
| 6007 | // Note when there are multiple flavours of libc++ the module json needs |
| 6008 | // to look at the command-line arguments for the proper json. These |
| 6009 | // flavours do not exist at the moment, but there are plans to provide a |
| 6010 | // variant that is built with sanitizer instrumentation enabled. |
| 6011 | |
| 6012 | // For example |
| 6013 | // StringRef modules = [&] { |
| 6014 | // const SanitizerArgs &Sanitize = TC.getSanitizerArgs(C.getArgs()); |
| 6015 | // if (Sanitize.needsAsanRt()) |
| 6016 | // return "libc++.modules-asan.json"; |
| 6017 | // return "libc++.modules.json"; |
| 6018 | // }(); |
| 6019 | |
| 6020 | SmallString<128> path(lib.begin(), lib.end()); |
| 6021 | llvm::sys::path::remove_filename(path); |
| 6022 | llvm::sys::path::append(path, a: "libc++.modules.json" ); |
| 6023 | if (TC.getVFS().exists(Path: path)) |
| 6024 | return static_cast<std::string>(path); |
| 6025 | |
| 6026 | return {}; |
| 6027 | }; |
| 6028 | |
| 6029 | if (std::optional<std::string> result = evaluate("libc++.so" ); result) |
| 6030 | return *result; |
| 6031 | |
| 6032 | return evaluate("libc++.a" ).value_or(u&: error); |
| 6033 | } |
| 6034 | |
| 6035 | case ToolChain::CST_Libstdcxx: { |
| 6036 | auto evaluate = [&](const char *library) -> std::optional<std::string> { |
| 6037 | std::string lib = GetFilePath(Name: library, TC); |
| 6038 | |
| 6039 | SmallString<128> path(lib.begin(), lib.end()); |
| 6040 | llvm::sys::path::remove_filename(path); |
| 6041 | llvm::sys::path::append(path, a: "libstdc++.modules.json" ); |
| 6042 | if (TC.getVFS().exists(Path: path)) |
| 6043 | return static_cast<std::string>(path); |
| 6044 | |
| 6045 | return {}; |
| 6046 | }; |
| 6047 | |
| 6048 | if (std::optional<std::string> result = evaluate("libstdc++.so" ); result) |
| 6049 | return *result; |
| 6050 | |
| 6051 | return evaluate("libstdc++.a" ).value_or(u&: error); |
| 6052 | } |
| 6053 | } |
| 6054 | |
| 6055 | return error; |
| 6056 | } |
| 6057 | |
| 6058 | std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const { |
| 6059 | SmallString<128> Path; |
| 6060 | std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, ResultPath&: Path); |
| 6061 | if (EC) { |
| 6062 | Diag(DiagID: clang::diag::err_unable_to_make_temp) << EC.message(); |
| 6063 | return "" ; |
| 6064 | } |
| 6065 | |
| 6066 | return std::string(Path); |
| 6067 | } |
| 6068 | |
| 6069 | std::string Driver::GetTemporaryDirectory(StringRef Prefix) const { |
| 6070 | SmallString<128> Path; |
| 6071 | std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, ResultPath&: Path); |
| 6072 | if (EC) { |
| 6073 | Diag(DiagID: clang::diag::err_unable_to_make_temp) << EC.message(); |
| 6074 | return "" ; |
| 6075 | } |
| 6076 | |
| 6077 | return std::string(Path); |
| 6078 | } |
| 6079 | |
| 6080 | std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { |
| 6081 | SmallString<128> Output; |
| 6082 | if (Arg *FpArg = C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fp)) { |
| 6083 | // FIXME: If anybody needs it, implement this obscure rule: |
| 6084 | // "If you specify a directory without a file name, the default file name |
| 6085 | // is VCx0.pch., where x is the major version of Visual C++ in use." |
| 6086 | Output = FpArg->getValue(); |
| 6087 | |
| 6088 | // "If you do not specify an extension as part of the path name, an |
| 6089 | // extension of .pch is assumed. " |
| 6090 | if (!llvm::sys::path::has_extension(path: Output)) |
| 6091 | Output += ".pch" ; |
| 6092 | } else { |
| 6093 | if (Arg *YcArg = C.getArgs().getLastArg(Ids: options::OPT__SLASH_Yc)) |
| 6094 | Output = YcArg->getValue(); |
| 6095 | if (Output.empty()) |
| 6096 | Output = BaseName; |
| 6097 | llvm::sys::path::replace_extension(path&: Output, extension: ".pch" ); |
| 6098 | } |
| 6099 | return std::string(Output); |
| 6100 | } |
| 6101 | |
| 6102 | const ToolChain &Driver::getOffloadToolChain( |
| 6103 | const llvm::opt::ArgList &Args, const Action::OffloadKind Kind, |
| 6104 | const llvm::Triple &Target, const llvm::Triple &AuxTarget) const { |
| 6105 | std::unique_ptr<ToolChain> &TC = |
| 6106 | ToolChains[Target.str() + "/" + AuxTarget.str()]; |
| 6107 | std::unique_ptr<ToolChain> &HostTC = ToolChains[AuxTarget.str()]; |
| 6108 | |
| 6109 | assert(HostTC && "Host toolchain for offloading doesn't exit?" ); |
| 6110 | if (!TC) { |
| 6111 | // Detect the toolchain based off of the target operating system. |
| 6112 | switch (Target.getOS()) { |
| 6113 | case llvm::Triple::CUDA: |
| 6114 | TC = std::make_unique<toolchains::CudaToolChain>(args: *this, args: Target, args&: *HostTC, |
| 6115 | args: Args); |
| 6116 | break; |
| 6117 | case llvm::Triple::AMDHSA: |
| 6118 | // For AMDHSA offloading (HIP, OpenMP), use the unified AMDGPUToolChain |
| 6119 | // This handles both amdgpu-amd-amdhsa and spirv64-amd-amdhsa |
| 6120 | // FIXME: This should not key off language or OS. |
| 6121 | if (Kind == Action::OFK_HIP || Kind == Action::OFK_OpenMP || |
| 6122 | Kind == Action::OFK_Cuda) |
| 6123 | TC = std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, args: Args, |
| 6124 | args: HostTC.get(), args: Kind); |
| 6125 | break; |
| 6126 | default: |
| 6127 | break; |
| 6128 | } |
| 6129 | } |
| 6130 | if (!TC) { |
| 6131 | // Detect the toolchain based off of the target architecture if that failed. |
| 6132 | switch (Target.getArch()) { |
| 6133 | case llvm::Triple::amdgpu: |
| 6134 | case llvm::Triple::r600: |
| 6135 | TC = std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, args: Args, |
| 6136 | args: HostTC.get(), args: Kind); |
| 6137 | break; |
| 6138 | case llvm::Triple::spir: |
| 6139 | case llvm::Triple::spir64: |
| 6140 | case llvm::Triple::spirv: |
| 6141 | case llvm::Triple::spirv32: |
| 6142 | case llvm::Triple::spirv64: |
| 6143 | switch (Kind) { |
| 6144 | case Action::OFK_SYCL: |
| 6145 | TC = std::make_unique<toolchains::SYCLToolChain>(args: *this, args: Target, args&: *HostTC, |
| 6146 | args: Args); |
| 6147 | break; |
| 6148 | case Action::OFK_HIP: |
| 6149 | TC = std::make_unique<toolchains::HIPSPVToolChain>(args: *this, args: Target, |
| 6150 | args&: *HostTC, args: Args); |
| 6151 | break; |
| 6152 | case Action::OFK_OpenMP: |
| 6153 | TC = std::make_unique<toolchains::SPIRVOpenMPToolChain>(args: *this, args: Target, |
| 6154 | args&: *HostTC, args: Args); |
| 6155 | break; |
| 6156 | case Action::OFK_Cuda: |
| 6157 | TC = std::make_unique<toolchains::CudaToolChain>(args: *this, args: Target, args&: *HostTC, |
| 6158 | args: Args); |
| 6159 | break; |
| 6160 | default: |
| 6161 | break; |
| 6162 | } |
| 6163 | break; |
| 6164 | default: |
| 6165 | break; |
| 6166 | } |
| 6167 | } |
| 6168 | |
| 6169 | // If all else fails, just look up the normal toolchain for the target. |
| 6170 | if (!TC) |
| 6171 | return getToolChain(Args, Target); |
| 6172 | return *TC; |
| 6173 | } |
| 6174 | |
| 6175 | const ToolChain &Driver::getToolChain(const ArgList &Args, |
| 6176 | const llvm::Triple &Target) const { |
| 6177 | |
| 6178 | auto &TC = ToolChains[Target.str()]; |
| 6179 | if (!TC) { |
| 6180 | switch (Target.getOS()) { |
| 6181 | case llvm::Triple::AIX: |
| 6182 | TC = std::make_unique<toolchains::AIX>(args: *this, args: Target, args: Args); |
| 6183 | break; |
| 6184 | case llvm::Triple::Haiku: |
| 6185 | TC = std::make_unique<toolchains::Haiku>(args: *this, args: Target, args: Args); |
| 6186 | break; |
| 6187 | case llvm::Triple::Darwin: |
| 6188 | case llvm::Triple::MacOSX: |
| 6189 | case llvm::Triple::IOS: |
| 6190 | case llvm::Triple::TvOS: |
| 6191 | case llvm::Triple::WatchOS: |
| 6192 | case llvm::Triple::XROS: |
| 6193 | case llvm::Triple::DriverKit: |
| 6194 | TC = std::make_unique<toolchains::DarwinClang>(args: *this, args: Target, args: Args); |
| 6195 | break; |
| 6196 | case llvm::Triple::DragonFly: |
| 6197 | TC = std::make_unique<toolchains::DragonFly>(args: *this, args: Target, args: Args); |
| 6198 | break; |
| 6199 | case llvm::Triple::OpenBSD: |
| 6200 | TC = std::make_unique<toolchains::OpenBSD>(args: *this, args: Target, args: Args); |
| 6201 | break; |
| 6202 | case llvm::Triple::NetBSD: |
| 6203 | TC = std::make_unique<toolchains::NetBSD>(args: *this, args: Target, args: Args); |
| 6204 | break; |
| 6205 | case llvm::Triple::FreeBSD: |
| 6206 | if (Target.isPPC()) |
| 6207 | TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(args: *this, args: Target, |
| 6208 | args: Args); |
| 6209 | else |
| 6210 | TC = std::make_unique<toolchains::FreeBSD>(args: *this, args: Target, args: Args); |
| 6211 | break; |
| 6212 | case llvm::Triple::Linux: |
| 6213 | case llvm::Triple::ELFIAMCU: |
| 6214 | if (Target.getArch() == llvm::Triple::hexagon) |
| 6215 | TC = std::make_unique<toolchains::HexagonToolChain>(args: *this, args: Target, |
| 6216 | args: Args); |
| 6217 | else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && |
| 6218 | !Target.hasEnvironment()) |
| 6219 | TC = std::make_unique<toolchains::MipsLLVMToolChain>(args: *this, args: Target, |
| 6220 | args: Args); |
| 6221 | else if (Target.isPPC()) |
| 6222 | TC = std::make_unique<toolchains::PPCLinuxToolChain>(args: *this, args: Target, |
| 6223 | args: Args); |
| 6224 | else if (Target.getArch() == llvm::Triple::ve) |
| 6225 | TC = std::make_unique<toolchains::VEToolChain>(args: *this, args: Target, args: Args); |
| 6226 | else if (Target.isOHOSFamily()) |
| 6227 | TC = std::make_unique<toolchains::OHOS>(args: *this, args: Target, args: Args); |
| 6228 | else if (Target.isWALI()) |
| 6229 | TC = std::make_unique<toolchains::WebAssembly>(args: *this, args: Target, args: Args); |
| 6230 | else if (Target.isLFI()) |
| 6231 | TC = std::make_unique<toolchains::LFILinux>(args: *this, args: Target, args: Args); |
| 6232 | else |
| 6233 | TC = std::make_unique<toolchains::Linux>(args: *this, args: Target, args: Args); |
| 6234 | break; |
| 6235 | case llvm::Triple::Fuchsia: |
| 6236 | TC = std::make_unique<toolchains::Fuchsia>(args: *this, args: Target, args: Args); |
| 6237 | break; |
| 6238 | case llvm::Triple::Managarm: |
| 6239 | TC = std::make_unique<toolchains::Managarm>(args: *this, args: Target, args: Args); |
| 6240 | break; |
| 6241 | case llvm::Triple::Serenity: |
| 6242 | TC = std::make_unique<toolchains::Serenity>(args: *this, args: Target, args: Args); |
| 6243 | break; |
| 6244 | case llvm::Triple::Solaris: |
| 6245 | TC = std::make_unique<toolchains::Solaris>(args: *this, args: Target, args: Args); |
| 6246 | break; |
| 6247 | case llvm::Triple::CUDA: |
| 6248 | TC = std::make_unique<toolchains::NVPTXToolChain>(args: *this, args: Target, args: Args); |
| 6249 | break; |
| 6250 | case llvm::Triple::AMDHSA: { |
| 6251 | if (Target.getArch() == llvm::Triple::spirv64) { |
| 6252 | TC = std::make_unique<toolchains::SPIRVAMDToolChain>(args: *this, args: Target, |
| 6253 | args: Args); |
| 6254 | } else { |
| 6255 | // Only link device libraries for OpenCL and LLVM IR inputs |
| 6256 | bool ShouldLinkDeviceLibs = usesInput(Args, Fn&: types::isOpenCL) || |
| 6257 | usesInput(Args, Fn&: types::isLLVMIR); |
| 6258 | TC = std::make_unique<toolchains::AMDGPUToolChain>( |
| 6259 | args: *this, args: Target, args: Args, args: nullptr, args: Action::OFK_None, |
| 6260 | args&: ShouldLinkDeviceLibs); |
| 6261 | } |
| 6262 | break; |
| 6263 | } |
| 6264 | case llvm::Triple::AMDPAL: |
| 6265 | case llvm::Triple::Mesa3D: |
| 6266 | TC = std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, args: Args); |
| 6267 | break; |
| 6268 | case llvm::Triple::UEFI: |
| 6269 | TC = std::make_unique<toolchains::UEFI>(args: *this, args: Target, args: Args); |
| 6270 | break; |
| 6271 | case llvm::Triple::Win32: |
| 6272 | switch (Target.getEnvironment()) { |
| 6273 | default: |
| 6274 | if (Target.isOSBinFormatELF()) |
| 6275 | TC = std::make_unique<toolchains::Generic_ELF>(args: *this, args: Target, args: Args); |
| 6276 | else if (Target.isOSBinFormatMachO()) |
| 6277 | TC = std::make_unique<toolchains::MachO>(args: *this, args: Target, args: Args); |
| 6278 | else |
| 6279 | TC = std::make_unique<toolchains::Generic_GCC>(args: *this, args: Target, args: Args); |
| 6280 | break; |
| 6281 | case llvm::Triple::GNU: |
| 6282 | TC = std::make_unique<toolchains::MinGW>(args: *this, args: Target, args: Args); |
| 6283 | break; |
| 6284 | case llvm::Triple::Cygnus: |
| 6285 | TC = std::make_unique<toolchains::Cygwin>(args: *this, args: Target, args: Args); |
| 6286 | break; |
| 6287 | case llvm::Triple::Itanium: |
| 6288 | TC = std::make_unique<toolchains::CrossWindowsToolChain>(args: *this, args: Target, |
| 6289 | args: Args); |
| 6290 | break; |
| 6291 | case llvm::Triple::MSVC: |
| 6292 | case llvm::Triple::UnknownEnvironment: |
| 6293 | if (Args.getLastArgValue(Id: options::OPT_fuse_ld_EQ) |
| 6294 | .starts_with_insensitive(Prefix: "bfd" )) |
| 6295 | TC = std::make_unique<toolchains::CrossWindowsToolChain>( |
| 6296 | args: *this, args: Target, args: Args); |
| 6297 | else |
| 6298 | TC = |
| 6299 | std::make_unique<toolchains::MSVCToolChain>(args: *this, args: Target, args: Args); |
| 6300 | break; |
| 6301 | } |
| 6302 | break; |
| 6303 | case llvm::Triple::PS4: |
| 6304 | TC = std::make_unique<toolchains::PS4CPU>(args: *this, args: Target, args: Args); |
| 6305 | break; |
| 6306 | case llvm::Triple::PS5: |
| 6307 | TC = std::make_unique<toolchains::PS5CPU>(args: *this, args: Target, args: Args); |
| 6308 | break; |
| 6309 | case llvm::Triple::Hurd: |
| 6310 | TC = std::make_unique<toolchains::Hurd>(args: *this, args: Target, args: Args); |
| 6311 | break; |
| 6312 | case llvm::Triple::LiteOS: |
| 6313 | TC = std::make_unique<toolchains::OHOS>(args: *this, args: Target, args: Args); |
| 6314 | break; |
| 6315 | case llvm::Triple::ZOS: |
| 6316 | TC = std::make_unique<toolchains::ZOS>(args: *this, args: Target, args: Args); |
| 6317 | break; |
| 6318 | case llvm::Triple::Vulkan: |
| 6319 | case llvm::Triple::ShaderModel: |
| 6320 | if ((Target.getArch() == llvm::Triple::spirv32 || |
| 6321 | Target.getArch() == llvm::Triple::spirv64) && |
| 6322 | !usesInput(Args, Fn&: types::isHLSL)) |
| 6323 | TC = std::make_unique<toolchains::SPIRVToolChain>(args: *this, args: Target, args: Args); |
| 6324 | else |
| 6325 | TC = std::make_unique<toolchains::HLSLToolChain>(args: *this, args: Target, args: Args); |
| 6326 | break; |
| 6327 | case llvm::Triple::ChipStar: |
| 6328 | TC = std::make_unique<toolchains::HIPSPVToolChain>(args: *this, args: Target, args: Args); |
| 6329 | break; |
| 6330 | default: |
| 6331 | // Of these targets, Hexagon is the only one that might have |
| 6332 | // an OS of Linux, in which case it got handled above already. |
| 6333 | switch (Target.getArch()) { |
| 6334 | case llvm::Triple::tce: |
| 6335 | TC = std::make_unique<toolchains::TCEToolChain>(args: *this, args: Target, args: Args); |
| 6336 | break; |
| 6337 | case llvm::Triple::tcele: |
| 6338 | TC = std::make_unique<toolchains::TCELEToolChain>(args: *this, args: Target, args: Args); |
| 6339 | break; |
| 6340 | case llvm::Triple::tcele64: |
| 6341 | TC = |
| 6342 | std::make_unique<toolchains::TCELE64ToolChain>(args: *this, args: Target, args: Args); |
| 6343 | break; |
| 6344 | case llvm::Triple::hexagon: |
| 6345 | TC = std::make_unique<toolchains::HexagonToolChain>(args: *this, args: Target, |
| 6346 | args: Args); |
| 6347 | break; |
| 6348 | case llvm::Triple::lanai: |
| 6349 | TC = std::make_unique<toolchains::LanaiToolChain>(args: *this, args: Target, args: Args); |
| 6350 | break; |
| 6351 | case llvm::Triple::xcore: |
| 6352 | TC = std::make_unique<toolchains::XCoreToolChain>(args: *this, args: Target, args: Args); |
| 6353 | break; |
| 6354 | case llvm::Triple::wasm32: |
| 6355 | case llvm::Triple::wasm64: |
| 6356 | TC = std::make_unique<toolchains::WebAssembly>(args: *this, args: Target, args: Args); |
| 6357 | break; |
| 6358 | case llvm::Triple::avr: |
| 6359 | TC = std::make_unique<toolchains::AVRToolChain>(args: *this, args: Target, args: Args); |
| 6360 | break; |
| 6361 | case llvm::Triple::msp430: |
| 6362 | TC = std::make_unique<toolchains::MSP430ToolChain>(args: *this, args: Target, args: Args); |
| 6363 | break; |
| 6364 | case llvm::Triple::riscv32: |
| 6365 | case llvm::Triple::riscv64: |
| 6366 | case llvm::Triple::riscv32be: |
| 6367 | case llvm::Triple::riscv64be: |
| 6368 | TC = std::make_unique<toolchains::BareMetal>(args: *this, args: Target, args: Args); |
| 6369 | break; |
| 6370 | case llvm::Triple::ve: |
| 6371 | TC = std::make_unique<toolchains::VEToolChain>(args: *this, args: Target, args: Args); |
| 6372 | break; |
| 6373 | case llvm::Triple::spirv32: |
| 6374 | case llvm::Triple::spirv64: |
| 6375 | TC = std::make_unique<toolchains::SPIRVToolChain>(args: *this, args: Target, args: Args); |
| 6376 | break; |
| 6377 | case llvm::Triple::csky: |
| 6378 | TC = std::make_unique<toolchains::CSKYToolChain>(args: *this, args: Target, args: Args); |
| 6379 | break; |
| 6380 | case llvm::Triple::amdgpu: |
| 6381 | case llvm::Triple::r600: |
| 6382 | TC = std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, args: Args); |
| 6383 | break; |
| 6384 | default: |
| 6385 | if (toolchains::BareMetal::handlesTarget(Triple: Target)) |
| 6386 | TC = std::make_unique<toolchains::BareMetal>(args: *this, args: Target, args: Args); |
| 6387 | else if (Target.isOSBinFormatELF()) |
| 6388 | TC = std::make_unique<toolchains::Generic_ELF>(args: *this, args: Target, args: Args); |
| 6389 | else if (Target.isAppleFirmware()) |
| 6390 | TC = std::make_unique<toolchains::DarwinClang>(args: *this, args: Target, args: Args); |
| 6391 | else if (Target.isAppleMachO()) |
| 6392 | TC = std::make_unique<toolchains::AppleMachO>(args: *this, args: Target, args: Args); |
| 6393 | else if (Target.isOSBinFormatMachO()) |
| 6394 | TC = std::make_unique<toolchains::MachO>(args: *this, args: Target, args: Args); |
| 6395 | else |
| 6396 | TC = std::make_unique<toolchains::Generic_GCC>(args: *this, args: Target, args: Args); |
| 6397 | } |
| 6398 | } |
| 6399 | } |
| 6400 | |
| 6401 | return *TC; |
| 6402 | } |
| 6403 | |
| 6404 | bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { |
| 6405 | // Say "no" if there is not exactly one input of a type clang understands. |
| 6406 | if (JA.size() != 1 || |
| 6407 | !types::isAcceptedByClang(Id: (*JA.input_begin())->getType())) |
| 6408 | return false; |
| 6409 | |
| 6410 | // And say "no" if this is not a kind of action clang understands. |
| 6411 | if (!isa<PreprocessJobAction>(Val: JA) && !isa<PrecompileJobAction>(Val: JA) && |
| 6412 | !isa<CompileJobAction>(Val: JA) && !isa<BackendJobAction>(Val: JA) && |
| 6413 | !isa<ExtractAPIJobAction>(Val: JA)) |
| 6414 | return false; |
| 6415 | |
| 6416 | return true; |
| 6417 | } |
| 6418 | |
| 6419 | bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const { |
| 6420 | // Say "no" if there is not exactly one input of a type flang understands. |
| 6421 | if (JA.size() != 1 || |
| 6422 | !types::isAcceptedByFlang(Id: (*JA.input_begin())->getType())) |
| 6423 | return false; |
| 6424 | |
| 6425 | // And say "no" if this is not a kind of action flang understands. |
| 6426 | if (!isa<PreprocessJobAction>(Val: JA) && !isa<PrecompileJobAction>(Val: JA) && |
| 6427 | !isa<CompileJobAction>(Val: JA) && !isa<BackendJobAction>(Val: JA)) |
| 6428 | return false; |
| 6429 | |
| 6430 | return true; |
| 6431 | } |
| 6432 | |
| 6433 | bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const { |
| 6434 | // Only emit static library if the flag is set explicitly. |
| 6435 | if (Args.hasArg(Ids: options::OPT_emit_static_lib)) |
| 6436 | return true; |
| 6437 | return false; |
| 6438 | } |
| 6439 | |
| 6440 | /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the |
| 6441 | /// grouped values as integers. Numbers which are not provided are set to 0. |
| 6442 | /// |
| 6443 | /// \return True if the entire string was parsed (9.2), or all groups were |
| 6444 | /// parsed (10.3.5extrastuff). |
| 6445 | bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, |
| 6446 | unsigned &Micro, bool &) { |
| 6447 | HadExtra = false; |
| 6448 | |
| 6449 | Major = Minor = Micro = 0; |
| 6450 | if (Str.empty()) |
| 6451 | return false; |
| 6452 | |
| 6453 | if (Str.consumeInteger(Radix: 10, Result&: Major)) |
| 6454 | return false; |
| 6455 | if (Str.empty()) |
| 6456 | return true; |
| 6457 | if (!Str.consume_front(Prefix: "." )) |
| 6458 | return false; |
| 6459 | |
| 6460 | if (Str.consumeInteger(Radix: 10, Result&: Minor)) |
| 6461 | return false; |
| 6462 | if (Str.empty()) |
| 6463 | return true; |
| 6464 | if (!Str.consume_front(Prefix: "." )) |
| 6465 | return false; |
| 6466 | |
| 6467 | if (Str.consumeInteger(Radix: 10, Result&: Micro)) |
| 6468 | return false; |
| 6469 | if (!Str.empty()) |
| 6470 | HadExtra = true; |
| 6471 | return true; |
| 6472 | } |
| 6473 | |
| 6474 | /// Parse digits from a string \p Str and fulfill \p Digits with |
| 6475 | /// the parsed numbers. This method assumes that the max number of |
| 6476 | /// digits to look for is equal to Digits.size(). |
| 6477 | /// |
| 6478 | /// \return True if the entire string was parsed and there are |
| 6479 | /// no extra characters remaining at the end. |
| 6480 | bool Driver::GetReleaseVersion(StringRef Str, |
| 6481 | MutableArrayRef<unsigned> Digits) { |
| 6482 | if (Str.empty()) |
| 6483 | return false; |
| 6484 | |
| 6485 | unsigned CurDigit = 0; |
| 6486 | while (CurDigit < Digits.size()) { |
| 6487 | unsigned Digit; |
| 6488 | if (Str.consumeInteger(Radix: 10, Result&: Digit)) |
| 6489 | return false; |
| 6490 | Digits[CurDigit] = Digit; |
| 6491 | if (Str.empty()) |
| 6492 | return true; |
| 6493 | if (!Str.consume_front(Prefix: "." )) |
| 6494 | return false; |
| 6495 | CurDigit++; |
| 6496 | } |
| 6497 | |
| 6498 | // More digits than requested, bail out... |
| 6499 | return false; |
| 6500 | } |
| 6501 | |
| 6502 | llvm::opt::Visibility |
| 6503 | Driver::getOptionVisibilityMask(bool UseDriverMode) const { |
| 6504 | if (!UseDriverMode) |
| 6505 | return llvm::opt::Visibility(options::ClangOption); |
| 6506 | if (IsCLMode()) |
| 6507 | return llvm::opt::Visibility(options::CLOption); |
| 6508 | if (IsDXCMode()) |
| 6509 | return llvm::opt::Visibility(options::DXCOption); |
| 6510 | if (IsFlangMode()) |
| 6511 | return llvm::opt::Visibility(options::FlangOption); |
| 6512 | return llvm::opt::Visibility(options::ClangOption); |
| 6513 | } |
| 6514 | |
| 6515 | const char *Driver::getExecutableForDriverMode(DriverMode Mode) { |
| 6516 | switch (Mode) { |
| 6517 | case GCCMode: |
| 6518 | return "clang" ; |
| 6519 | case GXXMode: |
| 6520 | return "clang++" ; |
| 6521 | case CPPMode: |
| 6522 | return "clang-cpp" ; |
| 6523 | case CLMode: |
| 6524 | return "clang-cl" ; |
| 6525 | case FlangMode: |
| 6526 | return "flang" ; |
| 6527 | case DXCMode: |
| 6528 | return "clang-dxc" ; |
| 6529 | } |
| 6530 | |
| 6531 | llvm_unreachable("Unhandled Mode" ); |
| 6532 | } |
| 6533 | |
| 6534 | bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { |
| 6535 | return Args.hasFlag(Pos: options::OPT_Ofast, Neg: options::OPT_O_Group, Default: false); |
| 6536 | } |
| 6537 | |
| 6538 | bool clang::driver::(const ArgList &Args) { |
| 6539 | // -fsave-optimization-record enables it. |
| 6540 | if (Args.hasFlag(Pos: options::OPT_fsave_optimization_record, |
| 6541 | Neg: options::OPT_fno_save_optimization_record, Default: false)) |
| 6542 | return true; |
| 6543 | |
| 6544 | // -fsave-optimization-record=<format> enables it as well. |
| 6545 | if (Args.hasFlag(Pos: options::OPT_fsave_optimization_record_EQ, |
| 6546 | Neg: options::OPT_fno_save_optimization_record, Default: false)) |
| 6547 | return true; |
| 6548 | |
| 6549 | // -foptimization-record-file alone enables it too. |
| 6550 | if (Args.hasFlag(Pos: options::OPT_foptimization_record_file_EQ, |
| 6551 | Neg: options::OPT_fno_save_optimization_record, Default: false)) |
| 6552 | return true; |
| 6553 | |
| 6554 | // -foptimization-record-passes alone enables it too. |
| 6555 | if (Args.hasFlag(Pos: options::OPT_foptimization_record_passes_EQ, |
| 6556 | Neg: options::OPT_fno_save_optimization_record, Default: false)) |
| 6557 | return true; |
| 6558 | return false; |
| 6559 | } |
| 6560 | |
| 6561 | llvm::StringRef clang::driver::getDriverMode(StringRef ProgName, |
| 6562 | ArrayRef<const char *> Args) { |
| 6563 | static StringRef OptName = |
| 6564 | getDriverOptTable().getOption(Opt: options::OPT_driver_mode).getPrefixedName(); |
| 6565 | llvm::StringRef Opt; |
| 6566 | for (StringRef Arg : Args) { |
| 6567 | if (!Arg.starts_with(Prefix: OptName)) |
| 6568 | continue; |
| 6569 | Opt = Arg; |
| 6570 | } |
| 6571 | if (Opt.empty()) |
| 6572 | Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode; |
| 6573 | return Opt.consume_front(Prefix: OptName) ? Opt : "" ; |
| 6574 | } |
| 6575 | |
| 6576 | bool driver::IsClangCL(StringRef DriverMode) { return DriverMode == "cl" ; } |
| 6577 | |
| 6578 | llvm::Error driver::expandResponseFiles(SmallVectorImpl<const char *> &Args, |
| 6579 | bool ClangCLMode, |
| 6580 | llvm::BumpPtrAllocator &Alloc, |
| 6581 | llvm::vfs::FileSystem *FS) { |
| 6582 | // Parse response files using the GNU syntax, unless we're in CL mode. There |
| 6583 | // are two ways to put clang in CL compatibility mode: ProgName is either |
| 6584 | // clang-cl or cl, or --driver-mode=cl is on the command line. The normal |
| 6585 | // command line parsing can't happen until after response file parsing, so we |
| 6586 | // have to manually search for a --driver-mode=cl argument the hard way. |
| 6587 | // Finally, our -cc1 tools don't care which tokenization mode we use because |
| 6588 | // response files written by clang will tokenize the same way in either mode. |
| 6589 | enum { Default, POSIX, Windows } RSPQuoting = Default; |
| 6590 | for (const char *F : Args) { |
| 6591 | if (strcmp(s1: F, s2: "--rsp-quoting=posix" ) == 0) |
| 6592 | RSPQuoting = POSIX; |
| 6593 | else if (strcmp(s1: F, s2: "--rsp-quoting=windows" ) == 0) |
| 6594 | RSPQuoting = Windows; |
| 6595 | } |
| 6596 | |
| 6597 | // Determines whether we want nullptr markers in Args to indicate response |
| 6598 | // files end-of-lines. We only use this for the /LINK driver argument with |
| 6599 | // clang-cl.exe on Windows. |
| 6600 | bool MarkEOLs = ClangCLMode; |
| 6601 | |
| 6602 | llvm::cl::TokenizerCallback Tokenizer; |
| 6603 | if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode)) |
| 6604 | Tokenizer = &llvm::cl::TokenizeWindowsCommandLine; |
| 6605 | else |
| 6606 | Tokenizer = &llvm::cl::TokenizeGNUCommandLine; |
| 6607 | |
| 6608 | if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).starts_with(Prefix: "-cc1" )) |
| 6609 | MarkEOLs = false; |
| 6610 | |
| 6611 | llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer); |
| 6612 | ECtx.setMarkEOLs(MarkEOLs); |
| 6613 | if (FS) |
| 6614 | ECtx.setVFS(FS); |
| 6615 | |
| 6616 | if (llvm::Error Err = ECtx.expandResponseFiles(Argv&: Args)) |
| 6617 | return Err; |
| 6618 | |
| 6619 | // If -cc1 came from a response file, remove the EOL sentinels. |
| 6620 | auto FirstArg = llvm::find_if(Range: llvm::drop_begin(RangeOrContainer&: Args), |
| 6621 | P: [](const char *A) { return A != nullptr; }); |
| 6622 | if (FirstArg != Args.end() && StringRef(*FirstArg).starts_with(Prefix: "-cc1" )) { |
| 6623 | // If -cc1 came from a response file, remove the EOL sentinels. |
| 6624 | if (MarkEOLs) { |
| 6625 | auto newEnd = std::remove(first: Args.begin(), last: Args.end(), value: nullptr); |
| 6626 | Args.resize(N: newEnd - Args.begin()); |
| 6627 | } |
| 6628 | } |
| 6629 | |
| 6630 | return llvm::Error::success(); |
| 6631 | } |
| 6632 | |
| 6633 | static const char *GetStableCStr(llvm::StringSet<> &SavedStrings, StringRef S) { |
| 6634 | return SavedStrings.insert(key: S).first->getKeyData(); |
| 6635 | } |
| 6636 | |
| 6637 | /// Apply a list of edits to the input argument lists. |
| 6638 | /// |
| 6639 | /// The input string is a space separated list of edits to perform, |
| 6640 | /// they are applied in order to the input argument lists. Edits |
| 6641 | /// should be one of the following forms: |
| 6642 | /// |
| 6643 | /// '#': Silence information about the changes to the command line arguments. |
| 6644 | /// |
| 6645 | /// '^FOO': Add FOO as a new argument at the beginning of the command line |
| 6646 | /// right after the name of the compiler executable. |
| 6647 | /// |
| 6648 | /// '+FOO': Add FOO as a new argument at the end of the command line. |
| 6649 | /// |
| 6650 | /// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command |
| 6651 | /// line. |
| 6652 | /// |
| 6653 | /// 'xOPTION': Removes all instances of the literal argument OPTION. |
| 6654 | /// |
| 6655 | /// 'XOPTION': Removes all instances of the literal argument OPTION, |
| 6656 | /// and the following argument. |
| 6657 | /// |
| 6658 | /// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox' |
| 6659 | /// at the end of the command line. |
| 6660 | /// |
| 6661 | /// \param OS - The stream to write edit information to. |
| 6662 | /// \param Args - The vector of command line arguments. |
| 6663 | /// \param Edit - The override command to perform. |
| 6664 | /// \param SavedStrings - Set to use for storing string representations. |
| 6665 | static void applyOneOverrideOption(raw_ostream &OS, |
| 6666 | SmallVectorImpl<const char *> &Args, |
| 6667 | StringRef Edit, |
| 6668 | llvm::StringSet<> &SavedStrings) { |
| 6669 | // This does not need to be efficient. |
| 6670 | |
| 6671 | if (Edit[0] == '^') { |
| 6672 | const char *Str = GetStableCStr(SavedStrings, S: Edit.substr(Start: 1)); |
| 6673 | OS << "### Adding argument " << Str << " at beginning\n" ; |
| 6674 | Args.insert(I: Args.begin() + 1, Elt: Str); |
| 6675 | } else if (Edit[0] == '+') { |
| 6676 | const char *Str = GetStableCStr(SavedStrings, S: Edit.substr(Start: 1)); |
| 6677 | OS << "### Adding argument " << Str << " at end\n" ; |
| 6678 | Args.push_back(Elt: Str); |
| 6679 | } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.ends_with(Suffix: "/" ) && |
| 6680 | Edit.slice(Start: 2, End: Edit.size() - 1).contains(C: '/')) { |
| 6681 | StringRef MatchPattern = Edit.substr(Start: 2).split(Separator: '/').first; |
| 6682 | StringRef ReplPattern = Edit.substr(Start: 2).split(Separator: '/').second; |
| 6683 | ReplPattern = ReplPattern.slice(Start: 0, End: ReplPattern.size() - 1); |
| 6684 | |
| 6685 | for (unsigned i = 1, e = Args.size(); i != e; ++i) { |
| 6686 | // Ignore end-of-line response file markers |
| 6687 | if (Args[i] == nullptr) |
| 6688 | continue; |
| 6689 | std::string Repl = llvm::Regex(MatchPattern).sub(Repl: ReplPattern, String: Args[i]); |
| 6690 | |
| 6691 | if (Repl != Args[i]) { |
| 6692 | OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n" ; |
| 6693 | Args[i] = GetStableCStr(SavedStrings, S: Repl); |
| 6694 | } |
| 6695 | } |
| 6696 | } else if (Edit[0] == 'x' || Edit[0] == 'X') { |
| 6697 | auto Option = Edit.substr(Start: 1); |
| 6698 | for (unsigned i = 1; i < Args.size();) { |
| 6699 | if (Option == Args[i]) { |
| 6700 | OS << "### Deleting argument " << Args[i] << '\n'; |
| 6701 | Args.erase(CI: Args.begin() + i); |
| 6702 | if (Edit[0] == 'X') { |
| 6703 | if (i < Args.size()) { |
| 6704 | OS << "### Deleting argument " << Args[i] << '\n'; |
| 6705 | Args.erase(CI: Args.begin() + i); |
| 6706 | } else |
| 6707 | OS << "### Invalid X edit, end of command line!\n" ; |
| 6708 | } |
| 6709 | } else |
| 6710 | ++i; |
| 6711 | } |
| 6712 | } else if (Edit[0] == 'O') { |
| 6713 | for (unsigned i = 1; i < Args.size();) { |
| 6714 | const char *A = Args[i]; |
| 6715 | // Ignore end-of-line response file markers |
| 6716 | if (A == nullptr) |
| 6717 | continue; |
| 6718 | if (A[0] == '-' && A[1] == 'O' && |
| 6719 | (A[2] == '\0' || (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' || |
| 6720 | ('0' <= A[2] && A[2] <= '9'))))) { |
| 6721 | OS << "### Deleting argument " << Args[i] << '\n'; |
| 6722 | Args.erase(CI: Args.begin() + i); |
| 6723 | } else |
| 6724 | ++i; |
| 6725 | } |
| 6726 | OS << "### Adding argument " << Edit << " at end\n" ; |
| 6727 | Args.push_back(Elt: GetStableCStr(SavedStrings, S: '-' + Edit.str())); |
| 6728 | } else { |
| 6729 | OS << "### Unrecognized edit: " << Edit << "\n" ; |
| 6730 | } |
| 6731 | } |
| 6732 | |
| 6733 | void driver::applyOverrideOptions(SmallVectorImpl<const char *> &Args, |
| 6734 | const char *OverrideStr, |
| 6735 | llvm::StringSet<> &SavedStrings, |
| 6736 | StringRef EnvVar, raw_ostream *OS) { |
| 6737 | if (!OS) |
| 6738 | OS = &llvm::nulls(); |
| 6739 | |
| 6740 | if (OverrideStr[0] == '#') { |
| 6741 | ++OverrideStr; |
| 6742 | OS = &llvm::nulls(); |
| 6743 | } |
| 6744 | |
| 6745 | *OS << "### " << EnvVar << ": " << OverrideStr << "\n" ; |
| 6746 | |
| 6747 | // This does not need to be efficient. |
| 6748 | |
| 6749 | const char *S = OverrideStr; |
| 6750 | while (*S) { |
| 6751 | const char *End = ::strchr(s: S, c: ' '); |
| 6752 | if (!End) |
| 6753 | End = S + strlen(s: S); |
| 6754 | if (End != S) |
| 6755 | applyOneOverrideOption(OS&: *OS, Args, Edit: std::string(S, End), SavedStrings); |
| 6756 | S = End; |
| 6757 | if (*S != '\0') |
| 6758 | ++S; |
| 6759 | } |
| 6760 | } |
| 6761 | |