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

source code of clang/lib/Driver/Driver.cpp