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