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