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