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