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