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