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