[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Driver / Driver.cpp
blob013d5b32074e9ea706ba1b9235d250364a0dd464
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 //===----------------------------------------------------------------------===//
9 #include "clang/Driver/Driver.h"
10 #include "ToolChains/AIX.h"
11 #include "ToolChains/AMDGPU.h"
12 #include "ToolChains/AMDGPUOpenMP.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
16 #include "ToolChains/CSKYToolChain.h"
17 #include "ToolChains/Clang.h"
18 #include "ToolChains/CloudABI.h"
19 #include "ToolChains/Contiki.h"
20 #include "ToolChains/CrossWindows.h"
21 #include "ToolChains/Cuda.h"
22 #include "ToolChains/Darwin.h"
23 #include "ToolChains/DragonFly.h"
24 #include "ToolChains/FreeBSD.h"
25 #include "ToolChains/Fuchsia.h"
26 #include "ToolChains/Gnu.h"
27 #include "ToolChains/HIPAMD.h"
28 #include "ToolChains/HIPSPV.h"
29 #include "ToolChains/HLSL.h"
30 #include "ToolChains/Haiku.h"
31 #include "ToolChains/Hexagon.h"
32 #include "ToolChains/Hurd.h"
33 #include "ToolChains/Lanai.h"
34 #include "ToolChains/Linux.h"
35 #include "ToolChains/MSP430.h"
36 #include "ToolChains/MSVC.h"
37 #include "ToolChains/MinGW.h"
38 #include "ToolChains/Minix.h"
39 #include "ToolChains/MipsLinux.h"
40 #include "ToolChains/Myriad.h"
41 #include "ToolChains/NaCl.h"
42 #include "ToolChains/NetBSD.h"
43 #include "ToolChains/OpenBSD.h"
44 #include "ToolChains/PPCFreeBSD.h"
45 #include "ToolChains/PPCLinux.h"
46 #include "ToolChains/PS4CPU.h"
47 #include "ToolChains/RISCVToolchain.h"
48 #include "ToolChains/SPIRV.h"
49 #include "ToolChains/Solaris.h"
50 #include "ToolChains/TCE.h"
51 #include "ToolChains/VEToolchain.h"
52 #include "ToolChains/WebAssembly.h"
53 #include "ToolChains/XCore.h"
54 #include "ToolChains/ZOS.h"
55 #include "clang/Basic/TargetID.h"
56 #include "clang/Basic/Version.h"
57 #include "clang/Config/config.h"
58 #include "clang/Driver/Action.h"
59 #include "clang/Driver/Compilation.h"
60 #include "clang/Driver/DriverDiagnostic.h"
61 #include "clang/Driver/InputInfo.h"
62 #include "clang/Driver/Job.h"
63 #include "clang/Driver/Options.h"
64 #include "clang/Driver/Phases.h"
65 #include "clang/Driver/SanitizerArgs.h"
66 #include "clang/Driver/Tool.h"
67 #include "clang/Driver/ToolChain.h"
68 #include "clang/Driver/Types.h"
69 #include "llvm/ADT/ArrayRef.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/StringExtras.h"
73 #include "llvm/ADT/StringRef.h"
74 #include "llvm/ADT/StringSet.h"
75 #include "llvm/ADT/StringSwitch.h"
76 #include "llvm/Config/llvm-config.h"
77 #include "llvm/MC/TargetRegistry.h"
78 #include "llvm/Option/Arg.h"
79 #include "llvm/Option/ArgList.h"
80 #include "llvm/Option/OptSpecifier.h"
81 #include "llvm/Option/OptTable.h"
82 #include "llvm/Option/Option.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/ExitCodes.h"
86 #include "llvm/Support/FileSystem.h"
87 #include "llvm/Support/FormatVariadic.h"
88 #include "llvm/Support/Host.h"
89 #include "llvm/Support/MD5.h"
90 #include "llvm/Support/Path.h"
91 #include "llvm/Support/PrettyStackTrace.h"
92 #include "llvm/Support/Process.h"
93 #include "llvm/Support/Program.h"
94 #include "llvm/Support/StringSaver.h"
95 #include "llvm/Support/VirtualFileSystem.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include <map>
98 #include <memory>
99 #include <utility>
100 #if LLVM_ON_UNIX
101 #include <unistd.h> // getpid
102 #endif
104 using namespace clang::driver;
105 using namespace clang;
106 using namespace llvm::opt;
108 static llvm::Optional<llvm::Triple>
109 getOffloadTargetTriple(const Driver &D, const ArgList &Args) {
110 auto OffloadTargets = Args.getAllArgValues(options::OPT_offload_EQ);
111 // Offload compilation flow does not support multiple targets for now. We
112 // need the HIPActionBuilder (and possibly the CudaActionBuilder{,Base}too)
113 // to support multiple tool chains first.
114 switch (OffloadTargets.size()) {
115 default:
116 D.Diag(diag::err_drv_only_one_offload_target_supported);
117 return llvm::None;
118 case 0:
119 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << "";
120 return llvm::None;
121 case 1:
122 break;
124 return llvm::Triple(OffloadTargets[0]);
127 static llvm::Optional<llvm::Triple>
128 getNVIDIAOffloadTargetTriple(const Driver &D, const ArgList &Args,
129 const llvm::Triple &HostTriple) {
130 if (!Args.hasArg(options::OPT_offload_EQ)) {
131 return llvm::Triple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
132 : "nvptx-nvidia-cuda");
134 auto TT = getOffloadTargetTriple(D, Args);
135 if (TT && (TT->getArch() == llvm::Triple::spirv32 ||
136 TT->getArch() == llvm::Triple::spirv64)) {
137 if (Args.hasArg(options::OPT_emit_llvm))
138 return TT;
139 D.Diag(diag::err_drv_cuda_offload_only_emit_bc);
140 return llvm::None;
142 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
143 return llvm::None;
145 static llvm::Optional<llvm::Triple>
146 getHIPOffloadTargetTriple(const Driver &D, const ArgList &Args) {
147 if (!Args.hasArg(options::OPT_offload_EQ)) {
148 return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple.
150 auto TT = getOffloadTargetTriple(D, Args);
151 if (!TT)
152 return llvm::None;
153 if (TT->getArch() == llvm::Triple::amdgcn &&
154 TT->getVendor() == llvm::Triple::AMD &&
155 TT->getOS() == llvm::Triple::AMDHSA)
156 return TT;
157 if (TT->getArch() == llvm::Triple::spirv64)
158 return TT;
159 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
160 return llvm::None;
163 // static
164 std::string Driver::GetResourcesPath(StringRef BinaryPath,
165 StringRef CustomResourceDir) {
166 // Since the resource directory is embedded in the module hash, it's important
167 // that all places that need it call this function, so that they get the
168 // exact same string ("a/../b/" and "b/" get different hashes, for example).
170 // Dir is bin/ or lib/, depending on where BinaryPath is.
171 std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
173 SmallString<128> P(Dir);
174 if (CustomResourceDir != "") {
175 llvm::sys::path::append(P, CustomResourceDir);
176 } else {
177 // On Windows, libclang.dll is in bin/.
178 // On non-Windows, libclang.so/.dylib is in lib/.
179 // With a static-library build of libclang, LibClangPath will contain the
180 // path of the embedding binary, which for LLVM binaries will be in bin/.
181 // ../lib gets us to lib/ in both cases.
182 P = llvm::sys::path::parent_path(Dir);
183 llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
184 CLANG_VERSION_STRING);
187 return std::string(P.str());
190 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
191 DiagnosticsEngine &Diags, std::string Title,
192 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
193 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
194 SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
195 Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None),
196 ModulesModeCXX20(false), LTOMode(LTOK_None),
197 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
198 DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
199 CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
200 CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
201 CheckInputsExist(true), ProbePrecompiled(true),
202 SuppressMissingInputWarning(false) {
203 // Provide a sane fallback if no VFS is specified.
204 if (!this->VFS)
205 this->VFS = llvm::vfs::getRealFileSystem();
207 Name = std::string(llvm::sys::path::filename(ClangExecutable));
208 Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
209 InstalledDir = Dir; // Provide a sensible default installed dir.
211 if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
212 // Prepend InstalledDir if SysRoot is relative
213 SmallString<128> P(InstalledDir);
214 llvm::sys::path::append(P, SysRoot);
215 SysRoot = std::string(P);
218 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
219 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
220 #endif
221 #if defined(CLANG_CONFIG_FILE_USER_DIR)
222 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
223 #endif
225 // Compute the path to the resource directory.
226 ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
229 void Driver::setDriverMode(StringRef Value) {
230 static const std::string OptName =
231 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
232 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
233 .Case("gcc", GCCMode)
234 .Case("g++", GXXMode)
235 .Case("cpp", CPPMode)
236 .Case("cl", CLMode)
237 .Case("flang", FlangMode)
238 .Case("dxc", DXCMode)
239 .Default(None))
240 Mode = *M;
241 else
242 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
245 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
246 bool IsClCompatMode,
247 bool &ContainsError) {
248 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
249 ContainsError = false;
251 unsigned IncludedFlagsBitmask;
252 unsigned ExcludedFlagsBitmask;
253 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
254 getIncludeExcludeOptionFlagMasks(IsClCompatMode);
256 // Make sure that Flang-only options don't pollute the Clang output
257 // TODO: Make sure that Clang-only options don't pollute Flang output
258 if (!IsFlangMode())
259 ExcludedFlagsBitmask |= options::FlangOnlyOption;
261 unsigned MissingArgIndex, MissingArgCount;
262 InputArgList Args =
263 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
264 IncludedFlagsBitmask, ExcludedFlagsBitmask);
266 // Check for missing argument error.
267 if (MissingArgCount) {
268 Diag(diag::err_drv_missing_argument)
269 << Args.getArgString(MissingArgIndex) << MissingArgCount;
270 ContainsError |=
271 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
272 SourceLocation()) > DiagnosticsEngine::Warning;
275 // Check for unsupported options.
276 for (const Arg *A : Args) {
277 if (A->getOption().hasFlag(options::Unsupported)) {
278 unsigned DiagID;
279 auto ArgString = A->getAsString(Args);
280 std::string Nearest;
281 if (getOpts().findNearest(
282 ArgString, Nearest, IncludedFlagsBitmask,
283 ExcludedFlagsBitmask | options::Unsupported) > 1) {
284 DiagID = diag::err_drv_unsupported_opt;
285 Diag(DiagID) << ArgString;
286 } else {
287 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
288 Diag(DiagID) << ArgString << Nearest;
290 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
291 DiagnosticsEngine::Warning;
292 continue;
295 // Warn about -mcpu= without an argument.
296 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
297 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
298 ContainsError |= Diags.getDiagnosticLevel(
299 diag::warn_drv_empty_joined_argument,
300 SourceLocation()) > DiagnosticsEngine::Warning;
304 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
305 unsigned DiagID;
306 auto ArgString = A->getAsString(Args);
307 std::string Nearest;
308 if (getOpts().findNearest(
309 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
310 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
311 : diag::err_drv_unknown_argument;
312 Diags.Report(DiagID) << ArgString;
313 } else {
314 DiagID = IsCLMode()
315 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
316 : diag::err_drv_unknown_argument_with_suggestion;
317 Diags.Report(DiagID) << ArgString << Nearest;
319 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
320 DiagnosticsEngine::Warning;
323 return Args;
326 // Determine which compilation mode we are in. We look for options which
327 // affect the phase, starting with the earliest phases, and record which
328 // option we used to determine the final phase.
329 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
330 Arg **FinalPhaseArg) const {
331 Arg *PhaseArg = nullptr;
332 phases::ID FinalPhase;
334 // -{E,EP,P,M,MM} only run the preprocessor.
335 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
336 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
337 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
338 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) ||
339 CCGenDiagnostics) {
340 FinalPhase = phases::Preprocess;
342 // --precompile only runs up to precompilation.
343 // Options that cause the output of C++20 compiled module interfaces or
344 // header units have the same effect.
345 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
346 (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
347 (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
348 options::OPT_fmodule_header_EQ))) {
349 FinalPhase = phases::Precompile;
350 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
351 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
352 (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
353 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
354 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
355 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
356 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
357 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
358 (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
359 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
360 FinalPhase = phases::Compile;
362 // -S only runs up to the backend.
363 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
364 FinalPhase = phases::Backend;
366 // -c compilation only runs up to the assembler.
367 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
368 FinalPhase = phases::Assemble;
370 } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) {
371 FinalPhase = phases::IfsMerge;
373 // Otherwise do everything.
374 } else
375 FinalPhase = phases::Link;
377 if (FinalPhaseArg)
378 *FinalPhaseArg = PhaseArg;
380 return FinalPhase;
383 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
384 StringRef Value, bool Claim = true) {
385 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
386 Args.getBaseArgs().MakeIndex(Value), Value.data());
387 Args.AddSynthesizedArg(A);
388 if (Claim)
389 A->claim();
390 return A;
393 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
394 const llvm::opt::OptTable &Opts = getOpts();
395 DerivedArgList *DAL = new DerivedArgList(Args);
397 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
398 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
399 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
400 bool IgnoreUnused = false;
401 for (Arg *A : Args) {
402 if (IgnoreUnused)
403 A->claim();
405 if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
406 IgnoreUnused = true;
407 continue;
409 if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
410 IgnoreUnused = false;
411 continue;
414 // Unfortunately, we have to parse some forwarding options (-Xassembler,
415 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
416 // (assembler and preprocessor), or bypass a previous driver ('collect2').
418 // Rewrite linker options, to replace --no-demangle with a custom internal
419 // option.
420 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
421 A->getOption().matches(options::OPT_Xlinker)) &&
422 A->containsValue("--no-demangle")) {
423 // Add the rewritten no-demangle argument.
424 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
426 // Add the remaining values as Xlinker arguments.
427 for (StringRef Val : A->getValues())
428 if (Val != "--no-demangle")
429 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
431 continue;
434 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
435 // some build systems. We don't try to be complete here because we don't
436 // care to encourage this usage model.
437 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
438 (A->getValue(0) == StringRef("-MD") ||
439 A->getValue(0) == StringRef("-MMD"))) {
440 // Rewrite to -MD/-MMD along with -MF.
441 if (A->getValue(0) == StringRef("-MD"))
442 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
443 else
444 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
445 if (A->getNumValues() == 2)
446 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
447 continue;
450 // Rewrite reserved library names.
451 if (A->getOption().matches(options::OPT_l)) {
452 StringRef Value = A->getValue();
454 // Rewrite unless -nostdlib is present.
455 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
456 Value == "stdc++") {
457 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
458 continue;
461 // Rewrite unconditionally.
462 if (Value == "cc_kext") {
463 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
464 continue;
468 // Pick up inputs via the -- option.
469 if (A->getOption().matches(options::OPT__DASH_DASH)) {
470 A->claim();
471 for (StringRef Val : A->getValues())
472 DAL->append(MakeInputArg(*DAL, Opts, Val, false));
473 continue;
476 DAL->append(A);
479 // Enforce -static if -miamcu is present.
480 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
481 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static));
483 // Add a default value of -mlinker-version=, if one was given and the user
484 // didn't specify one.
485 #if defined(HOST_LINK_VERSION)
486 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
487 strlen(HOST_LINK_VERSION) > 0) {
488 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
489 HOST_LINK_VERSION);
490 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
492 #endif
494 return DAL;
497 /// Compute target triple from args.
499 /// This routine provides the logic to compute a target triple from various
500 /// args passed to the driver and the default triple string.
501 static llvm::Triple computeTargetTriple(const Driver &D,
502 StringRef TargetTriple,
503 const ArgList &Args,
504 StringRef DarwinArchName = "") {
505 // FIXME: Already done in Compilation *Driver::BuildCompilation
506 if (const Arg *A = Args.getLastArg(options::OPT_target))
507 TargetTriple = A->getValue();
509 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
511 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
512 // -gnu* only, and we can not change this, so we have to detect that case as
513 // being the Hurd OS.
514 if (TargetTriple.contains("-unknown-gnu") || TargetTriple.contains("-pc-gnu"))
515 Target.setOSName("hurd");
517 // Handle Apple-specific options available here.
518 if (Target.isOSBinFormatMachO()) {
519 // If an explicit Darwin arch name is given, that trumps all.
520 if (!DarwinArchName.empty()) {
521 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
522 return Target;
525 // Handle the Darwin '-arch' flag.
526 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
527 StringRef ArchName = A->getValue();
528 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
532 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
533 // '-mbig-endian'/'-EB'.
534 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
535 options::OPT_mbig_endian)) {
536 if (A->getOption().matches(options::OPT_mlittle_endian)) {
537 llvm::Triple LE = Target.getLittleEndianArchVariant();
538 if (LE.getArch() != llvm::Triple::UnknownArch)
539 Target = std::move(LE);
540 } else {
541 llvm::Triple BE = Target.getBigEndianArchVariant();
542 if (BE.getArch() != llvm::Triple::UnknownArch)
543 Target = std::move(BE);
547 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
548 if (Target.getArch() == llvm::Triple::tce ||
549 Target.getOS() == llvm::Triple::Minix)
550 return Target;
552 // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
553 if (Target.isOSAIX()) {
554 if (Optional<std::string> ObjectModeValue =
555 llvm::sys::Process::GetEnv("OBJECT_MODE")) {
556 StringRef ObjectMode = *ObjectModeValue;
557 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
559 if (ObjectMode.equals("64")) {
560 AT = Target.get64BitArchVariant().getArch();
561 } else if (ObjectMode.equals("32")) {
562 AT = Target.get32BitArchVariant().getArch();
563 } else {
564 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
567 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
568 Target.setArch(AT);
572 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
573 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
574 options::OPT_m32, options::OPT_m16);
575 if (A) {
576 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
578 if (A->getOption().matches(options::OPT_m64)) {
579 AT = Target.get64BitArchVariant().getArch();
580 if (Target.getEnvironment() == llvm::Triple::GNUX32)
581 Target.setEnvironment(llvm::Triple::GNU);
582 else if (Target.getEnvironment() == llvm::Triple::MuslX32)
583 Target.setEnvironment(llvm::Triple::Musl);
584 } else if (A->getOption().matches(options::OPT_mx32) &&
585 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
586 AT = llvm::Triple::x86_64;
587 if (Target.getEnvironment() == llvm::Triple::Musl)
588 Target.setEnvironment(llvm::Triple::MuslX32);
589 else
590 Target.setEnvironment(llvm::Triple::GNUX32);
591 } else if (A->getOption().matches(options::OPT_m32)) {
592 AT = Target.get32BitArchVariant().getArch();
593 if (Target.getEnvironment() == llvm::Triple::GNUX32)
594 Target.setEnvironment(llvm::Triple::GNU);
595 else if (Target.getEnvironment() == llvm::Triple::MuslX32)
596 Target.setEnvironment(llvm::Triple::Musl);
597 } else if (A->getOption().matches(options::OPT_m16) &&
598 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
599 AT = llvm::Triple::x86;
600 Target.setEnvironment(llvm::Triple::CODE16);
603 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) {
604 Target.setArch(AT);
605 if (Target.isWindowsGNUEnvironment())
606 toolchains::MinGW::fixTripleArch(D, Target, Args);
610 // Handle -miamcu flag.
611 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
612 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
613 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
614 << Target.str();
616 if (A && !A->getOption().matches(options::OPT_m32))
617 D.Diag(diag::err_drv_argument_not_allowed_with)
618 << "-miamcu" << A->getBaseArg().getAsString(Args);
620 Target.setArch(llvm::Triple::x86);
621 Target.setArchName("i586");
622 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
623 Target.setEnvironmentName("");
624 Target.setOS(llvm::Triple::ELFIAMCU);
625 Target.setVendor(llvm::Triple::UnknownVendor);
626 Target.setVendorName("intel");
629 // If target is MIPS adjust the target triple
630 // accordingly to provided ABI name.
631 A = Args.getLastArg(options::OPT_mabi_EQ);
632 if (A && Target.isMIPS()) {
633 StringRef ABIName = A->getValue();
634 if (ABIName == "32") {
635 Target = Target.get32BitArchVariant();
636 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
637 Target.getEnvironment() == llvm::Triple::GNUABIN32)
638 Target.setEnvironment(llvm::Triple::GNU);
639 } else if (ABIName == "n32") {
640 Target = Target.get64BitArchVariant();
641 if (Target.getEnvironment() == llvm::Triple::GNU ||
642 Target.getEnvironment() == llvm::Triple::GNUABI64)
643 Target.setEnvironment(llvm::Triple::GNUABIN32);
644 } else if (ABIName == "64") {
645 Target = Target.get64BitArchVariant();
646 if (Target.getEnvironment() == llvm::Triple::GNU ||
647 Target.getEnvironment() == llvm::Triple::GNUABIN32)
648 Target.setEnvironment(llvm::Triple::GNUABI64);
652 // If target is RISC-V adjust the target triple according to
653 // provided architecture name
654 A = Args.getLastArg(options::OPT_march_EQ);
655 if (A && Target.isRISCV()) {
656 StringRef ArchName = A->getValue();
657 if (ArchName.startswith_insensitive("rv32"))
658 Target.setArch(llvm::Triple::riscv32);
659 else if (ArchName.startswith_insensitive("rv64"))
660 Target.setArch(llvm::Triple::riscv64);
663 return Target;
666 // Parse the LTO options and record the type of LTO compilation
667 // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)?
668 // option occurs last.
669 static driver::LTOKind parseLTOMode(Driver &D, const llvm::opt::ArgList &Args,
670 OptSpecifier OptEq, OptSpecifier OptNeg) {
671 if (!Args.hasFlag(OptEq, OptNeg, false))
672 return LTOK_None;
674 const Arg *A = Args.getLastArg(OptEq);
675 StringRef LTOName = A->getValue();
677 driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
678 .Case("full", LTOK_Full)
679 .Case("thin", LTOK_Thin)
680 .Default(LTOK_Unknown);
682 if (LTOMode == LTOK_Unknown) {
683 D.Diag(diag::err_drv_unsupported_option_argument)
684 << A->getOption().getName() << A->getValue();
685 return LTOK_None;
687 return LTOMode;
690 // Parse the LTO options.
691 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
692 LTOMode =
693 parseLTOMode(*this, Args, options::OPT_flto_EQ, options::OPT_fno_lto);
695 OffloadLTOMode = parseLTOMode(*this, Args, options::OPT_foffload_lto_EQ,
696 options::OPT_fno_offload_lto);
699 /// Compute the desired OpenMP runtime from the flags provided.
700 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
701 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
703 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
704 if (A)
705 RuntimeName = A->getValue();
707 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
708 .Case("libomp", OMPRT_OMP)
709 .Case("libgomp", OMPRT_GOMP)
710 .Case("libiomp5", OMPRT_IOMP5)
711 .Default(OMPRT_Unknown);
713 if (RT == OMPRT_Unknown) {
714 if (A)
715 Diag(diag::err_drv_unsupported_option_argument)
716 << A->getOption().getName() << A->getValue();
717 else
718 // FIXME: We could use a nicer diagnostic here.
719 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
722 return RT;
725 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
726 InputList &Inputs) {
729 // CUDA/HIP
731 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
732 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
733 bool IsCuda =
734 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
735 return types::isCuda(I.first);
737 bool IsHIP =
738 llvm::any_of(Inputs,
739 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
740 return types::isHIP(I.first);
741 }) ||
742 C.getInputArgs().hasArg(options::OPT_hip_link);
743 if (IsCuda && IsHIP) {
744 Diag(clang::diag::err_drv_mix_cuda_hip);
745 return;
747 if (IsCuda) {
748 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
749 const llvm::Triple &HostTriple = HostTC->getTriple();
750 auto OFK = Action::OFK_Cuda;
751 auto CudaTriple =
752 getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple);
753 if (!CudaTriple)
754 return;
755 // Use the CUDA and host triples as the key into the ToolChains map,
756 // because the device toolchain we create depends on both.
757 auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()];
758 if (!CudaTC) {
759 CudaTC = std::make_unique<toolchains::CudaToolChain>(
760 *this, *CudaTriple, *HostTC, C.getInputArgs());
762 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
763 } else if (IsHIP) {
764 if (auto *OMPTargetArg =
765 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
766 Diag(clang::diag::err_drv_unsupported_opt_for_language_mode)
767 << OMPTargetArg->getSpelling() << "HIP";
768 return;
770 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
771 auto OFK = Action::OFK_HIP;
772 auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
773 if (!HIPTriple)
774 return;
775 auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple,
776 *HostTC, OFK);
777 assert(HIPTC && "Could not create offloading device tool chain.");
778 C.addOffloadDeviceToolChain(HIPTC, OFK);
782 // OpenMP
784 // We need to generate an OpenMP toolchain if the user specified targets with
785 // the -fopenmp-targets option or used --offload-arch with OpenMP enabled.
786 bool IsOpenMPOffloading =
787 C.getInputArgs().hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
788 options::OPT_fno_openmp, false) &&
789 (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ) ||
790 C.getInputArgs().hasArg(options::OPT_offload_arch_EQ));
791 if (IsOpenMPOffloading) {
792 // We expect that -fopenmp-targets is always used in conjunction with the
793 // option -fopenmp specifying a valid runtime with offloading support, i.e.
794 // libomp or libiomp.
795 OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(C.getInputArgs());
796 if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) {
797 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
798 return;
801 llvm::StringMap<llvm::DenseSet<StringRef>> DerivedArchs;
802 llvm::StringMap<StringRef> FoundNormalizedTriples;
803 llvm::SmallVector<StringRef, 4> OpenMPTriples;
805 // If the user specified -fopenmp-targets= we create a toolchain for each
806 // valid triple. Otherwise, if only --offload-arch= was specified we instead
807 // attempt to derive the appropriate toolchains from the arguments.
808 if (Arg *OpenMPTargets =
809 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
810 if (OpenMPTargets && !OpenMPTargets->getNumValues()) {
811 Diag(clang::diag::warn_drv_empty_joined_argument)
812 << OpenMPTargets->getAsString(C.getInputArgs());
813 return;
815 llvm::copy(OpenMPTargets->getValues(), std::back_inserter(OpenMPTriples));
816 } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) &&
817 !IsHIP && !IsCuda) {
818 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
819 auto AMDTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
820 auto NVPTXTriple = getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(),
821 HostTC->getTriple());
823 // Attempt to deduce the offloading triple from the set of architectures.
824 // We can only correctly deduce NVPTX / AMDGPU triples currently.
825 llvm::DenseSet<StringRef> Archs =
826 getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr);
827 for (StringRef Arch : Archs) {
828 if (NVPTXTriple && IsNVIDIAGpuArch(StringToCudaArch(
829 getProcessorFromTargetID(*NVPTXTriple, Arch)))) {
830 DerivedArchs[NVPTXTriple->getTriple()].insert(Arch);
831 } else if (AMDTriple &&
832 IsAMDGpuArch(StringToCudaArch(
833 getProcessorFromTargetID(*AMDTriple, Arch)))) {
834 DerivedArchs[AMDTriple->getTriple()].insert(Arch);
835 } else {
836 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) << Arch;
837 return;
841 for (const auto &TripleAndArchs : DerivedArchs)
842 OpenMPTriples.push_back(TripleAndArchs.first());
845 for (StringRef Val : OpenMPTriples) {
846 llvm::Triple TT(ToolChain::getOpenMPTriple(Val));
847 std::string NormalizedName = TT.normalize();
849 // Make sure we don't have a duplicate triple.
850 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
851 if (Duplicate != FoundNormalizedTriples.end()) {
852 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
853 << Val << Duplicate->second;
854 continue;
857 // Store the current triple so that we can check for duplicates in the
858 // following iterations.
859 FoundNormalizedTriples[NormalizedName] = Val;
861 // If the specified target is invalid, emit a diagnostic.
862 if (TT.getArch() == llvm::Triple::UnknownArch)
863 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
864 else {
865 const ToolChain *TC;
866 // Device toolchains have to be selected differently. They pair host
867 // and device in their implementation.
868 if (TT.isNVPTX() || TT.isAMDGCN()) {
869 const ToolChain *HostTC =
870 C.getSingleOffloadToolChain<Action::OFK_Host>();
871 assert(HostTC && "Host toolchain should be always defined.");
872 auto &DeviceTC =
873 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
874 if (!DeviceTC) {
875 if (TT.isNVPTX())
876 DeviceTC = std::make_unique<toolchains::CudaToolChain>(
877 *this, TT, *HostTC, C.getInputArgs());
878 else if (TT.isAMDGCN())
879 DeviceTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
880 *this, TT, *HostTC, C.getInputArgs());
881 else
882 assert(DeviceTC && "Device toolchain not defined.");
885 TC = DeviceTC.get();
886 } else
887 TC = &getToolChain(C.getInputArgs(), TT);
888 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
889 if (DerivedArchs.find(TT.getTriple()) != DerivedArchs.end())
890 KnownArchs[TC] = DerivedArchs[TT.getTriple()];
893 } else if (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)) {
894 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
895 return;
899 // TODO: Add support for other offloading programming models here.
903 /// Looks the given directories for the specified file.
905 /// \param[out] FilePath File path, if the file was found.
906 /// \param[in] Dirs Directories used for the search.
907 /// \param[in] FileName Name of the file to search for.
908 /// \return True if file was found.
910 /// Looks for file specified by FileName sequentially in directories specified
911 /// by Dirs.
913 static bool searchForFile(SmallVectorImpl<char> &FilePath,
914 ArrayRef<StringRef> Dirs, StringRef FileName,
915 llvm::vfs::FileSystem &FS) {
916 SmallString<128> WPath;
917 for (const StringRef &Dir : Dirs) {
918 if (Dir.empty())
919 continue;
920 WPath.clear();
921 llvm::sys::path::append(WPath, Dir, FileName);
922 llvm::sys::path::native(WPath);
923 auto Status = FS.status(WPath);
924 if (Status && Status->getType() == llvm::sys::fs::file_type::regular_file) {
925 FilePath = std::move(WPath);
926 return true;
929 return false;
932 bool Driver::readConfigFile(StringRef FileName) {
933 // Try reading the given file.
934 SmallVector<const char *, 32> NewCfgArgs;
935 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs, getVFS())) {
936 Diag(diag::err_drv_cannot_read_config_file) << FileName;
937 return true;
940 // Read options from config file.
941 llvm::SmallString<128> CfgFileName(FileName);
942 llvm::sys::path::native(CfgFileName);
943 ConfigFile = std::string(CfgFileName);
944 bool ContainErrors;
945 CfgOptions = std::make_unique<InputArgList>(
946 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
947 if (ContainErrors) {
948 CfgOptions.reset();
949 return true;
952 if (CfgOptions->hasArg(options::OPT_config)) {
953 CfgOptions.reset();
954 Diag(diag::err_drv_nested_config_file);
955 return true;
958 // Claim all arguments that come from a configuration file so that the driver
959 // does not warn on any that is unused.
960 for (Arg *A : *CfgOptions)
961 A->claim();
962 return false;
965 bool Driver::loadConfigFile() {
966 std::string CfgFileName;
967 bool FileSpecifiedExplicitly = false;
969 // Process options that change search path for config files.
970 if (CLOptions) {
971 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
972 SmallString<128> CfgDir;
973 CfgDir.append(
974 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
975 if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
976 SystemConfigDir.clear();
977 else
978 SystemConfigDir = static_cast<std::string>(CfgDir);
980 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
981 SmallString<128> CfgDir;
982 CfgDir.append(
983 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
984 if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
985 UserConfigDir.clear();
986 else
987 UserConfigDir = static_cast<std::string>(CfgDir);
991 // First try to find config file specified in command line.
992 if (CLOptions) {
993 std::vector<std::string> ConfigFiles =
994 CLOptions->getAllArgValues(options::OPT_config);
995 if (ConfigFiles.size() > 1) {
996 if (!llvm::all_equal(ConfigFiles)) {
997 Diag(diag::err_drv_duplicate_config);
998 return true;
1002 if (!ConfigFiles.empty()) {
1003 CfgFileName = ConfigFiles.front();
1004 assert(!CfgFileName.empty());
1006 // If argument contains directory separator, treat it as a path to
1007 // configuration file.
1008 if (llvm::sys::path::has_parent_path(CfgFileName)) {
1009 SmallString<128> CfgFilePath(CfgFileName);
1010 if (llvm::sys::path::is_relative(CfgFilePath)) {
1011 if (getVFS().makeAbsolute(CfgFilePath))
1012 return true;
1013 auto Status = getVFS().status(CfgFilePath);
1014 if (!Status ||
1015 Status->getType() != llvm::sys::fs::file_type::regular_file) {
1016 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
1017 return true;
1020 return readConfigFile(CfgFilePath);
1023 FileSpecifiedExplicitly = true;
1027 if (!(CLOptions && CLOptions->hasArg(options::OPT_no_default_config))) {
1028 // If config file is not specified explicitly, try to deduce configuration
1029 // from executable name. For instance, an executable 'armv7l-clang' will
1030 // search for config file 'armv7l-clang.cfg'.
1031 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
1032 CfgFileName =
1033 ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
1036 if (CfgFileName.empty())
1037 return false;
1039 // Determine architecture part of the file name, if it is present.
1040 StringRef CfgFileArch = CfgFileName;
1041 size_t ArchPrefixLen = CfgFileArch.find('-');
1042 if (ArchPrefixLen == StringRef::npos)
1043 ArchPrefixLen = CfgFileArch.size();
1044 llvm::Triple CfgTriple;
1045 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
1046 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
1047 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
1048 ArchPrefixLen = 0;
1050 if (!StringRef(CfgFileName).endswith(".cfg"))
1051 CfgFileName += ".cfg";
1053 // If config file starts with architecture name and command line options
1054 // redefine architecture (with options like -m32 -LE etc), try finding new
1055 // config file with that architecture.
1056 SmallString<128> FixedConfigFile;
1057 size_t FixedArchPrefixLen = 0;
1058 if (ArchPrefixLen) {
1059 // Get architecture name from config file name like 'i386.cfg' or
1060 // 'armv7l-clang.cfg'.
1061 // Check if command line options changes effective triple.
1062 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
1063 CfgTriple.getTriple(), *CLOptions);
1064 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
1065 FixedConfigFile = EffectiveTriple.getArchName();
1066 FixedArchPrefixLen = FixedConfigFile.size();
1067 // Append the rest of original file name so that file name transforms
1068 // like: i386-clang.cfg -> x86_64-clang.cfg.
1069 if (ArchPrefixLen < CfgFileName.size())
1070 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
1074 // Prepare list of directories where config file is searched for.
1075 StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir};
1077 // Try to find config file. First try file with corrected architecture.
1078 llvm::SmallString<128> CfgFilePath;
1079 if (!FixedConfigFile.empty()) {
1080 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile,
1081 getVFS()))
1082 return readConfigFile(CfgFilePath);
1083 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
1084 FixedConfigFile.resize(FixedArchPrefixLen);
1085 FixedConfigFile.append(".cfg");
1086 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile,
1087 getVFS()))
1088 return readConfigFile(CfgFilePath);
1091 // Then try original file name.
1092 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName, getVFS()))
1093 return readConfigFile(CfgFilePath);
1095 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
1096 if (!ClangNameParts.ModeSuffix.empty() &&
1097 !ClangNameParts.TargetPrefix.empty()) {
1098 CfgFileName.assign(ClangNameParts.TargetPrefix);
1099 CfgFileName.append(".cfg");
1100 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName, getVFS()))
1101 return readConfigFile(CfgFilePath);
1104 // Report error but only if config file was specified explicitly, by option
1105 // --config. If it was deduced from executable name, it is not an error.
1106 if (FileSpecifiedExplicitly) {
1107 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
1108 for (const StringRef &SearchDir : CfgFileSearchDirs)
1109 if (!SearchDir.empty())
1110 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
1111 return true;
1114 return false;
1117 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
1118 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
1120 // FIXME: Handle environment options which affect driver behavior, somewhere
1121 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
1123 // We look for the driver mode option early, because the mode can affect
1124 // how other options are parsed.
1126 auto DriverMode = getDriverMode(ClangExecutable, ArgList.slice(1));
1127 if (!DriverMode.empty())
1128 setDriverMode(DriverMode);
1130 // FIXME: What are we going to do with -V and -b?
1132 // Arguments specified in command line.
1133 bool ContainsError;
1134 CLOptions = std::make_unique<InputArgList>(
1135 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
1137 // Try parsing configuration file.
1138 if (!ContainsError)
1139 ContainsError = loadConfigFile();
1140 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
1142 // All arguments, from both config file and command line.
1143 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
1144 : std::move(*CLOptions));
1146 // The args for config files or /clang: flags belong to different InputArgList
1147 // objects than Args. This copies an Arg from one of those other InputArgLists
1148 // to the ownership of Args.
1149 auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
1150 unsigned Index = Args.MakeIndex(Opt->getSpelling());
1151 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index),
1152 Index, BaseArg);
1153 Copy->getValues() = Opt->getValues();
1154 if (Opt->isClaimed())
1155 Copy->claim();
1156 Copy->setOwnsValues(Opt->getOwnsValues());
1157 Opt->setOwnsValues(false);
1158 Args.append(Copy);
1161 if (HasConfigFile)
1162 for (auto *Opt : *CLOptions) {
1163 if (Opt->getOption().matches(options::OPT_config))
1164 continue;
1165 const Arg *BaseArg = &Opt->getBaseArg();
1166 if (BaseArg == Opt)
1167 BaseArg = nullptr;
1168 appendOneArg(Opt, BaseArg);
1171 // In CL mode, look for any pass-through arguments
1172 if (IsCLMode() && !ContainsError) {
1173 SmallVector<const char *, 16> CLModePassThroughArgList;
1174 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1175 A->claim();
1176 CLModePassThroughArgList.push_back(A->getValue());
1179 if (!CLModePassThroughArgList.empty()) {
1180 // Parse any pass through args using default clang processing rather
1181 // than clang-cl processing.
1182 auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1183 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1185 if (!ContainsError)
1186 for (auto *Opt : *CLModePassThroughOptions) {
1187 appendOneArg(Opt, nullptr);
1192 // Check for working directory option before accessing any files
1193 if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1194 if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1195 Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1197 // FIXME: This stuff needs to go into the Compilation, not the driver.
1198 bool CCCPrintPhases;
1200 // Silence driver warnings if requested
1201 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1203 // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
1204 Args.ClaimAllArgs(options::OPT_canonical_prefixes);
1205 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1207 // f(no-)integated-cc1 is also used very early in main.
1208 Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1209 Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1211 // Ignore -pipe.
1212 Args.ClaimAllArgs(options::OPT_pipe);
1214 // Extract -ccc args.
1216 // FIXME: We need to figure out where this behavior should live. Most of it
1217 // should be outside in the client; the parts that aren't should have proper
1218 // options, either by introducing new ones or by overloading gcc ones like -V
1219 // or -b.
1220 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1221 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1222 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1223 CCCGenericGCCName = A->getValue();
1225 // Process -fproc-stat-report options.
1226 if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) {
1227 CCPrintProcessStats = true;
1228 CCPrintStatReportFilename = A->getValue();
1230 if (Args.hasArg(options::OPT_fproc_stat_report))
1231 CCPrintProcessStats = true;
1233 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1234 // and getToolChain is const.
1235 if (IsCLMode()) {
1236 // clang-cl targets MSVC-style Win32.
1237 llvm::Triple T(TargetTriple);
1238 T.setOS(llvm::Triple::Win32);
1239 T.setVendor(llvm::Triple::PC);
1240 T.setEnvironment(llvm::Triple::MSVC);
1241 T.setObjectFormat(llvm::Triple::COFF);
1242 TargetTriple = T.str();
1243 } else if (IsDXCMode()) {
1244 // Build TargetTriple from target_profile option for clang-dxc.
1245 if (const Arg *A = Args.getLastArg(options::OPT_target_profile)) {
1246 StringRef TargetProfile = A->getValue();
1247 if (auto Triple =
1248 toolchains::HLSLToolChain::parseTargetProfile(TargetProfile))
1249 TargetTriple = *Triple;
1250 else
1251 Diag(diag::err_drv_invalid_directx_shader_module) << TargetProfile;
1253 A->claim();
1254 } else {
1255 Diag(diag::err_drv_dxc_missing_target_profile);
1259 if (const Arg *A = Args.getLastArg(options::OPT_target))
1260 TargetTriple = A->getValue();
1261 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1262 Dir = InstalledDir = A->getValue();
1263 for (const Arg *A : Args.filtered(options::OPT_B)) {
1264 A->claim();
1265 PrefixDirs.push_back(A->getValue(0));
1267 if (Optional<std::string> CompilerPathValue =
1268 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
1269 StringRef CompilerPath = *CompilerPathValue;
1270 while (!CompilerPath.empty()) {
1271 std::pair<StringRef, StringRef> Split =
1272 CompilerPath.split(llvm::sys::EnvPathSeparator);
1273 PrefixDirs.push_back(std::string(Split.first));
1274 CompilerPath = Split.second;
1277 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1278 SysRoot = A->getValue();
1279 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1280 DyldPrefix = A->getValue();
1282 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1283 ResourceDir = A->getValue();
1285 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1286 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1287 .Case("cwd", SaveTempsCwd)
1288 .Case("obj", SaveTempsObj)
1289 .Default(SaveTempsCwd);
1292 if (const Arg *A = Args.getLastArg(options::OPT_offload_host_only,
1293 options::OPT_offload_device_only,
1294 options::OPT_offload_host_device)) {
1295 if (A->getOption().matches(options::OPT_offload_host_only))
1296 Offload = OffloadHost;
1297 else if (A->getOption().matches(options::OPT_offload_device_only))
1298 Offload = OffloadDevice;
1299 else
1300 Offload = OffloadHostDevice;
1303 setLTOMode(Args);
1305 // Process -fembed-bitcode= flags.
1306 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1307 StringRef Name = A->getValue();
1308 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1309 .Case("off", EmbedNone)
1310 .Case("all", EmbedBitcode)
1311 .Case("bitcode", EmbedBitcode)
1312 .Case("marker", EmbedMarker)
1313 .Default(~0U);
1314 if (Model == ~0U) {
1315 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1316 << Name;
1317 } else
1318 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1321 // Remove existing compilation database so that each job can append to it.
1322 if (Arg *A = Args.getLastArg(options::OPT_MJ))
1323 llvm::sys::fs::remove(A->getValue());
1325 // Setting up the jobs for some precompile cases depends on whether we are
1326 // treating them as PCH, implicit modules or C++20 ones.
1327 // TODO: inferring the mode like this seems fragile (it meets the objective
1328 // of not requiring anything new for operation, however).
1329 const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
1330 ModulesModeCXX20 =
1331 !Args.hasArg(options::OPT_fmodules) && Std &&
1332 (Std->containsValue("c++20") || Std->containsValue("c++2b") ||
1333 Std->containsValue("c++2a") || Std->containsValue("c++latest"));
1335 // Process -fmodule-header{=} flags.
1336 if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ,
1337 options::OPT_fmodule_header)) {
1338 // These flags force C++20 handling of headers.
1339 ModulesModeCXX20 = true;
1340 if (A->getOption().matches(options::OPT_fmodule_header))
1341 CXX20HeaderType = HeaderMode_Default;
1342 else {
1343 StringRef ArgName = A->getValue();
1344 unsigned Kind = llvm::StringSwitch<unsigned>(ArgName)
1345 .Case("user", HeaderMode_User)
1346 .Case("system", HeaderMode_System)
1347 .Default(~0U);
1348 if (Kind == ~0U) {
1349 Diags.Report(diag::err_drv_invalid_value)
1350 << A->getAsString(Args) << ArgName;
1351 } else
1352 CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind);
1356 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1357 std::make_unique<InputArgList>(std::move(Args));
1359 // Perform the default argument translations.
1360 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1362 // Owned by the host.
1363 const ToolChain &TC = getToolChain(
1364 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1366 // The compilation takes ownership of Args.
1367 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1368 ContainsError);
1370 if (!HandleImmediateArgs(*C))
1371 return C;
1373 // Construct the list of inputs.
1374 InputList Inputs;
1375 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1377 // Populate the tool chains for the offloading devices, if any.
1378 CreateOffloadingDeviceToolChains(*C, Inputs);
1380 // Construct the list of abstract actions to perform for this compilation. On
1381 // MachO targets this uses the driver-driver and universal actions.
1382 if (TC.getTriple().isOSBinFormatMachO())
1383 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1384 else
1385 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1387 if (CCCPrintPhases) {
1388 PrintActions(*C);
1389 return C;
1392 BuildJobs(*C);
1394 return C;
1397 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1398 llvm::opt::ArgStringList ASL;
1399 for (const auto *A : Args) {
1400 // Use user's original spelling of flags. For example, use
1401 // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
1402 // wrote the former.
1403 while (A->getAlias())
1404 A = A->getAlias();
1405 A->render(Args, ASL);
1408 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1409 if (I != ASL.begin())
1410 OS << ' ';
1411 llvm::sys::printArg(OS, *I, true);
1413 OS << '\n';
1416 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1417 SmallString<128> &CrashDiagDir) {
1418 using namespace llvm::sys;
1419 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1420 "Only knows about .crash files on Darwin");
1422 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1423 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1424 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1425 path::home_directory(CrashDiagDir);
1426 if (CrashDiagDir.startswith("/var/root"))
1427 CrashDiagDir = "/";
1428 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1429 int PID =
1430 #if LLVM_ON_UNIX
1431 getpid();
1432 #else
1434 #endif
1435 std::error_code EC;
1436 fs::file_status FileStatus;
1437 TimePoint<> LastAccessTime;
1438 SmallString<128> CrashFilePath;
1439 // Lookup the .crash files and get the one generated by a subprocess spawned
1440 // by this driver invocation.
1441 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1442 File != FileEnd && !EC; File.increment(EC)) {
1443 StringRef FileName = path::filename(File->path());
1444 if (!FileName.startswith(Name))
1445 continue;
1446 if (fs::status(File->path(), FileStatus))
1447 continue;
1448 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1449 llvm::MemoryBuffer::getFile(File->path());
1450 if (!CrashFile)
1451 continue;
1452 // The first line should start with "Process:", otherwise this isn't a real
1453 // .crash file.
1454 StringRef Data = CrashFile.get()->getBuffer();
1455 if (!Data.startswith("Process:"))
1456 continue;
1457 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1458 size_t ParentProcPos = Data.find("Parent Process:");
1459 if (ParentProcPos == StringRef::npos)
1460 continue;
1461 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1462 if (LineEnd == StringRef::npos)
1463 continue;
1464 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1465 int OpenBracket = -1, CloseBracket = -1;
1466 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1467 if (ParentProcess[i] == '[')
1468 OpenBracket = i;
1469 if (ParentProcess[i] == ']')
1470 CloseBracket = i;
1472 // Extract the parent process PID from the .crash file and check whether
1473 // it matches this driver invocation pid.
1474 int CrashPID;
1475 if (OpenBracket < 0 || CloseBracket < 0 ||
1476 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1477 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1478 continue;
1481 // Found a .crash file matching the driver pid. To avoid getting an older
1482 // and misleading crash file, continue looking for the most recent.
1483 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1484 // multiple crashes poiting to the same parent process. Since the driver
1485 // does not collect pid information for the dispatched invocation there's
1486 // currently no way to distinguish among them.
1487 const auto FileAccessTime = FileStatus.getLastModificationTime();
1488 if (FileAccessTime > LastAccessTime) {
1489 CrashFilePath.assign(File->path());
1490 LastAccessTime = FileAccessTime;
1494 // If found, copy it over to the location of other reproducer files.
1495 if (!CrashFilePath.empty()) {
1496 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1497 if (EC)
1498 return false;
1499 return true;
1502 return false;
1505 // When clang crashes, produce diagnostic information including the fully
1506 // preprocessed source file(s). Request that the developer attach the
1507 // diagnostic information to a bug report.
1508 void Driver::generateCompilationDiagnostics(
1509 Compilation &C, const Command &FailingCommand,
1510 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1511 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1512 return;
1514 unsigned Level = 1;
1515 if (Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ)) {
1516 Level = llvm::StringSwitch<unsigned>(A->getValue())
1517 .Case("off", 0)
1518 .Case("compiler", 1)
1519 .Case("all", 2)
1520 .Default(1);
1522 if (!Level)
1523 return;
1525 // Don't try to generate diagnostics for dsymutil jobs.
1526 if (FailingCommand.getCreator().isDsymutilJob())
1527 return;
1529 bool IsLLD = false;
1530 ArgStringList SavedTemps;
1531 if (FailingCommand.getCreator().isLinkJob()) {
1532 C.getDefaultToolChain().GetLinkerPath(&IsLLD);
1533 if (!IsLLD || Level < 2)
1534 return;
1536 // If lld crashed, we will re-run the same command with the input it used
1537 // to have. In that case we should not remove temp files in
1538 // initCompilationForDiagnostics yet. They will be added back and removed
1539 // later.
1540 SavedTemps = std::move(C.getTempFiles());
1541 assert(!C.getTempFiles().size());
1544 // Print the version of the compiler.
1545 PrintVersion(C, llvm::errs());
1547 // Suppress driver output and emit preprocessor output to temp file.
1548 CCGenDiagnostics = true;
1550 // Save the original job command(s).
1551 Command Cmd = FailingCommand;
1553 // Keep track of whether we produce any errors while trying to produce
1554 // preprocessed sources.
1555 DiagnosticErrorTrap Trap(Diags);
1557 // Suppress tool output.
1558 C.initCompilationForDiagnostics();
1560 // Construct the list of inputs.
1561 InputList Inputs;
1562 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1564 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1565 bool IgnoreInput = false;
1567 // Ignore input from stdin or any inputs that cannot be preprocessed.
1568 // Check type first as not all linker inputs have a value.
1569 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1570 IgnoreInput = true;
1571 } else if (!strcmp(it->second->getValue(), "-")) {
1572 Diag(clang::diag::note_drv_command_failed_diag_msg)
1573 << "Error generating preprocessed source(s) - "
1574 "ignoring input from stdin.";
1575 IgnoreInput = true;
1578 if (IgnoreInput) {
1579 it = Inputs.erase(it);
1580 ie = Inputs.end();
1581 } else {
1582 ++it;
1586 if (Inputs.empty()) {
1587 Diag(clang::diag::note_drv_command_failed_diag_msg)
1588 << "Error generating preprocessed source(s) - "
1589 "no preprocessable inputs.";
1590 return;
1593 // Don't attempt to generate preprocessed files if multiple -arch options are
1594 // used, unless they're all duplicates.
1595 llvm::StringSet<> ArchNames;
1596 for (const Arg *A : C.getArgs()) {
1597 if (A->getOption().matches(options::OPT_arch)) {
1598 StringRef ArchName = A->getValue();
1599 ArchNames.insert(ArchName);
1602 if (ArchNames.size() > 1) {
1603 Diag(clang::diag::note_drv_command_failed_diag_msg)
1604 << "Error generating preprocessed source(s) - cannot generate "
1605 "preprocessed source with multiple -arch options.";
1606 return;
1609 // Construct the list of abstract actions to perform for this compilation. On
1610 // Darwin OSes this uses the driver-driver and builds universal actions.
1611 const ToolChain &TC = C.getDefaultToolChain();
1612 if (TC.getTriple().isOSBinFormatMachO())
1613 BuildUniversalActions(C, TC, Inputs);
1614 else
1615 BuildActions(C, C.getArgs(), Inputs, C.getActions());
1617 BuildJobs(C);
1619 // If there were errors building the compilation, quit now.
1620 if (Trap.hasErrorOccurred()) {
1621 Diag(clang::diag::note_drv_command_failed_diag_msg)
1622 << "Error generating preprocessed source(s).";
1623 return;
1626 // Generate preprocessed output.
1627 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1628 C.ExecuteJobs(C.getJobs(), FailingCommands);
1630 // If any of the preprocessing commands failed, clean up and exit.
1631 if (!FailingCommands.empty()) {
1632 Diag(clang::diag::note_drv_command_failed_diag_msg)
1633 << "Error generating preprocessed source(s).";
1634 return;
1637 // If lld failed, rerun it again with --reproduce.
1638 if (IsLLD) {
1639 const char *TmpName = CreateTempFile(C, "linker-crash", "tar");
1640 Command NewLLDInvocation = Cmd;
1641 llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments();
1642 StringRef ReproduceOption =
1643 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment()
1644 ? "/reproduce:"
1645 : "--reproduce=";
1646 ArgList.push_back(Saver.save(Twine(ReproduceOption) + TmpName).data());
1647 NewLLDInvocation.replaceArguments(std::move(ArgList));
1649 // Redirect stdout/stderr to /dev/null.
1650 NewLLDInvocation.Execute({None, {""}, {""}}, nullptr, nullptr);
1653 const ArgStringList &TempFiles = C.getTempFiles();
1654 if (TempFiles.empty()) {
1655 Diag(clang::diag::note_drv_command_failed_diag_msg)
1656 << "Error generating preprocessed source(s).";
1657 return;
1660 Diag(clang::diag::note_drv_command_failed_diag_msg)
1661 << "\n********************\n\n"
1662 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1663 "Preprocessed source(s) and associated run script(s) are located at:";
1665 SmallString<128> VFS;
1666 SmallString<128> ReproCrashFilename;
1667 for (const char *TempFile : TempFiles) {
1668 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1669 if (Report)
1670 Report->TemporaryFiles.push_back(TempFile);
1671 if (ReproCrashFilename.empty()) {
1672 ReproCrashFilename = TempFile;
1673 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1675 if (StringRef(TempFile).endswith(".cache")) {
1676 // In some cases (modules) we'll dump extra data to help with reproducing
1677 // the crash into a directory next to the output.
1678 VFS = llvm::sys::path::filename(TempFile);
1679 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1683 for (const char *TempFile : SavedTemps)
1684 C.addTempFile(TempFile);
1686 // Assume associated files are based off of the first temporary file.
1687 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1689 llvm::SmallString<128> Script(CrashInfo.Filename);
1690 llvm::sys::path::replace_extension(Script, "sh");
1691 std::error_code EC;
1692 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew,
1693 llvm::sys::fs::FA_Write,
1694 llvm::sys::fs::OF_Text);
1695 if (EC) {
1696 Diag(clang::diag::note_drv_command_failed_diag_msg)
1697 << "Error generating run script: " << Script << " " << EC.message();
1698 } else {
1699 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1700 << "# Driver args: ";
1701 printArgList(ScriptOS, C.getInputArgs());
1702 ScriptOS << "# Original command: ";
1703 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1704 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1705 if (!AdditionalInformation.empty())
1706 ScriptOS << "\n# Additional information: " << AdditionalInformation
1707 << "\n";
1708 if (Report)
1709 Report->TemporaryFiles.push_back(std::string(Script.str()));
1710 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1713 // On darwin, provide information about the .crash diagnostic report.
1714 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1715 SmallString<128> CrashDiagDir;
1716 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1717 Diag(clang::diag::note_drv_command_failed_diag_msg)
1718 << ReproCrashFilename.str();
1719 } else { // Suggest a directory for the user to look for .crash files.
1720 llvm::sys::path::append(CrashDiagDir, Name);
1721 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1722 Diag(clang::diag::note_drv_command_failed_diag_msg)
1723 << "Crash backtrace is located in";
1724 Diag(clang::diag::note_drv_command_failed_diag_msg)
1725 << CrashDiagDir.str();
1726 Diag(clang::diag::note_drv_command_failed_diag_msg)
1727 << "(choose the .crash file that corresponds to your crash)";
1731 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file_EQ))
1732 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1734 Diag(clang::diag::note_drv_command_failed_diag_msg)
1735 << "\n\n********************";
1738 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1739 // Since commandLineFitsWithinSystemLimits() may underestimate system's
1740 // capacity if the tool does not support response files, there is a chance/
1741 // that things will just work without a response file, so we silently just
1742 // skip it.
1743 if (Cmd.getResponseFileSupport().ResponseKind ==
1744 ResponseFileSupport::RF_None ||
1745 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1746 Cmd.getArguments()))
1747 return;
1749 std::string TmpName = GetTemporaryPath("response", "txt");
1750 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1753 int Driver::ExecuteCompilation(
1754 Compilation &C,
1755 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1756 if (C.getArgs().hasArg(options::OPT_fdriver_only)) {
1757 if (C.getArgs().hasArg(options::OPT_v))
1758 C.getJobs().Print(llvm::errs(), "\n", true);
1760 C.ExecuteJobs(C.getJobs(), FailingCommands, /*LogOnly=*/true);
1762 // If there were errors building the compilation, quit now.
1763 if (!FailingCommands.empty() || Diags.hasErrorOccurred())
1764 return 1;
1766 return 0;
1769 // Just print if -### was present.
1770 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1771 C.getJobs().Print(llvm::errs(), "\n", true);
1772 return 0;
1775 // If there were errors building the compilation, quit now.
1776 if (Diags.hasErrorOccurred())
1777 return 1;
1779 // Set up response file names for each command, if necessary.
1780 for (auto &Job : C.getJobs())
1781 setUpResponseFiles(C, Job);
1783 C.ExecuteJobs(C.getJobs(), FailingCommands);
1785 // If the command succeeded, we are done.
1786 if (FailingCommands.empty())
1787 return 0;
1789 // Otherwise, remove result files and print extra information about abnormal
1790 // failures.
1791 int Res = 0;
1792 for (const auto &CmdPair : FailingCommands) {
1793 int CommandRes = CmdPair.first;
1794 const Command *FailingCommand = CmdPair.second;
1796 // Remove result files if we're not saving temps.
1797 if (!isSaveTempsEnabled()) {
1798 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1799 C.CleanupFileMap(C.getResultFiles(), JA, true);
1801 // Failure result files are valid unless we crashed.
1802 if (CommandRes < 0)
1803 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1806 #if LLVM_ON_UNIX
1807 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1808 // for SIGPIPE. Do not print diagnostics for this case.
1809 if (CommandRes == EX_IOERR) {
1810 Res = CommandRes;
1811 continue;
1813 #endif
1815 // Print extra information about abnormal failures, if possible.
1817 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1818 // status was 1, assume the command failed normally. In particular, if it
1819 // was the compiler then assume it gave a reasonable error code. Failures
1820 // in other tools are less common, and they generally have worse
1821 // diagnostics, so always print the diagnostic there.
1822 const Tool &FailingTool = FailingCommand->getCreator();
1824 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1825 // FIXME: See FIXME above regarding result code interpretation.
1826 if (CommandRes < 0)
1827 Diag(clang::diag::err_drv_command_signalled)
1828 << FailingTool.getShortName();
1829 else
1830 Diag(clang::diag::err_drv_command_failed)
1831 << FailingTool.getShortName() << CommandRes;
1834 return Res;
1837 void Driver::PrintHelp(bool ShowHidden) const {
1838 unsigned IncludedFlagsBitmask;
1839 unsigned ExcludedFlagsBitmask;
1840 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1841 getIncludeExcludeOptionFlagMasks(IsCLMode());
1843 ExcludedFlagsBitmask |= options::NoDriverOption;
1844 if (!ShowHidden)
1845 ExcludedFlagsBitmask |= HelpHidden;
1847 if (IsFlangMode())
1848 IncludedFlagsBitmask |= options::FlangOption;
1849 else
1850 ExcludedFlagsBitmask |= options::FlangOnlyOption;
1852 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1853 getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1854 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1855 /*ShowAllAliases=*/false);
1858 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1859 if (IsFlangMode()) {
1860 OS << getClangToolFullVersion("flang-new") << '\n';
1861 } else {
1862 // FIXME: The following handlers should use a callback mechanism, we don't
1863 // know what the client would like to do.
1864 OS << getClangFullVersion() << '\n';
1866 const ToolChain &TC = C.getDefaultToolChain();
1867 OS << "Target: " << TC.getTripleString() << '\n';
1869 // Print the threading model.
1870 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1871 // Don't print if the ToolChain would have barfed on it already
1872 if (TC.isThreadModelSupported(A->getValue()))
1873 OS << "Thread model: " << A->getValue();
1874 } else
1875 OS << "Thread model: " << TC.getThreadModel();
1876 OS << '\n';
1878 // Print out the install directory.
1879 OS << "InstalledDir: " << InstalledDir << '\n';
1881 // If configuration file was used, print its path.
1882 if (!ConfigFile.empty())
1883 OS << "Configuration file: " << ConfigFile << '\n';
1886 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1887 /// option.
1888 static void PrintDiagnosticCategories(raw_ostream &OS) {
1889 // Skip the empty category.
1890 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1891 ++i)
1892 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1895 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1896 if (PassedFlags == "")
1897 return;
1898 // Print out all options that start with a given argument. This is used for
1899 // shell autocompletion.
1900 std::vector<std::string> SuggestedCompletions;
1901 std::vector<std::string> Flags;
1903 unsigned int DisableFlags =
1904 options::NoDriverOption | options::Unsupported | options::Ignored;
1906 // Make sure that Flang-only options don't pollute the Clang output
1907 // TODO: Make sure that Clang-only options don't pollute Flang output
1908 if (!IsFlangMode())
1909 DisableFlags |= options::FlangOnlyOption;
1911 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1912 // because the latter indicates that the user put space before pushing tab
1913 // which should end up in a file completion.
1914 const bool HasSpace = PassedFlags.endswith(",");
1916 // Parse PassedFlags by "," as all the command-line flags are passed to this
1917 // function separated by ","
1918 StringRef TargetFlags = PassedFlags;
1919 while (TargetFlags != "") {
1920 StringRef CurFlag;
1921 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1922 Flags.push_back(std::string(CurFlag));
1925 // We want to show cc1-only options only when clang is invoked with -cc1 or
1926 // -Xclang.
1927 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1928 DisableFlags &= ~options::NoDriverOption;
1930 const llvm::opt::OptTable &Opts = getOpts();
1931 StringRef Cur;
1932 Cur = Flags.at(Flags.size() - 1);
1933 StringRef Prev;
1934 if (Flags.size() >= 2) {
1935 Prev = Flags.at(Flags.size() - 2);
1936 SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1939 if (SuggestedCompletions.empty())
1940 SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1942 // If Flags were empty, it means the user typed `clang [tab]` where we should
1943 // list all possible flags. If there was no value completion and the user
1944 // pressed tab after a space, we should fall back to a file completion.
1945 // We're printing a newline to be consistent with what we print at the end of
1946 // this function.
1947 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1948 llvm::outs() << '\n';
1949 return;
1952 // When flag ends with '=' and there was no value completion, return empty
1953 // string and fall back to the file autocompletion.
1954 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1955 // If the flag is in the form of "--autocomplete=-foo",
1956 // we were requested to print out all option names that start with "-foo".
1957 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1958 SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1960 // We have to query the -W flags manually as they're not in the OptTable.
1961 // TODO: Find a good way to add them to OptTable instead and them remove
1962 // this code.
1963 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1964 if (S.startswith(Cur))
1965 SuggestedCompletions.push_back(std::string(S));
1968 // Sort the autocomplete candidates so that shells print them out in a
1969 // deterministic order. We could sort in any way, but we chose
1970 // case-insensitive sorting for consistency with the -help option
1971 // which prints out options in the case-insensitive alphabetical order.
1972 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1973 if (int X = A.compare_insensitive(B))
1974 return X < 0;
1975 return A.compare(B) > 0;
1978 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1981 bool Driver::HandleImmediateArgs(const Compilation &C) {
1982 // The order these options are handled in gcc is all over the place, but we
1983 // don't expect inconsistencies w.r.t. that to matter in practice.
1985 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1986 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1987 return false;
1990 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1991 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1992 // return an answer which matches our definition of __VERSION__.
1993 llvm::outs() << CLANG_VERSION_STRING << "\n";
1994 return false;
1997 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1998 PrintDiagnosticCategories(llvm::outs());
1999 return false;
2002 if (C.getArgs().hasArg(options::OPT_help) ||
2003 C.getArgs().hasArg(options::OPT__help_hidden)) {
2004 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
2005 return false;
2008 if (C.getArgs().hasArg(options::OPT__version)) {
2009 // Follow gcc behavior and use stdout for --version and stderr for -v.
2010 PrintVersion(C, llvm::outs());
2011 return false;
2014 if (C.getArgs().hasArg(options::OPT_v) ||
2015 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
2016 C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
2017 PrintVersion(C, llvm::errs());
2018 SuppressMissingInputWarning = true;
2021 if (C.getArgs().hasArg(options::OPT_v)) {
2022 if (!SystemConfigDir.empty())
2023 llvm::errs() << "System configuration file directory: "
2024 << SystemConfigDir << "\n";
2025 if (!UserConfigDir.empty())
2026 llvm::errs() << "User configuration file directory: "
2027 << UserConfigDir << "\n";
2030 const ToolChain &TC = C.getDefaultToolChain();
2032 if (C.getArgs().hasArg(options::OPT_v))
2033 TC.printVerboseInfo(llvm::errs());
2035 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
2036 llvm::outs() << ResourceDir << '\n';
2037 return false;
2040 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
2041 llvm::outs() << "programs: =";
2042 bool separator = false;
2043 // Print -B and COMPILER_PATH.
2044 for (const std::string &Path : PrefixDirs) {
2045 if (separator)
2046 llvm::outs() << llvm::sys::EnvPathSeparator;
2047 llvm::outs() << Path;
2048 separator = true;
2050 for (const std::string &Path : TC.getProgramPaths()) {
2051 if (separator)
2052 llvm::outs() << llvm::sys::EnvPathSeparator;
2053 llvm::outs() << Path;
2054 separator = true;
2056 llvm::outs() << "\n";
2057 llvm::outs() << "libraries: =" << ResourceDir;
2059 StringRef sysroot = C.getSysRoot();
2061 for (const std::string &Path : TC.getFilePaths()) {
2062 // Always print a separator. ResourceDir was the first item shown.
2063 llvm::outs() << llvm::sys::EnvPathSeparator;
2064 // Interpretation of leading '=' is needed only for NetBSD.
2065 if (Path[0] == '=')
2066 llvm::outs() << sysroot << Path.substr(1);
2067 else
2068 llvm::outs() << Path;
2070 llvm::outs() << "\n";
2071 return false;
2074 if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) {
2075 std::string RuntimePath;
2076 // Get the first existing path, if any.
2077 for (auto Path : TC.getRuntimePaths()) {
2078 if (getVFS().exists(Path)) {
2079 RuntimePath = Path;
2080 break;
2083 if (!RuntimePath.empty())
2084 llvm::outs() << RuntimePath << '\n';
2085 else
2086 llvm::outs() << TC.getCompilerRTPath() << '\n';
2087 return false;
2090 if (C.getArgs().hasArg(options::OPT_print_diagnostic_options)) {
2091 std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags();
2092 for (std::size_t I = 0; I != Flags.size(); I += 2)
2093 llvm::outs() << " " << Flags[I] << "\n " << Flags[I + 1] << "\n\n";
2094 return false;
2097 // FIXME: The following handlers should use a callback mechanism, we don't
2098 // know what the client would like to do.
2099 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
2100 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
2101 return false;
2104 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
2105 StringRef ProgName = A->getValue();
2107 // Null program name cannot have a path.
2108 if (! ProgName.empty())
2109 llvm::outs() << GetProgramPath(ProgName, TC);
2111 llvm::outs() << "\n";
2112 return false;
2115 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
2116 StringRef PassedFlags = A->getValue();
2117 HandleAutocompletions(PassedFlags);
2118 return false;
2121 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
2122 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
2123 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2124 RegisterEffectiveTriple TripleRAII(TC, Triple);
2125 switch (RLT) {
2126 case ToolChain::RLT_CompilerRT:
2127 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
2128 break;
2129 case ToolChain::RLT_Libgcc:
2130 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
2131 break;
2133 return false;
2136 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
2137 for (const Multilib &Multilib : TC.getMultilibs())
2138 llvm::outs() << Multilib << "\n";
2139 return false;
2142 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
2143 const Multilib &Multilib = TC.getMultilib();
2144 if (Multilib.gccSuffix().empty())
2145 llvm::outs() << ".\n";
2146 else {
2147 StringRef Suffix(Multilib.gccSuffix());
2148 assert(Suffix.front() == '/');
2149 llvm::outs() << Suffix.substr(1) << "\n";
2151 return false;
2154 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
2155 llvm::outs() << TC.getTripleString() << "\n";
2156 return false;
2159 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
2160 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2161 llvm::outs() << Triple.getTriple() << "\n";
2162 return false;
2165 if (C.getArgs().hasArg(options::OPT_print_targets)) {
2166 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
2167 return false;
2170 return true;
2173 enum {
2174 TopLevelAction = 0,
2175 HeadSibAction = 1,
2176 OtherSibAction = 2,
2179 // Display an action graph human-readably. Action A is the "sink" node
2180 // and latest-occuring action. Traversal is in pre-order, visiting the
2181 // inputs to each action before printing the action itself.
2182 static unsigned PrintActions1(const Compilation &C, Action *A,
2183 std::map<Action *, unsigned> &Ids,
2184 Twine Indent = {}, int Kind = TopLevelAction) {
2185 if (Ids.count(A)) // A was already visited.
2186 return Ids[A];
2188 std::string str;
2189 llvm::raw_string_ostream os(str);
2191 auto getSibIndent = [](int K) -> Twine {
2192 return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "";
2195 Twine SibIndent = Indent + getSibIndent(Kind);
2196 int SibKind = HeadSibAction;
2197 os << Action::getClassName(A->getKind()) << ", ";
2198 if (InputAction *IA = dyn_cast<InputAction>(A)) {
2199 os << "\"" << IA->getInputArg().getValue() << "\"";
2200 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
2201 os << '"' << BIA->getArchName() << '"' << ", {"
2202 << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
2203 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2204 bool IsFirst = true;
2205 OA->doOnEachDependence(
2206 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
2207 assert(TC && "Unknown host toolchain");
2208 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
2209 // sm_35 this will generate:
2210 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
2211 // (nvptx64-nvidia-cuda:sm_35) {#ID}
2212 if (!IsFirst)
2213 os << ", ";
2214 os << '"';
2215 os << A->getOffloadingKindPrefix();
2216 os << " (";
2217 os << TC->getTriple().normalize();
2218 if (BoundArch)
2219 os << ":" << BoundArch;
2220 os << ")";
2221 os << '"';
2222 os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
2223 IsFirst = false;
2224 SibKind = OtherSibAction;
2226 } else {
2227 const ActionList *AL = &A->getInputs();
2229 if (AL->size()) {
2230 const char *Prefix = "{";
2231 for (Action *PreRequisite : *AL) {
2232 os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
2233 Prefix = ", ";
2234 SibKind = OtherSibAction;
2236 os << "}";
2237 } else
2238 os << "{}";
2241 // Append offload info for all options other than the offloading action
2242 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
2243 std::string offload_str;
2244 llvm::raw_string_ostream offload_os(offload_str);
2245 if (!isa<OffloadAction>(A)) {
2246 auto S = A->getOffloadingKindPrefix();
2247 if (!S.empty()) {
2248 offload_os << ", (" << S;
2249 if (A->getOffloadingArch())
2250 offload_os << ", " << A->getOffloadingArch();
2251 offload_os << ")";
2255 auto getSelfIndent = [](int K) -> Twine {
2256 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
2259 unsigned Id = Ids.size();
2260 Ids[A] = Id;
2261 llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
2262 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
2264 return Id;
2267 // Print the action graphs in a compilation C.
2268 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
2269 void Driver::PrintActions(const Compilation &C) const {
2270 std::map<Action *, unsigned> Ids;
2271 for (Action *A : C.getActions())
2272 PrintActions1(C, A, Ids);
2275 /// Check whether the given input tree contains any compilation or
2276 /// assembly actions.
2277 static bool ContainsCompileOrAssembleAction(const Action *A) {
2278 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
2279 isa<AssembleJobAction>(A))
2280 return true;
2282 return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction);
2285 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
2286 const InputList &BAInputs) const {
2287 DerivedArgList &Args = C.getArgs();
2288 ActionList &Actions = C.getActions();
2289 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2290 // Collect the list of architectures. Duplicates are allowed, but should only
2291 // be handled once (in the order seen).
2292 llvm::StringSet<> ArchNames;
2293 SmallVector<const char *, 4> Archs;
2294 for (Arg *A : Args) {
2295 if (A->getOption().matches(options::OPT_arch)) {
2296 // Validate the option here; we don't save the type here because its
2297 // particular spelling may participate in other driver choices.
2298 llvm::Triple::ArchType Arch =
2299 tools::darwin::getArchTypeForMachOArchName(A->getValue());
2300 if (Arch == llvm::Triple::UnknownArch) {
2301 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2302 continue;
2305 A->claim();
2306 if (ArchNames.insert(A->getValue()).second)
2307 Archs.push_back(A->getValue());
2311 // When there is no explicit arch for this platform, make sure we still bind
2312 // the architecture (to the default) so that -Xarch_ is handled correctly.
2313 if (!Archs.size())
2314 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
2316 ActionList SingleActions;
2317 BuildActions(C, Args, BAInputs, SingleActions);
2319 // Add in arch bindings for every top level action, as well as lipo and
2320 // dsymutil steps if needed.
2321 for (Action* Act : SingleActions) {
2322 // Make sure we can lipo this kind of output. If not (and it is an actual
2323 // output) then we disallow, since we can't create an output file with the
2324 // right name without overwriting it. We could remove this oddity by just
2325 // changing the output names to include the arch, which would also fix
2326 // -save-temps. Compatibility wins for now.
2328 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
2329 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
2330 << types::getTypeName(Act->getType());
2332 ActionList Inputs;
2333 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
2334 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
2336 // Lipo if necessary, we do it this way because we need to set the arch flag
2337 // so that -Xarch_ gets overwritten.
2338 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2339 Actions.append(Inputs.begin(), Inputs.end());
2340 else
2341 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2343 // Handle debug info queries.
2344 Arg *A = Args.getLastArg(options::OPT_g_Group);
2345 bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2346 !A->getOption().matches(options::OPT_gstabs);
2347 if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2348 ContainsCompileOrAssembleAction(Actions.back())) {
2350 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2351 // have a compile input. We need to run 'dsymutil' ourselves in such cases
2352 // because the debug info will refer to a temporary object file which
2353 // will be removed at the end of the compilation process.
2354 if (Act->getType() == types::TY_Image) {
2355 ActionList Inputs;
2356 Inputs.push_back(Actions.back());
2357 Actions.pop_back();
2358 Actions.push_back(
2359 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2362 // Verify the debug info output.
2363 if (Args.hasArg(options::OPT_verify_debug_info)) {
2364 Action* LastAction = Actions.back();
2365 Actions.pop_back();
2366 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2367 LastAction, types::TY_Nothing));
2373 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2374 types::ID Ty, bool TypoCorrect) const {
2375 if (!getCheckInputsExist())
2376 return true;
2378 // stdin always exists.
2379 if (Value == "-")
2380 return true;
2382 // If it's a header to be found in the system or user search path, then defer
2383 // complaints about its absence until those searches can be done. When we
2384 // are definitely processing headers for C++20 header units, extend this to
2385 // allow the user to put "-fmodule-header -xc++-header vector" for example.
2386 if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader ||
2387 (ModulesModeCXX20 && Ty == types::TY_CXXHeader))
2388 return true;
2390 if (getVFS().exists(Value))
2391 return true;
2393 if (TypoCorrect) {
2394 // Check if the filename is a typo for an option flag. OptTable thinks
2395 // that all args that are not known options and that start with / are
2396 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2397 // the option `/diagnostics:caret` than a reference to a file in the root
2398 // directory.
2399 unsigned IncludedFlagsBitmask;
2400 unsigned ExcludedFlagsBitmask;
2401 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2402 getIncludeExcludeOptionFlagMasks(IsCLMode());
2403 std::string Nearest;
2404 if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2405 ExcludedFlagsBitmask) <= 1) {
2406 Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2407 << Value << Nearest;
2408 return false;
2412 // In CL mode, don't error on apparently non-existent linker inputs, because
2413 // they can be influenced by linker flags the clang driver might not
2414 // understand.
2415 // Examples:
2416 // - `clang-cl main.cc ole32.lib` in a a non-MSVC shell will make the driver
2417 // module look for an MSVC installation in the registry. (We could ask
2418 // the MSVCToolChain object if it can find `ole32.lib`, but the logic to
2419 // look in the registry might move into lld-link in the future so that
2420 // lld-link invocations in non-MSVC shells just work too.)
2421 // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
2422 // including /libpath:, which is used to find .lib and .obj files.
2423 // So do not diagnose this on the driver level. Rely on the linker diagnosing
2424 // it. (If we don't end up invoking the linker, this means we'll emit a
2425 // "'linker' input unused [-Wunused-command-line-argument]" warning instead
2426 // of an error.)
2428 // Only do this skip after the typo correction step above. `/Brepo` is treated
2429 // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit
2430 // an error if we have a flag that's within an edit distance of 1 from a
2431 // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
2432 // driver in the unlikely case they run into this.)
2434 // Don't do this for inputs that start with a '/', else we'd pass options
2435 // like /libpath: through to the linker silently.
2437 // Emitting an error for linker inputs can also cause incorrect diagnostics
2438 // with the gcc driver. The command
2439 // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
2440 // will make lld look for some/dir/file.o, while we will diagnose here that
2441 // `/file.o` does not exist. However, configure scripts check if
2442 // `clang /GR-` compiles without error to see if the compiler is cl.exe,
2443 // so we can't downgrade diagnostics for `/GR-` from an error to a warning
2444 // in cc mode. (We can in cl mode because cl.exe itself only warns on
2445 // unknown flags.)
2446 if (IsCLMode() && Ty == types::TY_Object && !Value.startswith("/"))
2447 return true;
2449 Diag(clang::diag::err_drv_no_such_file) << Value;
2450 return false;
2453 // Get the C++20 Header Unit type corresponding to the input type.
2454 static types::ID CXXHeaderUnitType(ModuleHeaderMode HM) {
2455 switch (HM) {
2456 case HeaderMode_User:
2457 return types::TY_CXXUHeader;
2458 case HeaderMode_System:
2459 return types::TY_CXXSHeader;
2460 case HeaderMode_Default:
2461 break;
2462 case HeaderMode_None:
2463 llvm_unreachable("should not be called in this case");
2465 return types::TY_CXXHUHeader;
2468 // Construct a the list of inputs and their types.
2469 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2470 InputList &Inputs) const {
2471 const llvm::opt::OptTable &Opts = getOpts();
2472 // Track the current user specified (-x) input. We also explicitly track the
2473 // argument used to set the type; we only want to claim the type when we
2474 // actually use it, so we warn about unused -x arguments.
2475 types::ID InputType = types::TY_Nothing;
2476 Arg *InputTypeArg = nullptr;
2478 // The last /TC or /TP option sets the input type to C or C++ globally.
2479 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2480 options::OPT__SLASH_TP)) {
2481 InputTypeArg = TCTP;
2482 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2483 ? types::TY_C
2484 : types::TY_CXX;
2486 Arg *Previous = nullptr;
2487 bool ShowNote = false;
2488 for (Arg *A :
2489 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2490 if (Previous) {
2491 Diag(clang::diag::warn_drv_overriding_flag_option)
2492 << Previous->getSpelling() << A->getSpelling();
2493 ShowNote = true;
2495 Previous = A;
2497 if (ShowNote)
2498 Diag(clang::diag::note_drv_t_option_is_global);
2500 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2501 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2504 // Warn -x after last input file has no effect
2506 Arg *LastXArg = Args.getLastArgNoClaim(options::OPT_x);
2507 Arg *LastInputArg = Args.getLastArgNoClaim(options::OPT_INPUT);
2508 if (LastXArg && LastInputArg && LastInputArg->getIndex() < LastXArg->getIndex())
2509 Diag(clang::diag::warn_drv_unused_x) << LastXArg->getValue();
2512 for (Arg *A : Args) {
2513 if (A->getOption().getKind() == Option::InputClass) {
2514 const char *Value = A->getValue();
2515 types::ID Ty = types::TY_INVALID;
2517 // Infer the input type if necessary.
2518 if (InputType == types::TY_Nothing) {
2519 // If there was an explicit arg for this, claim it.
2520 if (InputTypeArg)
2521 InputTypeArg->claim();
2523 // stdin must be handled specially.
2524 if (memcmp(Value, "-", 2) == 0) {
2525 if (IsFlangMode()) {
2526 Ty = types::TY_Fortran;
2527 } else {
2528 // If running with -E, treat as a C input (this changes the
2529 // builtin macros, for example). This may be overridden by -ObjC
2530 // below.
2532 // Otherwise emit an error but still use a valid type to avoid
2533 // spurious errors (e.g., no inputs).
2534 assert(!CCGenDiagnostics && "stdin produces no crash reproducer");
2535 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2536 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2537 : clang::diag::err_drv_unknown_stdin_type);
2538 Ty = types::TY_C;
2540 } else {
2541 // Otherwise lookup by extension.
2542 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2543 // clang-cl /E, or Object otherwise.
2544 // We use a host hook here because Darwin at least has its own
2545 // idea of what .s is.
2546 if (const char *Ext = strrchr(Value, '.'))
2547 Ty = TC.LookupTypeForExtension(Ext + 1);
2549 if (Ty == types::TY_INVALID) {
2550 if (IsCLMode() && (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics))
2551 Ty = types::TY_CXX;
2552 else if (CCCIsCPP() || CCGenDiagnostics)
2553 Ty = types::TY_C;
2554 else
2555 Ty = types::TY_Object;
2558 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2559 // should autodetect some input files as C++ for g++ compatibility.
2560 if (CCCIsCXX()) {
2561 types::ID OldTy = Ty;
2562 Ty = types::lookupCXXTypeForCType(Ty);
2564 // Do not complain about foo.h, when we are known to be processing
2565 // it as a C++20 header unit.
2566 if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode()))
2567 Diag(clang::diag::warn_drv_treating_input_as_cxx)
2568 << getTypeName(OldTy) << getTypeName(Ty);
2571 // If running with -fthinlto-index=, extensions that normally identify
2572 // native object files actually identify LLVM bitcode files.
2573 if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2574 Ty == types::TY_Object)
2575 Ty = types::TY_LLVM_BC;
2578 // -ObjC and -ObjC++ override the default language, but only for "source
2579 // files". We just treat everything that isn't a linker input as a
2580 // source file.
2582 // FIXME: Clean this up if we move the phase sequence into the type.
2583 if (Ty != types::TY_Object) {
2584 if (Args.hasArg(options::OPT_ObjC))
2585 Ty = types::TY_ObjC;
2586 else if (Args.hasArg(options::OPT_ObjCXX))
2587 Ty = types::TY_ObjCXX;
2590 // Disambiguate headers that are meant to be header units from those
2591 // intended to be PCH. Avoid missing '.h' cases that are counted as
2592 // C headers by default - we know we are in C++ mode and we do not
2593 // want to issue a complaint about compiling things in the wrong mode.
2594 if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
2595 hasHeaderMode())
2596 Ty = CXXHeaderUnitType(CXX20HeaderType);
2597 } else {
2598 assert(InputTypeArg && "InputType set w/o InputTypeArg");
2599 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2600 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2601 // object files.
2602 const char *Ext = strrchr(Value, '.');
2603 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2604 Ty = types::TY_Object;
2606 if (Ty == types::TY_INVALID) {
2607 Ty = InputType;
2608 InputTypeArg->claim();
2612 if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2613 Inputs.push_back(std::make_pair(Ty, A));
2615 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2616 StringRef Value = A->getValue();
2617 if (DiagnoseInputExistence(Args, Value, types::TY_C,
2618 /*TypoCorrect=*/false)) {
2619 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2620 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2622 A->claim();
2623 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2624 StringRef Value = A->getValue();
2625 if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2626 /*TypoCorrect=*/false)) {
2627 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2628 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2630 A->claim();
2631 } else if (A->getOption().hasFlag(options::LinkerInput)) {
2632 // Just treat as object type, we could make a special type for this if
2633 // necessary.
2634 Inputs.push_back(std::make_pair(types::TY_Object, A));
2636 } else if (A->getOption().matches(options::OPT_x)) {
2637 InputTypeArg = A;
2638 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2639 A->claim();
2641 // Follow gcc behavior and treat as linker input for invalid -x
2642 // options. Its not clear why we shouldn't just revert to unknown; but
2643 // this isn't very important, we might as well be bug compatible.
2644 if (!InputType) {
2645 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2646 InputType = types::TY_Object;
2649 // If the user has put -fmodule-header{,=} then we treat C++ headers as
2650 // header unit inputs. So we 'promote' -xc++-header appropriately.
2651 if (InputType == types::TY_CXXHeader && hasHeaderMode())
2652 InputType = CXXHeaderUnitType(CXX20HeaderType);
2653 } else if (A->getOption().getID() == options::OPT_U) {
2654 assert(A->getNumValues() == 1 && "The /U option has one value.");
2655 StringRef Val = A->getValue(0);
2656 if (Val.find_first_of("/\\") != StringRef::npos) {
2657 // Warn about e.g. "/Users/me/myfile.c".
2658 Diag(diag::warn_slash_u_filename) << Val;
2659 Diag(diag::note_use_dashdash);
2663 if (CCCIsCPP() && Inputs.empty()) {
2664 // If called as standalone preprocessor, stdin is processed
2665 // if no other input is present.
2666 Arg *A = MakeInputArg(Args, Opts, "-");
2667 Inputs.push_back(std::make_pair(types::TY_C, A));
2671 namespace {
2672 /// Provides a convenient interface for different programming models to generate
2673 /// the required device actions.
2674 class OffloadingActionBuilder final {
2675 /// Flag used to trace errors in the builder.
2676 bool IsValid = false;
2678 /// The compilation that is using this builder.
2679 Compilation &C;
2681 /// Map between an input argument and the offload kinds used to process it.
2682 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2684 /// Map between a host action and its originating input argument.
2685 std::map<Action *, const Arg *> HostActionToInputArgMap;
2687 /// Builder interface. It doesn't build anything or keep any state.
2688 class DeviceActionBuilder {
2689 public:
2690 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2692 enum ActionBuilderReturnCode {
2693 // The builder acted successfully on the current action.
2694 ABRT_Success,
2695 // The builder didn't have to act on the current action.
2696 ABRT_Inactive,
2697 // The builder was successful and requested the host action to not be
2698 // generated.
2699 ABRT_Ignore_Host,
2702 protected:
2703 /// Compilation associated with this builder.
2704 Compilation &C;
2706 /// Tool chains associated with this builder. The same programming
2707 /// model may have associated one or more tool chains.
2708 SmallVector<const ToolChain *, 2> ToolChains;
2710 /// The derived arguments associated with this builder.
2711 DerivedArgList &Args;
2713 /// The inputs associated with this builder.
2714 const Driver::InputList &Inputs;
2716 /// The associated offload kind.
2717 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2719 public:
2720 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2721 const Driver::InputList &Inputs,
2722 Action::OffloadKind AssociatedOffloadKind)
2723 : C(C), Args(Args), Inputs(Inputs),
2724 AssociatedOffloadKind(AssociatedOffloadKind) {}
2725 virtual ~DeviceActionBuilder() {}
2727 /// Fill up the array \a DA with all the device dependences that should be
2728 /// added to the provided host action \a HostAction. By default it is
2729 /// inactive.
2730 virtual ActionBuilderReturnCode
2731 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2732 phases::ID CurPhase, phases::ID FinalPhase,
2733 PhasesTy &Phases) {
2734 return ABRT_Inactive;
2737 /// Update the state to include the provided host action \a HostAction as a
2738 /// dependency of the current device action. By default it is inactive.
2739 virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) {
2740 return ABRT_Inactive;
2743 /// Append top level actions generated by the builder.
2744 virtual void appendTopLevelActions(ActionList &AL) {}
2746 /// Append linker device actions generated by the builder.
2747 virtual void appendLinkDeviceActions(ActionList &AL) {}
2749 /// Append linker host action generated by the builder.
2750 virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2752 /// Append linker actions generated by the builder.
2753 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2755 /// Initialize the builder. Return true if any initialization errors are
2756 /// found.
2757 virtual bool initialize() { return false; }
2759 /// Return true if the builder can use bundling/unbundling.
2760 virtual bool canUseBundlerUnbundler() const { return false; }
2762 /// Return true if this builder is valid. We have a valid builder if we have
2763 /// associated device tool chains.
2764 bool isValid() { return !ToolChains.empty(); }
2766 /// Return the associated offload kind.
2767 Action::OffloadKind getAssociatedOffloadKind() {
2768 return AssociatedOffloadKind;
2772 /// Base class for CUDA/HIP action builder. It injects device code in
2773 /// the host backend action.
2774 class CudaActionBuilderBase : public DeviceActionBuilder {
2775 protected:
2776 /// Flags to signal if the user requested host-only or device-only
2777 /// compilation.
2778 bool CompileHostOnly = false;
2779 bool CompileDeviceOnly = false;
2780 bool EmitLLVM = false;
2781 bool EmitAsm = false;
2783 /// ID to identify each device compilation. For CUDA it is simply the
2784 /// GPU arch string. For HIP it is either the GPU arch string or GPU
2785 /// arch string plus feature strings delimited by a plus sign, e.g.
2786 /// gfx906+xnack.
2787 struct TargetID {
2788 /// Target ID string which is persistent throughout the compilation.
2789 const char *ID;
2790 TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); }
2791 TargetID(const char *ID) : ID(ID) {}
2792 operator const char *() { return ID; }
2793 operator StringRef() { return StringRef(ID); }
2795 /// List of GPU architectures to use in this compilation.
2796 SmallVector<TargetID, 4> GpuArchList;
2798 /// The CUDA actions for the current input.
2799 ActionList CudaDeviceActions;
2801 /// The CUDA fat binary if it was generated for the current input.
2802 Action *CudaFatBinary = nullptr;
2804 /// Flag that is set to true if this builder acted on the current input.
2805 bool IsActive = false;
2807 /// Flag for -fgpu-rdc.
2808 bool Relocatable = false;
2810 /// Default GPU architecture if there's no one specified.
2811 CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2813 /// Method to generate compilation unit ID specified by option
2814 /// '-fuse-cuid='.
2815 enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid };
2816 UseCUIDKind UseCUID = CUID_Hash;
2818 /// Compilation unit ID specified by option '-cuid='.
2819 StringRef FixedCUID;
2821 public:
2822 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2823 const Driver::InputList &Inputs,
2824 Action::OffloadKind OFKind)
2825 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2827 ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override {
2828 // While generating code for CUDA, we only depend on the host input action
2829 // to trigger the creation of all the CUDA device actions.
2831 // If we are dealing with an input action, replicate it for each GPU
2832 // architecture. If we are in host-only mode we return 'success' so that
2833 // the host uses the CUDA offload kind.
2834 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2835 assert(!GpuArchList.empty() &&
2836 "We should have at least one GPU architecture.");
2838 // If the host input is not CUDA or HIP, we don't need to bother about
2839 // this input.
2840 if (!(IA->getType() == types::TY_CUDA ||
2841 IA->getType() == types::TY_HIP ||
2842 IA->getType() == types::TY_PP_HIP)) {
2843 // The builder will ignore this input.
2844 IsActive = false;
2845 return ABRT_Inactive;
2848 // Set the flag to true, so that the builder acts on the current input.
2849 IsActive = true;
2851 if (CompileHostOnly)
2852 return ABRT_Success;
2854 // Replicate inputs for each GPU architecture.
2855 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2856 : types::TY_CUDA_DEVICE;
2857 std::string CUID = FixedCUID.str();
2858 if (CUID.empty()) {
2859 if (UseCUID == CUID_Random)
2860 CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
2861 /*LowerCase=*/true);
2862 else if (UseCUID == CUID_Hash) {
2863 llvm::MD5 Hasher;
2864 llvm::MD5::MD5Result Hash;
2865 SmallString<256> RealPath;
2866 llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath,
2867 /*expand_tilde=*/true);
2868 Hasher.update(RealPath);
2869 for (auto *A : Args) {
2870 if (A->getOption().matches(options::OPT_INPUT))
2871 continue;
2872 Hasher.update(A->getAsString(Args));
2874 Hasher.final(Hash);
2875 CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
2878 IA->setId(CUID);
2880 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2881 CudaDeviceActions.push_back(
2882 C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId()));
2885 return ABRT_Success;
2888 // If this is an unbundling action use it as is for each CUDA toolchain.
2889 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2891 // If -fgpu-rdc is disabled, should not unbundle since there is no
2892 // device code to link.
2893 if (UA->getType() == types::TY_Object && !Relocatable)
2894 return ABRT_Inactive;
2896 CudaDeviceActions.clear();
2897 auto *IA = cast<InputAction>(UA->getInputs().back());
2898 std::string FileName = IA->getInputArg().getAsString(Args);
2899 // Check if the type of the file is the same as the action. Do not
2900 // unbundle it if it is not. Do not unbundle .so files, for example,
2901 // which are not object files.
2902 if (IA->getType() == types::TY_Object &&
2903 (!llvm::sys::path::has_extension(FileName) ||
2904 types::lookupTypeForExtension(
2905 llvm::sys::path::extension(FileName).drop_front()) !=
2906 types::TY_Object))
2907 return ABRT_Inactive;
2909 for (auto Arch : GpuArchList) {
2910 CudaDeviceActions.push_back(UA);
2911 UA->registerDependentActionInfo(ToolChains[0], Arch,
2912 AssociatedOffloadKind);
2914 IsActive = true;
2915 return ABRT_Success;
2918 return IsActive ? ABRT_Success : ABRT_Inactive;
2921 void appendTopLevelActions(ActionList &AL) override {
2922 // Utility to append actions to the top level list.
2923 auto AddTopLevel = [&](Action *A, TargetID TargetID) {
2924 OffloadAction::DeviceDependences Dep;
2925 Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind);
2926 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2929 // If we have a fat binary, add it to the list.
2930 if (CudaFatBinary) {
2931 AddTopLevel(CudaFatBinary, CudaArch::UNUSED);
2932 CudaDeviceActions.clear();
2933 CudaFatBinary = nullptr;
2934 return;
2937 if (CudaDeviceActions.empty())
2938 return;
2940 // If we have CUDA actions at this point, that's because we have a have
2941 // partial compilation, so we should have an action for each GPU
2942 // architecture.
2943 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2944 "Expecting one action per GPU architecture.");
2945 assert(ToolChains.size() == 1 &&
2946 "Expecting to have a single CUDA toolchain.");
2947 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2948 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2950 CudaDeviceActions.clear();
2953 /// Get canonicalized offload arch option. \returns empty StringRef if the
2954 /// option is invalid.
2955 virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0;
2957 virtual llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
2958 getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0;
2960 bool initialize() override {
2961 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2962 AssociatedOffloadKind == Action::OFK_HIP);
2964 // We don't need to support CUDA.
2965 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2966 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2967 return false;
2969 // We don't need to support HIP.
2970 if (AssociatedOffloadKind == Action::OFK_HIP &&
2971 !C.hasOffloadToolChain<Action::OFK_HIP>())
2972 return false;
2974 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2975 options::OPT_fno_gpu_rdc, /*Default=*/false);
2977 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2978 assert(HostTC && "No toolchain for host compilation.");
2979 if (HostTC->getTriple().isNVPTX() ||
2980 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2981 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2982 // an error and abort pipeline construction early so we don't trip
2983 // asserts that assume device-side compilation.
2984 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2985 << HostTC->getTriple().getArchName();
2986 return true;
2989 ToolChains.push_back(
2990 AssociatedOffloadKind == Action::OFK_Cuda
2991 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2992 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2994 CompileHostOnly = C.getDriver().offloadHostOnly();
2995 CompileDeviceOnly = C.getDriver().offloadDeviceOnly();
2996 EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
2997 EmitAsm = Args.getLastArg(options::OPT_S);
2998 FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ);
2999 if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) {
3000 StringRef UseCUIDStr = A->getValue();
3001 UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr)
3002 .Case("hash", CUID_Hash)
3003 .Case("random", CUID_Random)
3004 .Case("none", CUID_None)
3005 .Default(CUID_Invalid);
3006 if (UseCUID == CUID_Invalid) {
3007 C.getDriver().Diag(diag::err_drv_invalid_value)
3008 << A->getAsString(Args) << UseCUIDStr;
3009 C.setContainsError();
3010 return true;
3014 // --offload and --offload-arch options are mutually exclusive.
3015 if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
3016 Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
3017 options::OPT_no_offload_arch_EQ)) {
3018 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch"
3019 << "--offload";
3022 // Collect all offload arch parameters, removing duplicates.
3023 std::set<StringRef> GpuArchs;
3024 bool Error = false;
3025 for (Arg *A : Args) {
3026 if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
3027 A->getOption().matches(options::OPT_no_offload_arch_EQ)))
3028 continue;
3029 A->claim();
3031 for (StringRef ArchStr : llvm::split(A->getValue(), ",")) {
3032 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
3033 ArchStr == "all") {
3034 GpuArchs.clear();
3035 } else {
3036 ArchStr = getCanonicalOffloadArch(ArchStr);
3037 if (ArchStr.empty()) {
3038 Error = true;
3039 } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
3040 GpuArchs.insert(ArchStr);
3041 else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
3042 GpuArchs.erase(ArchStr);
3043 else
3044 llvm_unreachable("Unexpected option.");
3049 auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs);
3050 if (ConflictingArchs) {
3051 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
3052 << ConflictingArchs->first << ConflictingArchs->second;
3053 C.setContainsError();
3054 return true;
3057 // Collect list of GPUs remaining in the set.
3058 for (auto Arch : GpuArchs)
3059 GpuArchList.push_back(Arch.data());
3061 // Default to sm_20 which is the lowest common denominator for
3062 // supported GPUs. sm_20 code should work correctly, if
3063 // suboptimally, on all newer GPUs.
3064 if (GpuArchList.empty()) {
3065 if (ToolChains.front()->getTriple().isSPIRV())
3066 GpuArchList.push_back(CudaArch::Generic);
3067 else
3068 GpuArchList.push_back(DefaultCudaArch);
3071 return Error;
3075 /// \brief CUDA action builder. It injects device code in the host backend
3076 /// action.
3077 class CudaActionBuilder final : public CudaActionBuilderBase {
3078 public:
3079 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
3080 const Driver::InputList &Inputs)
3081 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
3082 DefaultCudaArch = CudaArch::SM_35;
3085 StringRef getCanonicalOffloadArch(StringRef ArchStr) override {
3086 CudaArch Arch = StringToCudaArch(ArchStr);
3087 if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) {
3088 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
3089 return StringRef();
3091 return CudaArchToString(Arch);
3094 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
3095 getConflictOffloadArchCombination(
3096 const std::set<StringRef> &GpuArchs) override {
3097 return llvm::None;
3100 ActionBuilderReturnCode
3101 getDeviceDependences(OffloadAction::DeviceDependences &DA,
3102 phases::ID CurPhase, phases::ID FinalPhase,
3103 PhasesTy &Phases) override {
3104 if (!IsActive)
3105 return ABRT_Inactive;
3107 // If we don't have more CUDA actions, we don't have any dependences to
3108 // create for the host.
3109 if (CudaDeviceActions.empty())
3110 return ABRT_Success;
3112 assert(CudaDeviceActions.size() == GpuArchList.size() &&
3113 "Expecting one action per GPU architecture.");
3114 assert(!CompileHostOnly &&
3115 "Not expecting CUDA actions in host-only compilation.");
3117 // If we are generating code for the device or we are in a backend phase,
3118 // we attempt to generate the fat binary. We compile each arch to ptx and
3119 // assemble to cubin, then feed the cubin *and* the ptx into a device
3120 // "link" action, which uses fatbinary to combine these cubins into one
3121 // fatbin. The fatbin is then an input to the host action if not in
3122 // device-only mode.
3123 if (CompileDeviceOnly || CurPhase == phases::Backend) {
3124 ActionList DeviceActions;
3125 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3126 // Produce the device action from the current phase up to the assemble
3127 // phase.
3128 for (auto Ph : Phases) {
3129 // Skip the phases that were already dealt with.
3130 if (Ph < CurPhase)
3131 continue;
3132 // We have to be consistent with the host final phase.
3133 if (Ph > FinalPhase)
3134 break;
3136 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
3137 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
3139 if (Ph == phases::Assemble)
3140 break;
3143 // If we didn't reach the assemble phase, we can't generate the fat
3144 // binary. We don't need to generate the fat binary if we are not in
3145 // device-only mode.
3146 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
3147 CompileDeviceOnly)
3148 continue;
3150 Action *AssembleAction = CudaDeviceActions[I];
3151 assert(AssembleAction->getType() == types::TY_Object);
3152 assert(AssembleAction->getInputs().size() == 1);
3154 Action *BackendAction = AssembleAction->getInputs()[0];
3155 assert(BackendAction->getType() == types::TY_PP_Asm);
3157 for (auto &A : {AssembleAction, BackendAction}) {
3158 OffloadAction::DeviceDependences DDep;
3159 DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda);
3160 DeviceActions.push_back(
3161 C.MakeAction<OffloadAction>(DDep, A->getType()));
3165 // We generate the fat binary if we have device input actions.
3166 if (!DeviceActions.empty()) {
3167 CudaFatBinary =
3168 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
3170 if (!CompileDeviceOnly) {
3171 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3172 Action::OFK_Cuda);
3173 // Clear the fat binary, it is already a dependence to an host
3174 // action.
3175 CudaFatBinary = nullptr;
3178 // Remove the CUDA actions as they are already connected to an host
3179 // action or fat binary.
3180 CudaDeviceActions.clear();
3183 // We avoid creating host action in device-only mode.
3184 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3185 } else if (CurPhase > phases::Backend) {
3186 // If we are past the backend phase and still have a device action, we
3187 // don't have to do anything as this action is already a device
3188 // top-level action.
3189 return ABRT_Success;
3192 assert(CurPhase < phases::Backend && "Generating single CUDA "
3193 "instructions should only occur "
3194 "before the backend phase!");
3196 // By default, we produce an action for each device arch.
3197 for (Action *&A : CudaDeviceActions)
3198 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
3200 return ABRT_Success;
3203 /// \brief HIP action builder. It injects device code in the host backend
3204 /// action.
3205 class HIPActionBuilder final : public CudaActionBuilderBase {
3206 /// The linker inputs obtained for each device arch.
3207 SmallVector<ActionList, 8> DeviceLinkerInputs;
3208 // The default bundling behavior depends on the type of output, therefore
3209 // BundleOutput needs to be tri-value: None, true, or false.
3210 // Bundle code objects except --no-gpu-output is specified for device
3211 // only compilation. Bundle other type of output files only if
3212 // --gpu-bundle-output is specified for device only compilation.
3213 Optional<bool> BundleOutput;
3215 public:
3216 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
3217 const Driver::InputList &Inputs)
3218 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
3219 DefaultCudaArch = CudaArch::GFX803;
3220 if (Args.hasArg(options::OPT_gpu_bundle_output,
3221 options::OPT_no_gpu_bundle_output))
3222 BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output,
3223 options::OPT_no_gpu_bundle_output, true);
3226 bool canUseBundlerUnbundler() const override { return true; }
3228 StringRef getCanonicalOffloadArch(StringRef IdStr) override {
3229 llvm::StringMap<bool> Features;
3230 // getHIPOffloadTargetTriple() is known to return valid value as it has
3231 // been called successfully in the CreateOffloadingDeviceToolChains().
3232 auto ArchStr = parseTargetID(
3233 *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr,
3234 &Features);
3235 if (!ArchStr) {
3236 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
3237 C.setContainsError();
3238 return StringRef();
3240 auto CanId = getCanonicalTargetID(*ArchStr, Features);
3241 return Args.MakeArgStringRef(CanId);
3244 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
3245 getConflictOffloadArchCombination(
3246 const std::set<StringRef> &GpuArchs) override {
3247 return getConflictTargetIDCombination(GpuArchs);
3250 ActionBuilderReturnCode
3251 getDeviceDependences(OffloadAction::DeviceDependences &DA,
3252 phases::ID CurPhase, phases::ID FinalPhase,
3253 PhasesTy &Phases) override {
3254 if (!IsActive)
3255 return ABRT_Inactive;
3257 // amdgcn does not support linking of object files, therefore we skip
3258 // backend and assemble phases to output LLVM IR. Except for generating
3259 // non-relocatable device code, where we generate fat binary for device
3260 // code and pass to host in Backend phase.
3261 if (CudaDeviceActions.empty())
3262 return ABRT_Success;
3264 assert(((CurPhase == phases::Link && Relocatable) ||
3265 CudaDeviceActions.size() == GpuArchList.size()) &&
3266 "Expecting one action per GPU architecture.");
3267 assert(!CompileHostOnly &&
3268 "Not expecting HIP actions in host-only compilation.");
3270 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
3271 !EmitAsm) {
3272 // If we are in backend phase, we attempt to generate the fat binary.
3273 // We compile each arch to IR and use a link action to generate code
3274 // object containing ISA. Then we use a special "link" action to create
3275 // a fat binary containing all the code objects for different GPU's.
3276 // The fat binary is then an input to the host action.
3277 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3278 if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) {
3279 // When LTO is enabled, skip the backend and assemble phases and
3280 // use lld to link the bitcode.
3281 ActionList AL;
3282 AL.push_back(CudaDeviceActions[I]);
3283 // Create a link action to link device IR with device library
3284 // and generate ISA.
3285 CudaDeviceActions[I] =
3286 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3287 } else {
3288 // When LTO is not enabled, we follow the conventional
3289 // compiler phases, including backend and assemble phases.
3290 ActionList AL;
3291 Action *BackendAction = nullptr;
3292 if (ToolChains.front()->getTriple().isSPIRV()) {
3293 // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
3294 // (HIPSPVToolChain) runs post-link LLVM IR passes.
3295 types::ID Output = Args.hasArg(options::OPT_S)
3296 ? types::TY_LLVM_IR
3297 : types::TY_LLVM_BC;
3298 BackendAction =
3299 C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output);
3300 } else
3301 BackendAction = C.getDriver().ConstructPhaseAction(
3302 C, Args, phases::Backend, CudaDeviceActions[I],
3303 AssociatedOffloadKind);
3304 auto AssembleAction = C.getDriver().ConstructPhaseAction(
3305 C, Args, phases::Assemble, BackendAction,
3306 AssociatedOffloadKind);
3307 AL.push_back(AssembleAction);
3308 // Create a link action to link device IR with device library
3309 // and generate ISA.
3310 CudaDeviceActions[I] =
3311 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3314 // OffloadingActionBuilder propagates device arch until an offload
3315 // action. Since the next action for creating fatbin does
3316 // not have device arch, whereas the above link action and its input
3317 // have device arch, an offload action is needed to stop the null
3318 // device arch of the next action being propagated to the above link
3319 // action.
3320 OffloadAction::DeviceDependences DDep;
3321 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3322 AssociatedOffloadKind);
3323 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3324 DDep, CudaDeviceActions[I]->getType());
3327 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3328 // Create HIP fat binary with a special "link" action.
3329 CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions,
3330 types::TY_HIP_FATBIN);
3332 if (!CompileDeviceOnly) {
3333 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3334 AssociatedOffloadKind);
3335 // Clear the fat binary, it is already a dependence to an host
3336 // action.
3337 CudaFatBinary = nullptr;
3340 // Remove the CUDA actions as they are already connected to an host
3341 // action or fat binary.
3342 CudaDeviceActions.clear();
3345 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3346 } else if (CurPhase == phases::Link) {
3347 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
3348 // This happens to each device action originated from each input file.
3349 // Later on, device actions in DeviceLinkerInputs are used to create
3350 // device link actions in appendLinkDependences and the created device
3351 // link actions are passed to the offload action as device dependence.
3352 DeviceLinkerInputs.resize(CudaDeviceActions.size());
3353 auto LI = DeviceLinkerInputs.begin();
3354 for (auto *A : CudaDeviceActions) {
3355 LI->push_back(A);
3356 ++LI;
3359 // We will pass the device action as a host dependence, so we don't
3360 // need to do anything else with them.
3361 CudaDeviceActions.clear();
3362 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3365 // By default, we produce an action for each device arch.
3366 for (Action *&A : CudaDeviceActions)
3367 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
3368 AssociatedOffloadKind);
3370 if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput &&
3371 BundleOutput.value()) {
3372 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3373 OffloadAction::DeviceDependences DDep;
3374 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3375 AssociatedOffloadKind);
3376 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3377 DDep, CudaDeviceActions[I]->getType());
3379 CudaFatBinary =
3380 C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions);
3381 CudaDeviceActions.clear();
3384 return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
3385 : ABRT_Success;
3388 void appendLinkDeviceActions(ActionList &AL) override {
3389 if (DeviceLinkerInputs.size() == 0)
3390 return;
3392 assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
3393 "Linker inputs and GPU arch list sizes do not match.");
3395 ActionList Actions;
3396 unsigned I = 0;
3397 // Append a new link action for each device.
3398 // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
3399 for (auto &LI : DeviceLinkerInputs) {
3401 types::ID Output = Args.hasArg(options::OPT_emit_llvm)
3402 ? types::TY_LLVM_BC
3403 : types::TY_Image;
3405 auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output);
3406 // Linking all inputs for the current GPU arch.
3407 // LI contains all the inputs for the linker.
3408 OffloadAction::DeviceDependences DeviceLinkDeps;
3409 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
3410 GpuArchList[I], AssociatedOffloadKind);
3411 Actions.push_back(C.MakeAction<OffloadAction>(
3412 DeviceLinkDeps, DeviceLinkAction->getType()));
3413 ++I;
3415 DeviceLinkerInputs.clear();
3417 // If emitting LLVM, do not generate final host/device compilation action
3418 if (Args.hasArg(options::OPT_emit_llvm)) {
3419 AL.append(Actions);
3420 return;
3423 // Create a host object from all the device images by embedding them
3424 // in a fat binary for mixed host-device compilation. For device-only
3425 // compilation, creates a fat binary.
3426 OffloadAction::DeviceDependences DDeps;
3427 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3428 auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>(
3429 Actions,
3430 CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object);
3431 DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr,
3432 AssociatedOffloadKind);
3433 // Offload the host object to the host linker.
3434 AL.push_back(
3435 C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
3436 } else {
3437 AL.append(Actions);
3441 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
3443 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3447 /// TODO: Add the implementation for other specialized builders here.
3450 /// Specialized builders being used by this offloading action builder.
3451 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3453 /// Flag set to true if all valid builders allow file bundling/unbundling.
3454 bool CanUseBundler;
3456 public:
3457 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3458 const Driver::InputList &Inputs)
3459 : C(C) {
3460 // Create a specialized builder for each device toolchain.
3462 IsValid = true;
3464 // Create a specialized builder for CUDA.
3465 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3467 // Create a specialized builder for HIP.
3468 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3471 // TODO: Build other specialized builders here.
3474 // Initialize all the builders, keeping track of errors. If all valid
3475 // builders agree that we can use bundling, set the flag to true.
3476 unsigned ValidBuilders = 0u;
3477 unsigned ValidBuildersSupportingBundling = 0u;
3478 for (auto *SB : SpecializedBuilders) {
3479 IsValid = IsValid && !SB->initialize();
3481 // Update the counters if the builder is valid.
3482 if (SB->isValid()) {
3483 ++ValidBuilders;
3484 if (SB->canUseBundlerUnbundler())
3485 ++ValidBuildersSupportingBundling;
3488 CanUseBundler =
3489 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3492 ~OffloadingActionBuilder() {
3493 for (auto *SB : SpecializedBuilders)
3494 delete SB;
3497 /// Record a host action and its originating input argument.
3498 void recordHostAction(Action *HostAction, const Arg *InputArg) {
3499 assert(HostAction && "Invalid host action");
3500 assert(InputArg && "Invalid input argument");
3501 auto Loc = HostActionToInputArgMap.find(HostAction);
3502 if (Loc == HostActionToInputArgMap.end())
3503 HostActionToInputArgMap[HostAction] = InputArg;
3504 assert(HostActionToInputArgMap[HostAction] == InputArg &&
3505 "host action mapped to multiple input arguments");
3508 /// Generate an action that adds device dependences (if any) to a host action.
3509 /// If no device dependence actions exist, just return the host action \a
3510 /// HostAction. If an error is found or if no builder requires the host action
3511 /// to be generated, return nullptr.
3512 Action *
3513 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3514 phases::ID CurPhase, phases::ID FinalPhase,
3515 DeviceActionBuilder::PhasesTy &Phases) {
3516 if (!IsValid)
3517 return nullptr;
3519 if (SpecializedBuilders.empty())
3520 return HostAction;
3522 assert(HostAction && "Invalid host action!");
3523 recordHostAction(HostAction, InputArg);
3525 OffloadAction::DeviceDependences DDeps;
3526 // Check if all the programming models agree we should not emit the host
3527 // action. Also, keep track of the offloading kinds employed.
3528 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3529 unsigned InactiveBuilders = 0u;
3530 unsigned IgnoringBuilders = 0u;
3531 for (auto *SB : SpecializedBuilders) {
3532 if (!SB->isValid()) {
3533 ++InactiveBuilders;
3534 continue;
3537 auto RetCode =
3538 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3540 // If the builder explicitly says the host action should be ignored,
3541 // we need to increment the variable that tracks the builders that request
3542 // the host object to be ignored.
3543 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3544 ++IgnoringBuilders;
3546 // Unless the builder was inactive for this action, we have to record the
3547 // offload kind because the host will have to use it.
3548 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3549 OffloadKind |= SB->getAssociatedOffloadKind();
3552 // If all builders agree that the host object should be ignored, just return
3553 // nullptr.
3554 if (IgnoringBuilders &&
3555 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3556 return nullptr;
3558 if (DDeps.getActions().empty())
3559 return HostAction;
3561 // We have dependences we need to bundle together. We use an offload action
3562 // for that.
3563 OffloadAction::HostDependence HDep(
3564 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3565 /*BoundArch=*/nullptr, DDeps);
3566 return C.MakeAction<OffloadAction>(HDep, DDeps);
3569 /// Generate an action that adds a host dependence to a device action. The
3570 /// results will be kept in this action builder. Return true if an error was
3571 /// found.
3572 bool addHostDependenceToDeviceActions(Action *&HostAction,
3573 const Arg *InputArg) {
3574 if (!IsValid)
3575 return true;
3577 recordHostAction(HostAction, InputArg);
3579 // If we are supporting bundling/unbundling and the current action is an
3580 // input action of non-source file, we replace the host action by the
3581 // unbundling action. The bundler tool has the logic to detect if an input
3582 // is a bundle or not and if the input is not a bundle it assumes it is a
3583 // host file. Therefore it is safe to create an unbundling action even if
3584 // the input is not a bundle.
3585 if (CanUseBundler && isa<InputAction>(HostAction) &&
3586 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3587 (!types::isSrcFile(HostAction->getType()) ||
3588 HostAction->getType() == types::TY_PP_HIP)) {
3589 auto UnbundlingHostAction =
3590 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3591 UnbundlingHostAction->registerDependentActionInfo(
3592 C.getSingleOffloadToolChain<Action::OFK_Host>(),
3593 /*BoundArch=*/StringRef(), Action::OFK_Host);
3594 HostAction = UnbundlingHostAction;
3595 recordHostAction(HostAction, InputArg);
3598 assert(HostAction && "Invalid host action!");
3600 // Register the offload kinds that are used.
3601 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3602 for (auto *SB : SpecializedBuilders) {
3603 if (!SB->isValid())
3604 continue;
3606 auto RetCode = SB->addDeviceDependences(HostAction);
3608 // Host dependences for device actions are not compatible with that same
3609 // action being ignored.
3610 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3611 "Host dependence not expected to be ignored.!");
3613 // Unless the builder was inactive for this action, we have to record the
3614 // offload kind because the host will have to use it.
3615 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3616 OffloadKind |= SB->getAssociatedOffloadKind();
3619 // Do not use unbundler if the Host does not depend on device action.
3620 if (OffloadKind == Action::OFK_None && CanUseBundler)
3621 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3622 HostAction = UA->getInputs().back();
3624 return false;
3627 /// Add the offloading top level actions to the provided action list. This
3628 /// function can replace the host action by a bundling action if the
3629 /// programming models allow it.
3630 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3631 const Arg *InputArg) {
3632 if (HostAction)
3633 recordHostAction(HostAction, InputArg);
3635 // Get the device actions to be appended.
3636 ActionList OffloadAL;
3637 for (auto *SB : SpecializedBuilders) {
3638 if (!SB->isValid())
3639 continue;
3640 SB->appendTopLevelActions(OffloadAL);
3643 // If we can use the bundler, replace the host action by the bundling one in
3644 // the resulting list. Otherwise, just append the device actions. For
3645 // device only compilation, HostAction is a null pointer, therefore only do
3646 // this when HostAction is not a null pointer.
3647 if (CanUseBundler && HostAction &&
3648 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3649 // Add the host action to the list in order to create the bundling action.
3650 OffloadAL.push_back(HostAction);
3652 // We expect that the host action was just appended to the action list
3653 // before this method was called.
3654 assert(HostAction == AL.back() && "Host action not in the list??");
3655 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3656 recordHostAction(HostAction, InputArg);
3657 AL.back() = HostAction;
3658 } else
3659 AL.append(OffloadAL.begin(), OffloadAL.end());
3661 // Propagate to the current host action (if any) the offload information
3662 // associated with the current input.
3663 if (HostAction)
3664 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3665 /*BoundArch=*/nullptr);
3666 return false;
3669 void appendDeviceLinkActions(ActionList &AL) {
3670 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3671 if (!SB->isValid())
3672 continue;
3673 SB->appendLinkDeviceActions(AL);
3677 Action *makeHostLinkAction() {
3678 // Build a list of device linking actions.
3679 ActionList DeviceAL;
3680 appendDeviceLinkActions(DeviceAL);
3681 if (DeviceAL.empty())
3682 return nullptr;
3684 // Let builders add host linking actions.
3685 Action* HA = nullptr;
3686 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3687 if (!SB->isValid())
3688 continue;
3689 HA = SB->appendLinkHostActions(DeviceAL);
3690 // This created host action has no originating input argument, therefore
3691 // needs to set its offloading kind directly.
3692 if (HA)
3693 HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(),
3694 /*BoundArch=*/nullptr);
3696 return HA;
3699 /// Processes the host linker action. This currently consists of replacing it
3700 /// with an offload action if there are device link objects and propagate to
3701 /// the host action all the offload kinds used in the current compilation. The
3702 /// resulting action is returned.
3703 Action *processHostLinkAction(Action *HostAction) {
3704 // Add all the dependences from the device linking actions.
3705 OffloadAction::DeviceDependences DDeps;
3706 for (auto *SB : SpecializedBuilders) {
3707 if (!SB->isValid())
3708 continue;
3710 SB->appendLinkDependences(DDeps);
3713 // Calculate all the offload kinds used in the current compilation.
3714 unsigned ActiveOffloadKinds = 0u;
3715 for (auto &I : InputArgToOffloadKindMap)
3716 ActiveOffloadKinds |= I.second;
3718 // If we don't have device dependencies, we don't have to create an offload
3719 // action.
3720 if (DDeps.getActions().empty()) {
3721 // Set all the active offloading kinds to the link action. Given that it
3722 // is a link action it is assumed to depend on all actions generated so
3723 // far.
3724 HostAction->setHostOffloadInfo(ActiveOffloadKinds,
3725 /*BoundArch=*/nullptr);
3726 // Propagate active offloading kinds for each input to the link action.
3727 // Each input may have different active offloading kind.
3728 for (auto *A : HostAction->inputs()) {
3729 auto ArgLoc = HostActionToInputArgMap.find(A);
3730 if (ArgLoc == HostActionToInputArgMap.end())
3731 continue;
3732 auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second);
3733 if (OFKLoc == InputArgToOffloadKindMap.end())
3734 continue;
3735 A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr);
3737 return HostAction;
3740 // Create the offload action with all dependences. When an offload action
3741 // is created the kinds are propagated to the host action, so we don't have
3742 // to do that explicitly here.
3743 OffloadAction::HostDependence HDep(
3744 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3745 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3746 return C.MakeAction<OffloadAction>(HDep, DDeps);
3749 } // anonymous namespace.
3751 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3752 const InputList &Inputs,
3753 ActionList &Actions) const {
3755 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3756 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3757 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3758 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3759 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3760 Args.eraseArg(options::OPT__SLASH_Yc);
3761 Args.eraseArg(options::OPT__SLASH_Yu);
3762 YcArg = YuArg = nullptr;
3764 if (YcArg && Inputs.size() > 1) {
3765 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3766 Args.eraseArg(options::OPT__SLASH_Yc);
3767 YcArg = nullptr;
3770 Arg *FinalPhaseArg;
3771 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3773 if (FinalPhase == phases::Link) {
3774 // Emitting LLVM while linking disabled except in HIPAMD Toolchain
3775 if (Args.hasArg(options::OPT_emit_llvm) && !Args.hasArg(options::OPT_hip_link))
3776 Diag(clang::diag::err_drv_emit_llvm_link);
3777 if (IsCLMode() && LTOMode != LTOK_None &&
3778 !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
3779 .equals_insensitive("lld"))
3780 Diag(clang::diag::err_drv_lto_without_lld);
3783 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3784 // If only preprocessing or /Y- is used, all pch handling is disabled.
3785 // Rather than check for it everywhere, just remove clang-cl pch-related
3786 // flags here.
3787 Args.eraseArg(options::OPT__SLASH_Fp);
3788 Args.eraseArg(options::OPT__SLASH_Yc);
3789 Args.eraseArg(options::OPT__SLASH_Yu);
3790 YcArg = YuArg = nullptr;
3793 unsigned LastPLSize = 0;
3794 for (auto &I : Inputs) {
3795 types::ID InputType = I.first;
3796 const Arg *InputArg = I.second;
3798 auto PL = types::getCompilationPhases(InputType);
3799 LastPLSize = PL.size();
3801 // If the first step comes after the final phase we are doing as part of
3802 // this compilation, warn the user about it.
3803 phases::ID InitialPhase = PL[0];
3804 if (InitialPhase > FinalPhase) {
3805 if (InputArg->isClaimed())
3806 continue;
3808 // Claim here to avoid the more general unused warning.
3809 InputArg->claim();
3811 // Suppress all unused style warnings with -Qunused-arguments
3812 if (Args.hasArg(options::OPT_Qunused_arguments))
3813 continue;
3815 // Special case when final phase determined by binary name, rather than
3816 // by a command-line argument with a corresponding Arg.
3817 if (CCCIsCPP())
3818 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3819 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3820 // Special case '-E' warning on a previously preprocessed file to make
3821 // more sense.
3822 else if (InitialPhase == phases::Compile &&
3823 (Args.getLastArg(options::OPT__SLASH_EP,
3824 options::OPT__SLASH_P) ||
3825 Args.getLastArg(options::OPT_E) ||
3826 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3827 getPreprocessedType(InputType) == types::TY_INVALID)
3828 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3829 << InputArg->getAsString(Args) << !!FinalPhaseArg
3830 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3831 else
3832 Diag(clang::diag::warn_drv_input_file_unused)
3833 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3834 << !!FinalPhaseArg
3835 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3836 continue;
3839 if (YcArg) {
3840 // Add a separate precompile phase for the compile phase.
3841 if (FinalPhase >= phases::Compile) {
3842 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3843 // Build the pipeline for the pch file.
3844 Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3845 for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3846 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3847 assert(ClangClPch);
3848 Actions.push_back(ClangClPch);
3849 // The driver currently exits after the first failed command. This
3850 // relies on that behavior, to make sure if the pch generation fails,
3851 // the main compilation won't run.
3852 // FIXME: If the main compilation fails, the PCH generation should
3853 // probably not be considered successful either.
3858 // If we are linking, claim any options which are obviously only used for
3859 // compilation.
3860 // FIXME: Understand why the last Phase List length is used here.
3861 if (FinalPhase == phases::Link && LastPLSize == 1) {
3862 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3863 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3867 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3868 const InputList &Inputs, ActionList &Actions) const {
3869 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3871 if (!SuppressMissingInputWarning && Inputs.empty()) {
3872 Diag(clang::diag::err_drv_no_input_files);
3873 return;
3876 // Diagnose misuse of /Fo.
3877 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3878 StringRef V = A->getValue();
3879 if (Inputs.size() > 1 && !V.empty() &&
3880 !llvm::sys::path::is_separator(V.back())) {
3881 // Check whether /Fo tries to name an output file for multiple inputs.
3882 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3883 << A->getSpelling() << V;
3884 Args.eraseArg(options::OPT__SLASH_Fo);
3888 // Diagnose misuse of /Fa.
3889 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3890 StringRef V = A->getValue();
3891 if (Inputs.size() > 1 && !V.empty() &&
3892 !llvm::sys::path::is_separator(V.back())) {
3893 // Check whether /Fa tries to name an asm file for multiple inputs.
3894 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3895 << A->getSpelling() << V;
3896 Args.eraseArg(options::OPT__SLASH_Fa);
3900 // Diagnose misuse of /o.
3901 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3902 if (A->getValue()[0] == '\0') {
3903 // It has to have a value.
3904 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3905 Args.eraseArg(options::OPT__SLASH_o);
3909 handleArguments(C, Args, Inputs, Actions);
3911 // Builder to be used to build offloading actions.
3912 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3914 bool UseNewOffloadingDriver =
3915 C.isOffloadingHostKind(Action::OFK_OpenMP) ||
3916 Args.hasFlag(options::OPT_offload_new_driver,
3917 options::OPT_no_offload_new_driver, false);
3919 // Construct the actions to perform.
3920 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3921 ExtractAPIJobAction *ExtractAPIAction = nullptr;
3922 ActionList LinkerInputs;
3923 ActionList MergerInputs;
3925 for (auto &I : Inputs) {
3926 types::ID InputType = I.first;
3927 const Arg *InputArg = I.second;
3929 auto PL = types::getCompilationPhases(*this, Args, InputType);
3930 if (PL.empty())
3931 continue;
3933 auto FullPL = types::getCompilationPhases(InputType);
3935 // Build the pipeline for this file.
3936 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3938 // Use the current host action in any of the offloading actions, if
3939 // required.
3940 if (!UseNewOffloadingDriver)
3941 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3942 break;
3944 for (phases::ID Phase : PL) {
3946 // Add any offload action the host action depends on.
3947 if (!UseNewOffloadingDriver)
3948 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3949 Current, InputArg, Phase, PL.back(), FullPL);
3950 if (!Current)
3951 break;
3953 // Queue linker inputs.
3954 if (Phase == phases::Link) {
3955 assert(Phase == PL.back() && "linking must be final compilation step.");
3956 // We don't need to generate additional link commands if emitting AMD bitcode
3957 if (!(C.getInputArgs().hasArg(options::OPT_hip_link) &&
3958 (C.getInputArgs().hasArg(options::OPT_emit_llvm))))
3959 LinkerInputs.push_back(Current);
3960 Current = nullptr;
3961 break;
3964 // TODO: Consider removing this because the merged may not end up being
3965 // the final Phase in the pipeline. Perhaps the merged could just merge
3966 // and then pass an artifact of some sort to the Link Phase.
3967 // Queue merger inputs.
3968 if (Phase == phases::IfsMerge) {
3969 assert(Phase == PL.back() && "merging must be final compilation step.");
3970 MergerInputs.push_back(Current);
3971 Current = nullptr;
3972 break;
3975 // Each precompiled header file after a module file action is a module
3976 // header of that same module file, rather than being compiled to a
3977 // separate PCH.
3978 if (Phase == phases::Precompile && HeaderModuleAction &&
3979 getPrecompiledType(InputType) == types::TY_PCH) {
3980 HeaderModuleAction->addModuleHeaderInput(Current);
3981 Current = nullptr;
3982 break;
3985 if (Phase == phases::Precompile && ExtractAPIAction) {
3986 ExtractAPIAction->addHeaderInput(Current);
3987 Current = nullptr;
3988 break;
3991 // FIXME: Should we include any prior module file outputs as inputs of
3992 // later actions in the same command line?
3994 // Otherwise construct the appropriate action.
3995 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3997 // We didn't create a new action, so we will just move to the next phase.
3998 if (NewCurrent == Current)
3999 continue;
4001 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
4002 HeaderModuleAction = HMA;
4003 else if (auto *EAA = dyn_cast<ExtractAPIJobAction>(NewCurrent))
4004 ExtractAPIAction = EAA;
4006 Current = NewCurrent;
4008 // Use the current host action in any of the offloading actions, if
4009 // required.
4010 if (!UseNewOffloadingDriver)
4011 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
4012 break;
4014 // Try to build the offloading actions and add the result as a dependency
4015 // to the host.
4016 if (UseNewOffloadingDriver)
4017 Current = BuildOffloadingActions(C, Args, I, Current);
4019 if (Current->getType() == types::TY_Nothing)
4020 break;
4023 // If we ended with something, add to the output list.
4024 if (Current)
4025 Actions.push_back(Current);
4027 // Add any top level actions generated for offloading.
4028 if (!UseNewOffloadingDriver)
4029 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
4030 else if (Current)
4031 Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4032 /*BoundArch=*/nullptr);
4035 // Add a link action if necessary.
4037 if (LinkerInputs.empty()) {
4038 Arg *FinalPhaseArg;
4039 if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link)
4040 if (!UseNewOffloadingDriver)
4041 OffloadBuilder.appendDeviceLinkActions(Actions);
4044 if (!LinkerInputs.empty()) {
4045 if (!UseNewOffloadingDriver)
4046 if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
4047 LinkerInputs.push_back(Wrapper);
4048 Action *LA;
4049 // Check if this Linker Job should emit a static library.
4050 if (ShouldEmitStaticLibrary(Args)) {
4051 LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
4052 } else if (UseNewOffloadingDriver ||
4053 Args.hasArg(options::OPT_offload_link)) {
4054 LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image);
4055 LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4056 /*BoundArch=*/nullptr);
4057 } else {
4058 LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
4060 if (!UseNewOffloadingDriver)
4061 LA = OffloadBuilder.processHostLinkAction(LA);
4062 Actions.push_back(LA);
4065 // Add an interface stubs merge action if necessary.
4066 if (!MergerInputs.empty())
4067 Actions.push_back(
4068 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4070 if (Args.hasArg(options::OPT_emit_interface_stubs)) {
4071 auto PhaseList = types::getCompilationPhases(
4072 types::TY_IFS_CPP,
4073 Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge);
4075 ActionList MergerInputs;
4077 for (auto &I : Inputs) {
4078 types::ID InputType = I.first;
4079 const Arg *InputArg = I.second;
4081 // Currently clang and the llvm assembler do not support generating symbol
4082 // stubs from assembly, so we skip the input on asm files. For ifs files
4083 // we rely on the normal pipeline setup in the pipeline setup code above.
4084 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
4085 InputType == types::TY_Asm)
4086 continue;
4088 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4090 for (auto Phase : PhaseList) {
4091 switch (Phase) {
4092 default:
4093 llvm_unreachable(
4094 "IFS Pipeline can only consist of Compile followed by IfsMerge.");
4095 case phases::Compile: {
4096 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
4097 // files where the .o file is located. The compile action can not
4098 // handle this.
4099 if (InputType == types::TY_Object)
4100 break;
4102 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
4103 break;
4105 case phases::IfsMerge: {
4106 assert(Phase == PhaseList.back() &&
4107 "merging must be final compilation step.");
4108 MergerInputs.push_back(Current);
4109 Current = nullptr;
4110 break;
4115 // If we ended with something, add to the output list.
4116 if (Current)
4117 Actions.push_back(Current);
4120 // Add an interface stubs merge action if necessary.
4121 if (!MergerInputs.empty())
4122 Actions.push_back(
4123 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4126 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
4127 // Compile phase that prints out supported cpu models and quits.
4128 if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
4129 // Use the -mcpu=? flag as the dummy input to cc1.
4130 Actions.clear();
4131 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
4132 Actions.push_back(
4133 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
4134 for (auto &I : Inputs)
4135 I.second->claim();
4138 // Claim ignored clang-cl options.
4139 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
4142 /// Returns the canonical name for the offloading architecture when using a HIP
4143 /// or CUDA architecture.
4144 static StringRef getCanonicalArchString(Compilation &C,
4145 const llvm::opt::DerivedArgList &Args,
4146 StringRef ArchStr,
4147 const llvm::Triple &Triple) {
4148 // Lookup the CUDA / HIP architecture string. Only report an error if we were
4149 // expecting the triple to be only NVPTX / AMDGPU.
4150 CudaArch Arch = StringToCudaArch(getProcessorFromTargetID(Triple, ArchStr));
4151 if (Triple.isNVPTX() &&
4152 (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch))) {
4153 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4154 << "CUDA" << ArchStr;
4155 return StringRef();
4156 } else if (Triple.isAMDGPU() &&
4157 (Arch == CudaArch::UNKNOWN || !IsAMDGpuArch(Arch))) {
4158 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4159 << "HIP" << ArchStr;
4160 return StringRef();
4163 if (IsNVIDIAGpuArch(Arch))
4164 return Args.MakeArgStringRef(CudaArchToString(Arch));
4166 if (IsAMDGpuArch(Arch)) {
4167 llvm::StringMap<bool> Features;
4168 auto HIPTriple = getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs());
4169 if (!HIPTriple)
4170 return StringRef();
4171 auto Arch = parseTargetID(*HIPTriple, ArchStr, &Features);
4172 if (!Arch) {
4173 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr;
4174 C.setContainsError();
4175 return StringRef();
4177 return Args.MakeArgStringRef(getCanonicalTargetID(*Arch, Features));
4180 // If the input isn't CUDA or HIP just return the architecture.
4181 return ArchStr;
4184 /// Checks if the set offloading architectures does not conflict. Returns the
4185 /// incompatible pair if a conflict occurs.
4186 static llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
4187 getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs,
4188 Action::OffloadKind Kind) {
4189 if (Kind != Action::OFK_HIP)
4190 return None;
4192 std::set<StringRef> ArchSet;
4193 llvm::copy(Archs, std::inserter(ArchSet, ArchSet.begin()));
4194 return getConflictTargetIDCombination(ArchSet);
4197 llvm::DenseSet<StringRef>
4198 Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
4199 Action::OffloadKind Kind, const ToolChain *TC) const {
4200 if (!TC)
4201 TC = &C.getDefaultToolChain();
4203 // --offload and --offload-arch options are mutually exclusive.
4204 if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
4205 Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
4206 options::OPT_no_offload_arch_EQ)) {
4207 C.getDriver().Diag(diag::err_opt_not_valid_with_opt)
4208 << "--offload"
4209 << (Args.hasArgNoClaim(options::OPT_offload_arch_EQ)
4210 ? "--offload-arch"
4211 : "--no-offload-arch");
4214 if (KnownArchs.find(TC) != KnownArchs.end())
4215 return KnownArchs.lookup(TC);
4217 llvm::DenseSet<StringRef> Archs;
4218 for (auto *Arg : Args) {
4219 // Extract any '--[no-]offload-arch' arguments intended for this toolchain.
4220 std::unique_ptr<llvm::opt::Arg> ExtractedArg = nullptr;
4221 if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) &&
4222 ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()) {
4223 Arg->claim();
4224 unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1));
4225 ExtractedArg = getOpts().ParseOneArg(Args, Index);
4226 Arg = ExtractedArg.get();
4229 if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) {
4230 for (StringRef Arch : llvm::split(Arg->getValue(), ","))
4231 Archs.insert(getCanonicalArchString(C, Args, Arch, TC->getTriple()));
4232 } else if (Arg->getOption().matches(options::OPT_no_offload_arch_EQ)) {
4233 for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4234 if (Arch == StringRef("all"))
4235 Archs.clear();
4236 else
4237 Archs.erase(getCanonicalArchString(C, Args, Arch, TC->getTriple()));
4242 if (auto ConflictingArchs = getConflictOffloadArchCombination(Archs, Kind)) {
4243 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
4244 << ConflictingArchs->first << ConflictingArchs->second;
4245 C.setContainsError();
4248 if (Archs.empty()) {
4249 if (Kind == Action::OFK_Cuda)
4250 Archs.insert(CudaArchToString(CudaArch::CudaDefault));
4251 else if (Kind == Action::OFK_HIP)
4252 Archs.insert(CudaArchToString(CudaArch::HIPDefault));
4253 else if (Kind == Action::OFK_OpenMP)
4254 Archs.insert(StringRef());
4255 } else {
4256 Args.ClaimAllArgs(options::OPT_offload_arch_EQ);
4257 Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ);
4260 return Archs;
4263 Action *Driver::BuildOffloadingActions(Compilation &C,
4264 llvm::opt::DerivedArgList &Args,
4265 const InputTy &Input,
4266 Action *HostAction) const {
4267 // Don't build offloading actions if explicitly disabled or we do not have a
4268 // valid source input and compile action to embed it in. If preprocessing only
4269 // ignore embedding.
4270 if (offloadHostOnly() || !types::isSrcFile(Input.first) ||
4271 !(isa<CompileJobAction>(HostAction) ||
4272 getFinalPhase(Args) == phases::Preprocess))
4273 return HostAction;
4275 ActionList OffloadActions;
4276 OffloadAction::DeviceDependences DDeps;
4278 const Action::OffloadKind OffloadKinds[] = {
4279 Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP};
4281 for (Action::OffloadKind Kind : OffloadKinds) {
4282 SmallVector<const ToolChain *, 2> ToolChains;
4283 ActionList DeviceActions;
4285 auto TCRange = C.getOffloadToolChains(Kind);
4286 for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI)
4287 ToolChains.push_back(TI->second);
4289 if (ToolChains.empty())
4290 continue;
4292 types::ID InputType = Input.first;
4293 const Arg *InputArg = Input.second;
4295 // The toolchain can be active for unsupported file types.
4296 if ((Kind == Action::OFK_Cuda && !types::isCuda(InputType)) ||
4297 (Kind == Action::OFK_HIP && !types::isHIP(InputType)))
4298 continue;
4300 // Get the product of all bound architectures and toolchains.
4301 SmallVector<std::pair<const ToolChain *, StringRef>> TCAndArchs;
4302 for (const ToolChain *TC : ToolChains)
4303 for (StringRef Arch : getOffloadArchs(C, Args, Kind, TC))
4304 TCAndArchs.push_back(std::make_pair(TC, Arch));
4306 for (unsigned I = 0, E = TCAndArchs.size(); I != E; ++I)
4307 DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType));
4309 if (DeviceActions.empty())
4310 return HostAction;
4312 auto PL = types::getCompilationPhases(*this, Args, InputType);
4314 for (phases::ID Phase : PL) {
4315 if (Phase == phases::Link) {
4316 assert(Phase == PL.back() && "linking must be final compilation step.");
4317 break;
4320 auto TCAndArch = TCAndArchs.begin();
4321 for (Action *&A : DeviceActions) {
4322 if (A->getType() == types::TY_Nothing)
4323 continue;
4325 A = ConstructPhaseAction(C, Args, Phase, A, Kind);
4327 if (isa<CompileJobAction>(A) && isa<CompileJobAction>(HostAction) &&
4328 Kind == Action::OFK_OpenMP &&
4329 HostAction->getType() != types::TY_Nothing) {
4330 // OpenMP offloading has a dependency on the host compile action to
4331 // identify which declarations need to be emitted. This shouldn't be
4332 // collapsed with any other actions so we can use it in the device.
4333 HostAction->setCannotBeCollapsedWithNextDependentAction();
4334 OffloadAction::HostDependence HDep(
4335 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4336 TCAndArch->second.data(), Kind);
4337 OffloadAction::DeviceDependences DDep;
4338 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4339 A = C.MakeAction<OffloadAction>(HDep, DDep);
4341 ++TCAndArch;
4345 // Compiling HIP in non-RDC mode requires linking each action individually.
4346 for (Action *&A : DeviceActions) {
4347 if (A->getType() != types::TY_Object || Kind != Action::OFK_HIP ||
4348 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
4349 continue;
4350 ActionList LinkerInput = {A};
4351 A = C.MakeAction<LinkJobAction>(LinkerInput, types::TY_Image);
4354 auto TCAndArch = TCAndArchs.begin();
4355 for (Action *A : DeviceActions) {
4356 DDeps.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4357 OffloadAction::DeviceDependences DDep;
4358 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4359 OffloadActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType()));
4360 ++TCAndArch;
4364 if (offloadDeviceOnly())
4365 return C.MakeAction<OffloadAction>(DDeps, types::TY_Nothing);
4367 if (OffloadActions.empty())
4368 return HostAction;
4370 OffloadAction::DeviceDependences DDep;
4371 if (C.isOffloadingHostKind(Action::OFK_Cuda) &&
4372 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) {
4373 // If we are not in RDC-mode we just emit the final CUDA fatbinary for
4374 // each translation unit without requiring any linking.
4375 Action *FatbinAction =
4376 C.MakeAction<LinkJobAction>(OffloadActions, types::TY_CUDA_FATBIN);
4377 DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_Cuda>(),
4378 nullptr, Action::OFK_Cuda);
4379 } else if (C.isOffloadingHostKind(Action::OFK_HIP) &&
4380 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4381 false)) {
4382 // If we are not in RDC-mode we just emit the final HIP fatbinary for each
4383 // translation unit, linking each input individually.
4384 Action *FatbinAction =
4385 C.MakeAction<LinkJobAction>(OffloadActions, types::TY_HIP_FATBIN);
4386 DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_HIP>(),
4387 nullptr, Action::OFK_HIP);
4388 } else {
4389 // Package all the offloading actions into a single output that can be
4390 // embedded in the host and linked.
4391 Action *PackagerAction =
4392 C.MakeAction<OffloadPackagerJobAction>(OffloadActions, types::TY_Image);
4393 DDep.add(*PackagerAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4394 nullptr, C.getActiveOffloadKinds());
4397 // If we are unable to embed a single device output into the host, we need to
4398 // add each device output as a host dependency to ensure they are still built.
4399 bool SingleDeviceOutput = !llvm::any_of(OffloadActions, [](Action *A) {
4400 return A->getType() == types::TY_Nothing;
4401 }) && isa<CompileJobAction>(HostAction);
4402 OffloadAction::HostDependence HDep(
4403 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4404 /*BoundArch=*/nullptr, SingleDeviceOutput ? DDep : DDeps);
4405 return C.MakeAction<OffloadAction>(HDep, SingleDeviceOutput ? DDep : DDeps);
4408 Action *Driver::ConstructPhaseAction(
4409 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
4410 Action::OffloadKind TargetDeviceOffloadKind) const {
4411 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
4413 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
4414 // encode this in the steps because the intermediate type depends on
4415 // arguments. Just special case here.
4416 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
4417 return Input;
4419 // Build the appropriate action.
4420 switch (Phase) {
4421 case phases::Link:
4422 llvm_unreachable("link action invalid here.");
4423 case phases::IfsMerge:
4424 llvm_unreachable("ifsmerge action invalid here.");
4425 case phases::Preprocess: {
4426 types::ID OutputTy;
4427 // -M and -MM specify the dependency file name by altering the output type,
4428 // -if -MD and -MMD are not specified.
4429 if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
4430 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
4431 OutputTy = types::TY_Dependencies;
4432 } else {
4433 OutputTy = Input->getType();
4434 // For these cases, the preprocessor is only translating forms, the Output
4435 // still needs preprocessing.
4436 if (!Args.hasFlag(options::OPT_frewrite_includes,
4437 options::OPT_fno_rewrite_includes, false) &&
4438 !Args.hasFlag(options::OPT_frewrite_imports,
4439 options::OPT_fno_rewrite_imports, false) &&
4440 !Args.hasFlag(options::OPT_fdirectives_only,
4441 options::OPT_fno_directives_only, false) &&
4442 !CCGenDiagnostics)
4443 OutputTy = types::getPreprocessedType(OutputTy);
4444 assert(OutputTy != types::TY_INVALID &&
4445 "Cannot preprocess this input type!");
4447 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
4449 case phases::Precompile: {
4450 // API extraction should not generate an actual precompilation action.
4451 if (Args.hasArg(options::OPT_extract_api))
4452 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4454 types::ID OutputTy = getPrecompiledType(Input->getType());
4455 assert(OutputTy != types::TY_INVALID &&
4456 "Cannot precompile this input type!");
4458 // If we're given a module name, precompile header file inputs as a
4459 // module, not as a precompiled header.
4460 const char *ModName = nullptr;
4461 if (OutputTy == types::TY_PCH) {
4462 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
4463 ModName = A->getValue();
4464 if (ModName)
4465 OutputTy = types::TY_ModuleFile;
4468 if (Args.hasArg(options::OPT_fsyntax_only)) {
4469 // Syntax checks should not emit a PCH file
4470 OutputTy = types::TY_Nothing;
4473 if (ModName)
4474 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
4475 ModName);
4476 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
4478 case phases::Compile: {
4479 if (Args.hasArg(options::OPT_fsyntax_only))
4480 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
4481 if (Args.hasArg(options::OPT_rewrite_objc))
4482 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
4483 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
4484 return C.MakeAction<CompileJobAction>(Input,
4485 types::TY_RewrittenLegacyObjC);
4486 if (Args.hasArg(options::OPT__analyze))
4487 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
4488 if (Args.hasArg(options::OPT__migrate))
4489 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
4490 if (Args.hasArg(options::OPT_emit_ast))
4491 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
4492 if (Args.hasArg(options::OPT_module_file_info))
4493 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
4494 if (Args.hasArg(options::OPT_verify_pch))
4495 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
4496 if (Args.hasArg(options::OPT_extract_api))
4497 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4498 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
4500 case phases::Backend: {
4501 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
4502 types::ID Output =
4503 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4504 return C.MakeAction<BackendJobAction>(Input, Output);
4506 if (isUsingLTO(/* IsOffload */ true) &&
4507 TargetDeviceOffloadKind != Action::OFK_None) {
4508 types::ID Output =
4509 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4510 return C.MakeAction<BackendJobAction>(Input, Output);
4512 if (Args.hasArg(options::OPT_emit_llvm) ||
4513 (TargetDeviceOffloadKind == Action::OFK_HIP &&
4514 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4515 false))) {
4516 types::ID Output =
4517 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
4518 return C.MakeAction<BackendJobAction>(Input, Output);
4520 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
4522 case phases::Assemble:
4523 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
4526 llvm_unreachable("invalid phase in ConstructPhaseAction");
4529 void Driver::BuildJobs(Compilation &C) const {
4530 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4532 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4534 // It is an error to provide a -o option if we are making multiple output
4535 // files. There are exceptions:
4537 // IfsMergeJob: when generating interface stubs enabled we want to be able to
4538 // generate the stub file at the same time that we generate the real
4539 // library/a.out. So when a .o, .so, etc are the output, with clang interface
4540 // stubs there will also be a .ifs and .ifso at the same location.
4542 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
4543 // and -c is passed, we still want to be able to generate a .ifs file while
4544 // we are also generating .o files. So we allow more than one output file in
4545 // this case as well.
4547 // OffloadClass of type TY_Nothing: device-only output will place many outputs
4548 // into a single offloading action. We should count all inputs to the action
4549 // as outputs. Also ignore device-only outputs if we're compiling with
4550 // -fsyntax-only.
4551 if (FinalOutput) {
4552 unsigned NumOutputs = 0;
4553 unsigned NumIfsOutputs = 0;
4554 for (const Action *A : C.getActions()) {
4555 if (A->getType() != types::TY_Nothing &&
4556 !(A->getKind() == Action::IfsMergeJobClass ||
4557 (A->getType() == clang::driver::types::TY_IFS_CPP &&
4558 A->getKind() == clang::driver::Action::CompileJobClass &&
4559 0 == NumIfsOutputs++) ||
4560 (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
4561 A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
4562 ++NumOutputs;
4563 else if (A->getKind() == Action::OffloadClass &&
4564 A->getType() == types::TY_Nothing &&
4565 !C.getArgs().hasArg(options::OPT_fsyntax_only))
4566 NumOutputs += A->size();
4569 if (NumOutputs > 1) {
4570 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
4571 FinalOutput = nullptr;
4575 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
4576 if (RawTriple.isOSAIX()) {
4577 if (Arg *A = C.getArgs().getLastArg(options::OPT_G))
4578 Diag(diag::err_drv_unsupported_opt_for_target)
4579 << A->getSpelling() << RawTriple.str();
4580 if (LTOMode == LTOK_Thin)
4581 Diag(diag::err_drv_clang_unsupported) << "thinLTO on AIX";
4584 // Collect the list of architectures.
4585 llvm::StringSet<> ArchNames;
4586 if (RawTriple.isOSBinFormatMachO())
4587 for (const Arg *A : C.getArgs())
4588 if (A->getOption().matches(options::OPT_arch))
4589 ArchNames.insert(A->getValue());
4591 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
4592 std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults;
4593 for (Action *A : C.getActions()) {
4594 // If we are linking an image for multiple archs then the linker wants
4595 // -arch_multiple and -final_output <final image name>. Unfortunately, this
4596 // doesn't fit in cleanly because we have to pass this information down.
4598 // FIXME: This is a hack; find a cleaner way to integrate this into the
4599 // process.
4600 const char *LinkingOutput = nullptr;
4601 if (isa<LipoJobAction>(A)) {
4602 if (FinalOutput)
4603 LinkingOutput = FinalOutput->getValue();
4604 else
4605 LinkingOutput = getDefaultImageName();
4608 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
4609 /*BoundArch*/ StringRef(),
4610 /*AtTopLevel*/ true,
4611 /*MultipleArchs*/ ArchNames.size() > 1,
4612 /*LinkingOutput*/ LinkingOutput, CachedResults,
4613 /*TargetDeviceOffloadKind*/ Action::OFK_None);
4616 // If we have more than one job, then disable integrated-cc1 for now. Do this
4617 // also when we need to report process execution statistics.
4618 if (C.getJobs().size() > 1 || CCPrintProcessStats)
4619 for (auto &J : C.getJobs())
4620 J.InProcess = false;
4622 if (CCPrintProcessStats) {
4623 C.setPostCallback([=](const Command &Cmd, int Res) {
4624 Optional<llvm::sys::ProcessStatistics> ProcStat =
4625 Cmd.getProcessStatistics();
4626 if (!ProcStat)
4627 return;
4629 const char *LinkingOutput = nullptr;
4630 if (FinalOutput)
4631 LinkingOutput = FinalOutput->getValue();
4632 else if (!Cmd.getOutputFilenames().empty())
4633 LinkingOutput = Cmd.getOutputFilenames().front().c_str();
4634 else
4635 LinkingOutput = getDefaultImageName();
4637 if (CCPrintStatReportFilename.empty()) {
4638 using namespace llvm;
4639 // Human readable output.
4640 outs() << sys::path::filename(Cmd.getExecutable()) << ": "
4641 << "output=" << LinkingOutput;
4642 outs() << ", total="
4643 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
4644 << ", user="
4645 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
4646 << ", mem=" << ProcStat->PeakMemory << " Kb\n";
4647 } else {
4648 // CSV format.
4649 std::string Buffer;
4650 llvm::raw_string_ostream Out(Buffer);
4651 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
4652 /*Quote*/ true);
4653 Out << ',';
4654 llvm::sys::printArg(Out, LinkingOutput, true);
4655 Out << ',' << ProcStat->TotalTime.count() << ','
4656 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
4657 << '\n';
4658 Out.flush();
4659 std::error_code EC;
4660 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
4661 llvm::sys::fs::OF_Append |
4662 llvm::sys::fs::OF_Text);
4663 if (EC)
4664 return;
4665 auto L = OS.lock();
4666 if (!L) {
4667 llvm::errs() << "ERROR: Cannot lock file "
4668 << CCPrintStatReportFilename << ": "
4669 << toString(L.takeError()) << "\n";
4670 return;
4672 OS << Buffer;
4673 OS.flush();
4678 // If the user passed -Qunused-arguments or there were errors, don't warn
4679 // about any unused arguments.
4680 if (Diags.hasErrorOccurred() ||
4681 C.getArgs().hasArg(options::OPT_Qunused_arguments))
4682 return;
4684 // Claim -fdriver-only here.
4685 (void)C.getArgs().hasArg(options::OPT_fdriver_only);
4686 // Claim -### here.
4687 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4689 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4690 (void)C.getArgs().hasArg(options::OPT_driver_mode);
4691 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4693 for (Arg *A : C.getArgs()) {
4694 // FIXME: It would be nice to be able to send the argument to the
4695 // DiagnosticsEngine, so that extra values, position, and so on could be
4696 // printed.
4697 if (!A->isClaimed()) {
4698 if (A->getOption().hasFlag(options::NoArgumentUnused))
4699 continue;
4701 // Suppress the warning automatically if this is just a flag, and it is an
4702 // instance of an argument we already claimed.
4703 const Option &Opt = A->getOption();
4704 if (Opt.getKind() == Option::FlagClass) {
4705 bool DuplicateClaimed = false;
4707 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4708 if (AA->isClaimed()) {
4709 DuplicateClaimed = true;
4710 break;
4714 if (DuplicateClaimed)
4715 continue;
4718 // In clang-cl, don't mention unknown arguments here since they have
4719 // already been warned about.
4720 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
4721 Diag(clang::diag::warn_drv_unused_argument)
4722 << A->getAsString(C.getArgs());
4727 namespace {
4728 /// Utility class to control the collapse of dependent actions and select the
4729 /// tools accordingly.
4730 class ToolSelector final {
4731 /// The tool chain this selector refers to.
4732 const ToolChain &TC;
4734 /// The compilation this selector refers to.
4735 const Compilation &C;
4737 /// The base action this selector refers to.
4738 const JobAction *BaseAction;
4740 /// Set to true if the current toolchain refers to host actions.
4741 bool IsHostSelector;
4743 /// Set to true if save-temps and embed-bitcode functionalities are active.
4744 bool SaveTemps;
4745 bool EmbedBitcode;
4747 /// Get previous dependent action or null if that does not exist. If
4748 /// \a CanBeCollapsed is false, that action must be legal to collapse or
4749 /// null will be returned.
4750 const JobAction *getPrevDependentAction(const ActionList &Inputs,
4751 ActionList &SavedOffloadAction,
4752 bool CanBeCollapsed = true) {
4753 // An option can be collapsed only if it has a single input.
4754 if (Inputs.size() != 1)
4755 return nullptr;
4757 Action *CurAction = *Inputs.begin();
4758 if (CanBeCollapsed &&
4759 !CurAction->isCollapsingWithNextDependentActionLegal())
4760 return nullptr;
4762 // If the input action is an offload action. Look through it and save any
4763 // offload action that can be dropped in the event of a collapse.
4764 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
4765 // If the dependent action is a device action, we will attempt to collapse
4766 // only with other device actions. Otherwise, we would do the same but
4767 // with host actions only.
4768 if (!IsHostSelector) {
4769 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
4770 CurAction =
4771 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
4772 if (CanBeCollapsed &&
4773 !CurAction->isCollapsingWithNextDependentActionLegal())
4774 return nullptr;
4775 SavedOffloadAction.push_back(OA);
4776 return dyn_cast<JobAction>(CurAction);
4778 } else if (OA->hasHostDependence()) {
4779 CurAction = OA->getHostDependence();
4780 if (CanBeCollapsed &&
4781 !CurAction->isCollapsingWithNextDependentActionLegal())
4782 return nullptr;
4783 SavedOffloadAction.push_back(OA);
4784 return dyn_cast<JobAction>(CurAction);
4786 return nullptr;
4789 return dyn_cast<JobAction>(CurAction);
4792 /// Return true if an assemble action can be collapsed.
4793 bool canCollapseAssembleAction() const {
4794 return TC.useIntegratedAs() && !SaveTemps &&
4795 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
4796 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
4797 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
4800 /// Return true if a preprocessor action can be collapsed.
4801 bool canCollapsePreprocessorAction() const {
4802 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
4803 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
4804 !C.getArgs().hasArg(options::OPT_rewrite_objc);
4807 /// Struct that relates an action with the offload actions that would be
4808 /// collapsed with it.
4809 struct JobActionInfo final {
4810 /// The action this info refers to.
4811 const JobAction *JA = nullptr;
4812 /// The offload actions we need to take care off if this action is
4813 /// collapsed.
4814 ActionList SavedOffloadAction;
4817 /// Append collapsed offload actions from the give nnumber of elements in the
4818 /// action info array.
4819 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
4820 ArrayRef<JobActionInfo> &ActionInfo,
4821 unsigned ElementNum) {
4822 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
4823 for (unsigned I = 0; I < ElementNum; ++I)
4824 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
4825 ActionInfo[I].SavedOffloadAction.end());
4828 /// Functions that attempt to perform the combining. They detect if that is
4829 /// legal, and if so they update the inputs \a Inputs and the offload action
4830 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
4831 /// the combined action is returned. If the combining is not legal or if the
4832 /// tool does not exist, null is returned.
4833 /// Currently three kinds of collapsing are supported:
4834 /// - Assemble + Backend + Compile;
4835 /// - Assemble + Backend ;
4836 /// - Backend + Compile.
4837 const Tool *
4838 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4839 ActionList &Inputs,
4840 ActionList &CollapsedOffloadAction) {
4841 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
4842 return nullptr;
4843 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4844 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4845 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
4846 if (!AJ || !BJ || !CJ)
4847 return nullptr;
4849 // Get compiler tool.
4850 const Tool *T = TC.SelectTool(*CJ);
4851 if (!T)
4852 return nullptr;
4854 // Can't collapse if we don't have codegen support unless we are
4855 // emitting LLVM IR.
4856 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
4857 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
4858 return nullptr;
4860 // When using -fembed-bitcode, it is required to have the same tool (clang)
4861 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
4862 if (EmbedBitcode) {
4863 const Tool *BT = TC.SelectTool(*BJ);
4864 if (BT == T)
4865 return nullptr;
4868 if (!T->hasIntegratedAssembler())
4869 return nullptr;
4871 Inputs = CJ->getInputs();
4872 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4873 /*NumElements=*/3);
4874 return T;
4876 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4877 ActionList &Inputs,
4878 ActionList &CollapsedOffloadAction) {
4879 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4880 return nullptr;
4881 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4882 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4883 if (!AJ || !BJ)
4884 return nullptr;
4886 // Get backend tool.
4887 const Tool *T = TC.SelectTool(*BJ);
4888 if (!T)
4889 return nullptr;
4891 if (!T->hasIntegratedAssembler())
4892 return nullptr;
4894 Inputs = BJ->getInputs();
4895 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4896 /*NumElements=*/2);
4897 return T;
4899 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4900 ActionList &Inputs,
4901 ActionList &CollapsedOffloadAction) {
4902 if (ActionInfo.size() < 2)
4903 return nullptr;
4904 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4905 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4906 if (!BJ || !CJ)
4907 return nullptr;
4909 // Check if the initial input (to the compile job or its predessor if one
4910 // exists) is LLVM bitcode. In that case, no preprocessor step is required
4911 // and we can still collapse the compile and backend jobs when we have
4912 // -save-temps. I.e. there is no need for a separate compile job just to
4913 // emit unoptimized bitcode.
4914 bool InputIsBitcode = true;
4915 for (size_t i = 1; i < ActionInfo.size(); i++)
4916 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4917 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4918 InputIsBitcode = false;
4919 break;
4921 if (!InputIsBitcode && !canCollapsePreprocessorAction())
4922 return nullptr;
4924 // Get compiler tool.
4925 const Tool *T = TC.SelectTool(*CJ);
4926 if (!T)
4927 return nullptr;
4929 // Can't collapse if we don't have codegen support unless we are
4930 // emitting LLVM IR.
4931 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
4932 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
4933 return nullptr;
4935 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4936 return nullptr;
4938 Inputs = CJ->getInputs();
4939 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4940 /*NumElements=*/2);
4941 return T;
4944 /// Updates the inputs if the obtained tool supports combining with
4945 /// preprocessor action, and the current input is indeed a preprocessor
4946 /// action. If combining results in the collapse of offloading actions, those
4947 /// are appended to \a CollapsedOffloadAction.
4948 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4949 ActionList &CollapsedOffloadAction) {
4950 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4951 return;
4953 // Attempt to get a preprocessor action dependence.
4954 ActionList PreprocessJobOffloadActions;
4955 ActionList NewInputs;
4956 for (Action *A : Inputs) {
4957 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4958 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4959 NewInputs.push_back(A);
4960 continue;
4963 // This is legal to combine. Append any offload action we found and add the
4964 // current input to preprocessor inputs.
4965 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
4966 PreprocessJobOffloadActions.end());
4967 NewInputs.append(PJ->input_begin(), PJ->input_end());
4969 Inputs = NewInputs;
4972 public:
4973 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
4974 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
4975 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
4976 EmbedBitcode(EmbedBitcode) {
4977 assert(BaseAction && "Invalid base action.");
4978 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
4981 /// Check if a chain of actions can be combined and return the tool that can
4982 /// handle the combination of actions. The pointer to the current inputs \a
4983 /// Inputs and the list of offload actions \a CollapsedOffloadActions
4984 /// connected to collapsed actions are updated accordingly. The latter enables
4985 /// the caller of the selector to process them afterwards instead of just
4986 /// dropping them. If no suitable tool is found, null will be returned.
4987 const Tool *getTool(ActionList &Inputs,
4988 ActionList &CollapsedOffloadAction) {
4990 // Get the largest chain of actions that we could combine.
4993 SmallVector<JobActionInfo, 5> ActionChain(1);
4994 ActionChain.back().JA = BaseAction;
4995 while (ActionChain.back().JA) {
4996 const Action *CurAction = ActionChain.back().JA;
4998 // Grow the chain by one element.
4999 ActionChain.resize(ActionChain.size() + 1);
5000 JobActionInfo &AI = ActionChain.back();
5002 // Attempt to fill it with the
5003 AI.JA =
5004 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
5007 // Pop the last action info as it could not be filled.
5008 ActionChain.pop_back();
5011 // Attempt to combine actions. If all combining attempts failed, just return
5012 // the tool of the provided action. At the end we attempt to combine the
5013 // action with any preprocessor action it may depend on.
5016 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
5017 CollapsedOffloadAction);
5018 if (!T)
5019 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
5020 if (!T)
5021 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
5022 if (!T) {
5023 Inputs = BaseAction->getInputs();
5024 T = TC.SelectTool(*BaseAction);
5027 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
5028 return T;
5033 /// Return a string that uniquely identifies the result of a job. The bound arch
5034 /// is not necessarily represented in the toolchain's triple -- for example,
5035 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
5036 /// Also, we need to add the offloading device kind, as the same tool chain can
5037 /// be used for host and device for some programming models, e.g. OpenMP.
5038 static std::string GetTriplePlusArchString(const ToolChain *TC,
5039 StringRef BoundArch,
5040 Action::OffloadKind OffloadKind) {
5041 std::string TriplePlusArch = TC->getTriple().normalize();
5042 if (!BoundArch.empty()) {
5043 TriplePlusArch += "-";
5044 TriplePlusArch += BoundArch;
5046 TriplePlusArch += "-";
5047 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
5048 return TriplePlusArch;
5051 InputInfoList Driver::BuildJobsForAction(
5052 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5053 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5054 std::map<std::pair<const Action *, std::string>, InputInfoList>
5055 &CachedResults,
5056 Action::OffloadKind TargetDeviceOffloadKind) const {
5057 std::pair<const Action *, std::string> ActionTC = {
5058 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5059 auto CachedResult = CachedResults.find(ActionTC);
5060 if (CachedResult != CachedResults.end()) {
5061 return CachedResult->second;
5063 InputInfoList Result = BuildJobsForActionNoCache(
5064 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
5065 CachedResults, TargetDeviceOffloadKind);
5066 CachedResults[ActionTC] = Result;
5067 return Result;
5070 InputInfoList Driver::BuildJobsForActionNoCache(
5071 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5072 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5073 std::map<std::pair<const Action *, std::string>, InputInfoList>
5074 &CachedResults,
5075 Action::OffloadKind TargetDeviceOffloadKind) const {
5076 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
5078 InputInfoList OffloadDependencesInputInfo;
5079 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
5080 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
5081 // The 'Darwin' toolchain is initialized only when its arguments are
5082 // computed. Get the default arguments for OFK_None to ensure that
5083 // initialization is performed before processing the offload action.
5084 // FIXME: Remove when darwin's toolchain is initialized during construction.
5085 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
5087 // The offload action is expected to be used in four different situations.
5089 // a) Set a toolchain/architecture/kind for a host action:
5090 // Host Action 1 -> OffloadAction -> Host Action 2
5092 // b) Set a toolchain/architecture/kind for a device action;
5093 // Device Action 1 -> OffloadAction -> Device Action 2
5095 // c) Specify a device dependence to a host action;
5096 // Device Action 1 _
5097 // \
5098 // Host Action 1 ---> OffloadAction -> Host Action 2
5100 // d) Specify a host dependence to a device action.
5101 // Host Action 1 _
5102 // \
5103 // Device Action 1 ---> OffloadAction -> Device Action 2
5105 // For a) and b), we just return the job generated for the dependences. For
5106 // c) and d) we override the current action with the host/device dependence
5107 // if the current toolchain is host/device and set the offload dependences
5108 // info with the jobs obtained from the device/host dependence(s).
5110 // If there is a single device option or has no host action, just generate
5111 // the job for it.
5112 if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
5113 InputInfoList DevA;
5114 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
5115 const char *DepBoundArch) {
5116 DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
5117 /*MultipleArchs*/ !!DepBoundArch,
5118 LinkingOutput, CachedResults,
5119 DepA->getOffloadingDeviceKind()));
5121 return DevA;
5124 // If 'Action 2' is host, we generate jobs for the device dependences and
5125 // override the current action with the host dependence. Otherwise, we
5126 // generate the host dependences and override the action with the device
5127 // dependence. The dependences can't therefore be a top-level action.
5128 OA->doOnEachDependence(
5129 /*IsHostDependence=*/BuildingForOffloadDevice,
5130 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5131 OffloadDependencesInputInfo.append(BuildJobsForAction(
5132 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
5133 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
5134 DepA->getOffloadingDeviceKind()));
5137 A = BuildingForOffloadDevice
5138 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
5139 : OA->getHostDependence();
5141 // We may have already built this action as a part of the offloading
5142 // toolchain, return the cached input if so.
5143 std::pair<const Action *, std::string> ActionTC = {
5144 OA->getHostDependence(),
5145 GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5146 if (CachedResults.find(ActionTC) != CachedResults.end()) {
5147 InputInfoList Inputs = CachedResults[ActionTC];
5148 Inputs.append(OffloadDependencesInputInfo);
5149 return Inputs;
5153 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
5154 // FIXME: It would be nice to not claim this here; maybe the old scheme of
5155 // just using Args was better?
5156 const Arg &Input = IA->getInputArg();
5157 Input.claim();
5158 if (Input.getOption().matches(options::OPT_INPUT)) {
5159 const char *Name = Input.getValue();
5160 return {InputInfo(A, Name, /* _BaseInput = */ Name)};
5162 return {InputInfo(A, &Input, /* _BaseInput = */ "")};
5165 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
5166 const ToolChain *TC;
5167 StringRef ArchName = BAA->getArchName();
5169 if (!ArchName.empty())
5170 TC = &getToolChain(C.getArgs(),
5171 computeTargetTriple(*this, TargetTriple,
5172 C.getArgs(), ArchName));
5173 else
5174 TC = &C.getDefaultToolChain();
5176 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
5177 MultipleArchs, LinkingOutput, CachedResults,
5178 TargetDeviceOffloadKind);
5182 ActionList Inputs = A->getInputs();
5184 const JobAction *JA = cast<JobAction>(A);
5185 ActionList CollapsedOffloadActions;
5187 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
5188 embedBitcodeInObject() && !isUsingLTO());
5189 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
5191 if (!T)
5192 return {InputInfo()};
5194 if (BuildingForOffloadDevice &&
5195 A->getOffloadingDeviceKind() == Action::OFK_OpenMP) {
5196 if (TC->getTriple().isAMDGCN()) {
5197 // AMDGCN treats backend and assemble actions as no-op because
5198 // linker does not support object files.
5199 if (const BackendJobAction *BA = dyn_cast<BackendJobAction>(A)) {
5200 return BuildJobsForAction(C, *BA->input_begin(), TC, BoundArch,
5201 AtTopLevel, MultipleArchs, LinkingOutput,
5202 CachedResults, TargetDeviceOffloadKind);
5205 if (const AssembleJobAction *AA = dyn_cast<AssembleJobAction>(A)) {
5206 return BuildJobsForAction(C, *AA->input_begin(), TC, BoundArch,
5207 AtTopLevel, MultipleArchs, LinkingOutput,
5208 CachedResults, TargetDeviceOffloadKind);
5213 // If we've collapsed action list that contained OffloadAction we
5214 // need to build jobs for host/device-side inputs it may have held.
5215 for (const auto *OA : CollapsedOffloadActions)
5216 cast<OffloadAction>(OA)->doOnEachDependence(
5217 /*IsHostDependence=*/BuildingForOffloadDevice,
5218 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5219 OffloadDependencesInputInfo.append(BuildJobsForAction(
5220 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
5221 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
5222 DepA->getOffloadingDeviceKind()));
5225 // Only use pipes when there is exactly one input.
5226 InputInfoList InputInfos;
5227 for (const Action *Input : Inputs) {
5228 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
5229 // shouldn't get temporary output names.
5230 // FIXME: Clean this up.
5231 bool SubJobAtTopLevel =
5232 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
5233 InputInfos.append(BuildJobsForAction(
5234 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
5235 CachedResults, A->getOffloadingDeviceKind()));
5238 // Always use the first file input as the base input.
5239 const char *BaseInput = InputInfos[0].getBaseInput();
5240 for (auto &Info : InputInfos) {
5241 if (Info.isFilename()) {
5242 BaseInput = Info.getBaseInput();
5243 break;
5247 // ... except dsymutil actions, which use their actual input as the base
5248 // input.
5249 if (JA->getType() == types::TY_dSYM)
5250 BaseInput = InputInfos[0].getFilename();
5252 // ... and in header module compilations, which use the module name.
5253 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
5254 BaseInput = ModuleJA->getModuleName();
5256 // Append outputs of offload device jobs to the input list
5257 if (!OffloadDependencesInputInfo.empty())
5258 InputInfos.append(OffloadDependencesInputInfo.begin(),
5259 OffloadDependencesInputInfo.end());
5261 // Set the effective triple of the toolchain for the duration of this job.
5262 llvm::Triple EffectiveTriple;
5263 const ToolChain &ToolTC = T->getToolChain();
5264 const ArgList &Args =
5265 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
5266 if (InputInfos.size() != 1) {
5267 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
5268 } else {
5269 // Pass along the input type if it can be unambiguously determined.
5270 EffectiveTriple = llvm::Triple(
5271 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
5273 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
5275 // Determine the place to write output to, if any.
5276 InputInfo Result;
5277 InputInfoList UnbundlingResults;
5278 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
5279 // If we have an unbundling job, we need to create results for all the
5280 // outputs. We also update the results cache so that other actions using
5281 // this unbundling action can get the right results.
5282 for (auto &UI : UA->getDependentActionsInfo()) {
5283 assert(UI.DependentOffloadKind != Action::OFK_None &&
5284 "Unbundling with no offloading??");
5286 // Unbundling actions are never at the top level. When we generate the
5287 // offloading prefix, we also do that for the host file because the
5288 // unbundling action does not change the type of the output which can
5289 // cause a overwrite.
5290 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5291 UI.DependentOffloadKind,
5292 UI.DependentToolChain->getTriple().normalize(),
5293 /*CreatePrefixForHost=*/true);
5294 auto CurI = InputInfo(
5296 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
5297 /*AtTopLevel=*/false,
5298 MultipleArchs ||
5299 UI.DependentOffloadKind == Action::OFK_HIP,
5300 OffloadingPrefix),
5301 BaseInput);
5302 // Save the unbundling result.
5303 UnbundlingResults.push_back(CurI);
5305 // Get the unique string identifier for this dependence and cache the
5306 // result.
5307 StringRef Arch;
5308 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
5309 if (UI.DependentOffloadKind == Action::OFK_Host)
5310 Arch = StringRef();
5311 else
5312 Arch = UI.DependentBoundArch;
5313 } else
5314 Arch = BoundArch;
5316 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
5317 UI.DependentOffloadKind)}] = {
5318 CurI};
5321 // Now that we have all the results generated, select the one that should be
5322 // returned for the current depending action.
5323 std::pair<const Action *, std::string> ActionTC = {
5324 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5325 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
5326 "Result does not exist??");
5327 Result = CachedResults[ActionTC].front();
5328 } else if (JA->getType() == types::TY_Nothing)
5329 Result = {InputInfo(A, BaseInput)};
5330 else {
5331 // We only have to generate a prefix for the host if this is not a top-level
5332 // action.
5333 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5334 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
5335 /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) ||
5336 !(A->getOffloadingHostActiveKinds() == Action::OFK_None ||
5337 AtTopLevel));
5338 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
5339 AtTopLevel, MultipleArchs,
5340 OffloadingPrefix),
5341 BaseInput);
5344 if (CCCPrintBindings && !CCGenDiagnostics) {
5345 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
5346 << " - \"" << T->getName() << "\", inputs: [";
5347 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
5348 llvm::errs() << InputInfos[i].getAsString();
5349 if (i + 1 != e)
5350 llvm::errs() << ", ";
5352 if (UnbundlingResults.empty())
5353 llvm::errs() << "], output: " << Result.getAsString() << "\n";
5354 else {
5355 llvm::errs() << "], outputs: [";
5356 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
5357 llvm::errs() << UnbundlingResults[i].getAsString();
5358 if (i + 1 != e)
5359 llvm::errs() << ", ";
5361 llvm::errs() << "] \n";
5363 } else {
5364 if (UnbundlingResults.empty())
5365 T->ConstructJob(
5366 C, *JA, Result, InputInfos,
5367 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5368 LinkingOutput);
5369 else
5370 T->ConstructJobMultipleOutputs(
5371 C, *JA, UnbundlingResults, InputInfos,
5372 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5373 LinkingOutput);
5375 return {Result};
5378 const char *Driver::getDefaultImageName() const {
5379 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
5380 return Target.isOSWindows() ? "a.exe" : "a.out";
5383 /// Create output filename based on ArgValue, which could either be a
5384 /// full filename, filename without extension, or a directory. If ArgValue
5385 /// does not provide a filename, then use BaseName, and use the extension
5386 /// suitable for FileType.
5387 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
5388 StringRef BaseName,
5389 types::ID FileType) {
5390 SmallString<128> Filename = ArgValue;
5392 if (ArgValue.empty()) {
5393 // If the argument is empty, output to BaseName in the current dir.
5394 Filename = BaseName;
5395 } else if (llvm::sys::path::is_separator(Filename.back())) {
5396 // If the argument is a directory, output to BaseName in that dir.
5397 llvm::sys::path::append(Filename, BaseName);
5400 if (!llvm::sys::path::has_extension(ArgValue)) {
5401 // If the argument didn't provide an extension, then set it.
5402 const char *Extension = types::getTypeTempSuffix(FileType, true);
5404 if (FileType == types::TY_Image &&
5405 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
5406 // The output file is a dll.
5407 Extension = "dll";
5410 llvm::sys::path::replace_extension(Filename, Extension);
5413 return Args.MakeArgString(Filename.c_str());
5416 static bool HasPreprocessOutput(const Action &JA) {
5417 if (isa<PreprocessJobAction>(JA))
5418 return true;
5419 if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0]))
5420 return true;
5421 if (isa<OffloadBundlingJobAction>(JA) &&
5422 HasPreprocessOutput(*(JA.getInputs()[0])))
5423 return true;
5424 return false;
5427 const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix,
5428 StringRef Suffix, bool MultipleArchs,
5429 StringRef BoundArch) const {
5430 SmallString<128> TmpName;
5431 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
5432 Optional<std::string> CrashDirectory =
5433 CCGenDiagnostics && A
5434 ? std::string(A->getValue())
5435 : llvm::sys::Process::GetEnv("CLANG_CRASH_DIAGNOSTICS_DIR");
5436 if (CrashDirectory) {
5437 if (!getVFS().exists(*CrashDirectory))
5438 llvm::sys::fs::create_directories(*CrashDirectory);
5439 SmallString<128> Path(*CrashDirectory);
5440 llvm::sys::path::append(Path, Prefix);
5441 const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%";
5442 if (std::error_code EC =
5443 llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) {
5444 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5445 return "";
5447 } else {
5448 if (MultipleArchs && !BoundArch.empty()) {
5449 TmpName = GetTemporaryDirectory(Prefix);
5450 llvm::sys::path::append(TmpName,
5451 Twine(Prefix) + "-" + BoundArch + "." + Suffix);
5452 } else {
5453 TmpName = GetTemporaryPath(Prefix, Suffix);
5456 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5459 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
5460 const char *BaseInput,
5461 StringRef OrigBoundArch, bool AtTopLevel,
5462 bool MultipleArchs,
5463 StringRef OffloadingPrefix) const {
5464 std::string BoundArch = OrigBoundArch.str();
5465 if (is_style_windows(llvm::sys::path::Style::native)) {
5466 // BoundArch may contains ':', which is invalid in file names on Windows,
5467 // therefore replace it with '%'.
5468 std::replace(BoundArch.begin(), BoundArch.end(), ':', '@');
5471 llvm::PrettyStackTraceString CrashInfo("Computing output path");
5472 // Output to a user requested destination?
5473 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
5474 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
5475 return C.addResultFile(FinalOutput->getValue(), &JA);
5478 // For /P, preprocess to file named after BaseInput.
5479 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
5480 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
5481 StringRef BaseName = llvm::sys::path::filename(BaseInput);
5482 StringRef NameArg;
5483 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
5484 NameArg = A->getValue();
5485 return C.addResultFile(
5486 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
5487 &JA);
5490 // Default to writing to stdout?
5491 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
5492 return "-";
5495 if (JA.getType() == types::TY_ModuleFile &&
5496 C.getArgs().getLastArg(options::OPT_module_file_info)) {
5497 return "-";
5500 if (IsDXCMode() && !C.getArgs().hasArg(options::OPT_o))
5501 return "-";
5503 // Is this the assembly listing for /FA?
5504 if (JA.getType() == types::TY_PP_Asm &&
5505 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
5506 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
5507 // Use /Fa and the input filename to determine the asm file name.
5508 StringRef BaseName = llvm::sys::path::filename(BaseInput);
5509 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
5510 return C.addResultFile(
5511 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
5512 &JA);
5515 // Output to a temporary file?
5516 if ((!AtTopLevel && !isSaveTempsEnabled() &&
5517 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
5518 CCGenDiagnostics) {
5519 StringRef Name = llvm::sys::path::filename(BaseInput);
5520 std::pair<StringRef, StringRef> Split = Name.split('.');
5521 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
5522 return CreateTempFile(C, Split.first, Suffix, MultipleArchs, BoundArch);
5525 SmallString<128> BasePath(BaseInput);
5526 SmallString<128> ExternalPath("");
5527 StringRef BaseName;
5529 // Dsymutil actions should use the full path.
5530 if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) {
5531 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
5532 // We use posix style here because the tests (specifically
5533 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
5534 // even on Windows and if we don't then the similar test covering this
5535 // fails.
5536 llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
5537 llvm::sys::path::filename(BasePath));
5538 BaseName = ExternalPath;
5539 } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
5540 BaseName = BasePath;
5541 else
5542 BaseName = llvm::sys::path::filename(BasePath);
5544 // Determine what the derived output name should be.
5545 const char *NamedOutput;
5547 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
5548 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
5549 // The /Fo or /o flag decides the object filename.
5550 StringRef Val =
5551 C.getArgs()
5552 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
5553 ->getValue();
5554 NamedOutput =
5555 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5556 } else if (JA.getType() == types::TY_Image &&
5557 C.getArgs().hasArg(options::OPT__SLASH_Fe,
5558 options::OPT__SLASH_o)) {
5559 // The /Fe or /o flag names the linked file.
5560 StringRef Val =
5561 C.getArgs()
5562 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
5563 ->getValue();
5564 NamedOutput =
5565 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
5566 } else if (JA.getType() == types::TY_Image) {
5567 if (IsCLMode()) {
5568 // clang-cl uses BaseName for the executable name.
5569 NamedOutput =
5570 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
5571 } else {
5572 SmallString<128> Output(getDefaultImageName());
5573 // HIP image for device compilation with -fno-gpu-rdc is per compilation
5574 // unit.
5575 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5576 !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
5577 options::OPT_fno_gpu_rdc, false);
5578 bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(JA);
5579 if (UseOutExtension) {
5580 Output = BaseName;
5581 llvm::sys::path::replace_extension(Output, "");
5583 Output += OffloadingPrefix;
5584 if (MultipleArchs && !BoundArch.empty()) {
5585 Output += "-";
5586 Output.append(BoundArch);
5588 if (UseOutExtension)
5589 Output += ".out";
5590 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
5592 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
5593 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
5594 } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) &&
5595 C.getArgs().hasArg(options::OPT__SLASH_o)) {
5596 StringRef Val =
5597 C.getArgs()
5598 .getLastArg(options::OPT__SLASH_o)
5599 ->getValue();
5600 NamedOutput =
5601 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5602 } else {
5603 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
5604 assert(Suffix && "All types used for output should have a suffix.");
5606 std::string::size_type End = std::string::npos;
5607 if (!types::appendSuffixForType(JA.getType()))
5608 End = BaseName.rfind('.');
5609 SmallString<128> Suffixed(BaseName.substr(0, End));
5610 Suffixed += OffloadingPrefix;
5611 if (MultipleArchs && !BoundArch.empty()) {
5612 Suffixed += "-";
5613 Suffixed.append(BoundArch);
5615 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
5616 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
5617 // optimized bitcode output.
5618 auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
5619 const llvm::opt::DerivedArgList &Args) {
5620 // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
5621 // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
5622 // phase.)
5623 return isa<CompileJobAction>(JA) &&
5624 JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5625 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5626 false);
5628 if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
5629 (C.getArgs().hasArg(options::OPT_emit_llvm) ||
5630 IsHIPRDCInCompilePhase(JA, C.getArgs())))
5631 Suffixed += ".tmp";
5632 Suffixed += '.';
5633 Suffixed += Suffix;
5634 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
5637 // Prepend object file path if -save-temps=obj
5638 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
5639 JA.getType() != types::TY_PCH) {
5640 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
5641 SmallString<128> TempPath(FinalOutput->getValue());
5642 llvm::sys::path::remove_filename(TempPath);
5643 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
5644 llvm::sys::path::append(TempPath, OutputFileName);
5645 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
5648 // If we're saving temps and the temp file conflicts with the input file,
5649 // then avoid overwriting input file.
5650 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
5651 bool SameFile = false;
5652 SmallString<256> Result;
5653 llvm::sys::fs::current_path(Result);
5654 llvm::sys::path::append(Result, BaseName);
5655 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
5656 // Must share the same path to conflict.
5657 if (SameFile) {
5658 StringRef Name = llvm::sys::path::filename(BaseInput);
5659 std::pair<StringRef, StringRef> Split = Name.split('.');
5660 std::string TmpName = GetTemporaryPath(
5661 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
5662 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5666 // As an annoying special case, PCH generation doesn't strip the pathname.
5667 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
5668 llvm::sys::path::remove_filename(BasePath);
5669 if (BasePath.empty())
5670 BasePath = NamedOutput;
5671 else
5672 llvm::sys::path::append(BasePath, NamedOutput);
5673 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
5674 } else {
5675 return C.addResultFile(NamedOutput, &JA);
5679 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
5680 // Search for Name in a list of paths.
5681 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
5682 -> llvm::Optional<std::string> {
5683 // Respect a limited subset of the '-Bprefix' functionality in GCC by
5684 // attempting to use this prefix when looking for file paths.
5685 for (const auto &Dir : P) {
5686 if (Dir.empty())
5687 continue;
5688 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
5689 llvm::sys::path::append(P, Name);
5690 if (llvm::sys::fs::exists(Twine(P)))
5691 return std::string(P);
5693 return None;
5696 if (auto P = SearchPaths(PrefixDirs))
5697 return *P;
5699 SmallString<128> R(ResourceDir);
5700 llvm::sys::path::append(R, Name);
5701 if (llvm::sys::fs::exists(Twine(R)))
5702 return std::string(R.str());
5704 SmallString<128> P(TC.getCompilerRTPath());
5705 llvm::sys::path::append(P, Name);
5706 if (llvm::sys::fs::exists(Twine(P)))
5707 return std::string(P.str());
5709 SmallString<128> D(Dir);
5710 llvm::sys::path::append(D, "..", Name);
5711 if (llvm::sys::fs::exists(Twine(D)))
5712 return std::string(D.str());
5714 if (auto P = SearchPaths(TC.getLibraryPaths()))
5715 return *P;
5717 if (auto P = SearchPaths(TC.getFilePaths()))
5718 return *P;
5720 return std::string(Name);
5723 void Driver::generatePrefixedToolNames(
5724 StringRef Tool, const ToolChain &TC,
5725 SmallVectorImpl<std::string> &Names) const {
5726 // FIXME: Needs a better variable than TargetTriple
5727 Names.emplace_back((TargetTriple + "-" + Tool).str());
5728 Names.emplace_back(Tool);
5731 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
5732 llvm::sys::path::append(Dir, Name);
5733 if (llvm::sys::fs::can_execute(Twine(Dir)))
5734 return true;
5735 llvm::sys::path::remove_filename(Dir);
5736 return false;
5739 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
5740 SmallVector<std::string, 2> TargetSpecificExecutables;
5741 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
5743 // Respect a limited subset of the '-Bprefix' functionality in GCC by
5744 // attempting to use this prefix when looking for program paths.
5745 for (const auto &PrefixDir : PrefixDirs) {
5746 if (llvm::sys::fs::is_directory(PrefixDir)) {
5747 SmallString<128> P(PrefixDir);
5748 if (ScanDirForExecutable(P, Name))
5749 return std::string(P.str());
5750 } else {
5751 SmallString<128> P((PrefixDir + Name).str());
5752 if (llvm::sys::fs::can_execute(Twine(P)))
5753 return std::string(P.str());
5757 const ToolChain::path_list &List = TC.getProgramPaths();
5758 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
5759 // For each possible name of the tool look for it in
5760 // program paths first, then the path.
5761 // Higher priority names will be first, meaning that
5762 // a higher priority name in the path will be found
5763 // instead of a lower priority name in the program path.
5764 // E.g. <triple>-gcc on the path will be found instead
5765 // of gcc in the program path
5766 for (const auto &Path : List) {
5767 SmallString<128> P(Path);
5768 if (ScanDirForExecutable(P, TargetSpecificExecutable))
5769 return std::string(P.str());
5772 // Fall back to the path
5773 if (llvm::ErrorOr<std::string> P =
5774 llvm::sys::findProgramByName(TargetSpecificExecutable))
5775 return *P;
5778 return std::string(Name);
5781 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
5782 SmallString<128> Path;
5783 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
5784 if (EC) {
5785 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5786 return "";
5789 return std::string(Path.str());
5792 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
5793 SmallString<128> Path;
5794 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
5795 if (EC) {
5796 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5797 return "";
5800 return std::string(Path.str());
5803 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
5804 SmallString<128> Output;
5805 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
5806 // FIXME: If anybody needs it, implement this obscure rule:
5807 // "If you specify a directory without a file name, the default file name
5808 // is VCx0.pch., where x is the major version of Visual C++ in use."
5809 Output = FpArg->getValue();
5811 // "If you do not specify an extension as part of the path name, an
5812 // extension of .pch is assumed. "
5813 if (!llvm::sys::path::has_extension(Output))
5814 Output += ".pch";
5815 } else {
5816 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
5817 Output = YcArg->getValue();
5818 if (Output.empty())
5819 Output = BaseName;
5820 llvm::sys::path::replace_extension(Output, ".pch");
5822 return std::string(Output.str());
5825 const ToolChain &Driver::getToolChain(const ArgList &Args,
5826 const llvm::Triple &Target) const {
5828 auto &TC = ToolChains[Target.str()];
5829 if (!TC) {
5830 switch (Target.getOS()) {
5831 case llvm::Triple::AIX:
5832 TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
5833 break;
5834 case llvm::Triple::Haiku:
5835 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
5836 break;
5837 case llvm::Triple::Ananas:
5838 TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
5839 break;
5840 case llvm::Triple::CloudABI:
5841 TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
5842 break;
5843 case llvm::Triple::Darwin:
5844 case llvm::Triple::MacOSX:
5845 case llvm::Triple::IOS:
5846 case llvm::Triple::TvOS:
5847 case llvm::Triple::WatchOS:
5848 case llvm::Triple::DriverKit:
5849 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
5850 break;
5851 case llvm::Triple::DragonFly:
5852 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
5853 break;
5854 case llvm::Triple::OpenBSD:
5855 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
5856 break;
5857 case llvm::Triple::NetBSD:
5858 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
5859 break;
5860 case llvm::Triple::FreeBSD:
5861 if (Target.isPPC())
5862 TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target,
5863 Args);
5864 else
5865 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
5866 break;
5867 case llvm::Triple::Minix:
5868 TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
5869 break;
5870 case llvm::Triple::Linux:
5871 case llvm::Triple::ELFIAMCU:
5872 if (Target.getArch() == llvm::Triple::hexagon)
5873 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5874 Args);
5875 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
5876 !Target.hasEnvironment())
5877 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
5878 Args);
5879 else if (Target.isPPC())
5880 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
5881 Args);
5882 else if (Target.getArch() == llvm::Triple::ve)
5883 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5885 else
5886 TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
5887 break;
5888 case llvm::Triple::NaCl:
5889 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
5890 break;
5891 case llvm::Triple::Fuchsia:
5892 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
5893 break;
5894 case llvm::Triple::Solaris:
5895 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
5896 break;
5897 case llvm::Triple::AMDHSA:
5898 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
5899 break;
5900 case llvm::Triple::AMDPAL:
5901 case llvm::Triple::Mesa3D:
5902 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
5903 break;
5904 case llvm::Triple::Win32:
5905 switch (Target.getEnvironment()) {
5906 default:
5907 if (Target.isOSBinFormatELF())
5908 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5909 else if (Target.isOSBinFormatMachO())
5910 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5911 else
5912 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5913 break;
5914 case llvm::Triple::GNU:
5915 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
5916 break;
5917 case llvm::Triple::Itanium:
5918 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
5919 Args);
5920 break;
5921 case llvm::Triple::MSVC:
5922 case llvm::Triple::UnknownEnvironment:
5923 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
5924 .startswith_insensitive("bfd"))
5925 TC = std::make_unique<toolchains::CrossWindowsToolChain>(
5926 *this, Target, Args);
5927 else
5928 TC =
5929 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
5930 break;
5932 break;
5933 case llvm::Triple::PS4:
5934 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
5935 break;
5936 case llvm::Triple::PS5:
5937 TC = std::make_unique<toolchains::PS5CPU>(*this, Target, Args);
5938 break;
5939 case llvm::Triple::Contiki:
5940 TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
5941 break;
5942 case llvm::Triple::Hurd:
5943 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
5944 break;
5945 case llvm::Triple::ZOS:
5946 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args);
5947 break;
5948 case llvm::Triple::ShaderModel:
5949 TC = std::make_unique<toolchains::HLSLToolChain>(*this, Target, Args);
5950 break;
5951 default:
5952 // Of these targets, Hexagon is the only one that might have
5953 // an OS of Linux, in which case it got handled above already.
5954 switch (Target.getArch()) {
5955 case llvm::Triple::tce:
5956 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
5957 break;
5958 case llvm::Triple::tcele:
5959 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
5960 break;
5961 case llvm::Triple::hexagon:
5962 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5963 Args);
5964 break;
5965 case llvm::Triple::lanai:
5966 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
5967 break;
5968 case llvm::Triple::xcore:
5969 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
5970 break;
5971 case llvm::Triple::wasm32:
5972 case llvm::Triple::wasm64:
5973 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
5974 break;
5975 case llvm::Triple::avr:
5976 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
5977 break;
5978 case llvm::Triple::msp430:
5979 TC =
5980 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
5981 break;
5982 case llvm::Triple::riscv32:
5983 case llvm::Triple::riscv64:
5984 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
5985 TC =
5986 std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
5987 else
5988 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
5989 break;
5990 case llvm::Triple::ve:
5991 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5992 break;
5993 case llvm::Triple::spirv32:
5994 case llvm::Triple::spirv64:
5995 TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args);
5996 break;
5997 case llvm::Triple::csky:
5998 TC = std::make_unique<toolchains::CSKYToolChain>(*this, Target, Args);
5999 break;
6000 default:
6001 if (Target.getVendor() == llvm::Triple::Myriad)
6002 TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
6003 Args);
6004 else if (toolchains::BareMetal::handlesTarget(Target))
6005 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6006 else if (Target.isOSBinFormatELF())
6007 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
6008 else if (Target.isOSBinFormatMachO())
6009 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
6010 else
6011 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6016 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
6017 // compiles always need two toolchains, the CUDA toolchain and the host
6018 // toolchain. So the only valid way to create a CUDA toolchain is via
6019 // CreateOffloadingDeviceToolChains.
6021 return *TC;
6024 const ToolChain &Driver::getOffloadingDeviceToolChain(
6025 const ArgList &Args, const llvm::Triple &Target, const ToolChain &HostTC,
6026 const Action::OffloadKind &TargetDeviceOffloadKind) const {
6027 // Use device / host triples as the key into the ToolChains map because the
6028 // device ToolChain we create depends on both.
6029 auto &TC = ToolChains[Target.str() + "/" + HostTC.getTriple().str()];
6030 if (!TC) {
6031 // Categorized by offload kind > arch rather than OS > arch like
6032 // the normal getToolChain call, as it seems a reasonable way to categorize
6033 // things.
6034 switch (TargetDeviceOffloadKind) {
6035 case Action::OFK_HIP: {
6036 if (Target.getArch() == llvm::Triple::amdgcn &&
6037 Target.getVendor() == llvm::Triple::AMD &&
6038 Target.getOS() == llvm::Triple::AMDHSA)
6039 TC = std::make_unique<toolchains::HIPAMDToolChain>(*this, Target,
6040 HostTC, Args);
6041 else if (Target.getArch() == llvm::Triple::spirv64 &&
6042 Target.getVendor() == llvm::Triple::UnknownVendor &&
6043 Target.getOS() == llvm::Triple::UnknownOS)
6044 TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target,
6045 HostTC, Args);
6046 break;
6048 default:
6049 break;
6053 return *TC;
6056 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
6057 // Say "no" if there is not exactly one input of a type clang understands.
6058 if (JA.size() != 1 ||
6059 !types::isAcceptedByClang((*JA.input_begin())->getType()))
6060 return false;
6062 // And say "no" if this is not a kind of action clang understands.
6063 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
6064 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA) &&
6065 !isa<ExtractAPIJobAction>(JA))
6066 return false;
6068 return true;
6071 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
6072 // Say "no" if there is not exactly one input of a type flang understands.
6073 if (JA.size() != 1 ||
6074 !types::isAcceptedByFlang((*JA.input_begin())->getType()))
6075 return false;
6077 // And say "no" if this is not a kind of action flang understands.
6078 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) &&
6079 !isa<BackendJobAction>(JA))
6080 return false;
6082 return true;
6085 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
6086 // Only emit static library if the flag is set explicitly.
6087 if (Args.hasArg(options::OPT_emit_static_lib))
6088 return true;
6089 return false;
6092 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
6093 /// grouped values as integers. Numbers which are not provided are set to 0.
6095 /// \return True if the entire string was parsed (9.2), or all groups were
6096 /// parsed (10.3.5extrastuff).
6097 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
6098 unsigned &Micro, bool &HadExtra) {
6099 HadExtra = false;
6101 Major = Minor = Micro = 0;
6102 if (Str.empty())
6103 return false;
6105 if (Str.consumeInteger(10, Major))
6106 return false;
6107 if (Str.empty())
6108 return true;
6109 if (Str[0] != '.')
6110 return false;
6112 Str = Str.drop_front(1);
6114 if (Str.consumeInteger(10, Minor))
6115 return false;
6116 if (Str.empty())
6117 return true;
6118 if (Str[0] != '.')
6119 return false;
6120 Str = Str.drop_front(1);
6122 if (Str.consumeInteger(10, Micro))
6123 return false;
6124 if (!Str.empty())
6125 HadExtra = true;
6126 return true;
6129 /// Parse digits from a string \p Str and fulfill \p Digits with
6130 /// the parsed numbers. This method assumes that the max number of
6131 /// digits to look for is equal to Digits.size().
6133 /// \return True if the entire string was parsed and there are
6134 /// no extra characters remaining at the end.
6135 bool Driver::GetReleaseVersion(StringRef Str,
6136 MutableArrayRef<unsigned> Digits) {
6137 if (Str.empty())
6138 return false;
6140 unsigned CurDigit = 0;
6141 while (CurDigit < Digits.size()) {
6142 unsigned Digit;
6143 if (Str.consumeInteger(10, Digit))
6144 return false;
6145 Digits[CurDigit] = Digit;
6146 if (Str.empty())
6147 return true;
6148 if (Str[0] != '.')
6149 return false;
6150 Str = Str.drop_front(1);
6151 CurDigit++;
6154 // More digits than requested, bail out...
6155 return false;
6158 std::pair<unsigned, unsigned>
6159 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
6160 unsigned IncludedFlagsBitmask = 0;
6161 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
6163 if (IsClCompatMode) {
6164 // Include CL and Core options.
6165 IncludedFlagsBitmask |= options::CLOption;
6166 IncludedFlagsBitmask |= options::CLDXCOption;
6167 IncludedFlagsBitmask |= options::CoreOption;
6168 } else {
6169 ExcludedFlagsBitmask |= options::CLOption;
6171 if (IsDXCMode()) {
6172 // Include DXC and Core options.
6173 IncludedFlagsBitmask |= options::DXCOption;
6174 IncludedFlagsBitmask |= options::CLDXCOption;
6175 IncludedFlagsBitmask |= options::CoreOption;
6176 } else {
6177 ExcludedFlagsBitmask |= options::DXCOption;
6179 if (!IsClCompatMode && !IsDXCMode())
6180 ExcludedFlagsBitmask |= options::CLDXCOption;
6182 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
6185 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
6186 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
6189 bool clang::driver::willEmitRemarks(const ArgList &Args) {
6190 // -fsave-optimization-record enables it.
6191 if (Args.hasFlag(options::OPT_fsave_optimization_record,
6192 options::OPT_fno_save_optimization_record, false))
6193 return true;
6195 // -fsave-optimization-record=<format> enables it as well.
6196 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
6197 options::OPT_fno_save_optimization_record, false))
6198 return true;
6200 // -foptimization-record-file alone enables it too.
6201 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
6202 options::OPT_fno_save_optimization_record, false))
6203 return true;
6205 // -foptimization-record-passes alone enables it too.
6206 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
6207 options::OPT_fno_save_optimization_record, false))
6208 return true;
6209 return false;
6212 llvm::StringRef clang::driver::getDriverMode(StringRef ProgName,
6213 ArrayRef<const char *> Args) {
6214 static const std::string OptName =
6215 getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName();
6216 llvm::StringRef Opt;
6217 for (StringRef Arg : Args) {
6218 if (!Arg.startswith(OptName))
6219 continue;
6220 Opt = Arg;
6222 if (Opt.empty())
6223 Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode;
6224 return Opt.consume_front(OptName) ? Opt : "";
6227 bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); }