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