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