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