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