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->getSpelling() : "");
3531 else
3532 Diag(clang::diag::warn_drv_input_file_unused)
3533 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3534 << !FinalPhaseArg
3535 << (FinalPhaseArg ? FinalPhaseArg->getSpelling() : "");
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 // Like -emit-llvm, -c selects the binary form; bare -emit-cir and
4457 // -emit-cir -S keep emitting text.
4458 if (Args.hasArg(options::OPT_c) && !Args.hasArg(options::OPT_S))
4459 return C.MakeAction<CompileJobAction>(Input, types::TY_CIRBC);
4460 return C.MakeAction<CompileJobAction>(Input, types::TY_CIR);
4461 }
4462 if (Args.hasArg(options::OPT_module_file_info))
4463 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
4464 if (Args.hasArg(options::OPT_verify_pch))
4465 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
4466 if (Args.hasArg(options::OPT_extract_api))
4467 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4468 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
4469 }
4470 case phases::Backend: {
4471 if (TargetLTOMode != LTOK_None) {
4472 bool IsDeviceOffload = TargetDeviceOffloadKind != Action::OFK_None;
4473 if (!IsDeviceOffload) {
4474 types::ID Output;
4475 if (Args.hasArg(options::OPT_ffat_lto_objects) &&
4476 !Args.hasArg(options::OPT_emit_llvm))
4477 Output = types::TY_PP_Asm;
4478 else if (Args.hasArg(options::OPT_S))
4479 Output = types::TY_LTO_IR;
4480 else
4481 Output = types::TY_LTO_BC;
4482 return C.MakeAction<BackendJobAction>(Input, Output);
4483 }
4484 types::ID Output;
4485 if (Args.hasArg(options::OPT_emit_llvm)) {
4486 Output =
4487 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
4488 } else if (Args.hasArg(options::OPT_S) && offloadDeviceOnly() &&
4489 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4490 false)) {
4491 // For non-RDC device-only compilations with -S, produce real assembly
4492 // since the user explicitly requested assembly output.
4493 Output = types::TY_PP_Asm;
4494 } else if (Args.hasArg(options::OPT_S)) {
4495 Output = types::TY_LTO_IR;
4496 } else {
4497 Output = types::TY_LTO_BC;
4498 }
4499 return C.MakeAction<BackendJobAction>(Input, Output);
4500 }
4501 // SYCL device compilations produce IR unless the user explicitly requested
4502 // device-only assembly output, in which case emit textual SPIR-V.
4503 if (Args.hasArg(options::OPT_emit_llvm) ||
4504 (TargetDeviceOffloadKind == Action::OFK_SYCL &&
4505 !(offloadDeviceOnly() && Args.hasArg(options::OPT_S)))) {
4506 types::ID Output =
4507 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
4508 return C.MakeAction<BackendJobAction>(Input, Output);
4509 }
4510
4511 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
4512 }
4513 case phases::Assemble:
4514 // When -marm64x is used, construct jobs for the EC and native targets and
4515 // merge them into an archive with llvm-objcopy.
4516 const llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4517 if (Target.isOSWindows() && Args.hasArg(options::OPT_marm64x)) {
4518 Action *Act =
4519 C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
4520 ActionList Inputs;
4521 Inputs.push_back(C.MakeAction<BindArchAction>(Act, BoundArch("aarch64")));
4522 Inputs.push_back(C.MakeAction<BindArchAction>(Act, BoundArch("arm64ec")));
4523 return C.MakeAction<ObjcopyJobAction>(Inputs, types::TY_Object);
4524 }
4525 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
4526 }
4527
4528 llvm_unreachable("invalid phase in ConstructPhaseAction");
4529}
4530
4532 const Action &Source = Job.getSource();
4533 if (!isa<CompileJobAction>(Source) && !isa<BackendJobAction>(Source))
4534 return false;
4535
4536 if (Job.getBoundArch().empty() && !Source.getOffloadingArch().empty())
4537 Job.setBoundArch(Source.getOffloadingArch());
4538
4539 if (Job.getBoundArch().empty())
4540 return false;
4541
4542 if (StringRef(Job.getCreator().getName()) != "clang")
4543 return false;
4544
4545 Action::OffloadKind OKind = Source.getOffloadingDeviceKind();
4546 if (OKind != Action::OFK_None && OKind != Action::OFK_Host)
4547 return true;
4548
4549 const llvm::Triple &Triple = Job.getCreator().getToolChain().getTriple();
4550 return Triple.isAMDGPU() || Triple.isNVPTX() || Triple.isSPIROrSPIRV();
4551}
4552
4553static std::string getOffloadDeviceCC1ParallelJobGroup(const Command &Job) {
4554 const Action &Source = Job.getSource();
4555 // This key groups device cc1 jobs that can run in parallel. Jobs may differ
4556 // by offload arch, but must have the same offload kind, target triple,
4557 // action kind, and output type. For example, HIP compile jobs for gfx900 and
4558 // gfx906 can share a group, but HIP and OpenMP jobs cannot.
4559 return (Twine(Action::GetOffloadKindName(Source.getOffloadingDeviceKind())) +
4560 ":" + Job.getCreator().getToolChain().getTripleString() + ":" +
4561 Source.getClassName() + ":" + types::getTypeName(Source.getType()))
4562 .str();
4563}
4564
4565static void claimAndDiagnoseOffloadJobs(const Driver &D, const ArgList &Args) {
4566 auto OffloadJobs = tools::parseOffloadJobs(Args);
4567 if (!OffloadJobs.A)
4568 return;
4569
4570 if (!OffloadJobs.isValid())
4571 D.Diag(diag::err_drv_invalid_int_value)
4572 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
4573
4574 OffloadJobs.A->claim();
4575}
4576
4578 for (auto &Job : C.getJobs()) {
4580 continue;
4581
4582 Job.setOffloadDeviceParallelJobGroup(
4584 }
4585}
4586
4588 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4589
4590 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4591
4592 // It is an error to provide a -o option if we are making multiple output
4593 // files. There are exceptions:
4594 //
4595 // IfsMergeJob: when generating interface stubs enabled we want to be able to
4596 // generate the stub file at the same time that we generate the real
4597 // library/a.out. So when a .o, .so, etc are the output, with clang interface
4598 // stubs there will also be a .ifs and .ifso at the same location.
4599 //
4600 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
4601 // and -c is passed, we still want to be able to generate a .ifs file while
4602 // we are also generating .o files. So we allow more than one output file in
4603 // this case as well.
4604 //
4605 // OffloadClass of type TY_Nothing: device-only output will place many outputs
4606 // into a single offloading action. We should count all inputs to the action
4607 // as outputs. Also ignore device-only outputs if we're compiling with
4608 // -fsyntax-only.
4609 if (FinalOutput) {
4610 unsigned NumOutputs = 0;
4611 unsigned NumIfsOutputs = 0;
4612 for (const Action *A : C.getActions()) {
4613 // The actions below do not increase the number of outputs.
4616 continue;
4617
4618 // With -fmodules-driver, Standard library modules should not count toward
4619 // the number of outputs, since they are implicitly added to the input
4620 // list.
4621 if (isa<PrecompileJobAction>(A) && !A->getInputs().empty() &&
4622 (A->getInputs().front()->getType() == types::TY_CXXStdModule ||
4623 A->getInputs().front()->getType() == types::TY_PP_CXXStdModule))
4624 continue;
4625
4626 if (A->getType() != types::TY_Nothing &&
4628 (A->getType() == clang::driver::types::TY_IFS_CPP &&
4630 0 == NumIfsOutputs++) ||
4631 (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
4632 A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
4633 ++NumOutputs;
4634 else if (A->getKind() == Action::OffloadClass &&
4635 A->getType() == types::TY_Nothing &&
4636 !C.getArgs().hasArg(options::OPT_fsyntax_only))
4637 NumOutputs += A->size();
4638 }
4639
4640 if (NumOutputs > 1) {
4641 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
4642 FinalOutput = nullptr;
4643 }
4644 }
4645
4646 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
4647
4648 // Collect the list of architectures.
4649 llvm::StringSet<> ArchNames;
4650 if (RawTriple.isOSBinFormatMachO())
4651 for (const Arg *A : C.getArgs())
4652 if (A->getOption().matches(options::OPT_arch))
4653 ArchNames.insert(A->getValue());
4654
4655 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
4656 std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults;
4657 for (Action *A : C.getActions()) {
4658 // If we are linking an image for multiple archs then the linker wants
4659 // -arch_multiple and -final_output <final image name>. Unfortunately, this
4660 // doesn't fit in cleanly because we have to pass this information down.
4661 //
4662 // FIXME: This is a hack; find a cleaner way to integrate this into the
4663 // process.
4664 const char *LinkingOutput = nullptr;
4665 if (isa<LipoJobAction>(A)) {
4666 if (FinalOutput)
4667 LinkingOutput = FinalOutput->getValue();
4668 else
4669 LinkingOutput = getDefaultImageName();
4670 }
4671
4672 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
4673 /*BA=*/{},
4674 /*AtTopLevel*/ true,
4675 /*MultipleArchs*/ ArchNames.size() > 1 ||
4676 C.getArgs().hasArgNoClaim(options::OPT_marm64x),
4677 /*LinkingOutput*/ LinkingOutput, CachedResults,
4678 /*TargetDeviceOffloadKind*/ Action::OFK_None);
4679 }
4680
4681 // If we have more than one job, then disable integrated-cc1 for now. Do this
4682 // also when we need to report process execution statistics.
4683 if (C.getJobs().size() > 1 || CCPrintProcessStats)
4684 for (auto &J : C.getJobs())
4685 J.InProcess = false;
4686
4688 if (C.getActiveOffloadKinds() != Action::OFK_None)
4689 claimAndDiagnoseOffloadJobs(*this, C.getArgs());
4690
4691 if (CCPrintProcessStats) {
4692 C.setPostCallback([=](const Command &Cmd, int Res) {
4693 std::optional<llvm::sys::ProcessStatistics> ProcStat =
4695 if (!ProcStat)
4696 return;
4697
4698 const char *LinkingOutput = nullptr;
4699 if (FinalOutput)
4700 LinkingOutput = FinalOutput->getValue();
4701 else if (!Cmd.getOutputFilenames().empty())
4702 LinkingOutput = Cmd.getOutputFilenames().front().c_str();
4703 else
4704 LinkingOutput = getDefaultImageName();
4705
4706 if (CCPrintStatReportFilename.empty()) {
4707 using namespace llvm;
4708 // Human readable output.
4709 outs() << sys::path::filename(Cmd.getExecutable()) << ": "
4710 << "output=" << LinkingOutput;
4711 outs() << ", total="
4712 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
4713 << ", user="
4714 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
4715 << ", mem=" << ProcStat->PeakMemory << " Kb\n";
4716 } else {
4717 // CSV format.
4718 std::string Buffer;
4719 llvm::raw_string_ostream Out(Buffer);
4720 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
4721 /*Quote*/ true);
4722 Out << ',';
4723 llvm::sys::printArg(Out, LinkingOutput, true);
4724 Out << ',' << ProcStat->TotalTime.count() << ','
4725 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
4726 << '\n';
4727 Out.flush();
4728 std::error_code EC;
4729 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
4730 llvm::sys::fs::OF_Append |
4731 llvm::sys::fs::OF_Text);
4732 if (EC)
4733 return;
4734 auto L = OS.lock();
4735 if (!L) {
4736 llvm::errs() << "ERROR: Cannot lock file "
4737 << CCPrintStatReportFilename << ": "
4738 << toString(L.takeError()) << "\n";
4739 return;
4740 }
4741 OS << Buffer;
4742 OS.flush();
4743 }
4744 });
4745 }
4746
4747 // If the user passed -Qunused-arguments or there were errors, don't
4748 // warn about any unused arguments.
4749 bool ReportUnusedArguments =
4750 !Diags.hasErrorOccurred() &&
4751 !C.getArgs().hasArg(options::OPT_Qunused_arguments);
4752
4753 // Claim -fdriver-only here.
4754 (void)C.getArgs().hasArg(options::OPT_fdriver_only);
4755 // Claim -### here.
4756 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4757
4758 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4759 (void)C.getArgs().hasArg(options::OPT_driver_mode);
4760 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4761
4762 bool HasAssembleJob = llvm::any_of(C.getJobs(), [](auto &J) {
4763 // Match ClangAs and other derived assemblers of Tool. ClangAs uses a
4764 // longer ShortName "clang integrated assembler" while other assemblers just
4765 // use "assembler".
4766 return strstr(J.getCreator().getShortName(), "assembler");
4767 });
4768 for (Arg *A : C.getArgs()) {
4769 // FIXME: It would be nice to be able to send the argument to the
4770 // DiagnosticsEngine, so that extra values, position, and so on could be
4771 // printed.
4772 if (!A->isClaimed()) {
4773 if (A->getOption().hasFlag(options::NoArgumentUnused))
4774 continue;
4775
4776 // Suppress the warning automatically if this is just a flag, and it is an
4777 // instance of an argument we already claimed.
4778 const Option &Opt = A->getOption();
4779 if (Opt.getKind() == Option::FlagClass) {
4780 bool DuplicateClaimed = false;
4781
4782 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4783 if (AA->isClaimed()) {
4784 DuplicateClaimed = true;
4785 break;
4786 }
4787 }
4788
4789 if (DuplicateClaimed)
4790 continue;
4791 }
4792
4793 // In clang-cl, don't mention unknown arguments here since they have
4794 // already been warned about.
4795 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) {
4796 if (A->getOption().hasFlag(options::TargetSpecific) &&
4797 !A->isIgnoredTargetSpecific() && !HasAssembleJob &&
4798 // When for example -### or -v is used
4799 // without a file, target specific options are not
4800 // consumed/validated.
4801 // Instead emitting an error emit a warning instead.
4802 !C.getActions().empty()) {
4803 Diag(diag::err_drv_unsupported_opt_for_target)
4804 << A->getSpelling() << getTargetTriple();
4805 } else if (ReportUnusedArguments) {
4806 Diag(clang::diag::warn_drv_unused_argument)
4807 << A->getAsString(C.getArgs());
4808 }
4809 }
4810 }
4811 }
4812}
4813
4814namespace {
4815/// Utility class to control the collapse of dependent actions and select the
4816/// tools accordingly.
4817class ToolSelector final {
4818 /// The tool chain this selector refers to.
4819 const ToolChain &TC;
4820
4821 /// The compilation this selector refers to.
4822 const Compilation &C;
4823
4824 /// The base action this selector refers to.
4825 const JobAction *BaseAction;
4826
4827 /// Set to true if the current toolchain refers to host actions.
4828 bool IsHostSelector;
4829
4830 /// Set to true if save-temps and embed-bitcode functionalities are active.
4831 bool SaveTemps;
4832 bool EmbedBitcode;
4833
4834 /// Get previous dependent action or null if that does not exist. If
4835 /// \a CanBeCollapsed is false, that action must be legal to collapse or
4836 /// null will be returned.
4837 const JobAction *getPrevDependentAction(const ActionList &Inputs,
4838 ActionList &SavedOffloadAction,
4839 bool CanBeCollapsed = true) {
4840 // An option can be collapsed only if it has a single input.
4841 if (Inputs.size() != 1)
4842 return nullptr;
4843
4844 Action *CurAction = *Inputs.begin();
4845 if (CanBeCollapsed &&
4847 return nullptr;
4848
4849 // If the input action is an offload action. Look through it and save any
4850 // offload action that can be dropped in the event of a collapse.
4851 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
4852 // If the dependent action is a device action, we will attempt to collapse
4853 // only with other device actions. Otherwise, we would do the same but
4854 // with host actions only.
4855 if (!IsHostSelector) {
4856 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
4857 CurAction =
4858 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
4859 if (CanBeCollapsed &&
4861 return nullptr;
4862 SavedOffloadAction.push_back(OA);
4863 return dyn_cast<JobAction>(CurAction);
4864 }
4865 } else if (OA->hasHostDependence()) {
4866 CurAction = OA->getHostDependence();
4867 if (CanBeCollapsed &&
4869 return nullptr;
4870 SavedOffloadAction.push_back(OA);
4871 return dyn_cast<JobAction>(CurAction);
4872 }
4873 return nullptr;
4874 }
4875
4876 return dyn_cast<JobAction>(CurAction);
4877 }
4878
4879 /// Return true if an assemble action can be collapsed.
4880 bool canCollapseAssembleAction() const {
4881 return TC.useIntegratedAs() && !SaveTemps &&
4882 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
4883 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
4884 !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
4885 !C.getArgs().hasArg(options::OPT_dxc_Fc);
4886 }
4887
4888 /// Return true if a preprocessor action can be collapsed.
4889 bool canCollapsePreprocessorAction() const {
4890 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
4891 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
4892 !C.getArgs().hasArg(options::OPT_rewrite_objc);
4893 }
4894
4895 /// Struct that relates an action with the offload actions that would be
4896 /// collapsed with it.
4897 struct JobActionInfo final {
4898 /// The action this info refers to.
4899 const JobAction *JA = nullptr;
4900 /// The offload actions we need to take care off if this action is
4901 /// collapsed.
4902 ActionList SavedOffloadAction;
4903 };
4904
4905 /// Append collapsed offload actions from the give number of elements in the
4906 /// action info array.
4907 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
4908 ArrayRef<JobActionInfo> &ActionInfo,
4909 unsigned ElementNum) {
4910 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
4911 for (unsigned I = 0; I < ElementNum; ++I)
4912 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
4913 ActionInfo[I].SavedOffloadAction.end());
4914 }
4915
4916 /// Functions that attempt to perform the combining. They detect if that is
4917 /// legal, and if so they update the inputs \a Inputs and the offload action
4918 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
4919 /// the combined action is returned. If the combining is not legal or if the
4920 /// tool does not exist, null is returned.
4921 /// Currently three kinds of collapsing are supported:
4922 /// - Assemble + Backend + Compile;
4923 /// - Assemble + Backend ;
4924 /// - Backend + Compile.
4925 const Tool *
4926 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4927 ActionList &Inputs,
4928 ActionList &CollapsedOffloadAction) {
4929 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
4930 return nullptr;
4931 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4932 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4933 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
4934 if (!AJ || !BJ || !CJ)
4935 return nullptr;
4936
4937 // Get compiler tool.
4938 const Tool *T = TC.SelectTool(*CJ);
4939 if (!T)
4940 return nullptr;
4941
4942 // Can't collapse if we don't have codegen support unless we are
4943 // emitting LLVM IR.
4944 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
4945 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
4946 return nullptr;
4947
4948 // When using -fembed-bitcode, it is required to have the same tool (clang)
4949 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
4950 if (EmbedBitcode) {
4951 const Tool *BT = TC.SelectTool(*BJ);
4952 if (BT == T)
4953 return nullptr;
4954 }
4955
4956 if (!T->hasIntegratedAssembler())
4957 return nullptr;
4958
4959 Inputs = CJ->getInputs();
4960 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4961 /*NumElements=*/3);
4962 return T;
4963 }
4964 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4965 ActionList &Inputs,
4966 ActionList &CollapsedOffloadAction) {
4967 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4968 return nullptr;
4969 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4970 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4971 if (!AJ || !BJ)
4972 return nullptr;
4973
4974 // Get backend tool.
4975 const Tool *T = TC.SelectTool(*BJ);
4976 if (!T)
4977 return nullptr;
4978
4979 if (!T->hasIntegratedAssembler())
4980 return nullptr;
4981
4982 Inputs = BJ->getInputs();
4983 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4984 /*NumElements=*/2);
4985 return T;
4986 }
4987 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4988 ActionList &Inputs,
4989 ActionList &CollapsedOffloadAction) {
4990 if (ActionInfo.size() < 2)
4991 return nullptr;
4992 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4993 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4994 if (!BJ || !CJ)
4995 return nullptr;
4996
4997 auto HasBitcodeInput = [](const JobActionInfo &AI) {
4998 for (auto &Input : AI.JA->getInputs())
4999 if (!types::isLLVMIR(Input->getType()))
5000 return false;
5001 return true;
5002 };
5003
5004 // Check if the initial input (to the compile job or its predessor if one
5005 // exists) is LLVM bitcode. In that case, no preprocessor step is required
5006 // and we can still collapse the compile and backend jobs when we have
5007 // -save-temps. I.e. there is no need for a separate compile job just to
5008 // emit unoptimized bitcode.
5009 bool InputIsBitcode = all_of(ActionInfo, HasBitcodeInput);
5010 if (SaveTemps && !InputIsBitcode)
5011 return nullptr;
5012
5013 // Get compiler tool.
5014 const Tool *T = TC.SelectTool(*CJ);
5015 if (!T)
5016 return nullptr;
5017
5018 // Can't collapse if we don't have codegen support unless we are
5019 // emitting LLVM IR.
5020 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
5021 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
5022 return nullptr;
5023
5024 if (T->canEmitIR() && EmbedBitcode)
5025 return nullptr;
5026
5027 Inputs = CJ->getInputs();
5028 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5029 /*NumElements=*/2);
5030 return T;
5031 }
5032
5033 /// Updates the inputs if the obtained tool supports combining with
5034 /// preprocessor action, and the current input is indeed a preprocessor
5035 /// action. If combining results in the collapse of offloading actions, those
5036 /// are appended to \a CollapsedOffloadAction.
5037 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
5038 ActionList &CollapsedOffloadAction) {
5039 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
5040 return;
5041
5042 // Attempt to get a preprocessor action dependence.
5043 ActionList PreprocessJobOffloadActions;
5044 ActionList NewInputs;
5045 for (Action *A : Inputs) {
5046 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
5047 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
5048 NewInputs.push_back(A);
5049 continue;
5050 }
5051
5052 // This is legal to combine. Append any offload action we found and add the
5053 // current input to preprocessor inputs.
5054 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
5055 PreprocessJobOffloadActions.end());
5056 NewInputs.append(PJ->input_begin(), PJ->input_end());
5057 }
5058 Inputs = NewInputs;
5059 }
5060
5061public:
5062 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
5063 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
5064 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
5066 assert(BaseAction && "Invalid base action.");
5067 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
5068 }
5069
5070 /// Check if a chain of actions can be combined and return the tool that can
5071 /// handle the combination of actions. The pointer to the current inputs \a
5072 /// Inputs and the list of offload actions \a CollapsedOffloadActions
5073 /// connected to collapsed actions are updated accordingly. The latter enables
5074 /// the caller of the selector to process them afterwards instead of just
5075 /// dropping them. If no suitable tool is found, null will be returned.
5076 const Tool *getTool(ActionList &Inputs,
5077 ActionList &CollapsedOffloadAction) {
5078 //
5079 // Get the largest chain of actions that we could combine.
5080 //
5081
5082 SmallVector<JobActionInfo, 5> ActionChain(1);
5083 ActionChain.back().JA = BaseAction;
5084 while (ActionChain.back().JA) {
5085 const Action *CurAction = ActionChain.back().JA;
5086
5087 // Grow the chain by one element.
5088 ActionChain.resize(ActionChain.size() + 1);
5089 JobActionInfo &AI = ActionChain.back();
5090
5091 // Attempt to fill it with the
5092 AI.JA =
5093 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
5094 }
5095
5096 // Pop the last action info as it could not be filled.
5097 ActionChain.pop_back();
5098
5099 //
5100 // Attempt to combine actions. If all combining attempts failed, just return
5101 // the tool of the provided action. At the end we attempt to combine the
5102 // action with any preprocessor action it may depend on.
5103 //
5104
5105 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
5106 CollapsedOffloadAction);
5107 if (!T)
5108 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
5109 if (!T)
5110 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
5111 if (!T) {
5112 Inputs = BaseAction->getInputs();
5113 T = TC.SelectTool(*BaseAction);
5114 }
5115
5116 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
5117 return T;
5118 }
5119};
5120}
5121
5122/// Return a string that uniquely identifies the result of a job. The bound arch
5123/// is not necessarily represented in the toolchain's triple -- for example,
5124/// armv7 and armv7s both map to the same triple -- so we need both in our map.
5125/// Also, we need to add the offloading device kind, as the same tool chain can
5126/// be used for host and device for some programming models, e.g. OpenMP.
5127static std::string GetTriplePlusArchString(const ToolChain *TC, BoundArch BA,
5128 Action::OffloadKind OffloadKind) {
5129 std::string TriplePlusArch = TC->getTriple().normalize();
5130 if (!BA.empty()) {
5131 TriplePlusArch += "-";
5132 TriplePlusArch += BA.ArchName;
5133 }
5134 TriplePlusArch += "-";
5135 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
5136 return TriplePlusArch;
5137}
5138
5140 Compilation &C, const Action *A, const ToolChain *TC, BoundArch BA,
5141 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5142 std::map<std::pair<const Action *, std::string>, InputInfoList>
5143 &CachedResults,
5144 Action::OffloadKind TargetDeviceOffloadKind) const {
5145 std::pair<const Action *, std::string> ActionTC = {
5146 A, GetTriplePlusArchString(TC, BA, TargetDeviceOffloadKind)};
5147 auto CachedResult = CachedResults.find(ActionTC);
5148 if (CachedResult != CachedResults.end()) {
5149 return CachedResult->second;
5150 }
5151 InputInfoList Result = BuildJobsForActionNoCache(
5152 C, A, TC, BA, AtTopLevel, MultipleArchs, LinkingOutput, CachedResults,
5153 TargetDeviceOffloadKind);
5154 CachedResults[ActionTC] = Result;
5155 return Result;
5156}
5157
5158static void handleTimeTrace(Compilation &C, const ArgList &Args,
5159 const JobAction *JA, const char *BaseInput,
5160 const InputInfo &Result) {
5161 Arg *A =
5162 Args.getLastArg(options::OPT_ftime_trace, options::OPT_ftime_trace_EQ);
5163 if (!A)
5164 return;
5165
5166 SmallString<64> OffloadingPrefix;
5168 const ToolChain *TC = JA->getOffloadingToolChain();
5169 OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5170 JA->getOffloadingDeviceKind(), TC ? TC->getEffectiveTriple().str() : "",
5171 /*CreatePrefixForHost=*/false);
5173 if (!Arch.empty()) {
5174 OffloadingPrefix += "-";
5175 OffloadingPrefix += Arch.ArchName;
5176 }
5177 } else if (JA->getOffloadingHostActiveKinds() != Action::OFK_None &&
5178 C.getDriver().isSaveTempsEnabled()) {
5179 OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5180 Action::OFK_None, C.getDefaultToolChain().getTripleString(),
5181 /*CreatePrefixForHost=*/true);
5182 }
5183
5184 SmallString<128> Path;
5185 if (A->getOption().matches(options::OPT_ftime_trace_EQ)) {
5186 Path = A->getValue();
5187 if (llvm::sys::fs::is_directory(Path)) {
5188 SmallString<128> Tmp(OffloadingPrefix.empty()
5189 ? llvm::sys::path::stem(Result.getFilename())
5190 : llvm::sys::path::stem(BaseInput));
5191 Tmp += OffloadingPrefix;
5192 Tmp += ".json";
5193 llvm::sys::path::append(Path, Tmp);
5194 }
5195 } else {
5196 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
5197 // The trace file is ${dumpdir}${basename}${offloadprefix}.json. Note
5198 // that dumpdir may not end with a path separator.
5199 Path = DumpDir->getValue();
5200 Path += llvm::sys::path::stem(BaseInput);
5201 Path += OffloadingPrefix;
5202 Path += ".json";
5203 } else if (!OffloadingPrefix.empty()) {
5204 // For offloading, derive path from -o output directory combined with
5205 // the input filename and offload prefix.
5206 SmallString<128> TraceName(llvm::sys::path::stem(BaseInput));
5207 TraceName += OffloadingPrefix;
5208 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5209 Path = llvm::sys::path::parent_path(FinalOutput->getValue());
5210 llvm::sys::path::append(Path, TraceName);
5211 Path += ".json";
5212 } else {
5213 Path = Result.getFilename();
5214 llvm::sys::path::replace_extension(Path, "json");
5215 }
5216 }
5217 const char *ResultFile = C.getArgs().MakeArgString(Path);
5218 C.addTimeTraceFile(ResultFile, JA);
5219 C.addResultFile(ResultFile, JA);
5220}
5221
5222InputInfoList Driver::BuildJobsForActionNoCache(
5223 Compilation &C, const Action *A, const ToolChain *TC, BoundArch BA,
5224 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5225 std::map<std::pair<const Action *, std::string>, InputInfoList>
5226 &CachedResults,
5227 Action::OffloadKind TargetDeviceOffloadKind) const {
5228 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
5229
5230 // Track the bound arch for commands constructed in this scope so
5231 // generateCompilationDiagnostics can identify the crashing arch.
5232 BoundArch SavedBoundArch = C.getCurrentBoundArch();
5233 C.setCurrentBoundArch(BA);
5234 auto RestoreBoundArch =
5235 llvm::scope_exit([&] { C.setCurrentBoundArch(SavedBoundArch); });
5236
5237 InputInfoList OffloadDependencesInputInfo;
5238 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
5239 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
5240 // The 'Darwin' toolchain is initialized only when its arguments are
5241 // computed. Get the default arguments for OFK_None to ensure that
5242 // initialization is performed before processing the offload action.
5243 // FIXME: Remove when darwin's toolchain is initialized during construction.
5244 C.getArgsForToolChain(TC, BA, Action::OFK_Host);
5245
5246 // The offload action is expected to be used in four different situations.
5247 //
5248 // a) Set a toolchain/architecture/kind for a host action:
5249 // Host Action 1 -> OffloadAction -> Host Action 2
5250 //
5251 // b) Set a toolchain/architecture/kind for a device action;
5252 // Device Action 1 -> OffloadAction -> Device Action 2
5253 //
5254 // c) Specify a device dependence to a host action;
5255 // Device Action 1 _
5256 // \
5257 // Host Action 1 ---> OffloadAction -> Host Action 2
5258 //
5259 // d) Specify a host dependence to a device action.
5260 // Host Action 1 _
5261 // \
5262 // Device Action 1 ---> OffloadAction -> Device Action 2
5263 //
5264 // For a) and b), we just return the job generated for the dependences. For
5265 // c) and d) we override the current action with the host/device dependence
5266 // if the current toolchain is host/device and set the offload dependences
5267 // info with the jobs obtained from the device/host dependence(s).
5268
5269 // If there is a single device option or has no host action, just generate
5270 // the job for it.
5271 if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
5272 InputInfoList DevA;
5273 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
5274 BoundArch DepBoundArch) {
5275 DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
5276 /*MultipleArchs=*/!DepBoundArch.empty(),
5277 LinkingOutput, CachedResults,
5278 DepA->getOffloadingDeviceKind()));
5279 });
5280 return DevA;
5281 }
5282
5283 // If 'Action 2' is host, we generate jobs for the device dependences and
5284 // override the current action with the host dependence. Otherwise, we
5285 // generate the host dependences and override the action with the device
5286 // dependence. The dependences can't therefore be a top-level action.
5287 OA->doOnEachDependence(
5288 /*IsHostDependence=*/BuildingForOffloadDevice,
5289 [&](Action *DepA, const ToolChain *DepTC, BoundArch DepBoundArch) {
5290 OffloadDependencesInputInfo.append(BuildJobsForAction(
5291 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
5292 /*MultipleArchs=*/!DepBoundArch.empty(), LinkingOutput,
5293 CachedResults, DepA->getOffloadingDeviceKind()));
5294 });
5295
5296 A = BuildingForOffloadDevice
5297 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
5298 : OA->getHostDependence();
5299
5300 // We may have already built this action as a part of the offloading
5301 // toolchain, return the cached input if so.
5302 std::pair<const Action *, std::string> ActionTC = {
5303 OA->getHostDependence(),
5304 GetTriplePlusArchString(TC, BA, TargetDeviceOffloadKind)};
5305 auto It = CachedResults.find(ActionTC);
5306 if (It != CachedResults.end()) {
5307 InputInfoList Inputs = It->second;
5308 Inputs.append(OffloadDependencesInputInfo);
5309 return Inputs;
5310 }
5311 }
5312
5313 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
5314 // FIXME: It would be nice to not claim this here; maybe the old scheme of
5315 // just using Args was better?
5316 const Arg &Input = IA->getInputArg();
5317 Input.claim();
5318 if (Input.getOption().matches(options::OPT_INPUT)) {
5319 const char *Name = Input.getValue();
5320 return {InputInfo(A, Name, /* _BaseInput = */ Name)};
5321 }
5322 return {InputInfo(A, &Input, /* _BaseInput = */ "")};
5323 }
5324
5325 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
5326 const ToolChain *TC;
5327 BoundArch ArchName = BAA->getArch();
5328
5329 if (!ArchName.empty())
5330 TC = &getToolChain(C.getArgs(),
5331 computeTargetTriple(*this, TargetTriple, C.getArgs(),
5332 ArchName.ArchName));
5333 else
5334 TC = &C.getDefaultToolChain();
5335
5336 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
5337 MultipleArchs, LinkingOutput, CachedResults,
5338 TargetDeviceOffloadKind);
5339 }
5340
5341
5342 ActionList Inputs = A->getInputs();
5343
5344 const JobAction *JA = cast<JobAction>(A);
5345 ActionList CollapsedOffloadActions;
5346
5347 ToolSelector TS(
5348 JA, *TC, C, isSaveTempsEnabled(),
5350 !TC->isUsingLTO(C.getArgs(), JA->getOffloadingDeviceKind()));
5351 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
5352
5353 if (!T)
5354 return {InputInfo()};
5355
5356 // If we've collapsed action list that contained OffloadAction we
5357 // need to build jobs for host/device-side inputs it may have held.
5358 for (const auto *OA : CollapsedOffloadActions)
5359 cast<OffloadAction>(OA)->doOnEachDependence(
5360 /*IsHostDependence=*/BuildingForOffloadDevice,
5361 [&](Action *DepA, const ToolChain *DepTC, BoundArch DepBoundArch) {
5362 OffloadDependencesInputInfo.append(BuildJobsForAction(
5363 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
5364 /*MultipleArchs=*/!DepBoundArch.empty(), LinkingOutput,
5365 CachedResults, DepA->getOffloadingDeviceKind()));
5366 });
5367
5368 // Only use pipes when there is exactly one input.
5369 InputInfoList InputInfos;
5370 for (const Action *Input : Inputs) {
5371 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
5372 // shouldn't get temporary output names.
5373 // FIXME: Clean this up.
5374 bool SubJobAtTopLevel =
5375 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
5376 InputInfos.append(BuildJobsForAction(
5377 C, Input, TC, BA, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
5378 CachedResults, A->getOffloadingDeviceKind()));
5379 }
5380
5381 // Always use the first file input as the base input.
5382 const char *BaseInput = InputInfos[0].getBaseInput();
5383 for (auto &Info : InputInfos) {
5384 if (Info.isFilename()) {
5385 BaseInput = Info.getBaseInput();
5386 break;
5387 }
5388 }
5389
5390 // ... except dsymutil actions, which use their actual input as the base
5391 // input.
5392 if (JA->getType() == types::TY_dSYM)
5393 BaseInput = InputInfos[0].getFilename();
5394
5395 // Append outputs of offload device jobs to the input list
5396 if (!OffloadDependencesInputInfo.empty())
5397 InputInfos.append(OffloadDependencesInputInfo.begin(),
5398 OffloadDependencesInputInfo.end());
5399
5400 // Set the effective triple of the toolchain for the duration of this job.
5401 llvm::Triple EffectiveTriple;
5402 const ToolChain &ToolTC = T->getToolChain();
5403 const ArgList &Args =
5404 C.getArgsForToolChain(TC, BA, A->getOffloadingDeviceKind());
5405 if (InputInfos.size() != 1) {
5406 EffectiveTriple =
5407 llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args, BA));
5408 } else {
5409 // Pass along the input type if it can be unambiguously determined.
5410 EffectiveTriple = llvm::Triple(
5411 ToolTC.ComputeEffectiveClangTriple(Args, BA, InputInfos[0].getType()));
5412 }
5413 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
5414
5415 // Determine the place to write output to, if any.
5416 InputInfo Result;
5417 if (JA->getType() == types::TY_Nothing)
5418 Result = {InputInfo(A, BaseInput)};
5419 else {
5420 // We only have to generate a prefix for the host if this is not a top-level
5421 // action.
5422 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5423 A->getOffloadingDeviceKind(), EffectiveTriple.str(),
5424 /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) ||
5426 AtTopLevel));
5427 Result = InputInfo(A,
5428 GetNamedOutputPath(C, *JA, BaseInput, BA, AtTopLevel,
5429 MultipleArchs, OffloadingPrefix),
5430 BaseInput);
5431 if (T->canEmitIR())
5432 handleTimeTrace(C, Args, JA, BaseInput, Result);
5433 }
5434
5436 llvm::errs() << "# \"" << T->getToolChain().getEffectiveTriple().str()
5437 << '"' << " - \"" << T->getName() << "\", inputs: [";
5438 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
5439 llvm::errs() << InputInfos[i].getAsString();
5440 if (i + 1 != e)
5441 llvm::errs() << ", ";
5442 }
5443 llvm::errs() << "], output: " << Result.getAsString() << "\n";
5444 } else {
5445 T->ConstructJob(C, *JA, Result, InputInfos, Args, LinkingOutput);
5446 }
5447 return {Result};
5448}
5449
5450const char *Driver::getDefaultImageName() const {
5451 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
5452 return Target.isOSWindows() ? "a.exe" : "a.out";
5453}
5454
5455/// Create output filename based on ArgValue, which could either be a
5456/// full filename, filename without extension, or a directory. If ArgValue
5457/// does not provide a filename, then use BaseName, and use the extension
5458/// suitable for FileType.
5459static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
5460 StringRef BaseName,
5462 SmallString<128> Filename = ArgValue;
5463
5464 if (ArgValue.empty()) {
5465 // If the argument is empty, output to BaseName in the current dir.
5466 Filename = BaseName;
5467 } else if (llvm::sys::path::is_separator(Filename.back())) {
5468 // If the argument is a directory, output to BaseName in that dir.
5469 llvm::sys::path::append(Filename, BaseName);
5470 }
5471
5472 if (!llvm::sys::path::has_extension(ArgValue)) {
5473 // If the argument didn't provide an extension, then set it.
5474 const char *Extension = types::getTypeTempSuffix(FileType, true);
5475
5476 if (FileType == types::TY_Image &&
5477 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
5478 // The output file is a dll.
5479 Extension = "dll";
5480 }
5481
5482 llvm::sys::path::replace_extension(Filename, Extension);
5483 }
5484
5485 return Args.MakeArgString(Filename.c_str());
5486}
5487
5488static bool HasPreprocessOutput(const Action &JA) {
5490 return true;
5492 return true;
5494 HasPreprocessOutput(*(JA.getInputs()[0])))
5495 return true;
5496 return false;
5497}
5498
5499const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix,
5500 StringRef Suffix, bool MultipleArchs,
5501 StringRef BoundArchStr,
5502 bool NeedUniqueDirectory) const {
5503 SmallString<128> TmpName;
5504 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
5505 std::optional<std::string> CrashDirectory =
5506 CCGenDiagnostics && A
5507 ? std::string(A->getValue())
5508 : llvm::sys::Process::GetEnv("CLANG_CRASH_DIAGNOSTICS_DIR");
5509 if (CrashDirectory) {
5510 if (!getVFS().exists(*CrashDirectory))
5511 llvm::sys::fs::create_directories(*CrashDirectory);
5512 SmallString<128> Path(*CrashDirectory);
5513 llvm::sys::path::append(Path, Prefix);
5514 const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%";
5515 if (std::error_code EC =
5516 llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) {
5517 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5518 return "";
5519 }
5520 } else {
5521 if (MultipleArchs && !BoundArchStr.empty()) {
5522 if (NeedUniqueDirectory) {
5523 TmpName = GetTemporaryDirectory(Prefix);
5524 llvm::sys::path::append(TmpName, Twine(Prefix) + "-" + BoundArchStr +
5525 "." + Suffix);
5526 } else {
5527 TmpName = GetTemporaryPath((Twine(Prefix) + "-" + BoundArchStr).str(),
5528 Suffix);
5529 }
5530
5531 } else {
5532 TmpName = GetTemporaryPath(Prefix, Suffix);
5533 }
5534 }
5535 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5536}
5537
5538// Calculate the output path of the module file when compiling a module unit
5539// with the `-fmodule-output` option or `-fmodule-output=` option specified.
5540// The behavior is:
5541// - If `-fmodule-output=` is specfied, then the module file is
5542// writing to the value.
5543// - Otherwise if the output object file of the module unit is specified, the
5544// output path
5545// of the module file should be the same with the output object file except
5546// the corresponding suffix. This requires both `-o` and `-c` are specified.
5547// - Otherwise, the output path of the module file will be the same with the
5548// input with the corresponding suffix.
5549static const char *GetModuleOutputPath(Compilation &C, const JobAction &JA,
5550 const char *BaseInput) {
5551 assert(isa<PrecompileJobAction>(JA) && JA.getType() == types::TY_ModuleFile &&
5552 (C.getArgs().hasArg(options::OPT_fmodule_output) ||
5553 C.getArgs().hasArg(options::OPT_fmodule_output_EQ)));
5554
5555 SmallString<256> OutputPath =
5556 tools::getCXX20NamedModuleOutputPath(C.getArgs(), BaseInput);
5557
5558 return C.addResultFile(C.getArgs().MakeArgString(OutputPath.c_str()), &JA);
5559}
5560
5562 const char *BaseInput, BoundArch BA,
5563 bool AtTopLevel, bool MultipleArchs,
5564 StringRef OffloadingPrefix) const {
5565 std::string BoundArchStr = sanitizeTargetIDInFileName(BA.ArchName);
5566
5567 llvm::PrettyStackTraceString CrashInfo("Computing output path");
5568
5569 auto CreateTempOutputPath = [&](StringRef Prefix) {
5570 const char *Suffix =
5572 // The non-offloading toolchain on Darwin requires deterministic input
5573 // file name for binaries to be deterministic, therefore it needs unique
5574 // directory.
5575 const llvm::Triple Triple(C.getDriver().getTargetTriple());
5576 const bool NeedUniqueDirectory =
5579 Triple.isOSDarwin();
5580 return CreateTempFile(C, Prefix, Suffix, MultipleArchs, BoundArchStr,
5581 NeedUniqueDirectory);
5582 };
5583
5584 // Standard library output in -fmodules-driver?
5585 if (isa<PrecompileJobAction>(JA) && !JA.getInputs().empty() &&
5586 (JA.getInputs().front()->getType() == types::TY_CXXStdModule ||
5587 JA.getInputs().front()->getType() == types::TY_PP_CXXStdModule)) {
5588 StringRef Filename = llvm::sys::path::filename(BaseInput);
5589 StringRef Stem = llvm::sys::path::stem(Filename);
5590 return CreateTempOutputPath(Stem);
5591 }
5592
5593 // Output to a user requested destination?
5594 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
5595 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
5596 return C.addResultFile(FinalOutput->getValue(), &JA);
5597 }
5598
5599 // For /P, preprocess to file named after BaseInput.
5600 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
5601 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
5602 StringRef BaseName = llvm::sys::path::filename(BaseInput);
5603 StringRef NameArg;
5604 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
5605 NameArg = A->getValue();
5606 return C.addResultFile(
5607 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
5608 &JA);
5609 }
5610
5611 // Default to writing to stdout?
5612 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
5613 return "-";
5614 }
5615
5616 if (JA.getType() == types::TY_ModuleFile &&
5617 C.getArgs().getLastArg(options::OPT_module_file_info)) {
5618 return "-";
5619 }
5620
5621 if (JA.getType() == types::TY_PP_Asm &&
5622 C.getArgs().hasArg(options::OPT_dxc_Fc)) {
5623 StringRef FcValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fc);
5624 // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably
5625 // handle this as part of the SLASH_Fa handling below.
5626 return C.addResultFile(C.getArgs().MakeArgString(FcValue), &JA);
5627 }
5628
5629 if ((JA.getType() == types::TY_Object &&
5630 C.getArgs().hasArg(options::OPT_dxc_Fo)) ||
5631 JA.getType() == types::TY_DX_CONTAINER) {
5632 StringRef FoValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fo);
5633 assert((C.getDefaultToolChain().getTriple().isDXIL() ||
5634 C.getDefaultToolChain().getTriple().isSPIRV()) &&
5635 "expected DXIL or SPIR-V triple for HLSL output path");
5636 const auto &TC =
5637 static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain());
5638 // Fo can be empty here if the validator is running for a compiler flow
5639 // that is using Fc or just printing disassembly.
5640 if (TC.isLastOutputProducingJob(C.getArgs(), JA.getKind()) &&
5641 !FoValue.empty())
5642 return C.addResultFile(C.getArgs().MakeArgString(FoValue), &JA);
5643 StringRef Name = llvm::sys::path::filename(BaseInput);
5644 std::pair<StringRef, StringRef> Split = Name.split('.');
5645 const char *Suffix = types::getTypeTempSuffix(JA.getType(), true);
5646 return CreateTempFile(C, Split.first, Suffix, false);
5647 }
5648
5649 // Is this the assembly listing for /FA?
5650 if (JA.getType() == types::TY_PP_Asm &&
5651 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
5652 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
5653 // Use /Fa and the input filename to determine the asm file name.
5654 StringRef BaseName = llvm::sys::path::filename(BaseInput);
5655 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
5656 return C.addResultFile(
5657 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
5658 &JA);
5659 }
5660
5661 if (JA.getType() == types::TY_API_INFO &&
5662 C.getArgs().hasArg(options::OPT_emit_extension_symbol_graphs) &&
5663 C.getArgs().hasArg(options::OPT_o))
5664 Diag(clang::diag::err_drv_unexpected_symbol_graph_output)
5665 << C.getArgs().getLastArgValue(options::OPT_o);
5666
5667 // DXC defaults to standard out when generating assembly. We check this after
5668 // any DXC flags that might specify a file.
5669 if (AtTopLevel && JA.getType() == types::TY_PP_Asm && IsDXCMode())
5670 return "-";
5671
5672 bool SpecifiedModuleOutput =
5673 C.getArgs().hasArg(options::OPT_fmodule_output) ||
5674 C.getArgs().hasArg(options::OPT_fmodule_output_EQ);
5675 if (MultipleArchs && SpecifiedModuleOutput)
5676 Diag(clang::diag::err_drv_module_output_with_multiple_arch);
5677
5678 // If we're emitting a module output with the specified option
5679 // `-fmodule-output`.
5680 if (!AtTopLevel && isa<PrecompileJobAction>(JA) &&
5681 JA.getType() == types::TY_ModuleFile && SpecifiedModuleOutput) {
5682 assert(C.getArgs().hasArg(options::OPT_fno_modules_reduced_bmi));
5683 return GetModuleOutputPath(C, JA, BaseInput);
5684 }
5685
5686 // Output to a temporary file?
5687 if ((!AtTopLevel && !isSaveTempsEnabled() &&
5688 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
5690 StringRef Name = llvm::sys::path::filename(BaseInput);
5691 return CreateTempOutputPath(Name.split('.').first);
5692 }
5693
5694 SmallString<128> BasePath(BaseInput);
5695 SmallString<128> ExternalPath("");
5696 StringRef BaseName;
5697
5698 // Dsymutil actions should use the full path.
5699 if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) {
5700 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
5701 // We use posix style here because the tests (specifically
5702 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
5703 // even on Windows and if we don't then the similar test covering this
5704 // fails.
5705 llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
5706 llvm::sys::path::filename(BasePath));
5707 BaseName = ExternalPath;
5708 } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
5709 BaseName = BasePath;
5710 else
5711 BaseName = llvm::sys::path::filename(BasePath);
5712
5713 // Determine what the derived output name should be.
5714 const char *NamedOutput;
5715
5716 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC ||
5717 JA.getType() == types::TY_LLVM_BC ||
5718 JA.getType() == types::TY_LLVM_IR) &&
5719 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
5720 // The /Fo or /o flag decides the object filename.
5721 StringRef Val =
5722 C.getArgs()
5723 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
5724 ->getValue();
5725 NamedOutput =
5726 MakeCLOutputFilename(C.getArgs(), Val, BaseName, JA.getType());
5727 } else if (JA.getType() == types::TY_Image &&
5728 C.getArgs().hasArg(options::OPT__SLASH_Fe,
5729 options::OPT__SLASH_o)) {
5730 // The /Fe or /o flag names the linked file.
5731 StringRef Val =
5732 C.getArgs()
5733 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
5734 ->getValue();
5735 NamedOutput =
5736 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
5737 } else if (JA.getType() == types::TY_Image) {
5738 if (IsCLMode()) {
5739 // clang-cl uses BaseName for the executable name.
5740 NamedOutput =
5741 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
5742 } else {
5744 // HIP image for device compilation with -fno-gpu-rdc is per compilation
5745 // unit.
5746 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5747 !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
5748 options::OPT_fno_gpu_rdc, false);
5749 bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(JA);
5750 if (UseOutExtension) {
5751 Output = BaseName;
5752 llvm::sys::path::replace_extension(Output, "");
5753 }
5754 Output += OffloadingPrefix;
5755 if (MultipleArchs && !BoundArchStr.empty()) {
5756 Output += "-";
5757 Output.append(BoundArchStr);
5758 }
5759 if (UseOutExtension)
5760 Output += ".out";
5761 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
5762 }
5763 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
5764 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
5765 } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) &&
5766 C.getArgs().hasArg(options::OPT__SLASH_o)) {
5767 StringRef Val =
5768 C.getArgs()
5769 .getLastArg(options::OPT__SLASH_o)
5770 ->getValue();
5771 NamedOutput =
5772 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5773 } else {
5774 const char *Suffix =
5776 assert(Suffix && "All types used for output should have a suffix.");
5777
5778 std::string::size_type End = std::string::npos;
5780 End = BaseName.rfind('.');
5781 SmallString<128> Suffixed(BaseName.substr(0, End));
5782 Suffixed += OffloadingPrefix;
5783 if (MultipleArchs && !BoundArchStr.empty()) {
5784 Suffixed += "-";
5785 Suffixed.append(BoundArchStr);
5786 }
5787 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
5788 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
5789 // optimized bitcode output.
5790 auto IsAMDRDCInCompilePhase = [](const JobAction &JA,
5791 const llvm::opt::DerivedArgList &Args) {
5792 // The relocatable compilation in HIP and OpenMP implies -emit-llvm.
5793 // Similarly, use a ".tmp.bc" suffix for the unoptimized bitcode
5794 // (generated in the compile phase.)
5795 const ToolChain *TC = JA.getOffloadingToolChain();
5796 return isa<CompileJobAction>(JA) &&
5799 TC->getTriple().isAMDGPU()));
5800 };
5801
5802 // The linker wrapper may not support the input and output files to be the
5803 // same one, and without it -save-temps can fail.
5804 bool IsLinkerWrapper =
5805 JA.getType() == types::TY_Object && isa<LinkerWrapperJobAction>(JA);
5806 bool IsEmitBitcode = JA.getType() == types::TY_LLVM_BC &&
5807 (C.getArgs().hasArg(options::OPT_emit_llvm) ||
5808 IsAMDRDCInCompilePhase(JA, C.getArgs()));
5809
5810 if (!AtTopLevel && (IsLinkerWrapper || IsEmitBitcode))
5811 Suffixed += ".tmp";
5812 Suffixed += '.';
5813 Suffixed += Suffix;
5814 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
5815 }
5816
5817 // Prepend object file path if -save-temps=obj
5818 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
5819 JA.getType() != types::TY_PCH) {
5820 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
5821 SmallString<128> TempPath(FinalOutput->getValue());
5822 llvm::sys::path::remove_filename(TempPath);
5823 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
5824 llvm::sys::path::append(TempPath, OutputFileName);
5825 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
5826 }
5827
5828 // If we're saving temps and the temp file conflicts with the input file,
5829 // then avoid overwriting input file.
5830 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
5831 bool SameFile = false;
5833 llvm::sys::fs::current_path(Result);
5834 llvm::sys::path::append(Result, BaseName);
5835 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
5836 // Must share the same path to conflict.
5837 if (SameFile) {
5838 StringRef Name = llvm::sys::path::filename(BaseInput);
5839 std::pair<StringRef, StringRef> Split = Name.split('.');
5840 std::string TmpName = GetTemporaryPath(
5841 Split.first,
5843 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5844 }
5845 }
5846
5847 // As an annoying special case, PCH generation doesn't strip the pathname.
5848 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
5849 llvm::sys::path::remove_filename(BasePath);
5850 if (BasePath.empty())
5851 BasePath = NamedOutput;
5852 else
5853 llvm::sys::path::append(BasePath, NamedOutput);
5854 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
5855 }
5856
5857 return C.addResultFile(NamedOutput, &JA);
5858}
5859
5860std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
5861 // Search for Name in a list of paths.
5862 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
5863 -> std::optional<std::string> {
5864 // Respect a limited subset of the '-Bprefix' functionality in GCC by
5865 // attempting to use this prefix when looking for file paths.
5866 for (const auto &Dir : P) {
5867 if (Dir.empty())
5868 continue;
5869 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
5870 llvm::sys::path::append(P, Name);
5871 if (llvm::sys::fs::exists(Twine(P)))
5872 return std::string(P);
5873 }
5874 return std::nullopt;
5875 };
5876
5877 if (auto P = SearchPaths(PrefixDirs))
5878 return *P;
5879
5881 llvm::sys::path::append(R, Name);
5882 if (llvm::sys::fs::exists(Twine(R)))
5883 return std::string(R);
5884
5886 llvm::sys::path::append(P, Name);
5887 if (llvm::sys::fs::exists(Twine(P)))
5888 return std::string(P);
5889
5890 // With Flang, also look for intrinsic modules
5891 if (IsFlangMode()) {
5892 if (std::optional<std::string> IntrPath =
5894 SmallString<128> P(*IntrPath);
5895 llvm::sys::path::append(P, Name);
5896 if (llvm::sys::fs::exists(P))
5897 return std::string(P);
5898 }
5899 }
5900
5902 llvm::sys::path::append(D, "..", Name);
5903 if (llvm::sys::fs::exists(Twine(D)))
5904 return std::string(D);
5905
5906 if (auto P = SearchPaths(TC.getLibraryPaths()))
5907 return *P;
5908
5909 if (auto P = SearchPaths(TC.getFilePaths()))
5910 return *P;
5911
5913 llvm::sys::path::append(R2, "..", "..", Name);
5914 if (llvm::sys::fs::exists(Twine(R2)))
5915 return std::string(R2);
5916
5917 return std::string(Name);
5918}
5919
5920void Driver::generatePrefixedToolNames(
5921 StringRef Tool, const ToolChain &TC,
5922 SmallVectorImpl<std::string> &Names) const {
5923 // FIXME: Needs a better variable than TargetTriple
5924 Names.emplace_back((TargetTriple + "-" + Tool).str());
5925 Names.emplace_back(Tool);
5926}
5927
5928static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
5929 llvm::sys::path::append(Dir, Name);
5930 if (llvm::sys::fs::can_execute(Twine(Dir)))
5931 return true;
5932 llvm::sys::path::remove_filename(Dir);
5933 return false;
5934}
5935
5936std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
5937 SmallVector<std::string, 2> TargetSpecificExecutables;
5938 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
5939
5940 // Respect a limited subset of the '-Bprefix' functionality in GCC by
5941 // attempting to use this prefix when looking for program paths.
5942 for (const auto &PrefixDir : PrefixDirs) {
5943 if (llvm::sys::fs::is_directory(PrefixDir)) {
5944 SmallString<128> P(PrefixDir);
5945 if (ScanDirForExecutable(P, Name))
5946 return std::string(P);
5947 } else {
5948 SmallString<128> P((PrefixDir + Name).str());
5949 if (llvm::sys::fs::can_execute(Twine(P)))
5950 return std::string(P);
5951 }
5952 }
5953
5954 const ToolChain::path_list &List = TC.getProgramPaths();
5955 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
5956 // For each possible name of the tool look for it in
5957 // program paths first, then the path.
5958 // Higher priority names will be first, meaning that
5959 // a higher priority name in the path will be found
5960 // instead of a lower priority name in the program path.
5961 // E.g. <triple>-gcc on the path will be found instead
5962 // of gcc in the program path
5963 for (const auto &Path : List) {
5964 SmallString<128> P(Path);
5965 if (ScanDirForExecutable(P, TargetSpecificExecutable))
5966 return std::string(P);
5967 }
5968
5969 // Fall back to the path
5970 if (llvm::ErrorOr<std::string> P =
5971 llvm::sys::findProgramByName(TargetSpecificExecutable))
5972 return *P;
5973 }
5974
5975 return std::string(Name);
5976}
5977
5979 const ToolChain &TC) const {
5980 std::string error = "<NOT PRESENT>";
5981
5982 if (C.getArgs().hasArg(options::OPT_nostdlib))
5983 return error;
5984
5985 switch (TC.GetCXXStdlibType(C.getArgs())) {
5986 case ToolChain::CST_Libcxx: {
5987 auto evaluate = [&](const char *library) -> std::optional<std::string> {
5988 std::string lib = GetFilePath(library, TC);
5989
5990 // Note when there are multiple flavours of libc++ the module json needs
5991 // to look at the command-line arguments for the proper json. These
5992 // flavours do not exist at the moment, but there are plans to provide a
5993 // variant that is built with sanitizer instrumentation enabled.
5994
5995 // For example
5996 // StringRef modules = [&] {
5997 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs(C.getArgs());
5998 // if (Sanitize.needsAsanRt())
5999 // return "libc++.modules-asan.json";
6000 // return "libc++.modules.json";
6001 // }();
6002
6003 SmallString<128> path(lib.begin(), lib.end());
6004 llvm::sys::path::remove_filename(path);
6005 llvm::sys::path::append(path, "libc++.modules.json");
6006 if (TC.getVFS().exists(path))
6007 return static_cast<std::string>(path);
6008
6009 return {};
6010 };
6011
6012 if (std::optional<std::string> result = evaluate("libc++.so"); result)
6013 return *result;
6014
6015 return evaluate("libc++.a").value_or(error);
6016 }
6017
6019 auto evaluate = [&](const char *library) -> std::optional<std::string> {
6020 std::string lib = GetFilePath(library, TC);
6021
6022 SmallString<128> path(lib.begin(), lib.end());
6023 llvm::sys::path::remove_filename(path);
6024 llvm::sys::path::append(path, "libstdc++.modules.json");
6025 if (TC.getVFS().exists(path))
6026 return static_cast<std::string>(path);
6027
6028 return {};
6029 };
6030
6031 if (std::optional<std::string> result = evaluate("libstdc++.so"); result)
6032 return *result;
6033
6034 return evaluate("libstdc++.a").value_or(error);
6035 }
6036 }
6037
6038 return error;
6039}
6040
6041std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
6042 SmallString<128> Path;
6043 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
6044 if (EC) {
6045 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
6046 return "";
6047 }
6048
6049 return std::string(Path);
6050}
6051
6052std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
6053 SmallString<128> Path;
6054 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
6055 if (EC) {
6056 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
6057 return "";
6058 }
6059
6060 return std::string(Path);
6061}
6062
6063std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
6064 SmallString<128> Output;
6065 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
6066 // FIXME: If anybody needs it, implement this obscure rule:
6067 // "If you specify a directory without a file name, the default file name
6068 // is VCx0.pch., where x is the major version of Visual C++ in use."
6069 Output = FpArg->getValue();
6070
6071 // "If you do not specify an extension as part of the path name, an
6072 // extension of .pch is assumed. "
6073 if (!llvm::sys::path::has_extension(Output))
6074 Output += ".pch";
6075 } else {
6076 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
6077 Output = YcArg->getValue();
6078 if (Output.empty())
6079 Output = BaseName;
6080 llvm::sys::path::replace_extension(Output, ".pch");
6081 }
6082 return std::string(Output);
6083}
6084
6085const ToolChain &Driver::getOffloadToolChain(
6086 const llvm::opt::ArgList &Args, const Action::OffloadKind Kind,
6087 const llvm::Triple &Target, const llvm::Triple &AuxTarget) const {
6088 std::unique_ptr<ToolChain> &TC =
6089 ToolChains[Target.str() + "/" + AuxTarget.str()];
6090 std::unique_ptr<ToolChain> &HostTC = ToolChains[AuxTarget.str()];
6091
6092 assert(HostTC && "Host toolchain for offloading doesn't exit?");
6093 if (!TC) {
6094 // Detect the toolchain based off of the target operating system.
6095 switch (Target.getOS()) {
6096 case llvm::Triple::CUDA:
6097 TC = std::make_unique<toolchains::CudaToolChain>(*this, Target, *HostTC,
6098 Args);
6099 break;
6100 case llvm::Triple::AMDHSA:
6101 // For AMDHSA offloading (HIP, OpenMP), use the unified AMDGPUToolChain
6102 // This handles both amdgpu-amd-amdhsa and spirv64-amd-amdhsa
6103 // FIXME: This should not key off language or OS.
6104 if (Kind == Action::OFK_HIP || Kind == Action::OFK_OpenMP ||
6105 Kind == Action::OFK_Cuda)
6106 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args,
6107 HostTC.get(), Kind);
6108 break;
6109 default:
6110 break;
6111 }
6112 }
6113 if (!TC) {
6114 // Detect the toolchain based off of the target architecture if that failed.
6115 switch (Target.getArch()) {
6116 case llvm::Triple::amdgpu:
6117 case llvm::Triple::r600:
6118 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args,
6119 HostTC.get(), Kind);
6120 break;
6121 case llvm::Triple::spir:
6122 case llvm::Triple::spir64:
6123 case llvm::Triple::spirv:
6124 case llvm::Triple::spirv32:
6125 case llvm::Triple::spirv64:
6126 switch (Kind) {
6127 case Action::OFK_SYCL:
6128 TC = std::make_unique<toolchains::SYCLToolChain>(*this, Target, *HostTC,
6129 Args);
6130 break;
6131 case Action::OFK_HIP:
6132 TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target,
6133 *HostTC, Args);
6134 break;
6135 case Action::OFK_OpenMP:
6136 TC = std::make_unique<toolchains::SPIRVOpenMPToolChain>(*this, Target,
6137 *HostTC, Args);
6138 break;
6139 case Action::OFK_Cuda:
6140 TC = std::make_unique<toolchains::CudaToolChain>(*this, Target, *HostTC,
6141 Args);
6142 break;
6143 default:
6144 break;
6145 }
6146 break;
6147 default:
6148 break;
6149 }
6150 }
6151
6152 // If all else fails, just look up the normal toolchain for the target.
6153 if (!TC)
6154 return getToolChain(Args, Target);
6155 return *TC;
6156}
6157
6158const ToolChain &Driver::getToolChain(const ArgList &Args,
6159 const llvm::Triple &Target) const {
6160
6161 auto &TC = ToolChains[Target.str()];
6162 if (!TC) {
6163 switch (Target.getOS()) {
6164 case llvm::Triple::AIX:
6165 TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
6166 break;
6167 case llvm::Triple::Haiku:
6168 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
6169 break;
6170 case llvm::Triple::Darwin:
6171 case llvm::Triple::MacOSX:
6172 case llvm::Triple::IOS:
6173 case llvm::Triple::TvOS:
6174 case llvm::Triple::WatchOS:
6175 case llvm::Triple::XROS:
6176 case llvm::Triple::DriverKit:
6177 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
6178 break;
6179 case llvm::Triple::DragonFly:
6180 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
6181 break;
6182 case llvm::Triple::OpenBSD:
6183 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
6184 break;
6185 case llvm::Triple::NetBSD:
6186 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
6187 break;
6188 case llvm::Triple::FreeBSD:
6189 if (Target.isPPC())
6190 TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target,
6191 Args);
6192 else
6193 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
6194 break;
6195 case llvm::Triple::Linux:
6196 case llvm::Triple::ELFIAMCU:
6197 if (Target.getArch() == llvm::Triple::hexagon)
6198 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
6199 Args);
6200 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
6201 !Target.hasEnvironment())
6202 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
6203 Args);
6204 else if (Target.isPPC())
6205 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
6206 Args);
6207 else if (Target.getArch() == llvm::Triple::ve)
6208 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
6209 else if (Target.isOHOSFamily())
6210 TC = std::make_unique<toolchains::OHOS>(*this, Target, Args);
6211 else if (Target.isWALI())
6212 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
6213 else if (Target.isLFI())
6214 TC = std::make_unique<toolchains::LFILinux>(*this, Target, Args);
6215 else
6216 TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
6217 break;
6218 case llvm::Triple::Fuchsia:
6219 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
6220 break;
6221 case llvm::Triple::Managarm:
6222 TC = std::make_unique<toolchains::Managarm>(*this, Target, Args);
6223 break;
6224 case llvm::Triple::Serenity:
6225 TC = std::make_unique<toolchains::Serenity>(*this, Target, Args);
6226 break;
6227 case llvm::Triple::Solaris:
6228 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
6229 break;
6230 case llvm::Triple::CUDA:
6231 TC = std::make_unique<toolchains::NVPTXToolChain>(*this, Target, Args);
6232 break;
6233 case llvm::Triple::AMDHSA: {
6234 if (Target.getArch() == llvm::Triple::spirv64) {
6235 TC = std::make_unique<toolchains::SPIRVAMDToolChain>(*this, Target,
6236 Args);
6237 } else {
6238 // Only link device libraries for OpenCL and LLVM IR inputs
6239 bool ShouldLinkDeviceLibs = usesInput(Args, types::isOpenCL) ||
6241 TC = std::make_unique<toolchains::AMDGPUToolChain>(
6242 *this, Target, Args, nullptr, Action::OFK_None,
6243 ShouldLinkDeviceLibs);
6244 }
6245 break;
6246 }
6247 case llvm::Triple::AMDPAL:
6248 case llvm::Triple::Mesa3D:
6249 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
6250 break;
6251 case llvm::Triple::UEFI:
6252 TC = std::make_unique<toolchains::UEFI>(*this, Target, Args);
6253 break;
6254 case llvm::Triple::Win32:
6255 switch (Target.getEnvironment()) {
6256 default:
6257 if (Target.isOSBinFormatELF())
6258 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
6259 else if (Target.isOSBinFormatMachO())
6260 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
6261 else
6262 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6263 break;
6264 case llvm::Triple::GNU:
6265 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
6266 break;
6267 case llvm::Triple::Cygnus:
6268 TC = std::make_unique<toolchains::Cygwin>(*this, Target, Args);
6269 break;
6270 case llvm::Triple::Itanium:
6271 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
6272 Args);
6273 break;
6274 case llvm::Triple::MSVC:
6275 case llvm::Triple::UnknownEnvironment:
6276 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
6277 .starts_with_insensitive("bfd"))
6278 TC = std::make_unique<toolchains::CrossWindowsToolChain>(
6279 *this, Target, Args);
6280 else
6281 TC =
6282 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
6283 break;
6284 }
6285 break;
6286 case llvm::Triple::PS4:
6287 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
6288 break;
6289 case llvm::Triple::PS5:
6290 TC = std::make_unique<toolchains::PS5CPU>(*this, Target, Args);
6291 break;
6292 case llvm::Triple::Hurd:
6293 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
6294 break;
6295 case llvm::Triple::LiteOS:
6296 TC = std::make_unique<toolchains::OHOS>(*this, Target, Args);
6297 break;
6298 case llvm::Triple::ZOS:
6299 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args);
6300 break;
6301 case llvm::Triple::Vulkan:
6302 case llvm::Triple::ShaderModel:
6303 if ((Target.getArch() == llvm::Triple::spirv32 ||
6304 Target.getArch() == llvm::Triple::spirv64) &&
6305 !usesInput(Args, types::isHLSL))
6306 TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args);
6307 else
6308 TC = std::make_unique<toolchains::HLSLToolChain>(*this, Target, Args);
6309 break;
6310 case llvm::Triple::ChipStar:
6311 TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target, Args);
6312 break;
6313 default:
6314 // Of these targets, Hexagon is the only one that might have
6315 // an OS of Linux, in which case it got handled above already.
6316 switch (Target.getArch()) {
6317 case llvm::Triple::tce:
6318 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
6319 break;
6320 case llvm::Triple::tcele:
6321 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
6322 break;
6323 case llvm::Triple::tcele64:
6324 TC =
6325 std::make_unique<toolchains::TCELE64ToolChain>(*this, Target, Args);
6326 break;
6327 case llvm::Triple::hexagon:
6328 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
6329 Args);
6330 break;
6331 case llvm::Triple::lanai:
6332 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
6333 break;
6334 case llvm::Triple::xcore:
6335 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
6336 break;
6337 case llvm::Triple::wasm32:
6338 case llvm::Triple::wasm64:
6339 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
6340 break;
6341 case llvm::Triple::avr:
6342 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
6343 break;
6344 case llvm::Triple::msp430:
6345 TC = std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
6346 break;
6347 case llvm::Triple::riscv32:
6348 case llvm::Triple::riscv64:
6349 case llvm::Triple::riscv32be:
6350 case llvm::Triple::riscv64be:
6351 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6352 break;
6353 case llvm::Triple::ve:
6354 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
6355 break;
6356 case llvm::Triple::spirv32:
6357 case llvm::Triple::spirv64:
6358 TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args);
6359 break;
6360 case llvm::Triple::csky:
6361 TC = std::make_unique<toolchains::CSKYToolChain>(*this, Target, Args);
6362 break;
6363 case llvm::Triple::amdgpu:
6364 case llvm::Triple::r600:
6365 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
6366 break;
6367 default:
6369 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6370 else if (Target.isOSBinFormatELF())
6371 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
6372 else if (Target.isAppleFirmware())
6373 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
6374 else if (Target.isAppleMachO())
6375 TC = std::make_unique<toolchains::AppleMachO>(*this, Target, Args);
6376 else if (Target.isOSBinFormatMachO())
6377 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
6378 else
6379 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6380 }
6381 }
6382 }
6383
6384 return *TC;
6385}
6386
6388 // Say "no" if there is not exactly one input of a type clang understands.
6389 if (JA.size() != 1 ||
6390 !types::isAcceptedByClang((*JA.input_begin())->getType()))
6391 return false;
6392
6393 // And say "no" if this is not a kind of action clang understands.
6397 return false;
6398
6399 return true;
6400}
6401
6403 // Say "no" if there is not exactly one input of a type flang understands.
6404 if (JA.size() != 1 ||
6405 !types::isAcceptedByFlang((*JA.input_begin())->getType()))
6406 return false;
6407
6408 // And say "no" if this is not a kind of action flang understands.
6411 return false;
6412
6413 return true;
6414}
6415
6416bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
6417 // Only emit static library if the flag is set explicitly.
6418 if (Args.hasArg(options::OPT_emit_static_lib))
6419 return true;
6420 return false;
6421}
6422
6423/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
6424/// grouped values as integers. Numbers which are not provided are set to 0.
6425///
6426/// \return True if the entire string was parsed (9.2), or all groups were
6427/// parsed (10.3.5extrastuff).
6428bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
6429 unsigned &Micro, bool &HadExtra) {
6430 HadExtra = false;
6431
6432 Major = Minor = Micro = 0;
6433 if (Str.empty())
6434 return false;
6435
6436 if (Str.consumeInteger(10, Major))
6437 return false;
6438 if (Str.empty())
6439 return true;
6440 if (!Str.consume_front("."))
6441 return false;
6442
6443 if (Str.consumeInteger(10, Minor))
6444 return false;
6445 if (Str.empty())
6446 return true;
6447 if (!Str.consume_front("."))
6448 return false;
6449
6450 if (Str.consumeInteger(10, Micro))
6451 return false;
6452 if (!Str.empty())
6453 HadExtra = true;
6454 return true;
6455}
6456
6457/// Parse digits from a string \p Str and fulfill \p Digits with
6458/// the parsed numbers. This method assumes that the max number of
6459/// digits to look for is equal to Digits.size().
6460///
6461/// \return True if the entire string was parsed and there are
6462/// no extra characters remaining at the end.
6463bool Driver::GetReleaseVersion(StringRef Str,
6465 if (Str.empty())
6466 return false;
6467
6468 unsigned CurDigit = 0;
6469 while (CurDigit < Digits.size()) {
6470 unsigned Digit;
6471 if (Str.consumeInteger(10, Digit))
6472 return false;
6473 Digits[CurDigit] = Digit;
6474 if (Str.empty())
6475 return true;
6476 if (!Str.consume_front("."))
6477 return false;
6478 CurDigit++;
6479 }
6480
6481 // More digits than requested, bail out...
6482 return false;
6483}
6484
6485llvm::opt::Visibility
6486Driver::getOptionVisibilityMask(bool UseDriverMode) const {
6487 if (!UseDriverMode)
6488 return llvm::opt::Visibility(options::ClangOption);
6489 if (IsCLMode())
6490 return llvm::opt::Visibility(options::CLOption);
6491 if (IsDXCMode())
6492 return llvm::opt::Visibility(options::DXCOption);
6493 if (IsFlangMode())
6494 return llvm::opt::Visibility(options::FlangOption);
6495 return llvm::opt::Visibility(options::ClangOption);
6496}
6497
6498const char *Driver::getExecutableForDriverMode(DriverMode Mode) {
6499 switch (Mode) {
6500 case GCCMode:
6501 return "clang";
6502 case GXXMode:
6503 return "clang++";
6504 case CPPMode:
6505 return "clang-cpp";
6506 case CLMode:
6507 return "clang-cl";
6508 case FlangMode:
6509 return "flang";
6510 case DXCMode:
6511 return "clang-dxc";
6512 }
6513
6514 llvm_unreachable("Unhandled Mode");
6515}
6516
6517bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
6518 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
6519}
6520
6521bool clang::driver::willEmitRemarks(const ArgList &Args) {
6522 // -fsave-optimization-record enables it.
6523 if (Args.hasFlag(options::OPT_fsave_optimization_record,
6524 options::OPT_fno_save_optimization_record, false))
6525 return true;
6526
6527 // -fsave-optimization-record=<format> enables it as well.
6528 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
6529 options::OPT_fno_save_optimization_record, false))
6530 return true;
6531
6532 // -foptimization-record-file alone enables it too.
6533 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
6534 options::OPT_fno_save_optimization_record, false))
6535 return true;
6536
6537 // -foptimization-record-passes alone enables it too.
6538 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
6539 options::OPT_fno_save_optimization_record, false))
6540 return true;
6541 return false;
6542}
6543
6544llvm::StringRef clang::driver::getDriverMode(StringRef ProgName,
6546 static StringRef OptName =
6547 getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName();
6548 llvm::StringRef Opt;
6549 for (StringRef Arg : Args) {
6550 if (!Arg.starts_with(OptName))
6551 continue;
6552 Opt = Arg;
6553 }
6554 if (Opt.empty())
6556 return Opt.consume_front(OptName) ? Opt : "";
6557}
6558
6559bool driver::IsClangCL(StringRef DriverMode) { return DriverMode == "cl"; }
6560
6562 bool ClangCLMode,
6563 llvm::BumpPtrAllocator &Alloc,
6564 llvm::vfs::FileSystem *FS) {
6565 // Parse response files using the GNU syntax, unless we're in CL mode. There
6566 // are two ways to put clang in CL compatibility mode: ProgName is either
6567 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
6568 // command line parsing can't happen until after response file parsing, so we
6569 // have to manually search for a --driver-mode=cl argument the hard way.
6570 // Finally, our -cc1 tools don't care which tokenization mode we use because
6571 // response files written by clang will tokenize the same way in either mode.
6572 enum { Default, POSIX, Windows } RSPQuoting = Default;
6573 for (const char *F : Args) {
6574 if (strcmp(F, "--rsp-quoting=posix") == 0)
6575 RSPQuoting = POSIX;
6576 else if (strcmp(F, "--rsp-quoting=windows") == 0)
6577 RSPQuoting = Windows;
6578 }
6579
6580 // Determines whether we want nullptr markers in Args to indicate response
6581 // files end-of-lines. We only use this for the /LINK driver argument with
6582 // clang-cl.exe on Windows.
6583 bool MarkEOLs = ClangCLMode;
6584
6585 llvm::cl::TokenizerCallback Tokenizer;
6586 if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
6587 Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
6588 else
6589 Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
6590
6591 if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).starts_with("-cc1"))
6592 MarkEOLs = false;
6593
6594 llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
6595 ECtx.setMarkEOLs(MarkEOLs);
6596 if (FS)
6597 ECtx.setVFS(FS);
6598
6599 if (llvm::Error Err = ECtx.expandResponseFiles(Args))
6600 return Err;
6601
6602 // If -cc1 came from a response file, remove the EOL sentinels.
6603 auto FirstArg = llvm::find_if(llvm::drop_begin(Args),
6604 [](const char *A) { return A != nullptr; });
6605 if (FirstArg != Args.end() && StringRef(*FirstArg).starts_with("-cc1")) {
6606 // If -cc1 came from a response file, remove the EOL sentinels.
6607 if (MarkEOLs) {
6608 auto newEnd = std::remove(Args.begin(), Args.end(), nullptr);
6609 Args.resize(newEnd - Args.begin());
6610 }
6611 }
6612
6613 return llvm::Error::success();
6614}
6615
6616static const char *GetStableCStr(llvm::StringSet<> &SavedStrings, StringRef S) {
6617 return SavedStrings.insert(S).first->getKeyData();
6618}
6619
6620/// Apply a list of edits to the input argument lists.
6621///
6622/// The input string is a space separated list of edits to perform,
6623/// they are applied in order to the input argument lists. Edits
6624/// should be one of the following forms:
6625///
6626/// '#': Silence information about the changes to the command line arguments.
6627///
6628/// '^FOO': Add FOO as a new argument at the beginning of the command line
6629/// right after the name of the compiler executable.
6630///
6631/// '+FOO': Add FOO as a new argument at the end of the command line.
6632///
6633/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
6634/// line.
6635///
6636/// 'xOPTION': Removes all instances of the literal argument OPTION.
6637///
6638/// 'XOPTION': Removes all instances of the literal argument OPTION,
6639/// and the following argument.
6640///
6641/// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
6642/// at the end of the command line.
6643///
6644/// \param OS - The stream to write edit information to.
6645/// \param Args - The vector of command line arguments.
6646/// \param Edit - The override command to perform.
6647/// \param SavedStrings - Set to use for storing string representations.
6648static void applyOneOverrideOption(raw_ostream &OS,
6650 StringRef Edit,
6651 llvm::StringSet<> &SavedStrings) {
6652 // This does not need to be efficient.
6653
6654 if (Edit[0] == '^') {
6655 const char *Str = GetStableCStr(SavedStrings, Edit.substr(1));
6656 OS << "### Adding argument " << Str << " at beginning\n";
6657 Args.insert(Args.begin() + 1, Str);
6658 } else if (Edit[0] == '+') {
6659 const char *Str = GetStableCStr(SavedStrings, Edit.substr(1));
6660 OS << "### Adding argument " << Str << " at end\n";
6661 Args.push_back(Str);
6662 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.ends_with("/") &&
6663 Edit.slice(2, Edit.size() - 1).contains('/')) {
6664 StringRef MatchPattern = Edit.substr(2).split('/').first;
6665 StringRef ReplPattern = Edit.substr(2).split('/').second;
6666 ReplPattern = ReplPattern.slice(0, ReplPattern.size() - 1);
6667
6668 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
6669 // Ignore end-of-line response file markers
6670 if (Args[i] == nullptr)
6671 continue;
6672 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
6673
6674 if (Repl != Args[i]) {
6675 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
6676 Args[i] = GetStableCStr(SavedStrings, Repl);
6677 }
6678 }
6679 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
6680 auto Option = Edit.substr(1);
6681 for (unsigned i = 1; i < Args.size();) {
6682 if (Option == Args[i]) {
6683 OS << "### Deleting argument " << Args[i] << '\n';
6684 Args.erase(Args.begin() + i);
6685 if (Edit[0] == 'X') {
6686 if (i < Args.size()) {
6687 OS << "### Deleting argument " << Args[i] << '\n';
6688 Args.erase(Args.begin() + i);
6689 } else
6690 OS << "### Invalid X edit, end of command line!\n";
6691 }
6692 } else
6693 ++i;
6694 }
6695 } else if (Edit[0] == 'O') {
6696 for (unsigned i = 1; i < Args.size();) {
6697 const char *A = Args[i];
6698 // Ignore end-of-line response file markers
6699 if (A == nullptr)
6700 continue;
6701 if (A[0] == '-' && A[1] == 'O' &&
6702 (A[2] == '\0' || (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
6703 ('0' <= A[2] && A[2] <= '9'))))) {
6704 OS << "### Deleting argument " << Args[i] << '\n';
6705 Args.erase(Args.begin() + i);
6706 } else
6707 ++i;
6708 }
6709 OS << "### Adding argument " << Edit << " at end\n";
6710 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
6711 } else {
6712 OS << "### Unrecognized edit: " << Edit << "\n";
6713 }
6714}
6715
6717 const char *OverrideStr,
6718 llvm::StringSet<> &SavedStrings,
6719 StringRef EnvVar, raw_ostream *OS) {
6720 if (!OS)
6721 OS = &llvm::nulls();
6722
6723 if (OverrideStr[0] == '#') {
6724 ++OverrideStr;
6725 OS = &llvm::nulls();
6726 }
6727
6728 *OS << "### " << EnvVar << ": " << OverrideStr << "\n";
6729
6730 // This does not need to be efficient.
6731
6732 const char *S = OverrideStr;
6733 while (*S) {
6734 const char *End = ::strchr(S, ' ');
6735 if (!End)
6736 End = S + strlen(S);
6737 if (End != S)
6738 applyOneOverrideOption(*OS, Args, std::string(S, End), SavedStrings);
6739 S = End;
6740 if (*S != '\0')
6741 ++S;
6742 }
6743}
#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:4553
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:6648
static void printCXXStdlibIncludeDirs(const ToolChain &TC, const ArgList &Args)
Definition Driver.cpp:144
static bool HasPreprocessOutput(const Action &JA)
Definition Driver.cpp:5488
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:5127
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:4577
static const char * GetModuleOutputPath(Compilation &C, const JobAction &JA, const char *BaseInput)
Definition Driver.cpp:5549
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:5459
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:5158
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:6616
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:4531
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:5928
static void claimAndDiagnoseOffloadJobs(const Driver &D, const ArgList &Args)
Definition Driver.cpp:4565
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:241
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:71
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:93
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:193
std::string UserConfigDir
User directory for config files.
Definition Driver.h:183
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:444
bool isSaveTempsEnabled() const
Definition Driver.h:436
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:4587
std::string GetFilePath(StringRef Name, const ToolChain &TC) const
GetFilePath - Lookup Name in the list of file search paths.
Definition Driver.cpp:5860
unsigned CCPrintProcessStats
Set CC_PRINT_PROC_STAT mode, which causes the driver to dump performance report to CC_PRINT_PROC_STAT...
Definition Driver.h:276
DiagnosticsEngine & getDiags() const
Definition Driver.h:407
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:5561
std::string GetTemporaryDirectory(StringRef Prefix) const
GetTemporaryDirectory - Return the pathname of a temporary directory to use as part of compilation; t...
Definition Driver.cpp:6052
bool IsDXCMode() const
Whether the driver should follow dxc.exe like behavior.
Definition Driver.h:236
const char * getDefaultImageName() const
Returns the default name for linked images (e.g., "a.out").
Definition Driver.cpp:5450
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:229
std::string DyldPrefix
Dynamic loader prefix, if present.
Definition Driver.h:196
bool ShouldEmitStaticLibrary(const llvm::opt::ArgList &Args) const
ShouldEmitStaticLibrary - Should the linker emit a static library.
Definition Driver.cpp:6416
std::string DriverTitle
Driver title to use with help.
Definition Driver.h:199
unsigned CCCPrintBindings
Only print tool bindings, don't build any jobs.
Definition Driver.h:240
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition Driver.h:267
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:271
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:157
std::string SystemConfigDir
System directory for config files.
Definition Driver.h:180
ParsedClangName ClangNameParts
Target and driver mode components extracted from clang executable name.
Definition Driver.h:174
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition Driver.h:281
static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra)
GetReleaseVersion - Parse (([0-9]+)(.
Definition Driver.cpp:6428
std::string Name
The name the driver was invoked as.
Definition Driver.h:164
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:6063
const llvm::opt::OptTable & getOpts() const
Definition Driver.h:405
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:443
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:725
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:5139
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:6402
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:5936
bool isSaveTempsObj() const
Definition Driver.h:437
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:177
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:409
unsigned CCPrintOptions
Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to CCPrintOptionsFilename or to std...
Definition Driver.h:245
bool ShouldUseClangCompiler(const JobAction &JA) const
ShouldUseClangCompiler - Should the clang compiler be used to handle this action.
Definition Driver.cpp:6387
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:6041
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition Driver.h:168
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:5499
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:153
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:143
@ OMPRT_Unknown
An unknown OpenMP runtime.
Definition Driver.h:139
@ OMPRT_GOMP
The GNU OpenMP runtime.
Definition Driver.h:148
std::string getTargetTriple() const
Definition Driver.h:426
bool getCheckInputsExist() const
Definition Driver.h:411
std::string GetStdModuleManifestPath(const Compilation &C, const ToolChain &TC) const
Lookup the path to the Standard library module manifest.
Definition Driver.cpp:5978
bool IsFlangMode() const
Whether the driver should invoke flang for fortran inputs.
Definition Driver.h:233
prefix_list PrefixDirs
Definition Driver.h:190
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:171
bool embedBitcodeInObject() const
Definition Driver.h:440
std::string CCPrintStatReportFilename
The file to log CC_PRINT_PROC_STAT_FILE output to, if enabled.
Definition Driver.h:205
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:223
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:220
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:935
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:92
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:906
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:328
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
path_list & getFilePaths()
Definition ToolChain.h:322
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:298
const Driver & getDriver() const
Definition ToolChain.h:282
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:453
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:770
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:325
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition ToolChain.h:310
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:699
const llvm::Triple & getTriple() const
Definition ToolChain.h:284
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:330
StringRef getTripleString() const
Definition ToolChain.h:307
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:319
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:299
SmallVector< std::string, 16 > path_list
Definition ToolChain.h:94
Tool - Information on a specific compilation tool.
Definition Tool.h:32
virtual bool isDsymutilJob() const
Definition Tool.h:59
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:925
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:409
bool isHLSL(ID Id)
isHLSL - Is this an HLSL input.
Definition Types.cpp:329
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:305
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition Types.cpp:292
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:253
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:424
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition Types.cpp:331
ID lookupCXXTypeForCType(ID Id)
lookupCXXTypeForCType - Lookup CXX input type that corresponds to given C type (used for clang++ emul...
Definition Types.cpp:440
bool isHIP(ID Id)
isHIP - Is this a HIP input.
Definition Types.cpp:317
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:456
ID lookupTypeForExtension(llvm::StringRef Ext)
lookupTypeForExtension - Lookup the type to use for the file extension Ext.
Definition Types.cpp:335
bool isAcceptedByFlang(ID Id)
isAcceptedByFlang - Can flang handle this input type.
Definition Types.cpp:181
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:6716
LTOKind
Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
Definition Driver.h:57
ModuleHeaderMode
Whether headers used to construct C++20 module units should be looked up by the path supplied on the ...
Definition Driver.h:62
@ HeaderMode_System
Definition Driver.h:66
@ HeaderMode_None
Definition Driver.h:63
@ HeaderMode_Default
Definition Driver.h:64
@ HeaderMode_User
Definition Driver.h:65
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:49
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:6544
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:6561
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:6559
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:553
const char * DriverMode
Corresponding driver mode argument, as '–driver-mode=g++'.
Definition ToolChain.h:73
ResponseFileKind ResponseKind
The level of support for response files.
Definition Job.h:58
The parsed Standard library module manifest.