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