1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang/Driver/Driver.h"
10 #include "InputInfo.h"
11 #include "ToolChains/AIX.h"
12 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
16 #include "ToolChains/Clang.h"
17 #include "ToolChains/CloudABI.h"
18 #include "ToolChains/Contiki.h"
19 #include "ToolChains/CrossWindows.h"
20 #include "ToolChains/Cuda.h"
21 #include "ToolChains/Darwin.h"
22 #include "ToolChains/DragonFly.h"
23 #include "ToolChains/FreeBSD.h"
24 #include "ToolChains/Fuchsia.h"
25 #include "ToolChains/Gnu.h"
26 #include "ToolChains/HIP.h"
27 #include "ToolChains/Haiku.h"
28 #include "ToolChains/Hexagon.h"
29 #include "ToolChains/Hurd.h"
30 #include "ToolChains/Lanai.h"
31 #include "ToolChains/Linux.h"
32 #include "ToolChains/MSP430.h"
33 #include "ToolChains/MSVC.h"
34 #include "ToolChains/MinGW.h"
35 #include "ToolChains/Minix.h"
36 #include "ToolChains/MipsLinux.h"
37 #include "ToolChains/Myriad.h"
38 #include "ToolChains/NaCl.h"
39 #include "ToolChains/NetBSD.h"
40 #include "ToolChains/OpenBSD.h"
41 #include "ToolChains/PPCLinux.h"
42 #include "ToolChains/PS4CPU.h"
43 #include "ToolChains/RISCVToolchain.h"
44 #include "ToolChains/Solaris.h"
45 #include "ToolChains/TCE.h"
46 #include "ToolChains/VEToolchain.h"
47 #include "ToolChains/WebAssembly.h"
48 #include "ToolChains/XCore.h"
49 #include "clang/Basic/Version.h"
50 #include "clang/Config/config.h"
51 #include "clang/Driver/Action.h"
52 #include "clang/Driver/Compilation.h"
53 #include "clang/Driver/DriverDiagnostic.h"
54 #include "clang/Driver/Job.h"
55 #include "clang/Driver/Options.h"
56 #include "clang/Driver/SanitizerArgs.h"
57 #include "clang/Driver/Tool.h"
58 #include "clang/Driver/ToolChain.h"
59 #include "llvm/ADT/ArrayRef.h"
60 #include "llvm/ADT/STLExtras.h"
61 #include "llvm/ADT/SmallSet.h"
62 #include "llvm/ADT/StringExtras.h"
63 #include "llvm/ADT/StringSet.h"
64 #include "llvm/ADT/StringSwitch.h"
65 #include "llvm/Config/llvm-config.h"
66 #include "llvm/Option/Arg.h"
67 #include "llvm/Option/ArgList.h"
68 #include "llvm/Option/OptSpecifier.h"
69 #include "llvm/Option/OptTable.h"
70 #include "llvm/Option/Option.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/FileSystem.h"
74 #include "llvm/Support/FormatVariadic.h"
75 #include "llvm/Support/Host.h"
76 #include "llvm/Support/Path.h"
77 #include "llvm/Support/PrettyStackTrace.h"
78 #include "llvm/Support/Process.h"
79 #include "llvm/Support/Program.h"
80 #include "llvm/Support/StringSaver.h"
81 #include "llvm/Support/TargetRegistry.h"
82 #include "llvm/Support/VirtualFileSystem.h"
83 #include "llvm/Support/raw_ostream.h"
88 #include <unistd.h> // getpid
89 #include <sysexits.h> // EX_IOERR
92 using namespace clang::driver;
93 using namespace clang;
94 using namespace llvm::opt;
97 std::string Driver::GetResourcesPath(StringRef BinaryPath,
98 StringRef CustomResourceDir) {
99 // Since the resource directory is embedded in the module hash, it's important
100 // that all places that need it call this function, so that they get the
101 // exact same string ("a/../b/" and "b/" get different hashes, for example).
103 // Dir is bin/ or lib/, depending on where BinaryPath is.
104 std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
106 SmallString<128> P(Dir);
107 if (CustomResourceDir != "") {
108 llvm::sys::path::append(P, CustomResourceDir);
110 // On Windows, libclang.dll is in bin/.
111 // On non-Windows, libclang.so/.dylib is in lib/.
112 // With a static-library build of libclang, LibClangPath will contain the
113 // path of the embedding binary, which for LLVM binaries will be in bin/.
114 // ../lib gets us to lib/ in both cases.
115 P = llvm::sys::path::parent_path(Dir);
116 llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
117 CLANG_VERSION_STRING);
120 return std::string(P.str());
123 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
124 DiagnosticsEngine &Diags,
125 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
126 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
127 SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
128 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
129 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
130 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
131 CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false),
132 CCLogDiagnostics(false), CCGenDiagnostics(false),
133 TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),
134 CheckInputsExist(true), GenReproducer(false),
135 SuppressMissingInputWarning(false) {
136 // Provide a sane fallback if no VFS is specified.
138 this->VFS = llvm::vfs::getRealFileSystem();
140 Name = std::string(llvm::sys::path::filename(ClangExecutable));
141 Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
142 InstalledDir = Dir; // Provide a sensible default installed dir.
144 if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
145 // Prepend InstalledDir if SysRoot is relative
146 SmallString<128> P(InstalledDir);
147 llvm::sys::path::append(P, SysRoot);
148 SysRoot = std::string(P);
151 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
152 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
154 #if defined(CLANG_CONFIG_FILE_USER_DIR)
155 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
158 // Compute the path to the resource directory.
159 ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
162 void Driver::ParseDriverMode(StringRef ProgramName,
163 ArrayRef<const char *> Args) {
164 if (ClangNameParts.isEmpty())
165 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
166 setDriverModeFromOption(ClangNameParts.DriverMode);
168 for (const char *ArgPtr : Args) {
169 // Ignore nullptrs, they are the response file's EOL markers.
170 if (ArgPtr == nullptr)
172 const StringRef Arg = ArgPtr;
173 setDriverModeFromOption(Arg);
177 void Driver::setDriverModeFromOption(StringRef Opt) {
178 const std::string OptName =
179 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
180 if (!Opt.startswith(OptName))
182 StringRef Value = Opt.drop_front(OptName.size());
184 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
185 .Case("gcc", GCCMode)
186 .Case("g++", GXXMode)
187 .Case("cpp", CPPMode)
189 .Case("flang", FlangMode)
193 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
196 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
198 bool &ContainsError) {
199 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
200 ContainsError = false;
202 unsigned IncludedFlagsBitmask;
203 unsigned ExcludedFlagsBitmask;
204 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
205 getIncludeExcludeOptionFlagMasks(IsClCompatMode);
207 unsigned MissingArgIndex, MissingArgCount;
209 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
210 IncludedFlagsBitmask, ExcludedFlagsBitmask);
212 // Check for missing argument error.
213 if (MissingArgCount) {
214 Diag(diag::err_drv_missing_argument)
215 << Args.getArgString(MissingArgIndex) << MissingArgCount;
217 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
218 SourceLocation()) > DiagnosticsEngine::Warning;
221 // Check for unsupported options.
222 for (const Arg *A : Args) {
223 if (A->getOption().hasFlag(options::Unsupported)) {
225 auto ArgString = A->getAsString(Args);
227 if (getOpts().findNearest(
228 ArgString, Nearest, IncludedFlagsBitmask,
229 ExcludedFlagsBitmask | options::Unsupported) > 1) {
230 DiagID = diag::err_drv_unsupported_opt;
231 Diag(DiagID) << ArgString;
233 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
234 Diag(DiagID) << ArgString << Nearest;
236 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
237 DiagnosticsEngine::Warning;
241 // Warn about -mcpu= without an argument.
242 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
243 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
244 ContainsError |= Diags.getDiagnosticLevel(
245 diag::warn_drv_empty_joined_argument,
246 SourceLocation()) > DiagnosticsEngine::Warning;
250 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
252 auto ArgString = A->getAsString(Args);
254 if (getOpts().findNearest(
255 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
256 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
257 : diag::err_drv_unknown_argument;
258 Diags.Report(DiagID) << ArgString;
261 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
262 : diag::err_drv_unknown_argument_with_suggestion;
263 Diags.Report(DiagID) << ArgString << Nearest;
265 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
266 DiagnosticsEngine::Warning;
272 // Determine which compilation mode we are in. We look for options which
273 // affect the phase, starting with the earliest phases, and record which
274 // option we used to determine the final phase.
275 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
276 Arg **FinalPhaseArg) const {
277 Arg *PhaseArg = nullptr;
278 phases::ID FinalPhase;
280 // -{E,EP,P,M,MM} only run the preprocessor.
281 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
282 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
283 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
284 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
285 FinalPhase = phases::Preprocess;
287 // --precompile only runs up to precompilation.
288 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
289 FinalPhase = phases::Precompile;
291 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
292 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
293 (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
294 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
295 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
296 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
297 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
298 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
299 (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
300 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
301 FinalPhase = phases::Compile;
303 // -S only runs up to the backend.
304 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
305 FinalPhase = phases::Backend;
307 // -c compilation only runs up to the assembler.
308 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
309 FinalPhase = phases::Assemble;
311 // Otherwise do everything.
313 FinalPhase = phases::Link;
316 *FinalPhaseArg = PhaseArg;
321 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
322 StringRef Value, bool Claim = true) {
323 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
324 Args.getBaseArgs().MakeIndex(Value), Value.data());
325 Args.AddSynthesizedArg(A);
331 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
332 const llvm::opt::OptTable &Opts = getOpts();
333 DerivedArgList *DAL = new DerivedArgList(Args);
335 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
336 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
337 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
338 for (Arg *A : Args) {
339 // Unfortunately, we have to parse some forwarding options (-Xassembler,
340 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
341 // (assembler and preprocessor), or bypass a previous driver ('collect2').
343 // Rewrite linker options, to replace --no-demangle with a custom internal
345 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
346 A->getOption().matches(options::OPT_Xlinker)) &&
347 A->containsValue("--no-demangle")) {
348 // Add the rewritten no-demangle argument.
349 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
351 // Add the remaining values as Xlinker arguments.
352 for (StringRef Val : A->getValues())
353 if (Val != "--no-demangle")
354 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
359 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
360 // some build systems. We don't try to be complete here because we don't
361 // care to encourage this usage model.
362 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
363 (A->getValue(0) == StringRef("-MD") ||
364 A->getValue(0) == StringRef("-MMD"))) {
365 // Rewrite to -MD/-MMD along with -MF.
366 if (A->getValue(0) == StringRef("-MD"))
367 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
369 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
370 if (A->getNumValues() == 2)
371 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
375 // Rewrite reserved library names.
376 if (A->getOption().matches(options::OPT_l)) {
377 StringRef Value = A->getValue();
379 // Rewrite unless -nostdlib is present.
380 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
382 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
386 // Rewrite unconditionally.
387 if (Value == "cc_kext") {
388 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
393 // Pick up inputs via the -- option.
394 if (A->getOption().matches(options::OPT__DASH_DASH)) {
396 for (StringRef Val : A->getValues())
397 DAL->append(MakeInputArg(*DAL, Opts, Val, false));
404 // Enforce -static if -miamcu is present.
405 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
406 DAL->AddFlagArg(0, Opts.getOption(options::OPT_static));
408 // Add a default value of -mlinker-version=, if one was given and the user
409 // didn't specify one.
410 #if defined(HOST_LINK_VERSION)
411 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
412 strlen(HOST_LINK_VERSION) > 0) {
413 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
415 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
422 /// Compute target triple from args.
424 /// This routine provides the logic to compute a target triple from various
425 /// args passed to the driver and the default triple string.
426 static llvm::Triple computeTargetTriple(const Driver &D,
427 StringRef TargetTriple,
429 StringRef DarwinArchName = "") {
430 // FIXME: Already done in Compilation *Driver::BuildCompilation
431 if (const Arg *A = Args.getLastArg(options::OPT_target))
432 TargetTriple = A->getValue();
434 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
436 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
437 // -gnu* only, and we can not change this, so we have to detect that case as
438 // being the Hurd OS.
439 if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
440 TargetTriple.find("-pc-gnu") != StringRef::npos)
441 Target.setOSName("hurd");
443 // Handle Apple-specific options available here.
444 if (Target.isOSBinFormatMachO()) {
445 // If an explicit Darwin arch name is given, that trumps all.
446 if (!DarwinArchName.empty()) {
447 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
451 // Handle the Darwin '-arch' flag.
452 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
453 StringRef ArchName = A->getValue();
454 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
458 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
459 // '-mbig-endian'/'-EB'.
460 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
461 options::OPT_mbig_endian)) {
462 if (A->getOption().matches(options::OPT_mlittle_endian)) {
463 llvm::Triple LE = Target.getLittleEndianArchVariant();
464 if (LE.getArch() != llvm::Triple::UnknownArch)
465 Target = std::move(LE);
467 llvm::Triple BE = Target.getBigEndianArchVariant();
468 if (BE.getArch() != llvm::Triple::UnknownArch)
469 Target = std::move(BE);
473 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
474 if (Target.getArch() == llvm::Triple::tce ||
475 Target.getOS() == llvm::Triple::Minix)
478 // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
479 if (Target.isOSAIX()) {
480 if (Optional<std::string> ObjectModeValue =
481 llvm::sys::Process::GetEnv("OBJECT_MODE")) {
482 StringRef ObjectMode = *ObjectModeValue;
483 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
485 if (ObjectMode.equals("64")) {
486 AT = Target.get64BitArchVariant().getArch();
487 } else if (ObjectMode.equals("32")) {
488 AT = Target.get32BitArchVariant().getArch();
490 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
493 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
498 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
499 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
500 options::OPT_m32, options::OPT_m16);
502 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
504 if (A->getOption().matches(options::OPT_m64)) {
505 AT = Target.get64BitArchVariant().getArch();
506 if (Target.getEnvironment() == llvm::Triple::GNUX32)
507 Target.setEnvironment(llvm::Triple::GNU);
508 } else if (A->getOption().matches(options::OPT_mx32) &&
509 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
510 AT = llvm::Triple::x86_64;
511 Target.setEnvironment(llvm::Triple::GNUX32);
512 } else if (A->getOption().matches(options::OPT_m32)) {
513 AT = Target.get32BitArchVariant().getArch();
514 if (Target.getEnvironment() == llvm::Triple::GNUX32)
515 Target.setEnvironment(llvm::Triple::GNU);
516 } else if (A->getOption().matches(options::OPT_m16) &&
517 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
518 AT = llvm::Triple::x86;
519 Target.setEnvironment(llvm::Triple::CODE16);
522 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
526 // Handle -miamcu flag.
527 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
528 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
529 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
532 if (A && !A->getOption().matches(options::OPT_m32))
533 D.Diag(diag::err_drv_argument_not_allowed_with)
534 << "-miamcu" << A->getBaseArg().getAsString(Args);
536 Target.setArch(llvm::Triple::x86);
537 Target.setArchName("i586");
538 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
539 Target.setEnvironmentName("");
540 Target.setOS(llvm::Triple::ELFIAMCU);
541 Target.setVendor(llvm::Triple::UnknownVendor);
542 Target.setVendorName("intel");
545 // If target is MIPS adjust the target triple
546 // accordingly to provided ABI name.
547 A = Args.getLastArg(options::OPT_mabi_EQ);
548 if (A && Target.isMIPS()) {
549 StringRef ABIName = A->getValue();
550 if (ABIName == "32") {
551 Target = Target.get32BitArchVariant();
552 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
553 Target.getEnvironment() == llvm::Triple::GNUABIN32)
554 Target.setEnvironment(llvm::Triple::GNU);
555 } else if (ABIName == "n32") {
556 Target = Target.get64BitArchVariant();
557 if (Target.getEnvironment() == llvm::Triple::GNU ||
558 Target.getEnvironment() == llvm::Triple::GNUABI64)
559 Target.setEnvironment(llvm::Triple::GNUABIN32);
560 } else if (ABIName == "64") {
561 Target = Target.get64BitArchVariant();
562 if (Target.getEnvironment() == llvm::Triple::GNU ||
563 Target.getEnvironment() == llvm::Triple::GNUABIN32)
564 Target.setEnvironment(llvm::Triple::GNUABI64);
568 // If target is RISC-V adjust the target triple according to
569 // provided architecture name
570 A = Args.getLastArg(options::OPT_march_EQ);
571 if (A && Target.isRISCV()) {
572 StringRef ArchName = A->getValue();
573 if (ArchName.startswith_lower("rv32"))
574 Target.setArch(llvm::Triple::riscv32);
575 else if (ArchName.startswith_lower("rv64"))
576 Target.setArch(llvm::Triple::riscv64);
582 // Parse the LTO options and record the type of LTO compilation
583 // based on which -f(no-)?lto(=.*)? option occurs last.
584 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
586 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
587 options::OPT_fno_lto, false))
590 StringRef LTOName("full");
592 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
594 LTOName = A->getValue();
596 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
597 .Case("full", LTOK_Full)
598 .Case("thin", LTOK_Thin)
599 .Default(LTOK_Unknown);
601 if (LTOMode == LTOK_Unknown) {
603 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
608 /// Compute the desired OpenMP runtime from the flags provided.
609 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
610 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
612 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
614 RuntimeName = A->getValue();
616 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
617 .Case("libomp", OMPRT_OMP)
618 .Case("libgomp", OMPRT_GOMP)
619 .Case("libiomp5", OMPRT_IOMP5)
620 .Default(OMPRT_Unknown);
622 if (RT == OMPRT_Unknown) {
624 Diag(diag::err_drv_unsupported_option_argument)
625 << A->getOption().getName() << A->getValue();
627 // FIXME: We could use a nicer diagnostic here.
628 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
634 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
640 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
641 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
643 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
644 return types::isCuda(I.first);
648 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
649 return types::isHIP(I.first);
651 C.getInputArgs().hasArg(options::OPT_hip_link);
652 if (IsCuda && IsHIP) {
653 Diag(clang::diag::err_drv_mix_cuda_hip);
657 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
658 const llvm::Triple &HostTriple = HostTC->getTriple();
659 StringRef DeviceTripleStr;
660 auto OFK = Action::OFK_Cuda;
662 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
663 llvm::Triple CudaTriple(DeviceTripleStr);
664 // Use the CUDA and host triples as the key into the ToolChains map,
665 // because the device toolchain we create depends on both.
666 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
668 CudaTC = std::make_unique<toolchains::CudaToolChain>(
669 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
671 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
673 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
674 const llvm::Triple &HostTriple = HostTC->getTriple();
675 StringRef DeviceTripleStr;
676 auto OFK = Action::OFK_HIP;
677 DeviceTripleStr = "amdgcn-amd-amdhsa";
678 llvm::Triple HIPTriple(DeviceTripleStr);
679 // Use the HIP and host triples as the key into the ToolChains map,
680 // because the device toolchain we create depends on both.
681 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
683 HIPTC = std::make_unique<toolchains::HIPToolChain>(
684 *this, HIPTriple, *HostTC, C.getInputArgs());
686 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
692 // We need to generate an OpenMP toolchain if the user specified targets with
693 // the -fopenmp-targets option.
694 if (Arg *OpenMPTargets =
695 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
696 if (OpenMPTargets->getNumValues()) {
697 // We expect that -fopenmp-targets is always used in conjunction with the
698 // option -fopenmp specifying a valid runtime with offloading support,
699 // i.e. libomp or libiomp.
700 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
701 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
702 options::OPT_fno_openmp, false);
703 if (HasValidOpenMPRuntime) {
704 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
705 HasValidOpenMPRuntime =
706 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
709 if (HasValidOpenMPRuntime) {
710 llvm::StringMap<const char *> FoundNormalizedTriples;
711 for (const char *Val : OpenMPTargets->getValues()) {
712 llvm::Triple TT(Val);
713 std::string NormalizedName = TT.normalize();
715 // Make sure we don't have a duplicate triple.
716 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
717 if (Duplicate != FoundNormalizedTriples.end()) {
718 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
719 << Val << Duplicate->second;
723 // Store the current triple so that we can check for duplicates in the
724 // following iterations.
725 FoundNormalizedTriples[NormalizedName] = Val;
727 // If the specified target is invalid, emit a diagnostic.
728 if (TT.getArch() == llvm::Triple::UnknownArch)
729 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
732 // CUDA toolchains have to be selected differently. They pair host
733 // and device in their implementation.
735 const ToolChain *HostTC =
736 C.getSingleOffloadToolChain<Action::OFK_Host>();
737 assert(HostTC && "Host toolchain should be always defined.");
739 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
741 CudaTC = std::make_unique<toolchains::CudaToolChain>(
742 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
745 TC = &getToolChain(C.getInputArgs(), TT);
746 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
750 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
752 Diag(clang::diag::warn_drv_empty_joined_argument)
753 << OpenMPTargets->getAsString(C.getInputArgs());
757 // TODO: Add support for other offloading programming models here.
761 /// Looks the given directories for the specified file.
763 /// \param[out] FilePath File path, if the file was found.
764 /// \param[in] Dirs Directories used for the search.
765 /// \param[in] FileName Name of the file to search for.
766 /// \return True if file was found.
768 /// Looks for file specified by FileName sequentially in directories specified
771 static bool searchForFile(SmallVectorImpl<char> &FilePath,
772 ArrayRef<std::string> Dirs,
773 StringRef FileName) {
774 SmallString<128> WPath;
775 for (const std::string &Dir : Dirs) {
779 llvm::sys::path::append(WPath, Dir, FileName);
780 llvm::sys::path::native(WPath);
781 if (llvm::sys::fs::is_regular_file(WPath)) {
782 FilePath = std::move(WPath);
789 bool Driver::readConfigFile(StringRef FileName) {
790 // Try reading the given file.
791 SmallVector<const char *, 32> NewCfgArgs;
792 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
793 Diag(diag::err_drv_cannot_read_config_file) << FileName;
797 // Read options from config file.
798 llvm::SmallString<128> CfgFileName(FileName);
799 llvm::sys::path::native(CfgFileName);
800 ConfigFile = std::string(CfgFileName.str());
802 CfgOptions = std::make_unique<InputArgList>(
803 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
809 if (CfgOptions->hasArg(options::OPT_config)) {
811 Diag(diag::err_drv_nested_config_file);
815 // Claim all arguments that come from a configuration file so that the driver
816 // does not warn on any that is unused.
817 for (Arg *A : *CfgOptions)
822 bool Driver::loadConfigFile() {
823 std::string CfgFileName;
824 bool FileSpecifiedExplicitly = false;
826 // Process options that change search path for config files.
828 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
829 SmallString<128> CfgDir;
831 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
832 if (!CfgDir.empty()) {
833 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
834 SystemConfigDir.clear();
836 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
839 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
840 SmallString<128> CfgDir;
842 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
843 if (!CfgDir.empty()) {
844 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
845 UserConfigDir.clear();
847 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
852 // First try to find config file specified in command line.
854 std::vector<std::string> ConfigFiles =
855 CLOptions->getAllArgValues(options::OPT_config);
856 if (ConfigFiles.size() > 1) {
858 ConfigFiles.begin(), ConfigFiles.end(),
859 [ConfigFiles](std::string s) { return s == ConfigFiles[0]; })) {
860 Diag(diag::err_drv_duplicate_config);
865 if (!ConfigFiles.empty()) {
866 CfgFileName = ConfigFiles.front();
867 assert(!CfgFileName.empty());
869 // If argument contains directory separator, treat it as a path to
870 // configuration file.
871 if (llvm::sys::path::has_parent_path(CfgFileName)) {
872 SmallString<128> CfgFilePath;
873 if (llvm::sys::path::is_relative(CfgFileName))
874 llvm::sys::fs::current_path(CfgFilePath);
875 llvm::sys::path::append(CfgFilePath, CfgFileName);
876 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
877 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
880 return readConfigFile(CfgFilePath);
883 FileSpecifiedExplicitly = true;
887 // If config file is not specified explicitly, try to deduce configuration
888 // from executable name. For instance, an executable 'armv7l-clang' will
889 // search for config file 'armv7l-clang.cfg'.
890 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
891 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
893 if (CfgFileName.empty())
896 // Determine architecture part of the file name, if it is present.
897 StringRef CfgFileArch = CfgFileName;
898 size_t ArchPrefixLen = CfgFileArch.find('-');
899 if (ArchPrefixLen == StringRef::npos)
900 ArchPrefixLen = CfgFileArch.size();
901 llvm::Triple CfgTriple;
902 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
903 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
904 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
907 if (!StringRef(CfgFileName).endswith(".cfg"))
908 CfgFileName += ".cfg";
910 // If config file starts with architecture name and command line options
911 // redefine architecture (with options like -m32 -LE etc), try finding new
912 // config file with that architecture.
913 SmallString<128> FixedConfigFile;
914 size_t FixedArchPrefixLen = 0;
916 // Get architecture name from config file name like 'i386.cfg' or
917 // 'armv7l-clang.cfg'.
918 // Check if command line options changes effective triple.
919 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
920 CfgTriple.getTriple(), *CLOptions);
921 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
922 FixedConfigFile = EffectiveTriple.getArchName();
923 FixedArchPrefixLen = FixedConfigFile.size();
924 // Append the rest of original file name so that file name transforms
925 // like: i386-clang.cfg -> x86_64-clang.cfg.
926 if (ArchPrefixLen < CfgFileName.size())
927 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
931 // Prepare list of directories where config file is searched for.
932 SmallVector<std::string, 3> CfgFileSearchDirs;
933 CfgFileSearchDirs.push_back(UserConfigDir);
934 CfgFileSearchDirs.push_back(SystemConfigDir);
935 CfgFileSearchDirs.push_back(Dir);
937 // Try to find config file. First try file with corrected architecture.
938 llvm::SmallString<128> CfgFilePath;
939 if (!FixedConfigFile.empty()) {
940 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
941 return readConfigFile(CfgFilePath);
942 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
943 FixedConfigFile.resize(FixedArchPrefixLen);
944 FixedConfigFile.append(".cfg");
945 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
946 return readConfigFile(CfgFilePath);
949 // Then try original file name.
950 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
951 return readConfigFile(CfgFilePath);
953 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
954 if (!ClangNameParts.ModeSuffix.empty() &&
955 !ClangNameParts.TargetPrefix.empty()) {
956 CfgFileName.assign(ClangNameParts.TargetPrefix);
957 CfgFileName.append(".cfg");
958 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
959 return readConfigFile(CfgFilePath);
962 // Report error but only if config file was specified explicitly, by option
963 // --config. If it was deduced from executable name, it is not an error.
964 if (FileSpecifiedExplicitly) {
965 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
966 for (const std::string &SearchDir : CfgFileSearchDirs)
967 if (!SearchDir.empty())
968 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
975 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
976 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
978 // FIXME: Handle environment options which affect driver behavior, somewhere
979 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
981 if (Optional<std::string> CompilerPathValue =
982 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
983 StringRef CompilerPath = *CompilerPathValue;
984 while (!CompilerPath.empty()) {
985 std::pair<StringRef, StringRef> Split =
986 CompilerPath.split(llvm::sys::EnvPathSeparator);
987 PrefixDirs.push_back(std::string(Split.first));
988 CompilerPath = Split.second;
992 // We look for the driver mode option early, because the mode can affect
993 // how other options are parsed.
994 ParseDriverMode(ClangExecutable, ArgList.slice(1));
996 // FIXME: What are we going to do with -V and -b?
998 // Arguments specified in command line.
1000 CLOptions = std::make_unique<InputArgList>(
1001 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
1003 // Try parsing configuration file.
1005 ContainsError = loadConfigFile();
1006 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
1008 // All arguments, from both config file and command line.
1009 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
1010 : std::move(*CLOptions));
1012 // The args for config files or /clang: flags belong to different InputArgList
1013 // objects than Args. This copies an Arg from one of those other InputArgLists
1014 // to the ownership of Args.
1015 auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
1016 unsigned Index = Args.MakeIndex(Opt->getSpelling());
1017 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
1019 Copy->getValues() = Opt->getValues();
1020 if (Opt->isClaimed())
1026 for (auto *Opt : *CLOptions) {
1027 if (Opt->getOption().matches(options::OPT_config))
1029 const Arg *BaseArg = &Opt->getBaseArg();
1032 appendOneArg(Opt, BaseArg);
1035 // In CL mode, look for any pass-through arguments
1036 if (IsCLMode() && !ContainsError) {
1037 SmallVector<const char *, 16> CLModePassThroughArgList;
1038 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1040 CLModePassThroughArgList.push_back(A->getValue());
1043 if (!CLModePassThroughArgList.empty()) {
1044 // Parse any pass through args using default clang processing rather
1045 // than clang-cl processing.
1046 auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1047 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1050 for (auto *Opt : *CLModePassThroughOptions) {
1051 appendOneArg(Opt, nullptr);
1056 // Check for working directory option before accessing any files
1057 if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1058 if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1059 Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1061 // FIXME: This stuff needs to go into the Compilation, not the driver.
1062 bool CCCPrintPhases;
1064 // Silence driver warnings if requested
1065 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1067 // -no-canonical-prefixes is used very early in main.
1068 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1070 // f(no-)integated-cc1 is also used very early in main.
1071 Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1072 Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1075 Args.ClaimAllArgs(options::OPT_pipe);
1077 // Extract -ccc args.
1079 // FIXME: We need to figure out where this behavior should live. Most of it
1080 // should be outside in the client; the parts that aren't should have proper
1081 // options, either by introducing new ones or by overloading gcc ones like -V
1083 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1084 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1085 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1086 CCCGenericGCCName = A->getValue();
1087 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1088 options::OPT_fno_crash_diagnostics,
1089 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
1090 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1091 // and getToolChain is const.
1093 // clang-cl targets MSVC-style Win32.
1094 llvm::Triple T(TargetTriple);
1095 T.setOS(llvm::Triple::Win32);
1096 T.setVendor(llvm::Triple::PC);
1097 T.setEnvironment(llvm::Triple::MSVC);
1098 T.setObjectFormat(llvm::Triple::COFF);
1099 TargetTriple = T.str();
1101 if (const Arg *A = Args.getLastArg(options::OPT_target))
1102 TargetTriple = A->getValue();
1103 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1104 Dir = InstalledDir = A->getValue();
1105 for (const Arg *A : Args.filtered(options::OPT_B)) {
1107 PrefixDirs.push_back(A->getValue(0));
1109 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1110 SysRoot = A->getValue();
1111 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1112 DyldPrefix = A->getValue();
1114 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1115 ResourceDir = A->getValue();
1117 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1118 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1119 .Case("cwd", SaveTempsCwd)
1120 .Case("obj", SaveTempsObj)
1121 .Default(SaveTempsCwd);
1126 // Process -fembed-bitcode= flags.
1127 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1128 StringRef Name = A->getValue();
1129 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1130 .Case("off", EmbedNone)
1131 .Case("all", EmbedBitcode)
1132 .Case("bitcode", EmbedBitcode)
1133 .Case("marker", EmbedMarker)
1136 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1139 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1142 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1143 std::make_unique<InputArgList>(std::move(Args));
1145 // Perform the default argument translations.
1146 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1148 // Owned by the host.
1149 const ToolChain &TC = getToolChain(
1150 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1152 // The compilation takes ownership of Args.
1153 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1156 if (!HandleImmediateArgs(*C))
1159 // Construct the list of inputs.
1161 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1163 // Populate the tool chains for the offloading devices, if any.
1164 CreateOffloadingDeviceToolChains(*C, Inputs);
1166 // Construct the list of abstract actions to perform for this compilation. On
1167 // MachO targets this uses the driver-driver and universal actions.
1168 if (TC.getTriple().isOSBinFormatMachO())
1169 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1171 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1173 if (CCCPrintPhases) {
1183 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1184 llvm::opt::ArgStringList ASL;
1185 for (const auto *A : Args)
1186 A->render(Args, ASL);
1188 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1189 if (I != ASL.begin())
1191 llvm::sys::printArg(OS, *I, true);
1196 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1197 SmallString<128> &CrashDiagDir) {
1198 using namespace llvm::sys;
1199 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1200 "Only knows about .crash files on Darwin");
1202 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1203 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1204 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1205 path::home_directory(CrashDiagDir);
1206 if (CrashDiagDir.startswith("/var/root"))
1208 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1216 fs::file_status FileStatus;
1217 TimePoint<> LastAccessTime;
1218 SmallString<128> CrashFilePath;
1219 // Lookup the .crash files and get the one generated by a subprocess spawned
1220 // by this driver invocation.
1221 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1222 File != FileEnd && !EC; File.increment(EC)) {
1223 StringRef FileName = path::filename(File->path());
1224 if (!FileName.startswith(Name))
1226 if (fs::status(File->path(), FileStatus))
1228 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1229 llvm::MemoryBuffer::getFile(File->path());
1232 // The first line should start with "Process:", otherwise this isn't a real
1234 StringRef Data = CrashFile.get()->getBuffer();
1235 if (!Data.startswith("Process:"))
1237 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1238 size_t ParentProcPos = Data.find("Parent Process:");
1239 if (ParentProcPos == StringRef::npos)
1241 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1242 if (LineEnd == StringRef::npos)
1244 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1245 int OpenBracket = -1, CloseBracket = -1;
1246 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1247 if (ParentProcess[i] == '[')
1249 if (ParentProcess[i] == ']')
1252 // Extract the parent process PID from the .crash file and check whether
1253 // it matches this driver invocation pid.
1255 if (OpenBracket < 0 || CloseBracket < 0 ||
1256 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1257 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1261 // Found a .crash file matching the driver pid. To avoid getting an older
1262 // and misleading crash file, continue looking for the most recent.
1263 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1264 // multiple crashes poiting to the same parent process. Since the driver
1265 // does not collect pid information for the dispatched invocation there's
1266 // currently no way to distinguish among them.
1267 const auto FileAccessTime = FileStatus.getLastModificationTime();
1268 if (FileAccessTime > LastAccessTime) {
1269 CrashFilePath.assign(File->path());
1270 LastAccessTime = FileAccessTime;
1274 // If found, copy it over to the location of other reproducer files.
1275 if (!CrashFilePath.empty()) {
1276 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1285 // When clang crashes, produce diagnostic information including the fully
1286 // preprocessed source file(s). Request that the developer attach the
1287 // diagnostic information to a bug report.
1288 void Driver::generateCompilationDiagnostics(
1289 Compilation &C, const Command &FailingCommand,
1290 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1291 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1294 // Don't try to generate diagnostics for link or dsymutil jobs.
1295 if (FailingCommand.getCreator().isLinkJob() ||
1296 FailingCommand.getCreator().isDsymutilJob())
1299 // Print the version of the compiler.
1300 PrintVersion(C, llvm::errs());
1302 // Suppress driver output and emit preprocessor output to temp file.
1304 CCGenDiagnostics = true;
1306 // Save the original job command(s).
1307 Command Cmd = FailingCommand;
1309 // Keep track of whether we produce any errors while trying to produce
1310 // preprocessed sources.
1311 DiagnosticErrorTrap Trap(Diags);
1313 // Suppress tool output.
1314 C.initCompilationForDiagnostics();
1316 // Construct the list of inputs.
1318 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1320 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1321 bool IgnoreInput = false;
1323 // Ignore input from stdin or any inputs that cannot be preprocessed.
1324 // Check type first as not all linker inputs have a value.
1325 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1327 } else if (!strcmp(it->second->getValue(), "-")) {
1328 Diag(clang::diag::note_drv_command_failed_diag_msg)
1329 << "Error generating preprocessed source(s) - "
1330 "ignoring input from stdin.";
1335 it = Inputs.erase(it);
1342 if (Inputs.empty()) {
1343 Diag(clang::diag::note_drv_command_failed_diag_msg)
1344 << "Error generating preprocessed source(s) - "
1345 "no preprocessable inputs.";
1349 // Don't attempt to generate preprocessed files if multiple -arch options are
1350 // used, unless they're all duplicates.
1351 llvm::StringSet<> ArchNames;
1352 for (const Arg *A : C.getArgs()) {
1353 if (A->getOption().matches(options::OPT_arch)) {
1354 StringRef ArchName = A->getValue();
1355 ArchNames.insert(ArchName);
1358 if (ArchNames.size() > 1) {
1359 Diag(clang::diag::note_drv_command_failed_diag_msg)
1360 << "Error generating preprocessed source(s) - cannot generate "
1361 "preprocessed source with multiple -arch options.";
1365 // Construct the list of abstract actions to perform for this compilation. On
1366 // Darwin OSes this uses the driver-driver and builds universal actions.
1367 const ToolChain &TC = C.getDefaultToolChain();
1368 if (TC.getTriple().isOSBinFormatMachO())
1369 BuildUniversalActions(C, TC, Inputs);
1371 BuildActions(C, C.getArgs(), Inputs, C.getActions());
1375 // If there were errors building the compilation, quit now.
1376 if (Trap.hasErrorOccurred()) {
1377 Diag(clang::diag::note_drv_command_failed_diag_msg)
1378 << "Error generating preprocessed source(s).";
1382 // Generate preprocessed output.
1383 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1384 C.ExecuteJobs(C.getJobs(), FailingCommands);
1386 // If any of the preprocessing commands failed, clean up and exit.
1387 if (!FailingCommands.empty()) {
1388 Diag(clang::diag::note_drv_command_failed_diag_msg)
1389 << "Error generating preprocessed source(s).";
1393 const ArgStringList &TempFiles = C.getTempFiles();
1394 if (TempFiles.empty()) {
1395 Diag(clang::diag::note_drv_command_failed_diag_msg)
1396 << "Error generating preprocessed source(s).";
1400 Diag(clang::diag::note_drv_command_failed_diag_msg)
1401 << "\n********************\n\n"
1402 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1403 "Preprocessed source(s) and associated run script(s) are located at:";
1405 SmallString<128> VFS;
1406 SmallString<128> ReproCrashFilename;
1407 for (const char *TempFile : TempFiles) {
1408 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1410 Report->TemporaryFiles.push_back(TempFile);
1411 if (ReproCrashFilename.empty()) {
1412 ReproCrashFilename = TempFile;
1413 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1415 if (StringRef(TempFile).endswith(".cache")) {
1416 // In some cases (modules) we'll dump extra data to help with reproducing
1417 // the crash into a directory next to the output.
1418 VFS = llvm::sys::path::filename(TempFile);
1419 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1423 // Assume associated files are based off of the first temporary file.
1424 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1426 llvm::SmallString<128> Script(CrashInfo.Filename);
1427 llvm::sys::path::replace_extension(Script, "sh");
1429 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
1431 Diag(clang::diag::note_drv_command_failed_diag_msg)
1432 << "Error generating run script: " << Script << " " << EC.message();
1434 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1435 << "# Driver args: ";
1436 printArgList(ScriptOS, C.getInputArgs());
1437 ScriptOS << "# Original command: ";
1438 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1439 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1440 if (!AdditionalInformation.empty())
1441 ScriptOS << "\n# Additional information: " << AdditionalInformation
1444 Report->TemporaryFiles.push_back(std::string(Script.str()));
1445 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1448 // On darwin, provide information about the .crash diagnostic report.
1449 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1450 SmallString<128> CrashDiagDir;
1451 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1452 Diag(clang::diag::note_drv_command_failed_diag_msg)
1453 << ReproCrashFilename.str();
1454 } else { // Suggest a directory for the user to look for .crash files.
1455 llvm::sys::path::append(CrashDiagDir, Name);
1456 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1457 Diag(clang::diag::note_drv_command_failed_diag_msg)
1458 << "Crash backtrace is located in";
1459 Diag(clang::diag::note_drv_command_failed_diag_msg)
1460 << CrashDiagDir.str();
1461 Diag(clang::diag::note_drv_command_failed_diag_msg)
1462 << "(choose the .crash file that corresponds to your crash)";
1466 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1467 options::OPT_frewrite_map_file_EQ))
1468 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1470 Diag(clang::diag::note_drv_command_failed_diag_msg)
1471 << "\n\n********************";
1474 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1475 // Since commandLineFitsWithinSystemLimits() may underestimate system's
1476 // capacity if the tool does not support response files, there is a chance/
1477 // that things will just work without a response file, so we silently just
1479 if (Cmd.getResponseFileSupport().ResponseKind ==
1480 ResponseFileSupport::RF_None ||
1481 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1482 Cmd.getArguments()))
1485 std::string TmpName = GetTemporaryPath("response", "txt");
1486 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1489 int Driver::ExecuteCompilation(
1491 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1492 // Just print if -### was present.
1493 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1494 C.getJobs().Print(llvm::errs(), "\n", true);
1498 // If there were errors building the compilation, quit now.
1499 if (Diags.hasErrorOccurred())
1502 // Set up response file names for each command, if necessary
1503 for (auto &Job : C.getJobs())
1504 setUpResponseFiles(C, Job);
1506 C.ExecuteJobs(C.getJobs(), FailingCommands);
1508 // If the command succeeded, we are done.
1509 if (FailingCommands.empty())
1512 // Otherwise, remove result files and print extra information about abnormal
1515 for (const auto &CmdPair : FailingCommands) {
1516 int CommandRes = CmdPair.first;
1517 const Command *FailingCommand = CmdPair.second;
1519 // Remove result files if we're not saving temps.
1520 if (!isSaveTempsEnabled()) {
1521 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1522 C.CleanupFileMap(C.getResultFiles(), JA, true);
1524 // Failure result files are valid unless we crashed.
1526 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1530 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1531 // for SIGPIPE. Do not print diagnostics for this case.
1532 if (CommandRes == EX_IOERR) {
1538 // Print extra information about abnormal failures, if possible.
1540 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1541 // status was 1, assume the command failed normally. In particular, if it
1542 // was the compiler then assume it gave a reasonable error code. Failures
1543 // in other tools are less common, and they generally have worse
1544 // diagnostics, so always print the diagnostic there.
1545 const Tool &FailingTool = FailingCommand->getCreator();
1547 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1548 // FIXME: See FIXME above regarding result code interpretation.
1550 Diag(clang::diag::err_drv_command_signalled)
1551 << FailingTool.getShortName();
1553 Diag(clang::diag::err_drv_command_failed)
1554 << FailingTool.getShortName() << CommandRes;
1560 void Driver::PrintHelp(bool ShowHidden) const {
1561 unsigned IncludedFlagsBitmask;
1562 unsigned ExcludedFlagsBitmask;
1563 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1564 getIncludeExcludeOptionFlagMasks(IsCLMode());
1566 ExcludedFlagsBitmask |= options::NoDriverOption;
1568 ExcludedFlagsBitmask |= HelpHidden;
1570 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1571 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1572 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1573 /*ShowAllAliases=*/false);
1576 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1577 // FIXME: The following handlers should use a callback mechanism, we don't
1578 // know what the client would like to do.
1579 OS << getClangFullVersion() << '\n';
1580 const ToolChain &TC = C.getDefaultToolChain();
1581 OS << "Target: " << TC.getTripleString() << '\n';
1583 // Print the threading model.
1584 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1585 // Don't print if the ToolChain would have barfed on it already
1586 if (TC.isThreadModelSupported(A->getValue()))
1587 OS << "Thread model: " << A->getValue();
1589 OS << "Thread model: " << TC.getThreadModel();
1592 // Print out the install directory.
1593 OS << "InstalledDir: " << InstalledDir << '\n';
1595 // If configuration file was used, print its path.
1596 if (!ConfigFile.empty())
1597 OS << "Configuration file: " << ConfigFile << '\n';
1600 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1602 static void PrintDiagnosticCategories(raw_ostream &OS) {
1603 // Skip the empty category.
1604 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1606 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1609 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1610 if (PassedFlags == "")
1612 // Print out all options that start with a given argument. This is used for
1613 // shell autocompletion.
1614 std::vector<std::string> SuggestedCompletions;
1615 std::vector<std::string> Flags;
1617 unsigned short DisableFlags =
1618 options::NoDriverOption | options::Unsupported | options::Ignored;
1620 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1621 // because the latter indicates that the user put space before pushing tab
1622 // which should end up in a file completion.
1623 const bool HasSpace = PassedFlags.endswith(",");
1625 // Parse PassedFlags by "," as all the command-line flags are passed to this
1626 // function separated by ","
1627 StringRef TargetFlags = PassedFlags;
1628 while (TargetFlags != "") {
1630 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1631 Flags.push_back(std::string(CurFlag));
1634 // We want to show cc1-only options only when clang is invoked with -cc1 or
1636 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1637 DisableFlags &= ~options::NoDriverOption;
1639 const llvm::opt::OptTable &Opts = getOpts();
1641 Cur = Flags.at(Flags.size() - 1);
1643 if (Flags.size() >= 2) {
1644 Prev = Flags.at(Flags.size() - 2);
1645 SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1648 if (SuggestedCompletions.empty())
1649 SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1651 // If Flags were empty, it means the user typed `clang [tab]` where we should
1652 // list all possible flags. If there was no value completion and the user
1653 // pressed tab after a space, we should fall back to a file completion.
1654 // We're printing a newline to be consistent with what we print at the end of
1656 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1657 llvm::outs() << '\n';
1661 // When flag ends with '=' and there was no value completion, return empty
1662 // string and fall back to the file autocompletion.
1663 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1664 // If the flag is in the form of "--autocomplete=-foo",
1665 // we were requested to print out all option names that start with "-foo".
1666 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1667 SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1669 // We have to query the -W flags manually as they're not in the OptTable.
1670 // TODO: Find a good way to add them to OptTable instead and them remove
1672 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1673 if (S.startswith(Cur))
1674 SuggestedCompletions.push_back(std::string(S));
1677 // Sort the autocomplete candidates so that shells print them out in a
1678 // deterministic order. We could sort in any way, but we chose
1679 // case-insensitive sorting for consistency with the -help option
1680 // which prints out options in the case-insensitive alphabetical order.
1681 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1682 if (int X = A.compare_lower(B))
1684 return A.compare(B) > 0;
1687 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1690 bool Driver::HandleImmediateArgs(const Compilation &C) {
1691 // The order these options are handled in gcc is all over the place, but we
1692 // don't expect inconsistencies w.r.t. that to matter in practice.
1694 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1695 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1699 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1700 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1701 // return an answer which matches our definition of __VERSION__.
1702 llvm::outs() << CLANG_VERSION_STRING << "\n";
1706 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1707 PrintDiagnosticCategories(llvm::outs());
1711 if (C.getArgs().hasArg(options::OPT_help) ||
1712 C.getArgs().hasArg(options::OPT__help_hidden)) {
1713 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1717 if (C.getArgs().hasArg(options::OPT__version)) {
1718 // Follow gcc behavior and use stdout for --version and stderr for -v.
1719 PrintVersion(C, llvm::outs());
1723 if (C.getArgs().hasArg(options::OPT_v) ||
1724 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
1725 C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
1726 PrintVersion(C, llvm::errs());
1727 SuppressMissingInputWarning = true;
1730 if (C.getArgs().hasArg(options::OPT_v)) {
1731 if (!SystemConfigDir.empty())
1732 llvm::errs() << "System configuration file directory: "
1733 << SystemConfigDir << "\n";
1734 if (!UserConfigDir.empty())
1735 llvm::errs() << "User configuration file directory: "
1736 << UserConfigDir << "\n";
1739 const ToolChain &TC = C.getDefaultToolChain();
1741 if (C.getArgs().hasArg(options::OPT_v))
1742 TC.printVerboseInfo(llvm::errs());
1744 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1745 llvm::outs() << ResourceDir << '\n';
1749 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1750 llvm::outs() << "programs: =";
1751 bool separator = false;
1752 for (const std::string &Path : TC.getProgramPaths()) {
1754 llvm::outs() << llvm::sys::EnvPathSeparator;
1755 llvm::outs() << Path;
1758 llvm::outs() << "\n";
1759 llvm::outs() << "libraries: =" << ResourceDir;
1761 StringRef sysroot = C.getSysRoot();
1763 for (const std::string &Path : TC.getFilePaths()) {
1764 // Always print a separator. ResourceDir was the first item shown.
1765 llvm::outs() << llvm::sys::EnvPathSeparator;
1766 // Interpretation of leading '=' is needed only for NetBSD.
1768 llvm::outs() << sysroot << Path.substr(1);
1770 llvm::outs() << Path;
1772 llvm::outs() << "\n";
1776 // FIXME: The following handlers should use a callback mechanism, we don't
1777 // know what the client would like to do.
1778 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1779 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1783 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1784 StringRef ProgName = A->getValue();
1786 // Null program name cannot have a path.
1787 if (! ProgName.empty())
1788 llvm::outs() << GetProgramPath(ProgName, TC);
1790 llvm::outs() << "\n";
1794 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1795 StringRef PassedFlags = A->getValue();
1796 HandleAutocompletions(PassedFlags);
1800 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1801 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1802 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1803 RegisterEffectiveTriple TripleRAII(TC, Triple);
1805 case ToolChain::RLT_CompilerRT:
1806 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1808 case ToolChain::RLT_Libgcc:
1809 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1815 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1816 for (const Multilib &Multilib : TC.getMultilibs())
1817 llvm::outs() << Multilib << "\n";
1821 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1822 const Multilib &Multilib = TC.getMultilib();
1823 if (Multilib.gccSuffix().empty())
1824 llvm::outs() << ".\n";
1826 StringRef Suffix(Multilib.gccSuffix());
1827 assert(Suffix.front() == '/');
1828 llvm::outs() << Suffix.substr(1) << "\n";
1833 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1834 llvm::outs() << TC.getTripleString() << "\n";
1838 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1839 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1840 llvm::outs() << Triple.getTriple() << "\n";
1844 if (C.getArgs().hasArg(options::OPT_print_targets)) {
1845 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
1858 // Display an action graph human-readably. Action A is the "sink" node
1859 // and latest-occuring action. Traversal is in pre-order, visiting the
1860 // inputs to each action before printing the action itself.
1861 static unsigned PrintActions1(const Compilation &C, Action *A,
1862 std::map<Action *, unsigned> &Ids,
1863 Twine Indent = {}, int Kind = TopLevelAction) {
1864 if (Ids.count(A)) // A was already visited.
1868 llvm::raw_string_ostream os(str);
1870 auto getSibIndent = [](int K) -> Twine {
1871 return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "";
1874 Twine SibIndent = Indent + getSibIndent(Kind);
1875 int SibKind = HeadSibAction;
1876 os << Action::getClassName(A->getKind()) << ", ";
1877 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1878 os << "\"" << IA->getInputArg().getValue() << "\"";
1879 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1880 os << '"' << BIA->getArchName() << '"' << ", {"
1881 << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
1882 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1883 bool IsFirst = true;
1884 OA->doOnEachDependence(
1885 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1886 assert(TC && "Unknown host toolchain");
1887 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1888 // sm_35 this will generate:
1889 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1890 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1894 os << A->getOffloadingKindPrefix();
1896 os << TC->getTriple().normalize();
1898 os << ":" << BoundArch;
1901 os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
1903 SibKind = OtherSibAction;
1906 const ActionList *AL = &A->getInputs();
1909 const char *Prefix = "{";
1910 for (Action *PreRequisite : *AL) {
1911 os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
1913 SibKind = OtherSibAction;
1920 // Append offload info for all options other than the offloading action
1921 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1922 std::string offload_str;
1923 llvm::raw_string_ostream offload_os(offload_str);
1924 if (!isa<OffloadAction>(A)) {
1925 auto S = A->getOffloadingKindPrefix();
1927 offload_os << ", (" << S;
1928 if (A->getOffloadingArch())
1929 offload_os << ", " << A->getOffloadingArch();
1934 auto getSelfIndent = [](int K) -> Twine {
1935 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
1938 unsigned Id = Ids.size();
1940 llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
1941 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1946 // Print the action graphs in a compilation C.
1947 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1948 void Driver::PrintActions(const Compilation &C) const {
1949 std::map<Action *, unsigned> Ids;
1950 for (Action *A : C.getActions())
1951 PrintActions1(C, A, Ids);
1954 /// Check whether the given input tree contains any compilation or
1955 /// assembly actions.
1956 static bool ContainsCompileOrAssembleAction(const Action *A) {
1957 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1958 isa<AssembleJobAction>(A))
1961 for (const Action *Input : A->inputs())
1962 if (ContainsCompileOrAssembleAction(Input))
1968 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1969 const InputList &BAInputs) const {
1970 DerivedArgList &Args = C.getArgs();
1971 ActionList &Actions = C.getActions();
1972 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1973 // Collect the list of architectures. Duplicates are allowed, but should only
1974 // be handled once (in the order seen).
1975 llvm::StringSet<> ArchNames;
1976 SmallVector<const char *, 4> Archs;
1977 for (Arg *A : Args) {
1978 if (A->getOption().matches(options::OPT_arch)) {
1979 // Validate the option here; we don't save the type here because its
1980 // particular spelling may participate in other driver choices.
1981 llvm::Triple::ArchType Arch =
1982 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1983 if (Arch == llvm::Triple::UnknownArch) {
1984 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1989 if (ArchNames.insert(A->getValue()).second)
1990 Archs.push_back(A->getValue());
1994 // When there is no explicit arch for this platform, make sure we still bind
1995 // the architecture (to the default) so that -Xarch_ is handled correctly.
1997 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1999 ActionList SingleActions;
2000 BuildActions(C, Args, BAInputs, SingleActions);
2002 // Add in arch bindings for every top level action, as well as lipo and
2003 // dsymutil steps if needed.
2004 for (Action* Act : SingleActions) {
2005 // Make sure we can lipo this kind of output. If not (and it is an actual
2006 // output) then we disallow, since we can't create an output file with the
2007 // right name without overwriting it. We could remove this oddity by just
2008 // changing the output names to include the arch, which would also fix
2009 // -save-temps. Compatibility wins for now.
2011 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
2012 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
2013 << types::getTypeName(Act->getType());
2016 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
2017 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
2019 // Lipo if necessary, we do it this way because we need to set the arch flag
2020 // so that -Xarch_ gets overwritten.
2021 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2022 Actions.append(Inputs.begin(), Inputs.end());
2024 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2026 // Handle debug info queries.
2027 Arg *A = Args.getLastArg(options::OPT_g_Group);
2028 bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2029 !A->getOption().matches(options::OPT_gstabs);
2030 if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2031 ContainsCompileOrAssembleAction(Actions.back())) {
2033 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2034 // have a compile input. We need to run 'dsymutil' ourselves in such cases
2035 // because the debug info will refer to a temporary object file which
2036 // will be removed at the end of the compilation process.
2037 if (Act->getType() == types::TY_Image) {
2039 Inputs.push_back(Actions.back());
2042 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2045 // Verify the debug info output.
2046 if (Args.hasArg(options::OPT_verify_debug_info)) {
2047 Action* LastAction = Actions.back();
2049 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2050 LastAction, types::TY_Nothing));
2056 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2057 types::ID Ty, bool TypoCorrect) const {
2058 if (!getCheckInputsExist())
2061 // stdin always exists.
2065 if (getVFS().exists(Value))
2069 if (!llvm::sys::path::is_absolute(Twine(Value)) &&
2070 llvm::sys::Process::FindInEnvPath("LIB", Value))
2073 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2074 // Arguments to the /link flag might cause the linker to search for object
2075 // and library files in paths we don't know about. Don't error in such
2082 // Check if the filename is a typo for an option flag. OptTable thinks
2083 // that all args that are not known options and that start with / are
2084 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2085 // the option `/diagnostics:caret` than a reference to a file in the root
2087 unsigned IncludedFlagsBitmask;
2088 unsigned ExcludedFlagsBitmask;
2089 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2090 getIncludeExcludeOptionFlagMasks(IsCLMode());
2091 std::string Nearest;
2092 if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2093 ExcludedFlagsBitmask) <= 1) {
2094 Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2095 << Value << Nearest;
2100 Diag(clang::diag::err_drv_no_such_file) << Value;
2104 // Construct a the list of inputs and their types.
2105 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2106 InputList &Inputs) const {
2107 const llvm::opt::OptTable &Opts = getOpts();
2108 // Track the current user specified (-x) input. We also explicitly track the
2109 // argument used to set the type; we only want to claim the type when we
2110 // actually use it, so we warn about unused -x arguments.
2111 types::ID InputType = types::TY_Nothing;
2112 Arg *InputTypeArg = nullptr;
2114 // The last /TC or /TP option sets the input type to C or C++ globally.
2115 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2116 options::OPT__SLASH_TP)) {
2117 InputTypeArg = TCTP;
2118 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2122 Arg *Previous = nullptr;
2123 bool ShowNote = false;
2125 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2127 Diag(clang::diag::warn_drv_overriding_flag_option)
2128 << Previous->getSpelling() << A->getSpelling();
2134 Diag(clang::diag::note_drv_t_option_is_global);
2136 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2137 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2140 for (Arg *A : Args) {
2141 if (A->getOption().getKind() == Option::InputClass) {
2142 const char *Value = A->getValue();
2143 types::ID Ty = types::TY_INVALID;
2145 // Infer the input type if necessary.
2146 if (InputType == types::TY_Nothing) {
2147 // If there was an explicit arg for this, claim it.
2149 InputTypeArg->claim();
2151 // stdin must be handled specially.
2152 if (memcmp(Value, "-", 2) == 0) {
2153 // If running with -E, treat as a C input (this changes the builtin
2154 // macros, for example). This may be overridden by -ObjC below.
2156 // Otherwise emit an error but still use a valid type to avoid
2157 // spurious errors (e.g., no inputs).
2158 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2159 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2160 : clang::diag::err_drv_unknown_stdin_type);
2163 // Otherwise lookup by extension.
2164 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2165 // clang-cl /E, or Object otherwise.
2166 // We use a host hook here because Darwin at least has its own
2167 // idea of what .s is.
2168 if (const char *Ext = strrchr(Value, '.'))
2169 Ty = TC.LookupTypeForExtension(Ext + 1);
2171 if (Ty == types::TY_INVALID) {
2174 else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2177 Ty = types::TY_Object;
2180 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2181 // should autodetect some input files as C++ for g++ compatibility.
2183 types::ID OldTy = Ty;
2184 Ty = types::lookupCXXTypeForCType(Ty);
2187 Diag(clang::diag::warn_drv_treating_input_as_cxx)
2188 << getTypeName(OldTy) << getTypeName(Ty);
2191 // If running with -fthinlto-index=, extensions that normally identify
2192 // native object files actually identify LLVM bitcode files.
2193 if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2194 Ty == types::TY_Object)
2195 Ty = types::TY_LLVM_BC;
2198 // -ObjC and -ObjC++ override the default language, but only for "source
2199 // files". We just treat everything that isn't a linker input as a
2202 // FIXME: Clean this up if we move the phase sequence into the type.
2203 if (Ty != types::TY_Object) {
2204 if (Args.hasArg(options::OPT_ObjC))
2205 Ty = types::TY_ObjC;
2206 else if (Args.hasArg(options::OPT_ObjCXX))
2207 Ty = types::TY_ObjCXX;
2210 assert(InputTypeArg && "InputType set w/o InputTypeArg");
2211 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2212 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2214 const char *Ext = strrchr(Value, '.');
2215 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2216 Ty = types::TY_Object;
2218 if (Ty == types::TY_INVALID) {
2220 InputTypeArg->claim();
2224 if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2225 Inputs.push_back(std::make_pair(Ty, A));
2227 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2228 StringRef Value = A->getValue();
2229 if (DiagnoseInputExistence(Args, Value, types::TY_C,
2230 /*TypoCorrect=*/false)) {
2231 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2232 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2235 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2236 StringRef Value = A->getValue();
2237 if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2238 /*TypoCorrect=*/false)) {
2239 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2240 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2243 } else if (A->getOption().hasFlag(options::LinkerInput)) {
2244 // Just treat as object type, we could make a special type for this if
2246 Inputs.push_back(std::make_pair(types::TY_Object, A));
2248 } else if (A->getOption().matches(options::OPT_x)) {
2250 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2253 // Follow gcc behavior and treat as linker input for invalid -x
2254 // options. Its not clear why we shouldn't just revert to unknown; but
2255 // this isn't very important, we might as well be bug compatible.
2257 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2258 InputType = types::TY_Object;
2260 } else if (A->getOption().getID() == options::OPT_U) {
2261 assert(A->getNumValues() == 1 && "The /U option has one value.");
2262 StringRef Val = A->getValue(0);
2263 if (Val.find_first_of("/\\") != StringRef::npos) {
2264 // Warn about e.g. "/Users/me/myfile.c".
2265 Diag(diag::warn_slash_u_filename) << Val;
2266 Diag(diag::note_use_dashdash);
2270 if (CCCIsCPP() && Inputs.empty()) {
2271 // If called as standalone preprocessor, stdin is processed
2272 // if no other input is present.
2273 Arg *A = MakeInputArg(Args, Opts, "-");
2274 Inputs.push_back(std::make_pair(types::TY_C, A));
2279 /// Provides a convenient interface for different programming models to generate
2280 /// the required device actions.
2281 class OffloadingActionBuilder final {
2282 /// Flag used to trace errors in the builder.
2283 bool IsValid = false;
2285 /// The compilation that is using this builder.
2288 /// Map between an input argument and the offload kinds used to process it.
2289 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2291 /// Builder interface. It doesn't build anything or keep any state.
2292 class DeviceActionBuilder {
2294 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2296 enum ActionBuilderReturnCode {
2297 // The builder acted successfully on the current action.
2299 // The builder didn't have to act on the current action.
2301 // The builder was successful and requested the host action to not be
2307 /// Compilation associated with this builder.
2310 /// Tool chains associated with this builder. The same programming
2311 /// model may have associated one or more tool chains.
2312 SmallVector<const ToolChain *, 2> ToolChains;
2314 /// The derived arguments associated with this builder.
2315 DerivedArgList &Args;
2317 /// The inputs associated with this builder.
2318 const Driver::InputList &Inputs;
2320 /// The associated offload kind.
2321 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2324 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2325 const Driver::InputList &Inputs,
2326 Action::OffloadKind AssociatedOffloadKind)
2327 : C(C), Args(Args), Inputs(Inputs),
2328 AssociatedOffloadKind(AssociatedOffloadKind) {}
2329 virtual ~DeviceActionBuilder() {}
2331 /// Fill up the array \a DA with all the device dependences that should be
2332 /// added to the provided host action \a HostAction. By default it is
2334 virtual ActionBuilderReturnCode
2335 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2336 phases::ID CurPhase, phases::ID FinalPhase,
2338 return ABRT_Inactive;
2341 /// Update the state to include the provided host action \a HostAction as a
2342 /// dependency of the current device action. By default it is inactive.
2343 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2344 return ABRT_Inactive;
2347 /// Append top level actions generated by the builder.
2348 virtual void appendTopLevelActions(ActionList &AL) {}
2350 /// Append linker device actions generated by the builder.
2351 virtual void appendLinkDeviceActions(ActionList &AL) {}
2353 /// Append linker host action generated by the builder.
2354 virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2356 /// Append linker actions generated by the builder.
2357 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2359 /// Initialize the builder. Return true if any initialization errors are
2361 virtual bool initialize() { return false; }
2363 /// Return true if the builder can use bundling/unbundling.
2364 virtual bool canUseBundlerUnbundler() const { return false; }
2366 /// Return true if this builder is valid. We have a valid builder if we have
2367 /// associated device tool chains.
2368 bool isValid() { return !ToolChains.empty(); }
2370 /// Return the associated offload kind.
2371 Action::OffloadKind getAssociatedOffloadKind() {
2372 return AssociatedOffloadKind;
2376 /// Base class for CUDA/HIP action builder. It injects device code in
2377 /// the host backend action.
2378 class CudaActionBuilderBase : public DeviceActionBuilder {
2380 /// Flags to signal if the user requested host-only or device-only
2382 bool CompileHostOnly = false;
2383 bool CompileDeviceOnly = false;
2384 bool EmitLLVM = false;
2385 bool EmitAsm = false;
2387 /// List of GPU architectures to use in this compilation.
2388 SmallVector<CudaArch, 4> GpuArchList;
2390 /// The CUDA actions for the current input.
2391 ActionList CudaDeviceActions;
2393 /// The CUDA fat binary if it was generated for the current input.
2394 Action *CudaFatBinary = nullptr;
2396 /// Flag that is set to true if this builder acted on the current input.
2397 bool IsActive = false;
2399 /// Flag for -fgpu-rdc.
2400 bool Relocatable = false;
2402 /// Default GPU architecture if there's no one specified.
2403 CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2406 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2407 const Driver::InputList &Inputs,
2408 Action::OffloadKind OFKind)
2409 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2411 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2412 // While generating code for CUDA, we only depend on the host input action
2413 // to trigger the creation of all the CUDA device actions.
2415 // If we are dealing with an input action, replicate it for each GPU
2416 // architecture. If we are in host-only mode we return 'success' so that
2417 // the host uses the CUDA offload kind.
2418 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2419 assert(!GpuArchList.empty() &&
2420 "We should have at least one GPU architecture.");
2422 // If the host input is not CUDA or HIP, we don't need to bother about
2424 if (IA->getType() != types::TY_CUDA &&
2425 IA->getType() != types::TY_HIP) {
2426 // The builder will ignore this input.
2428 return ABRT_Inactive;
2431 // Set the flag to true, so that the builder acts on the current input.
2434 if (CompileHostOnly)
2435 return ABRT_Success;
2437 // Replicate inputs for each GPU architecture.
2438 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2439 : types::TY_CUDA_DEVICE;
2440 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2441 CudaDeviceActions.push_back(
2442 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2445 return ABRT_Success;
2448 // If this is an unbundling action use it as is for each CUDA toolchain.
2449 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2451 // If -fgpu-rdc is disabled, should not unbundle since there is no
2452 // device code to link.
2454 return ABRT_Inactive;
2456 CudaDeviceActions.clear();
2457 auto *IA = cast<InputAction>(UA->getInputs().back());
2458 std::string FileName = IA->getInputArg().getAsString(Args);
2459 // Check if the type of the file is the same as the action. Do not
2460 // unbundle it if it is not. Do not unbundle .so files, for example,
2461 // which are not object files.
2462 if (IA->getType() == types::TY_Object &&
2463 (!llvm::sys::path::has_extension(FileName) ||
2464 types::lookupTypeForExtension(
2465 llvm::sys::path::extension(FileName).drop_front()) !=
2467 return ABRT_Inactive;
2469 for (auto Arch : GpuArchList) {
2470 CudaDeviceActions.push_back(UA);
2471 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2472 AssociatedOffloadKind);
2474 return ABRT_Success;
2477 return IsActive ? ABRT_Success : ABRT_Inactive;
2480 void appendTopLevelActions(ActionList &AL) override {
2481 // Utility to append actions to the top level list.
2482 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2483 OffloadAction::DeviceDependences Dep;
2484 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2485 AssociatedOffloadKind);
2486 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2489 // If we have a fat binary, add it to the list.
2490 if (CudaFatBinary) {
2491 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2492 CudaDeviceActions.clear();
2493 CudaFatBinary = nullptr;
2497 if (CudaDeviceActions.empty())
2500 // If we have CUDA actions at this point, that's because we have a have
2501 // partial compilation, so we should have an action for each GPU
2503 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2504 "Expecting one action per GPU architecture.");
2505 assert(ToolChains.size() == 1 &&
2506 "Expecting to have a sing CUDA toolchain.");
2507 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2508 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2510 CudaDeviceActions.clear();
2513 bool initialize() override {
2514 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2515 AssociatedOffloadKind == Action::OFK_HIP);
2517 // We don't need to support CUDA.
2518 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2519 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2522 // We don't need to support HIP.
2523 if (AssociatedOffloadKind == Action::OFK_HIP &&
2524 !C.hasOffloadToolChain<Action::OFK_HIP>())
2527 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2528 options::OPT_fno_gpu_rdc, /*Default=*/false);
2530 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2531 assert(HostTC && "No toolchain for host compilation.");
2532 if (HostTC->getTriple().isNVPTX() ||
2533 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2534 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2535 // an error and abort pipeline construction early so we don't trip
2536 // asserts that assume device-side compilation.
2537 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2538 << HostTC->getTriple().getArchName();
2542 ToolChains.push_back(
2543 AssociatedOffloadKind == Action::OFK_Cuda
2544 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2545 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2547 Arg *PartialCompilationArg = Args.getLastArg(
2548 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2549 options::OPT_cuda_compile_host_device);
2550 CompileHostOnly = PartialCompilationArg &&
2551 PartialCompilationArg->getOption().matches(
2552 options::OPT_cuda_host_only);
2553 CompileDeviceOnly = PartialCompilationArg &&
2554 PartialCompilationArg->getOption().matches(
2555 options::OPT_cuda_device_only);
2556 EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
2557 EmitAsm = Args.getLastArg(options::OPT_S);
2559 // Collect all cuda_gpu_arch parameters, removing duplicates.
2560 std::set<CudaArch> GpuArchs;
2562 for (Arg *A : Args) {
2563 if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
2564 A->getOption().matches(options::OPT_no_offload_arch_EQ)))
2568 const StringRef ArchStr = A->getValue();
2569 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
2574 CudaArch Arch = StringToCudaArch(ArchStr);
2575 if (Arch == CudaArch::UNKNOWN) {
2576 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2578 } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
2579 GpuArchs.insert(Arch);
2580 else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
2581 GpuArchs.erase(Arch);
2583 llvm_unreachable("Unexpected option.");
2586 // Collect list of GPUs remaining in the set.
2587 for (CudaArch Arch : GpuArchs)
2588 GpuArchList.push_back(Arch);
2590 // Default to sm_20 which is the lowest common denominator for
2591 // supported GPUs. sm_20 code should work correctly, if
2592 // suboptimally, on all newer GPUs.
2593 if (GpuArchList.empty())
2594 GpuArchList.push_back(DefaultCudaArch);
2600 /// \brief CUDA action builder. It injects device code in the host backend
2602 class CudaActionBuilder final : public CudaActionBuilderBase {
2604 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2605 const Driver::InputList &Inputs)
2606 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
2607 DefaultCudaArch = CudaArch::SM_20;
2610 ActionBuilderReturnCode
2611 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2612 phases::ID CurPhase, phases::ID FinalPhase,
2613 PhasesTy &Phases) override {
2615 return ABRT_Inactive;
2617 // If we don't have more CUDA actions, we don't have any dependences to
2618 // create for the host.
2619 if (CudaDeviceActions.empty())
2620 return ABRT_Success;
2622 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2623 "Expecting one action per GPU architecture.");
2624 assert(!CompileHostOnly &&
2625 "Not expecting CUDA actions in host-only compilation.");
2627 // If we are generating code for the device or we are in a backend phase,
2628 // we attempt to generate the fat binary. We compile each arch to ptx and
2629 // assemble to cubin, then feed the cubin *and* the ptx into a device
2630 // "link" action, which uses fatbinary to combine these cubins into one
2631 // fatbin. The fatbin is then an input to the host action if not in
2632 // device-only mode.
2633 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2634 ActionList DeviceActions;
2635 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2636 // Produce the device action from the current phase up to the assemble
2638 for (auto Ph : Phases) {
2639 // Skip the phases that were already dealt with.
2642 // We have to be consistent with the host final phase.
2643 if (Ph > FinalPhase)
2646 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2647 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2649 if (Ph == phases::Assemble)
2653 // If we didn't reach the assemble phase, we can't generate the fat
2654 // binary. We don't need to generate the fat binary if we are not in
2655 // device-only mode.
2656 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2660 Action *AssembleAction = CudaDeviceActions[I];
2661 assert(AssembleAction->getType() == types::TY_Object);
2662 assert(AssembleAction->getInputs().size() == 1);
2664 Action *BackendAction = AssembleAction->getInputs()[0];
2665 assert(BackendAction->getType() == types::TY_PP_Asm);
2667 for (auto &A : {AssembleAction, BackendAction}) {
2668 OffloadAction::DeviceDependences DDep;
2669 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2671 DeviceActions.push_back(
2672 C.MakeAction<OffloadAction>(DDep, A->getType()));
2676 // We generate the fat binary if we have device input actions.
2677 if (!DeviceActions.empty()) {
2679 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2681 if (!CompileDeviceOnly) {
2682 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2684 // Clear the fat binary, it is already a dependence to an host
2686 CudaFatBinary = nullptr;
2689 // Remove the CUDA actions as they are already connected to an host
2690 // action or fat binary.
2691 CudaDeviceActions.clear();
2694 // We avoid creating host action in device-only mode.
2695 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2696 } else if (CurPhase > phases::Backend) {
2697 // If we are past the backend phase and still have a device action, we
2698 // don't have to do anything as this action is already a device
2699 // top-level action.
2700 return ABRT_Success;
2703 assert(CurPhase < phases::Backend && "Generating single CUDA "
2704 "instructions should only occur "
2705 "before the backend phase!");
2707 // By default, we produce an action for each device arch.
2708 for (Action *&A : CudaDeviceActions)
2709 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2711 return ABRT_Success;
2714 /// \brief HIP action builder. It injects device code in the host backend
2716 class HIPActionBuilder final : public CudaActionBuilderBase {
2717 /// The linker inputs obtained for each device arch.
2718 SmallVector<ActionList, 8> DeviceLinkerInputs;
2721 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2722 const Driver::InputList &Inputs)
2723 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
2724 DefaultCudaArch = CudaArch::GFX803;
2727 bool canUseBundlerUnbundler() const override { return true; }
2729 ActionBuilderReturnCode
2730 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2731 phases::ID CurPhase, phases::ID FinalPhase,
2732 PhasesTy &Phases) override {
2733 // amdgcn does not support linking of object files, therefore we skip
2734 // backend and assemble phases to output LLVM IR. Except for generating
2735 // non-relocatable device coee, where we generate fat binary for device
2736 // code and pass to host in Backend phase.
2737 if (CudaDeviceActions.empty())
2738 return ABRT_Success;
2740 assert(((CurPhase == phases::Link && Relocatable) ||
2741 CudaDeviceActions.size() == GpuArchList.size()) &&
2742 "Expecting one action per GPU architecture.");
2743 assert(!CompileHostOnly &&
2744 "Not expecting CUDA actions in host-only compilation.");
2746 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
2748 // If we are in backend phase, we attempt to generate the fat binary.
2749 // We compile each arch to IR and use a link action to generate code
2750 // object containing ISA. Then we use a special "link" action to create
2751 // a fat binary containing all the code objects for different GPU's.
2752 // The fat binary is then an input to the host action.
2753 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2754 auto BackendAction = C.getDriver().ConstructPhaseAction(
2755 C, Args, phases::Backend, CudaDeviceActions[I],
2756 AssociatedOffloadKind);
2757 auto AssembleAction = C.getDriver().ConstructPhaseAction(
2758 C, Args, phases::Assemble, BackendAction, AssociatedOffloadKind);
2759 // Create a link action to link device IR with device library
2760 // and generate ISA.
2762 AL.push_back(AssembleAction);
2763 CudaDeviceActions[I] =
2764 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2766 // OffloadingActionBuilder propagates device arch until an offload
2767 // action. Since the next action for creating fatbin does
2768 // not have device arch, whereas the above link action and its input
2769 // have device arch, an offload action is needed to stop the null
2770 // device arch of the next action being propagated to the above link
2772 OffloadAction::DeviceDependences DDep;
2773 DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2774 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2775 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2776 DDep, CudaDeviceActions[I]->getType());
2778 // Create HIP fat binary with a special "link" action.
2780 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2781 types::TY_HIP_FATBIN);
2783 if (!CompileDeviceOnly) {
2784 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2785 AssociatedOffloadKind);
2786 // Clear the fat binary, it is already a dependence to an host
2788 CudaFatBinary = nullptr;
2791 // Remove the CUDA actions as they are already connected to an host
2792 // action or fat binary.
2793 CudaDeviceActions.clear();
2795 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2796 } else if (CurPhase == phases::Link) {
2797 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2798 // This happens to each device action originated from each input file.
2799 // Later on, device actions in DeviceLinkerInputs are used to create
2800 // device link actions in appendLinkDependences and the created device
2801 // link actions are passed to the offload action as device dependence.
2802 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2803 auto LI = DeviceLinkerInputs.begin();
2804 for (auto *A : CudaDeviceActions) {
2809 // We will pass the device action as a host dependence, so we don't
2810 // need to do anything else with them.
2811 CudaDeviceActions.clear();
2812 return ABRT_Success;
2815 // By default, we produce an action for each device arch.
2816 for (Action *&A : CudaDeviceActions)
2817 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2818 AssociatedOffloadKind);
2820 return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
2824 void appendLinkDeviceActions(ActionList &AL) override {
2825 if (DeviceLinkerInputs.size() == 0)
2828 assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
2829 "Linker inputs and GPU arch list sizes do not match.");
2831 // Append a new link action for each device.
2833 for (auto &LI : DeviceLinkerInputs) {
2834 // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
2835 auto *DeviceLinkAction =
2836 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2837 // Linking all inputs for the current GPU arch.
2838 // LI contains all the inputs for the linker.
2839 OffloadAction::DeviceDependences DeviceLinkDeps;
2840 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
2841 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2842 AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2843 DeviceLinkAction->getType()));
2846 DeviceLinkerInputs.clear();
2848 // Create a host object from all the device images by embedding them
2850 OffloadAction::DeviceDependences DDeps;
2851 auto *TopDeviceLinkAction =
2852 C.MakeAction<LinkJobAction>(AL, types::TY_Object);
2853 DDeps.add(*TopDeviceLinkAction, *ToolChains[0],
2854 nullptr, AssociatedOffloadKind);
2856 // Offload the host object to the host linker.
2857 AL.push_back(C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
2860 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
2862 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2865 /// OpenMP action builder. The host bitcode is passed to the device frontend
2866 /// and all the device linked images are passed to the host link phase.
2867 class OpenMPActionBuilder final : public DeviceActionBuilder {
2868 /// The OpenMP actions for the current input.
2869 ActionList OpenMPDeviceActions;
2871 /// The linker inputs obtained for each toolchain.
2872 SmallVector<ActionList, 8> DeviceLinkerInputs;
2875 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2876 const Driver::InputList &Inputs)
2877 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2879 ActionBuilderReturnCode
2880 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2881 phases::ID CurPhase, phases::ID FinalPhase,
2882 PhasesTy &Phases) override {
2883 if (OpenMPDeviceActions.empty())
2884 return ABRT_Inactive;
2886 // We should always have an action for each input.
2887 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2888 "Number of OpenMP actions and toolchains do not match.");
2890 // The host only depends on device action in the linking phase, when all
2891 // the device images have to be embedded in the host image.
2892 if (CurPhase == phases::Link) {
2893 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2894 "Toolchains and linker inputs sizes do not match.");
2895 auto LI = DeviceLinkerInputs.begin();
2896 for (auto *A : OpenMPDeviceActions) {
2901 // We passed the device action as a host dependence, so we don't need to
2902 // do anything else with them.
2903 OpenMPDeviceActions.clear();
2904 return ABRT_Success;
2907 // By default, we produce an action for each device arch.
2908 for (Action *&A : OpenMPDeviceActions)
2909 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2911 return ABRT_Success;
2914 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2916 // If this is an input action replicate it for each OpenMP toolchain.
2917 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2918 OpenMPDeviceActions.clear();
2919 for (unsigned I = 0; I < ToolChains.size(); ++I)
2920 OpenMPDeviceActions.push_back(
2921 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2922 return ABRT_Success;
2925 // If this is an unbundling action use it as is for each OpenMP toolchain.
2926 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2927 OpenMPDeviceActions.clear();
2928 auto *IA = cast<InputAction>(UA->getInputs().back());
2929 std::string FileName = IA->getInputArg().getAsString(Args);
2930 // Check if the type of the file is the same as the action. Do not
2931 // unbundle it if it is not. Do not unbundle .so files, for example,
2932 // which are not object files.
2933 if (IA->getType() == types::TY_Object &&
2934 (!llvm::sys::path::has_extension(FileName) ||
2935 types::lookupTypeForExtension(
2936 llvm::sys::path::extension(FileName).drop_front()) !=
2938 return ABRT_Inactive;
2939 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2940 OpenMPDeviceActions.push_back(UA);
2941 UA->registerDependentActionInfo(
2942 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2944 return ABRT_Success;
2947 // When generating code for OpenMP we use the host compile phase result as
2948 // a dependence to the device compile phase so that it can learn what
2949 // declarations should be emitted. However, this is not the only use for
2950 // the host action, so we prevent it from being collapsed.
2951 if (isa<CompileJobAction>(HostAction)) {
2952 HostAction->setCannotBeCollapsedWithNextDependentAction();
2953 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2954 "Toolchains and device action sizes do not match.");
2955 OffloadAction::HostDependence HDep(
2956 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2957 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2958 auto TC = ToolChains.begin();
2959 for (Action *&A : OpenMPDeviceActions) {
2960 assert(isa<CompileJobAction>(A));
2961 OffloadAction::DeviceDependences DDep;
2962 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2963 A = C.MakeAction<OffloadAction>(HDep, DDep);
2967 return ABRT_Success;
2970 void appendTopLevelActions(ActionList &AL) override {
2971 if (OpenMPDeviceActions.empty())
2974 // We should always have an action for each input.
2975 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2976 "Number of OpenMP actions and toolchains do not match.");
2978 // Append all device actions followed by the proper offload action.
2979 auto TI = ToolChains.begin();
2980 for (auto *A : OpenMPDeviceActions) {
2981 OffloadAction::DeviceDependences Dep;
2982 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2983 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2986 // We no longer need the action stored in this builder.
2987 OpenMPDeviceActions.clear();
2990 void appendLinkDeviceActions(ActionList &AL) override {
2991 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2992 "Toolchains and linker inputs sizes do not match.");
2994 // Append a new link action for each device.
2995 auto TC = ToolChains.begin();
2996 for (auto &LI : DeviceLinkerInputs) {
2997 auto *DeviceLinkAction =
2998 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2999 OffloadAction::DeviceDependences DeviceLinkDeps;
3000 DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
3001 Action::OFK_OpenMP);
3002 AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
3003 DeviceLinkAction->getType()));
3006 DeviceLinkerInputs.clear();
3009 Action* appendLinkHostActions(ActionList &AL) override {
3010 // Create wrapper bitcode from the result of device link actions and compile
3011 // it to an object which will be added to the host link command.
3012 auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC);
3013 auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
3014 return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
3017 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3019 bool initialize() override {
3020 // Get the OpenMP toolchains. If we don't get any, the action builder will
3021 // know there is nothing to do related to OpenMP offloading.
3022 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
3023 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
3025 ToolChains.push_back(TI->second);
3027 DeviceLinkerInputs.resize(ToolChains.size());
3031 bool canUseBundlerUnbundler() const override {
3032 // OpenMP should use bundled files whenever possible.
3038 /// TODO: Add the implementation for other specialized builders here.
3041 /// Specialized builders being used by this offloading action builder.
3042 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3044 /// Flag set to true if all valid builders allow file bundling/unbundling.
3048 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3049 const Driver::InputList &Inputs)
3051 // Create a specialized builder for each device toolchain.
3055 // Create a specialized builder for CUDA.
3056 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3058 // Create a specialized builder for HIP.
3059 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3061 // Create a specialized builder for OpenMP.
3062 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
3065 // TODO: Build other specialized builders here.
3068 // Initialize all the builders, keeping track of errors. If all valid
3069 // builders agree that we can use bundling, set the flag to true.
3070 unsigned ValidBuilders = 0u;
3071 unsigned ValidBuildersSupportingBundling = 0u;
3072 for (auto *SB : SpecializedBuilders) {
3073 IsValid = IsValid && !SB->initialize();
3075 // Update the counters if the builder is valid.
3076 if (SB->isValid()) {
3078 if (SB->canUseBundlerUnbundler())
3079 ++ValidBuildersSupportingBundling;
3083 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3086 ~OffloadingActionBuilder() {
3087 for (auto *SB : SpecializedBuilders)
3091 /// Generate an action that adds device dependences (if any) to a host action.
3092 /// If no device dependence actions exist, just return the host action \a
3093 /// HostAction. If an error is found or if no builder requires the host action
3094 /// to be generated, return nullptr.
3096 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3097 phases::ID CurPhase, phases::ID FinalPhase,
3098 DeviceActionBuilder::PhasesTy &Phases) {
3102 if (SpecializedBuilders.empty())
3105 assert(HostAction && "Invalid host action!");
3107 OffloadAction::DeviceDependences DDeps;
3108 // Check if all the programming models agree we should not emit the host
3109 // action. Also, keep track of the offloading kinds employed.
3110 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3111 unsigned InactiveBuilders = 0u;
3112 unsigned IgnoringBuilders = 0u;
3113 for (auto *SB : SpecializedBuilders) {
3114 if (!SB->isValid()) {
3120 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3122 // If the builder explicitly says the host action should be ignored,
3123 // we need to increment the variable that tracks the builders that request
3124 // the host object to be ignored.
3125 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3128 // Unless the builder was inactive for this action, we have to record the
3129 // offload kind because the host will have to use it.
3130 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3131 OffloadKind |= SB->getAssociatedOffloadKind();
3134 // If all builders agree that the host object should be ignored, just return
3136 if (IgnoringBuilders &&
3137 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3140 if (DDeps.getActions().empty())
3143 // We have dependences we need to bundle together. We use an offload action
3145 OffloadAction::HostDependence HDep(
3146 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3147 /*BoundArch=*/nullptr, DDeps);
3148 return C.MakeAction<OffloadAction>(HDep, DDeps);
3151 /// Generate an action that adds a host dependence to a device action. The
3152 /// results will be kept in this action builder. Return true if an error was
3154 bool addHostDependenceToDeviceActions(Action *&HostAction,
3155 const Arg *InputArg) {
3159 // If we are supporting bundling/unbundling and the current action is an
3160 // input action of non-source file, we replace the host action by the
3161 // unbundling action. The bundler tool has the logic to detect if an input
3162 // is a bundle or not and if the input is not a bundle it assumes it is a
3163 // host file. Therefore it is safe to create an unbundling action even if
3164 // the input is not a bundle.
3165 if (CanUseBundler && isa<InputAction>(HostAction) &&
3166 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3167 !types::isSrcFile(HostAction->getType())) {
3168 auto UnbundlingHostAction =
3169 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3170 UnbundlingHostAction->registerDependentActionInfo(
3171 C.getSingleOffloadToolChain<Action::OFK_Host>(),
3172 /*BoundArch=*/StringRef(), Action::OFK_Host);
3173 HostAction = UnbundlingHostAction;
3176 assert(HostAction && "Invalid host action!");
3178 // Register the offload kinds that are used.
3179 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3180 for (auto *SB : SpecializedBuilders) {
3184 auto RetCode = SB->addDeviceDepences(HostAction);
3186 // Host dependences for device actions are not compatible with that same
3187 // action being ignored.
3188 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3189 "Host dependence not expected to be ignored.!");
3191 // Unless the builder was inactive for this action, we have to record the
3192 // offload kind because the host will have to use it.
3193 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3194 OffloadKind |= SB->getAssociatedOffloadKind();
3197 // Do not use unbundler if the Host does not depend on device action.
3198 if (OffloadKind == Action::OFK_None && CanUseBundler)
3199 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3200 HostAction = UA->getInputs().back();
3205 /// Add the offloading top level actions to the provided action list. This
3206 /// function can replace the host action by a bundling action if the
3207 /// programming models allow it.
3208 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3209 const Arg *InputArg) {
3210 // Get the device actions to be appended.
3211 ActionList OffloadAL;
3212 for (auto *SB : SpecializedBuilders) {
3215 SB->appendTopLevelActions(OffloadAL);
3218 // If we can use the bundler, replace the host action by the bundling one in
3219 // the resulting list. Otherwise, just append the device actions. For
3220 // device only compilation, HostAction is a null pointer, therefore only do
3221 // this when HostAction is not a null pointer.
3222 if (CanUseBundler && HostAction &&
3223 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3224 // Add the host action to the list in order to create the bundling action.
3225 OffloadAL.push_back(HostAction);
3227 // We expect that the host action was just appended to the action list
3228 // before this method was called.
3229 assert(HostAction == AL.back() && "Host action not in the list??");
3230 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3231 AL.back() = HostAction;
3233 AL.append(OffloadAL.begin(), OffloadAL.end());
3235 // Propagate to the current host action (if any) the offload information
3236 // associated with the current input.
3238 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3239 /*BoundArch=*/nullptr);
3243 Action* makeHostLinkAction() {
3244 // Build a list of device linking actions.
3245 ActionList DeviceAL;
3246 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3249 SB->appendLinkDeviceActions(DeviceAL);
3252 if (DeviceAL.empty())
3255 // Let builders add host linking actions.
3257 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3260 HA = SB->appendLinkHostActions(DeviceAL);
3265 /// Processes the host linker action. This currently consists of replacing it
3266 /// with an offload action if there are device link objects and propagate to
3267 /// the host action all the offload kinds used in the current compilation. The
3268 /// resulting action is returned.
3269 Action *processHostLinkAction(Action *HostAction) {
3270 // Add all the dependences from the device linking actions.
3271 OffloadAction::DeviceDependences DDeps;
3272 for (auto *SB : SpecializedBuilders) {
3276 SB->appendLinkDependences(DDeps);
3279 // Calculate all the offload kinds used in the current compilation.
3280 unsigned ActiveOffloadKinds = 0u;
3281 for (auto &I : InputArgToOffloadKindMap)
3282 ActiveOffloadKinds |= I.second;
3284 // If we don't have device dependencies, we don't have to create an offload
3286 if (DDeps.getActions().empty()) {
3287 // Propagate all the active kinds to host action. Given that it is a link
3288 // action it is assumed to depend on all actions generated so far.
3289 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3290 /*BoundArch=*/nullptr);
3294 // Create the offload action with all dependences. When an offload action
3295 // is created the kinds are propagated to the host action, so we don't have
3296 // to do that explicitly here.
3297 OffloadAction::HostDependence HDep(
3298 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3299 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3300 return C.MakeAction<OffloadAction>(HDep, DDeps);
3303 } // anonymous namespace.
3305 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3306 const InputList &Inputs,
3307 ActionList &Actions) const {
3309 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3310 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3311 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3312 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3313 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3314 Args.eraseArg(options::OPT__SLASH_Yc);
3315 Args.eraseArg(options::OPT__SLASH_Yu);
3316 YcArg = YuArg = nullptr;
3318 if (YcArg && Inputs.size() > 1) {
3319 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3320 Args.eraseArg(options::OPT__SLASH_Yc);
3325 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3327 if (FinalPhase == phases::Link) {
3328 if (Args.hasArg(options::OPT_emit_llvm))
3329 Diag(clang::diag::err_drv_emit_llvm_link);
3330 if (IsCLMode() && LTOMode != LTOK_None &&
3331 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3332 Diag(clang::diag::err_drv_lto_without_lld);
3335 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3336 // If only preprocessing or /Y- is used, all pch handling is disabled.
3337 // Rather than check for it everywhere, just remove clang-cl pch-related
3339 Args.eraseArg(options::OPT__SLASH_Fp);
3340 Args.eraseArg(options::OPT__SLASH_Yc);
3341 Args.eraseArg(options::OPT__SLASH_Yu);
3342 YcArg = YuArg = nullptr;
3345 unsigned LastPLSize = 0;
3346 for (auto &I : Inputs) {
3347 types::ID InputType = I.first;
3348 const Arg *InputArg = I.second;
3350 auto PL = types::getCompilationPhases(InputType);
3351 LastPLSize = PL.size();
3353 // If the first step comes after the final phase we are doing as part of
3354 // this compilation, warn the user about it.
3355 phases::ID InitialPhase = PL[0];
3356 if (InitialPhase > FinalPhase) {
3357 if (InputArg->isClaimed())
3360 // Claim here to avoid the more general unused warning.
3363 // Suppress all unused style warnings with -Qunused-arguments
3364 if (Args.hasArg(options::OPT_Qunused_arguments))
3367 // Special case when final phase determined by binary name, rather than
3368 // by a command-line argument with a corresponding Arg.
3370 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3371 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3372 // Special case '-E' warning on a previously preprocessed file to make
3374 else if (InitialPhase == phases::Compile &&
3375 (Args.getLastArg(options::OPT__SLASH_EP,
3376 options::OPT__SLASH_P) ||
3377 Args.getLastArg(options::OPT_E) ||
3378 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3379 getPreprocessedType(InputType) == types::TY_INVALID)
3380 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3381 << InputArg->getAsString(Args) << !!FinalPhaseArg
3382 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3384 Diag(clang::diag::warn_drv_input_file_unused)
3385 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3387 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3392 // Add a separate precompile phase for the compile phase.
3393 if (FinalPhase >= phases::Compile) {
3394 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3395 // Build the pipeline for the pch file.
3396 Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3397 for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3398 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3400 Actions.push_back(ClangClPch);
3401 // The driver currently exits after the first failed command. This
3402 // relies on that behavior, to make sure if the pch generation fails,
3403 // the main compilation won't run.
3404 // FIXME: If the main compilation fails, the PCH generation should
3405 // probably not be considered successful either.
3410 // If we are linking, claim any options which are obviously only used for
3412 // FIXME: Understand why the last Phase List length is used here.
3413 if (FinalPhase == phases::Link && LastPLSize == 1) {
3414 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3415 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3419 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3420 const InputList &Inputs, ActionList &Actions) const {
3421 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3423 if (!SuppressMissingInputWarning && Inputs.empty()) {
3424 Diag(clang::diag::err_drv_no_input_files);
3428 // Reject -Z* at the top level, these options should never have been exposed
3430 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3431 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3433 // Diagnose misuse of /Fo.
3434 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3435 StringRef V = A->getValue();
3436 if (Inputs.size() > 1 && !V.empty() &&
3437 !llvm::sys::path::is_separator(V.back())) {
3438 // Check whether /Fo tries to name an output file for multiple inputs.
3439 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3440 << A->getSpelling() << V;
3441 Args.eraseArg(options::OPT__SLASH_Fo);
3445 // Diagnose misuse of /Fa.
3446 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3447 StringRef V = A->getValue();
3448 if (Inputs.size() > 1 && !V.empty() &&
3449 !llvm::sys::path::is_separator(V.back())) {
3450 // Check whether /Fa tries to name an asm file for multiple inputs.
3451 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3452 << A->getSpelling() << V;
3453 Args.eraseArg(options::OPT__SLASH_Fa);
3457 // Diagnose misuse of /o.
3458 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3459 if (A->getValue()[0] == '\0') {
3460 // It has to have a value.
3461 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3462 Args.eraseArg(options::OPT__SLASH_o);
3466 handleArguments(C, Args, Inputs, Actions);
3468 // Builder to be used to build offloading actions.
3469 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3471 // Construct the actions to perform.
3472 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3473 ActionList LinkerInputs;
3474 ActionList MergerInputs;
3476 for (auto &I : Inputs) {
3477 types::ID InputType = I.first;
3478 const Arg *InputArg = I.second;
3480 auto PL = types::getCompilationPhases(*this, Args, InputType);
3484 auto FullPL = types::getCompilationPhases(InputType);
3486 // Build the pipeline for this file.
3487 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3489 // Use the current host action in any of the offloading actions, if
3491 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3494 for (phases::ID Phase : PL) {
3496 // Add any offload action the host action depends on.
3497 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3498 Current, InputArg, Phase, PL.back(), FullPL);
3502 // Queue linker inputs.
3503 if (Phase == phases::Link) {
3504 assert(Phase == PL.back() && "linking must be final compilation step.");
3505 LinkerInputs.push_back(Current);
3510 // TODO: Consider removing this because the merged may not end up being
3511 // the final Phase in the pipeline. Perhaps the merged could just merge
3512 // and then pass an artifact of some sort to the Link Phase.
3513 // Queue merger inputs.
3514 if (Phase == phases::IfsMerge) {
3515 assert(Phase == PL.back() && "merging must be final compilation step.");
3516 MergerInputs.push_back(Current);
3521 // Each precompiled header file after a module file action is a module
3522 // header of that same module file, rather than being compiled to a
3524 if (Phase == phases::Precompile && HeaderModuleAction &&
3525 getPrecompiledType(InputType) == types::TY_PCH) {
3526 HeaderModuleAction->addModuleHeaderInput(Current);
3531 // FIXME: Should we include any prior module file outputs as inputs of
3532 // later actions in the same command line?
3534 // Otherwise construct the appropriate action.
3535 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3537 // We didn't create a new action, so we will just move to the next phase.
3538 if (NewCurrent == Current)
3541 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3542 HeaderModuleAction = HMA;
3544 Current = NewCurrent;
3546 // Use the current host action in any of the offloading actions, if
3548 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3551 if (Current->getType() == types::TY_Nothing)
3555 // If we ended with something, add to the output list.
3557 Actions.push_back(Current);
3559 // Add any top level actions generated for offloading.
3560 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3563 // Add a link action if necessary.
3564 if (!LinkerInputs.empty()) {
3565 if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
3566 LinkerInputs.push_back(Wrapper);
3568 // Check if this Linker Job should emit a static library.
3569 if (ShouldEmitStaticLibrary(Args)) {
3570 LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
3572 LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3574 LA = OffloadBuilder.processHostLinkAction(LA);
3575 Actions.push_back(LA);
3578 // Add an interface stubs merge action if necessary.
3579 if (!MergerInputs.empty())
3581 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3583 if (Args.hasArg(options::OPT_emit_interface_stubs)) {
3584 auto PhaseList = types::getCompilationPhases(
3586 Args.hasArg(options::OPT_c) ? phases::Compile : phases::LastPhase);
3588 ActionList MergerInputs;
3590 for (auto &I : Inputs) {
3591 types::ID InputType = I.first;
3592 const Arg *InputArg = I.second;
3594 // Currently clang and the llvm assembler do not support generating symbol
3595 // stubs from assembly, so we skip the input on asm files. For ifs files
3596 // we rely on the normal pipeline setup in the pipeline setup code above.
3597 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
3598 InputType == types::TY_Asm)
3601 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3603 for (auto Phase : PhaseList) {
3607 "IFS Pipeline can only consist of Compile followed by IfsMerge.");
3608 case phases::Compile: {
3609 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
3610 // files where the .o file is located. The compile action can not
3612 if (InputType == types::TY_Object)
3615 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
3618 case phases::IfsMerge: {
3619 assert(Phase == PhaseList.back() &&
3620 "merging must be final compilation step.");
3621 MergerInputs.push_back(Current);
3628 // If we ended with something, add to the output list.
3630 Actions.push_back(Current);
3633 // Add an interface stubs merge action if necessary.
3634 if (!MergerInputs.empty())
3636 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3639 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
3640 // Compile phase that prints out supported cpu models and quits.
3641 if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
3642 // Use the -mcpu=? flag as the dummy input to cc1.
3644 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
3646 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
3647 for (auto &I : Inputs)
3651 // Claim ignored clang-cl options.
3652 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3654 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3655 // to non-CUDA compilations and should not trigger warnings there.
3656 Args.ClaimAllArgs(options::OPT_cuda_host_only);
3657 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3660 Action *Driver::ConstructPhaseAction(
3661 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3662 Action::OffloadKind TargetDeviceOffloadKind) const {
3663 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3665 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3666 // encode this in the steps because the intermediate type depends on
3667 // arguments. Just special case here.
3668 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3671 // Build the appropriate action.
3674 llvm_unreachable("link action invalid here.");
3675 case phases::IfsMerge:
3676 llvm_unreachable("ifsmerge action invalid here.");
3677 case phases::Preprocess: {
3679 // -M and -MM specify the dependency file name by altering the output type,
3680 // -if -MD and -MMD are not specified.
3681 if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
3682 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
3683 OutputTy = types::TY_Dependencies;
3685 OutputTy = Input->getType();
3686 if (!Args.hasFlag(options::OPT_frewrite_includes,
3687 options::OPT_fno_rewrite_includes, false) &&
3688 !Args.hasFlag(options::OPT_frewrite_imports,
3689 options::OPT_fno_rewrite_imports, false) &&
3691 OutputTy = types::getPreprocessedType(OutputTy);
3692 assert(OutputTy != types::TY_INVALID &&
3693 "Cannot preprocess this input type!");
3695 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3697 case phases::Precompile: {
3698 types::ID OutputTy = getPrecompiledType(Input->getType());
3699 assert(OutputTy != types::TY_INVALID &&
3700 "Cannot precompile this input type!");
3702 // If we're given a module name, precompile header file inputs as a
3703 // module, not as a precompiled header.
3704 const char *ModName = nullptr;
3705 if (OutputTy == types::TY_PCH) {
3706 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3707 ModName = A->getValue();
3709 OutputTy = types::TY_ModuleFile;
3712 if (Args.hasArg(options::OPT_fsyntax_only)) {
3713 // Syntax checks should not emit a PCH file
3714 OutputTy = types::TY_Nothing;
3718 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3720 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3722 case phases::Compile: {
3723 if (Args.hasArg(options::OPT_fsyntax_only))
3724 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3725 if (Args.hasArg(options::OPT_rewrite_objc))
3726 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3727 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3728 return C.MakeAction<CompileJobAction>(Input,
3729 types::TY_RewrittenLegacyObjC);
3730 if (Args.hasArg(options::OPT__analyze))
3731 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3732 if (Args.hasArg(options::OPT__migrate))
3733 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3734 if (Args.hasArg(options::OPT_emit_ast))
3735 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3736 if (Args.hasArg(options::OPT_module_file_info))
3737 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3738 if (Args.hasArg(options::OPT_verify_pch))
3739 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3740 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3742 case phases::Backend: {
3743 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3745 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
3746 return C.MakeAction<BackendJobAction>(Input, Output);
3748 if (Args.hasArg(options::OPT_emit_llvm) ||
3749 (TargetDeviceOffloadKind == Action::OFK_HIP &&
3750 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
3753 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
3754 return C.MakeAction<BackendJobAction>(Input, Output);
3756 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3758 case phases::Assemble:
3759 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3762 llvm_unreachable("invalid phase in ConstructPhaseAction");
3765 void Driver::BuildJobs(Compilation &C) const {
3766 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3768 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3770 // It is an error to provide a -o option if we are making multiple output
3771 // files. There are exceptions:
3773 // IfsMergeJob: when generating interface stubs enabled we want to be able to
3774 // generate the stub file at the same time that we generate the real
3775 // library/a.out. So when a .o, .so, etc are the output, with clang interface
3776 // stubs there will also be a .ifs and .ifso at the same location.
3778 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
3779 // and -c is passed, we still want to be able to generate a .ifs file while
3780 // we are also generating .o files. So we allow more than one output file in
3781 // this case as well.
3784 unsigned NumOutputs = 0;
3785 unsigned NumIfsOutputs = 0;
3786 for (const Action *A : C.getActions())
3787 if (A->getType() != types::TY_Nothing &&
3788 !(A->getKind() == Action::IfsMergeJobClass ||
3789 (A->getType() == clang::driver::types::TY_IFS_CPP &&
3790 A->getKind() == clang::driver::Action::CompileJobClass &&
3791 0 == NumIfsOutputs++) ||
3792 (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
3793 A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
3796 if (NumOutputs > 1) {
3797 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3798 FinalOutput = nullptr;
3802 // Collect the list of architectures.
3803 llvm::StringSet<> ArchNames;
3804 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3805 for (const Arg *A : C.getArgs())
3806 if (A->getOption().matches(options::OPT_arch))
3807 ArchNames.insert(A->getValue());
3809 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3810 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3811 for (Action *A : C.getActions()) {
3812 // If we are linking an image for multiple archs then the linker wants
3813 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3814 // doesn't fit in cleanly because we have to pass this information down.
3816 // FIXME: This is a hack; find a cleaner way to integrate this into the
3818 const char *LinkingOutput = nullptr;
3819 if (isa<LipoJobAction>(A)) {
3821 LinkingOutput = FinalOutput->getValue();
3823 LinkingOutput = getDefaultImageName();
3826 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3827 /*BoundArch*/ StringRef(),
3828 /*AtTopLevel*/ true,
3829 /*MultipleArchs*/ ArchNames.size() > 1,
3830 /*LinkingOutput*/ LinkingOutput, CachedResults,
3831 /*TargetDeviceOffloadKind*/ Action::OFK_None);
3834 // If we have more than one job, then disable integrated-cc1 for now.
3835 if (C.getJobs().size() > 1)
3836 for (auto &J : C.getJobs())
3837 J.InProcess = false;
3839 // If the user passed -Qunused-arguments or there were errors, don't warn
3840 // about any unused arguments.
3841 if (Diags.hasErrorOccurred() ||
3842 C.getArgs().hasArg(options::OPT_Qunused_arguments))
3846 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
3848 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
3849 (void)C.getArgs().hasArg(options::OPT_driver_mode);
3850 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
3852 for (Arg *A : C.getArgs()) {
3853 // FIXME: It would be nice to be able to send the argument to the
3854 // DiagnosticsEngine, so that extra values, position, and so on could be
3856 if (!A->isClaimed()) {
3857 if (A->getOption().hasFlag(options::NoArgumentUnused))
3860 // Suppress the warning automatically if this is just a flag, and it is an
3861 // instance of an argument we already claimed.
3862 const Option &Opt = A->getOption();
3863 if (Opt.getKind() == Option::FlagClass) {
3864 bool DuplicateClaimed = false;
3866 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3867 if (AA->isClaimed()) {
3868 DuplicateClaimed = true;
3873 if (DuplicateClaimed)
3877 // In clang-cl, don't mention unknown arguments here since they have
3878 // already been warned about.
3879 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3880 Diag(clang::diag::warn_drv_unused_argument)
3881 << A->getAsString(C.getArgs());
3887 /// Utility class to control the collapse of dependent actions and select the
3888 /// tools accordingly.
3889 class ToolSelector final {
3890 /// The tool chain this selector refers to.
3891 const ToolChain &TC;
3893 /// The compilation this selector refers to.
3894 const Compilation &C;
3896 /// The base action this selector refers to.
3897 const JobAction *BaseAction;
3899 /// Set to true if the current toolchain refers to host actions.
3900 bool IsHostSelector;
3902 /// Set to true if save-temps and embed-bitcode functionalities are active.
3906 /// Get previous dependent action or null if that does not exist. If
3907 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3908 /// null will be returned.
3909 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3910 ActionList &SavedOffloadAction,
3911 bool CanBeCollapsed = true) {
3912 // An option can be collapsed only if it has a single input.
3913 if (Inputs.size() != 1)
3916 Action *CurAction = *Inputs.begin();
3917 if (CanBeCollapsed &&
3918 !CurAction->isCollapsingWithNextDependentActionLegal())
3921 // If the input action is an offload action. Look through it and save any
3922 // offload action that can be dropped in the event of a collapse.
3923 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3924 // If the dependent action is a device action, we will attempt to collapse
3925 // only with other device actions. Otherwise, we would do the same but
3926 // with host actions only.
3927 if (!IsHostSelector) {
3928 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3930 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3931 if (CanBeCollapsed &&
3932 !CurAction->isCollapsingWithNextDependentActionLegal())
3934 SavedOffloadAction.push_back(OA);
3935 return dyn_cast<JobAction>(CurAction);
3937 } else if (OA->hasHostDependence()) {
3938 CurAction = OA->getHostDependence();
3939 if (CanBeCollapsed &&
3940 !CurAction->isCollapsingWithNextDependentActionLegal())
3942 SavedOffloadAction.push_back(OA);
3943 return dyn_cast<JobAction>(CurAction);
3948 return dyn_cast<JobAction>(CurAction);
3951 /// Return true if an assemble action can be collapsed.
3952 bool canCollapseAssembleAction() const {
3953 return TC.useIntegratedAs() && !SaveTemps &&
3954 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3955 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3956 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3959 /// Return true if a preprocessor action can be collapsed.
3960 bool canCollapsePreprocessorAction() const {
3961 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3962 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3963 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3966 /// Struct that relates an action with the offload actions that would be
3967 /// collapsed with it.
3968 struct JobActionInfo final {
3969 /// The action this info refers to.
3970 const JobAction *JA = nullptr;
3971 /// The offload actions we need to take care off if this action is
3973 ActionList SavedOffloadAction;
3976 /// Append collapsed offload actions from the give nnumber of elements in the
3977 /// action info array.
3978 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3979 ArrayRef<JobActionInfo> &ActionInfo,
3980 unsigned ElementNum) {
3981 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3982 for (unsigned I = 0; I < ElementNum; ++I)
3983 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3984 ActionInfo[I].SavedOffloadAction.end());
3987 /// Functions that attempt to perform the combining. They detect if that is
3988 /// legal, and if so they update the inputs \a Inputs and the offload action
3989 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3990 /// the combined action is returned. If the combining is not legal or if the
3991 /// tool does not exist, null is returned.
3992 /// Currently three kinds of collapsing are supported:
3993 /// - Assemble + Backend + Compile;
3994 /// - Assemble + Backend ;
3995 /// - Backend + Compile.
3997 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3999 ActionList &CollapsedOffloadAction) {
4000 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
4002 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4003 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4004 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
4005 if (!AJ || !BJ || !CJ)
4008 // Get compiler tool.
4009 const Tool *T = TC.SelectTool(*CJ);
4013 // When using -fembed-bitcode, it is required to have the same tool (clang)
4014 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
4016 const Tool *BT = TC.SelectTool(*BJ);
4021 if (!T->hasIntegratedAssembler())
4024 Inputs = CJ->getInputs();
4025 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4029 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4031 ActionList &CollapsedOffloadAction) {
4032 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4034 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4035 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4039 // Get backend tool.
4040 const Tool *T = TC.SelectTool(*BJ);
4044 if (!T->hasIntegratedAssembler())
4047 Inputs = BJ->getInputs();
4048 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4052 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4054 ActionList &CollapsedOffloadAction) {
4055 if (ActionInfo.size() < 2)
4057 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4058 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4062 // Check if the initial input (to the compile job or its predessor if one
4063 // exists) is LLVM bitcode. In that case, no preprocessor step is required
4064 // and we can still collapse the compile and backend jobs when we have
4065 // -save-temps. I.e. there is no need for a separate compile job just to
4066 // emit unoptimized bitcode.
4067 bool InputIsBitcode = true;
4068 for (size_t i = 1; i < ActionInfo.size(); i++)
4069 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4070 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4071 InputIsBitcode = false;
4074 if (!InputIsBitcode && !canCollapsePreprocessorAction())
4077 // Get compiler tool.
4078 const Tool *T = TC.SelectTool(*CJ);
4082 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4085 Inputs = CJ->getInputs();
4086 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4091 /// Updates the inputs if the obtained tool supports combining with
4092 /// preprocessor action, and the current input is indeed a preprocessor
4093 /// action. If combining results in the collapse of offloading actions, those
4094 /// are appended to \a CollapsedOffloadAction.
4095 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4096 ActionList &CollapsedOffloadAction) {
4097 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4100 // Attempt to get a preprocessor action dependence.
4101 ActionList PreprocessJobOffloadActions;
4102 ActionList NewInputs;
4103 for (Action *A : Inputs) {
4104 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4105 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4106 NewInputs.push_back(A);
4110 // This is legal to combine. Append any offload action we found and add the
4111 // current input to preprocessor inputs.
4112 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
4113 PreprocessJobOffloadActions.end());
4114 NewInputs.append(PJ->input_begin(), PJ->input_end());
4120 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
4121 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
4122 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
4123 EmbedBitcode(EmbedBitcode) {
4124 assert(BaseAction && "Invalid base action.");
4125 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
4128 /// Check if a chain of actions can be combined and return the tool that can
4129 /// handle the combination of actions. The pointer to the current inputs \a
4130 /// Inputs and the list of offload actions \a CollapsedOffloadActions
4131 /// connected to collapsed actions are updated accordingly. The latter enables
4132 /// the caller of the selector to process them afterwards instead of just
4133 /// dropping them. If no suitable tool is found, null will be returned.
4134 const Tool *getTool(ActionList &Inputs,
4135 ActionList &CollapsedOffloadAction) {
4137 // Get the largest chain of actions that we could combine.
4140 SmallVector<JobActionInfo, 5> ActionChain(1);
4141 ActionChain.back().JA = BaseAction;
4142 while (ActionChain.back().JA) {
4143 const Action *CurAction = ActionChain.back().JA;
4145 // Grow the chain by one element.
4146 ActionChain.resize(ActionChain.size() + 1);
4147 JobActionInfo &AI = ActionChain.back();
4149 // Attempt to fill it with the
4151 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
4154 // Pop the last action info as it could not be filled.
4155 ActionChain.pop_back();
4158 // Attempt to combine actions. If all combining attempts failed, just return
4159 // the tool of the provided action. At the end we attempt to combine the
4160 // action with any preprocessor action it may depend on.
4163 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
4164 CollapsedOffloadAction);
4166 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
4168 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
4170 Inputs = BaseAction->getInputs();
4171 T = TC.SelectTool(*BaseAction);
4174 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
4180 /// Return a string that uniquely identifies the result of a job. The bound arch
4181 /// is not necessarily represented in the toolchain's triple -- for example,
4182 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
4183 /// Also, we need to add the offloading device kind, as the same tool chain can
4184 /// be used for host and device for some programming models, e.g. OpenMP.
4185 static std::string GetTriplePlusArchString(const ToolChain *TC,
4186 StringRef BoundArch,
4187 Action::OffloadKind OffloadKind) {
4188 std::string TriplePlusArch = TC->getTriple().normalize();
4189 if (!BoundArch.empty()) {
4190 TriplePlusArch += "-";
4191 TriplePlusArch += BoundArch;
4193 TriplePlusArch += "-";
4194 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
4195 return TriplePlusArch;
4198 InputInfo Driver::BuildJobsForAction(
4199 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4200 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4201 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4202 Action::OffloadKind TargetDeviceOffloadKind) const {
4203 std::pair<const Action *, std::string> ActionTC = {
4204 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4205 auto CachedResult = CachedResults.find(ActionTC);
4206 if (CachedResult != CachedResults.end()) {
4207 return CachedResult->second;
4209 InputInfo Result = BuildJobsForActionNoCache(
4210 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
4211 CachedResults, TargetDeviceOffloadKind);
4212 CachedResults[ActionTC] = Result;
4216 InputInfo Driver::BuildJobsForActionNoCache(
4217 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4218 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4219 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4220 Action::OffloadKind TargetDeviceOffloadKind) const {
4221 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4223 InputInfoList OffloadDependencesInputInfo;
4224 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
4225 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
4226 // The 'Darwin' toolchain is initialized only when its arguments are
4227 // computed. Get the default arguments for OFK_None to ensure that
4228 // initialization is performed before processing the offload action.
4229 // FIXME: Remove when darwin's toolchain is initialized during construction.
4230 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
4232 // The offload action is expected to be used in four different situations.
4234 // a) Set a toolchain/architecture/kind for a host action:
4235 // Host Action 1 -> OffloadAction -> Host Action 2
4237 // b) Set a toolchain/architecture/kind for a device action;
4238 // Device Action 1 -> OffloadAction -> Device Action 2
4240 // c) Specify a device dependence to a host action;
4241 // Device Action 1 _
4243 // Host Action 1 ---> OffloadAction -> Host Action 2
4245 // d) Specify a host dependence to a device action.
4248 // Device Action 1 ---> OffloadAction -> Device Action 2
4250 // For a) and b), we just return the job generated for the dependence. For
4251 // c) and d) we override the current action with the host/device dependence
4252 // if the current toolchain is host/device and set the offload dependences
4253 // info with the jobs obtained from the device/host dependence(s).
4255 // If there is a single device option, just generate the job for it.
4256 if (OA->hasSingleDeviceDependence()) {
4258 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
4259 const char *DepBoundArch) {
4261 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
4262 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
4263 CachedResults, DepA->getOffloadingDeviceKind());
4268 // If 'Action 2' is host, we generate jobs for the device dependences and
4269 // override the current action with the host dependence. Otherwise, we
4270 // generate the host dependences and override the action with the device
4271 // dependence. The dependences can't therefore be a top-level action.
4272 OA->doOnEachDependence(
4273 /*IsHostDependence=*/BuildingForOffloadDevice,
4274 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4275 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4276 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
4277 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
4278 DepA->getOffloadingDeviceKind()));
4281 A = BuildingForOffloadDevice
4282 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
4283 : OA->getHostDependence();
4286 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
4287 // FIXME: It would be nice to not claim this here; maybe the old scheme of
4288 // just using Args was better?
4289 const Arg &Input = IA->getInputArg();
4291 if (Input.getOption().matches(options::OPT_INPUT)) {
4292 const char *Name = Input.getValue();
4293 return InputInfo(A, Name, /* _BaseInput = */ Name);
4295 return InputInfo(A, &Input, /* _BaseInput = */ "");
4298 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
4299 const ToolChain *TC;
4300 StringRef ArchName = BAA->getArchName();
4302 if (!ArchName.empty())
4303 TC = &getToolChain(C.getArgs(),
4304 computeTargetTriple(*this, TargetTriple,
4305 C.getArgs(), ArchName));
4307 TC = &C.getDefaultToolChain();
4309 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
4310 MultipleArchs, LinkingOutput, CachedResults,
4311 TargetDeviceOffloadKind);
4315 ActionList Inputs = A->getInputs();
4317 const JobAction *JA = cast<JobAction>(A);
4318 ActionList CollapsedOffloadActions;
4320 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4321 embedBitcodeInObject() && !isUsingLTO());
4322 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4327 // If we've collapsed action list that contained OffloadAction we
4328 // need to build jobs for host/device-side inputs it may have held.
4329 for (const auto *OA : CollapsedOffloadActions)
4330 cast<OffloadAction>(OA)->doOnEachDependence(
4331 /*IsHostDependence=*/BuildingForOffloadDevice,
4332 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4333 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4334 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4335 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4336 DepA->getOffloadingDeviceKind()));
4339 // Only use pipes when there is exactly one input.
4340 InputInfoList InputInfos;
4341 for (const Action *Input : Inputs) {
4342 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4343 // shouldn't get temporary output names.
4344 // FIXME: Clean this up.
4345 bool SubJobAtTopLevel =
4346 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
4347 InputInfos.push_back(BuildJobsForAction(
4348 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4349 CachedResults, A->getOffloadingDeviceKind()));
4352 // Always use the first input as the base input.
4353 const char *BaseInput = InputInfos[0].getBaseInput();
4355 // ... except dsymutil actions, which use their actual input as the base
4357 if (JA->getType() == types::TY_dSYM)
4358 BaseInput = InputInfos[0].getFilename();
4360 // ... and in header module compilations, which use the module name.
4361 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4362 BaseInput = ModuleJA->getModuleName();
4364 // Append outputs of offload device jobs to the input list
4365 if (!OffloadDependencesInputInfo.empty())
4366 InputInfos.append(OffloadDependencesInputInfo.begin(),
4367 OffloadDependencesInputInfo.end());
4369 // Set the effective triple of the toolchain for the duration of this job.
4370 llvm::Triple EffectiveTriple;
4371 const ToolChain &ToolTC = T->getToolChain();
4372 const ArgList &Args =
4373 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4374 if (InputInfos.size() != 1) {
4375 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4377 // Pass along the input type if it can be unambiguously determined.
4378 EffectiveTriple = llvm::Triple(
4379 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4381 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4383 // Determine the place to write output to, if any.
4385 InputInfoList UnbundlingResults;
4386 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4387 // If we have an unbundling job, we need to create results for all the
4388 // outputs. We also update the results cache so that other actions using
4389 // this unbundling action can get the right results.
4390 for (auto &UI : UA->getDependentActionsInfo()) {
4391 assert(UI.DependentOffloadKind != Action::OFK_None &&
4392 "Unbundling with no offloading??");
4394 // Unbundling actions are never at the top level. When we generate the
4395 // offloading prefix, we also do that for the host file because the
4396 // unbundling action does not change the type of the output which can
4397 // cause a overwrite.
4398 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4399 UI.DependentOffloadKind,
4400 UI.DependentToolChain->getTriple().normalize(),
4401 /*CreatePrefixForHost=*/true);
4402 auto CurI = InputInfo(
4404 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4405 /*AtTopLevel=*/false,
4407 UI.DependentOffloadKind == Action::OFK_HIP,
4410 // Save the unbundling result.
4411 UnbundlingResults.push_back(CurI);
4413 // Get the unique string identifier for this dependence and cache the
4416 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4417 if (UI.DependentOffloadKind == Action::OFK_Host)
4420 Arch = UI.DependentBoundArch;
4424 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4425 UI.DependentOffloadKind)}] =
4429 // Now that we have all the results generated, select the one that should be
4430 // returned for the current depending action.
4431 std::pair<const Action *, std::string> ActionTC = {
4432 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4433 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4434 "Result does not exist??");
4435 Result = CachedResults[ActionTC];
4436 } else if (JA->getType() == types::TY_Nothing)
4437 Result = InputInfo(A, BaseInput);
4439 // We only have to generate a prefix for the host if this is not a top-level
4441 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4442 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4443 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4445 if (isa<OffloadWrapperJobAction>(JA)) {
4446 OffloadingPrefix += "-wrapper";
4447 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4448 BaseInput = FinalOutput->getValue();
4450 BaseInput = getDefaultImageName();
4452 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4453 AtTopLevel, MultipleArchs,
4458 if (CCCPrintBindings && !CCGenDiagnostics) {
4459 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4460 << " - \"" << T->getName() << "\", inputs: [";
4461 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4462 llvm::errs() << InputInfos[i].getAsString();
4464 llvm::errs() << ", ";
4466 if (UnbundlingResults.empty())
4467 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4469 llvm::errs() << "], outputs: [";
4470 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4471 llvm::errs() << UnbundlingResults[i].getAsString();
4473 llvm::errs() << ", ";
4475 llvm::errs() << "] \n";
4478 if (UnbundlingResults.empty())
4480 C, *JA, Result, InputInfos,
4481 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4484 T->ConstructJobMultipleOutputs(
4485 C, *JA, UnbundlingResults, InputInfos,
4486 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4492 const char *Driver::getDefaultImageName() const {
4493 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4494 return Target.isOSWindows() ? "a.exe" : "a.out";
4497 /// Create output filename based on ArgValue, which could either be a
4498 /// full filename, filename without extension, or a directory. If ArgValue
4499 /// does not provide a filename, then use BaseName, and use the extension
4500 /// suitable for FileType.
4501 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4503 types::ID FileType) {
4504 SmallString<128> Filename = ArgValue;
4506 if (ArgValue.empty()) {
4507 // If the argument is empty, output to BaseName in the current dir.
4508 Filename = BaseName;
4509 } else if (llvm::sys::path::is_separator(Filename.back())) {
4510 // If the argument is a directory, output to BaseName in that dir.
4511 llvm::sys::path::append(Filename, BaseName);
4514 if (!llvm::sys::path::has_extension(ArgValue)) {
4515 // If the argument didn't provide an extension, then set it.
4516 const char *Extension = types::getTypeTempSuffix(FileType, true);
4518 if (FileType == types::TY_Image &&
4519 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4520 // The output file is a dll.
4524 llvm::sys::path::replace_extension(Filename, Extension);
4527 return Args.MakeArgString(Filename.c_str());
4530 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4531 const char *BaseInput,
4532 StringRef BoundArch, bool AtTopLevel,
4534 StringRef OffloadingPrefix) const {
4535 llvm::PrettyStackTraceString CrashInfo("Computing output path");
4536 // Output to a user requested destination?
4537 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
4538 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4539 return C.addResultFile(FinalOutput->getValue(), &JA);
4542 // For /P, preprocess to file named after BaseInput.
4543 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4544 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4545 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4547 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4548 NameArg = A->getValue();
4549 return C.addResultFile(
4550 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4554 // Default to writing to stdout?
4555 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
4558 // Is this the assembly listing for /FA?
4559 if (JA.getType() == types::TY_PP_Asm &&
4560 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4561 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4562 // Use /Fa and the input filename to determine the asm file name.
4563 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4564 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4565 return C.addResultFile(
4566 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4570 // Output to a temporary file?
4571 if ((!AtTopLevel && !isSaveTempsEnabled() &&
4572 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4574 StringRef Name = llvm::sys::path::filename(BaseInput);
4575 std::pair<StringRef, StringRef> Split = Name.split('.');
4576 SmallString<128> TmpName;
4577 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4578 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4579 if (CCGenDiagnostics && A) {
4580 SmallString<128> CrashDirectory(A->getValue());
4581 if (!getVFS().exists(CrashDirectory))
4582 llvm::sys::fs::create_directories(CrashDirectory);
4583 llvm::sys::path::append(CrashDirectory, Split.first);
4584 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4585 std::error_code EC = llvm::sys::fs::createUniqueFile(
4586 CrashDirectory + Middle + Suffix, TmpName);
4588 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4592 TmpName = GetTemporaryPath(Split.first, Suffix);
4594 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4597 SmallString<128> BasePath(BaseInput);
4600 // Dsymutil actions should use the full path.
4601 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4602 BaseName = BasePath;
4604 BaseName = llvm::sys::path::filename(BasePath);
4606 // Determine what the derived output name should be.
4607 const char *NamedOutput;
4609 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4610 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4611 // The /Fo or /o flag decides the object filename.
4614 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4617 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4618 } else if (JA.getType() == types::TY_Image &&
4619 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4620 options::OPT__SLASH_o)) {
4621 // The /Fe or /o flag names the linked file.
4624 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4627 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4628 } else if (JA.getType() == types::TY_Image) {
4630 // clang-cl uses BaseName for the executable name.
4632 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4634 SmallString<128> Output(getDefaultImageName());
4635 // HIP image for device compilation with -fno-gpu-rdc is per compilation
4637 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4638 !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
4639 options::OPT_fno_gpu_rdc, false);
4642 llvm::sys::path::replace_extension(Output, "");
4644 Output += OffloadingPrefix;
4645 if (MultipleArchs && !BoundArch.empty()) {
4647 Output.append(BoundArch);
4651 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4653 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
4654 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4656 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4657 assert(Suffix && "All types used for output should have a suffix.");
4659 std::string::size_type End = std::string::npos;
4660 if (!types::appendSuffixForType(JA.getType()))
4661 End = BaseName.rfind('.');
4662 SmallString<128> Suffixed(BaseName.substr(0, End));
4663 Suffixed += OffloadingPrefix;
4664 if (MultipleArchs && !BoundArch.empty()) {
4666 Suffixed.append(BoundArch);
4668 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4669 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4670 // optimized bitcode output.
4671 auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
4672 const llvm::opt::DerivedArgList &Args) {
4673 // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
4674 // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
4676 return isa<CompileJobAction>(JA) &&
4677 JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4678 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4681 if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
4682 (C.getArgs().hasArg(options::OPT_emit_llvm) ||
4683 IsHIPRDCInCompilePhase(JA, C.getArgs())))
4687 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4690 // Prepend object file path if -save-temps=obj
4691 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4692 JA.getType() != types::TY_PCH) {
4693 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4694 SmallString<128> TempPath(FinalOutput->getValue());
4695 llvm::sys::path::remove_filename(TempPath);
4696 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4697 llvm::sys::path::append(TempPath, OutputFileName);
4698 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4701 // If we're saving temps and the temp file conflicts with the input file,
4702 // then avoid overwriting input file.
4703 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
4704 bool SameFile = false;
4705 SmallString<256> Result;
4706 llvm::sys::fs::current_path(Result);
4707 llvm::sys::path::append(Result, BaseName);
4708 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4709 // Must share the same path to conflict.
4711 StringRef Name = llvm::sys::path::filename(BaseInput);
4712 std::pair<StringRef, StringRef> Split = Name.split('.');
4713 std::string TmpName = GetTemporaryPath(
4714 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4715 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4719 // As an annoying special case, PCH generation doesn't strip the pathname.
4720 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
4721 llvm::sys::path::remove_filename(BasePath);
4722 if (BasePath.empty())
4723 BasePath = NamedOutput;
4725 llvm::sys::path::append(BasePath, NamedOutput);
4726 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4728 return C.addResultFile(NamedOutput, &JA);
4732 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4733 // Search for Name in a list of paths.
4734 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4735 -> llvm::Optional<std::string> {
4736 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4737 // attempting to use this prefix when looking for file paths.
4738 for (const auto &Dir : P) {
4741 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4742 llvm::sys::path::append(P, Name);
4743 if (llvm::sys::fs::exists(Twine(P)))
4744 return std::string(P);
4749 if (auto P = SearchPaths(PrefixDirs))
4752 SmallString<128> R(ResourceDir);
4753 llvm::sys::path::append(R, Name);
4754 if (llvm::sys::fs::exists(Twine(R)))
4755 return std::string(R.str());
4757 SmallString<128> P(TC.getCompilerRTPath());
4758 llvm::sys::path::append(P, Name);
4759 if (llvm::sys::fs::exists(Twine(P)))
4760 return std::string(P.str());
4762 SmallString<128> D(Dir);
4763 llvm::sys::path::append(D, "..", Name);
4764 if (llvm::sys::fs::exists(Twine(D)))
4765 return std::string(D.str());
4767 if (auto P = SearchPaths(TC.getLibraryPaths()))
4770 if (auto P = SearchPaths(TC.getFilePaths()))
4773 return std::string(Name);
4776 void Driver::generatePrefixedToolNames(
4777 StringRef Tool, const ToolChain &TC,
4778 SmallVectorImpl<std::string> &Names) const {
4779 // FIXME: Needs a better variable than TargetTriple
4780 Names.emplace_back((TargetTriple + "-" + Tool).str());
4781 Names.emplace_back(Tool);
4783 // Allow the discovery of tools prefixed with LLVM's default target triple.
4784 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4785 if (DefaultTargetTriple != TargetTriple)
4786 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4789 static bool ScanDirForExecutable(SmallString<128> &Dir,
4790 const std::string &Name) {
4791 llvm::sys::path::append(Dir, Name);
4792 if (llvm::sys::fs::can_execute(Twine(Dir)))
4794 llvm::sys::path::remove_filename(Dir);
4798 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4799 SmallVector<std::string, 2> TargetSpecificExecutables;
4800 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4802 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4803 // attempting to use this prefix when looking for program paths.
4804 for (const auto &PrefixDir : PrefixDirs) {
4805 if (llvm::sys::fs::is_directory(PrefixDir)) {
4806 SmallString<128> P(PrefixDir);
4807 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4808 if (ScanDirForExecutable(P, TargetSpecificExecutable))
4809 return std::string(P.str());
4811 SmallString<128> P((PrefixDir + Name).str());
4812 if (llvm::sys::fs::can_execute(Twine(P)))
4813 return std::string(P.str());
4817 const ToolChain::path_list &List = TC.getProgramPaths();
4818 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
4819 // For each possible name of the tool look for it in
4820 // program paths first, then the path.
4821 // Higher priority names will be first, meaning that
4822 // a higher priority name in the path will be found
4823 // instead of a lower priority name in the program path.
4824 // E.g. <triple>-gcc on the path will be found instead
4825 // of gcc in the program path
4826 for (const auto &Path : List) {
4827 SmallString<128> P(Path);
4828 if (ScanDirForExecutable(P, TargetSpecificExecutable))
4829 return std::string(P.str());
4832 // Fall back to the path
4833 if (llvm::ErrorOr<std::string> P =
4834 llvm::sys::findProgramByName(TargetSpecificExecutable))
4838 return std::string(Name);
4841 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
4842 SmallString<128> Path;
4843 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
4845 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4849 return std::string(Path.str());
4852 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4853 SmallString<128> Path;
4854 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4856 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4860 return std::string(Path.str());
4863 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4864 SmallString<128> Output;
4865 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4866 // FIXME: If anybody needs it, implement this obscure rule:
4867 // "If you specify a directory without a file name, the default file name
4868 // is VCx0.pch., where x is the major version of Visual C++ in use."
4869 Output = FpArg->getValue();
4871 // "If you do not specify an extension as part of the path name, an
4872 // extension of .pch is assumed. "
4873 if (!llvm::sys::path::has_extension(Output))
4876 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4877 Output = YcArg->getValue();
4880 llvm::sys::path::replace_extension(Output, ".pch");
4882 return std::string(Output.str());
4885 const ToolChain &Driver::getToolChain(const ArgList &Args,
4886 const llvm::Triple &Target) const {
4888 auto &TC = ToolChains[Target.str()];
4890 switch (Target.getOS()) {
4891 case llvm::Triple::AIX:
4892 TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
4894 case llvm::Triple::Haiku:
4895 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
4897 case llvm::Triple::Ananas:
4898 TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
4900 case llvm::Triple::CloudABI:
4901 TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
4903 case llvm::Triple::Darwin:
4904 case llvm::Triple::MacOSX:
4905 case llvm::Triple::IOS:
4906 case llvm::Triple::TvOS:
4907 case llvm::Triple::WatchOS:
4908 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
4910 case llvm::Triple::DragonFly:
4911 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
4913 case llvm::Triple::OpenBSD:
4914 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
4916 case llvm::Triple::NetBSD:
4917 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
4919 case llvm::Triple::FreeBSD:
4920 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
4922 case llvm::Triple::Minix:
4923 TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
4925 case llvm::Triple::Linux:
4926 case llvm::Triple::ELFIAMCU:
4927 if (Target.getArch() == llvm::Triple::hexagon)
4928 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
4930 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4931 !Target.hasEnvironment())
4932 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4934 else if (Target.getArch() == llvm::Triple::ppc ||
4935 Target.getArch() == llvm::Triple::ppc64 ||
4936 Target.getArch() == llvm::Triple::ppc64le)
4937 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
4939 else if (Target.getArch() == llvm::Triple::ve)
4940 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
4943 TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
4945 case llvm::Triple::NaCl:
4946 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
4948 case llvm::Triple::Fuchsia:
4949 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
4951 case llvm::Triple::Solaris:
4952 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
4954 case llvm::Triple::AMDHSA:
4955 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
4957 case llvm::Triple::AMDPAL:
4958 case llvm::Triple::Mesa3D:
4959 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
4961 case llvm::Triple::Win32:
4962 switch (Target.getEnvironment()) {
4964 if (Target.isOSBinFormatELF())
4965 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4966 else if (Target.isOSBinFormatMachO())
4967 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
4969 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4971 case llvm::Triple::GNU:
4972 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
4974 case llvm::Triple::Itanium:
4975 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4978 case llvm::Triple::MSVC:
4979 case llvm::Triple::UnknownEnvironment:
4980 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4981 .startswith_lower("bfd"))
4982 TC = std::make_unique<toolchains::CrossWindowsToolChain>(
4983 *this, Target, Args);
4986 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
4990 case llvm::Triple::PS4:
4991 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
4993 case llvm::Triple::Contiki:
4994 TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
4996 case llvm::Triple::Hurd:
4997 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
5000 // Of these targets, Hexagon is the only one that might have
5001 // an OS of Linux, in which case it got handled above already.
5002 switch (Target.getArch()) {
5003 case llvm::Triple::tce:
5004 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
5006 case llvm::Triple::tcele:
5007 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
5009 case llvm::Triple::hexagon:
5010 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5013 case llvm::Triple::lanai:
5014 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
5016 case llvm::Triple::xcore:
5017 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
5019 case llvm::Triple::wasm32:
5020 case llvm::Triple::wasm64:
5021 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
5023 case llvm::Triple::avr:
5024 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
5026 case llvm::Triple::msp430:
5028 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
5030 case llvm::Triple::riscv32:
5031 case llvm::Triple::riscv64:
5032 TC = std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
5034 case llvm::Triple::ve:
5035 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5038 if (Target.getVendor() == llvm::Triple::Myriad)
5039 TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
5041 else if (toolchains::BareMetal::handlesTarget(Target))
5042 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
5043 else if (Target.isOSBinFormatELF())
5044 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5045 else if (Target.isOSBinFormatMachO())
5046 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5048 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5053 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
5054 // compiles always need two toolchains, the CUDA toolchain and the host
5055 // toolchain. So the only valid way to create a CUDA toolchain is via
5056 // CreateOffloadingDeviceToolChains.
5061 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
5062 // Say "no" if there is not exactly one input of a type clang understands.
5063 if (JA.size() != 1 ||
5064 !types::isAcceptedByClang((*JA.input_begin())->getType()))
5067 // And say "no" if this is not a kind of action clang understands.
5068 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
5069 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5075 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
5076 // Say "no" if there is not exactly one input of a type flang understands.
5077 if (JA.size() != 1 ||
5078 !types::isFortran((*JA.input_begin())->getType()))
5081 // And say "no" if this is not a kind of action flang understands.
5082 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5088 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
5089 // Only emit static library if the flag is set explicitly.
5090 if (Args.hasArg(options::OPT_emit_static_lib))
5095 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
5096 /// grouped values as integers. Numbers which are not provided are set to 0.
5098 /// \return True if the entire string was parsed (9.2), or all groups were
5099 /// parsed (10.3.5extrastuff).
5100 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
5101 unsigned &Micro, bool &HadExtra) {
5104 Major = Minor = Micro = 0;
5108 if (Str.consumeInteger(10, Major))
5115 Str = Str.drop_front(1);
5117 if (Str.consumeInteger(10, Minor))
5123 Str = Str.drop_front(1);
5125 if (Str.consumeInteger(10, Micro))
5132 /// Parse digits from a string \p Str and fulfill \p Digits with
5133 /// the parsed numbers. This method assumes that the max number of
5134 /// digits to look for is equal to Digits.size().
5136 /// \return True if the entire string was parsed and there are
5137 /// no extra characters remaining at the end.
5138 bool Driver::GetReleaseVersion(StringRef Str,
5139 MutableArrayRef<unsigned> Digits) {
5143 unsigned CurDigit = 0;
5144 while (CurDigit < Digits.size()) {
5146 if (Str.consumeInteger(10, Digit))
5148 Digits[CurDigit] = Digit;
5153 Str = Str.drop_front(1);
5157 // More digits than requested, bail out...
5161 std::pair<unsigned, unsigned>
5162 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
5163 unsigned IncludedFlagsBitmask = 0;
5164 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
5166 if (IsClCompatMode) {
5167 // Include CL and Core options.
5168 IncludedFlagsBitmask |= options::CLOption;
5169 IncludedFlagsBitmask |= options::CoreOption;
5171 ExcludedFlagsBitmask |= options::CLOption;
5174 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
5177 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
5178 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
5181 bool clang::driver::willEmitRemarks(const ArgList &Args) {
5182 // -fsave-optimization-record enables it.
5183 if (Args.hasFlag(options::OPT_fsave_optimization_record,
5184 options::OPT_fno_save_optimization_record, false))
5187 // -fsave-optimization-record=<format> enables it as well.
5188 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5189 options::OPT_fno_save_optimization_record, false))
5192 // -foptimization-record-file alone enables it too.
5193 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
5194 options::OPT_fno_save_optimization_record, false))
5197 // -foptimization-record-passes alone enables it too.
5198 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5199 options::OPT_fno_save_optimization_record, false))