1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Driver/Driver.h"
11 #include "InputInfo.h"
12 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Bitrig.h"
15 #include "ToolChains/Clang.h"
16 #include "ToolChains/CloudABI.h"
17 #include "ToolChains/Contiki.h"
18 #include "ToolChains/CrossWindows.h"
19 #include "ToolChains/Cuda.h"
20 #include "ToolChains/Darwin.h"
21 #include "ToolChains/DragonFly.h"
22 #include "ToolChains/FreeBSD.h"
23 #include "ToolChains/Fuchsia.h"
24 #include "ToolChains/Gnu.h"
25 #include "ToolChains/Haiku.h"
26 #include "ToolChains/Hexagon.h"
27 #include "ToolChains/Lanai.h"
28 #include "ToolChains/Linux.h"
29 #include "ToolChains/MinGW.h"
30 #include "ToolChains/Minix.h"
31 #include "ToolChains/MipsLinux.h"
32 #include "ToolChains/MSVC.h"
33 #include "ToolChains/Myriad.h"
34 #include "ToolChains/NaCl.h"
35 #include "ToolChains/NetBSD.h"
36 #include "ToolChains/OpenBSD.h"
37 #include "ToolChains/PS4CPU.h"
38 #include "ToolChains/Solaris.h"
39 #include "ToolChains/TCE.h"
40 #include "ToolChains/WebAssembly.h"
41 #include "ToolChains/XCore.h"
42 #include "clang/Basic/Version.h"
43 #include "clang/Basic/VirtualFileSystem.h"
44 #include "clang/Config/config.h"
45 #include "clang/Driver/Action.h"
46 #include "clang/Driver/Compilation.h"
47 #include "clang/Driver/DriverDiagnostic.h"
48 #include "clang/Driver/Job.h"
49 #include "clang/Driver/Options.h"
50 #include "clang/Driver/SanitizerArgs.h"
51 #include "clang/Driver/Tool.h"
52 #include "clang/Driver/ToolChain.h"
53 #include "llvm/ADT/ArrayRef.h"
54 #include "llvm/ADT/STLExtras.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/ADT/StringSet.h"
58 #include "llvm/ADT/StringSwitch.h"
59 #include "llvm/Option/Arg.h"
60 #include "llvm/Option/ArgList.h"
61 #include "llvm/Option/OptSpecifier.h"
62 #include "llvm/Option/OptTable.h"
63 #include "llvm/Option/Option.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/FileSystem.h"
66 #include "llvm/Support/Path.h"
67 #include "llvm/Support/PrettyStackTrace.h"
68 #include "llvm/Support/Process.h"
69 #include "llvm/Support/Program.h"
70 #include "llvm/Support/raw_ostream.h"
75 #include <unistd.h> // getpid
78 using namespace clang::driver;
79 using namespace clang;
80 using namespace llvm::opt;
82 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
83 DiagnosticsEngine &Diags,
84 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
85 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
86 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
87 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
88 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
89 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
90 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
91 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
92 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
93 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
94 GenReproducer(false), SuppressMissingInputWarning(false) {
96 // Provide a sane fallback if no VFS is specified.
98 this->VFS = vfs::getRealFileSystem();
100 Name = llvm::sys::path::filename(ClangExecutable);
101 Dir = llvm::sys::path::parent_path(ClangExecutable);
102 InstalledDir = Dir; // Provide a sensible default installed dir.
104 // Compute the path to the resource directory.
105 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
106 SmallString<128> P(Dir);
107 if (ClangResourceDir != "") {
108 llvm::sys::path::append(P, ClangResourceDir);
110 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
111 P = llvm::sys::path::parent_path(Dir);
112 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
113 CLANG_VERSION_STRING);
115 ResourceDir = P.str();
118 void Driver::ParseDriverMode(StringRef ProgramName,
119 ArrayRef<const char *> Args) {
120 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
121 StringRef DefaultMode(Default.second);
122 setDriverModeFromOption(DefaultMode);
124 for (const char *ArgPtr : Args) {
125 // Ingore nullptrs, they are response file's EOL markers
126 if (ArgPtr == nullptr)
128 const StringRef Arg = ArgPtr;
129 setDriverModeFromOption(Arg);
133 void Driver::setDriverModeFromOption(StringRef Opt) {
134 const std::string OptName =
135 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
136 if (!Opt.startswith(OptName))
138 StringRef Value = Opt.drop_front(OptName.size());
140 const unsigned M = llvm::StringSwitch<unsigned>(Value)
141 .Case("gcc", GCCMode)
142 .Case("g++", GXXMode)
143 .Case("cpp", CPPMode)
148 Mode = static_cast<DriverMode>(M);
150 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
153 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
154 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
156 unsigned IncludedFlagsBitmask;
157 unsigned ExcludedFlagsBitmask;
158 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
159 getIncludeExcludeOptionFlagMasks();
161 unsigned MissingArgIndex, MissingArgCount;
163 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
164 IncludedFlagsBitmask, ExcludedFlagsBitmask);
166 // Check for missing argument error.
168 Diag(clang::diag::err_drv_missing_argument)
169 << Args.getArgString(MissingArgIndex) << MissingArgCount;
171 // Check for unsupported options.
172 for (const Arg *A : Args) {
173 if (A->getOption().hasFlag(options::Unsupported)) {
174 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
178 // Warn about -mcpu= without an argument.
179 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
180 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
184 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
185 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
186 diag::err_drv_unknown_argument)
187 << A->getAsString(Args);
192 // Determine which compilation mode we are in. We look for options which
193 // affect the phase, starting with the earliest phases, and record which
194 // option we used to determine the final phase.
195 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
196 Arg **FinalPhaseArg) const {
197 Arg *PhaseArg = nullptr;
198 phases::ID FinalPhase;
200 // -{E,EP,P,M,MM} only run the preprocessor.
201 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
202 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
203 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
204 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
205 FinalPhase = phases::Preprocess;
207 // --precompile only runs up to precompilation.
208 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
209 FinalPhase = phases::Precompile;
211 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
212 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
213 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
214 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
215 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
216 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
217 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
218 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
219 options::OPT__analyze_auto)) ||
220 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
221 FinalPhase = phases::Compile;
223 // -S only runs up to the backend.
224 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
225 FinalPhase = phases::Backend;
227 // -c compilation only runs up to the assembler.
228 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
229 FinalPhase = phases::Assemble;
231 // Otherwise do everything.
233 FinalPhase = phases::Link;
236 *FinalPhaseArg = PhaseArg;
241 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
243 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
244 Args.getBaseArgs().MakeIndex(Value), Value.data());
245 Args.AddSynthesizedArg(A);
250 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
251 DerivedArgList *DAL = new DerivedArgList(Args);
253 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
254 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
255 for (Arg *A : Args) {
256 // Unfortunately, we have to parse some forwarding options (-Xassembler,
257 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
258 // (assembler and preprocessor), or bypass a previous driver ('collect2').
260 // Rewrite linker options, to replace --no-demangle with a custom internal
262 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
263 A->getOption().matches(options::OPT_Xlinker)) &&
264 A->containsValue("--no-demangle")) {
265 // Add the rewritten no-demangle argument.
266 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
268 // Add the remaining values as Xlinker arguments.
269 for (StringRef Val : A->getValues())
270 if (Val != "--no-demangle")
271 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
276 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
277 // some build systems. We don't try to be complete here because we don't
278 // care to encourage this usage model.
279 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
280 (A->getValue(0) == StringRef("-MD") ||
281 A->getValue(0) == StringRef("-MMD"))) {
282 // Rewrite to -MD/-MMD along with -MF.
283 if (A->getValue(0) == StringRef("-MD"))
284 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
286 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
287 if (A->getNumValues() == 2)
288 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
293 // Rewrite reserved library names.
294 if (A->getOption().matches(options::OPT_l)) {
295 StringRef Value = A->getValue();
297 // Rewrite unless -nostdlib is present.
298 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
299 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
303 // Rewrite unconditionally.
304 if (Value == "cc_kext") {
305 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
310 // Pick up inputs via the -- option.
311 if (A->getOption().matches(options::OPT__DASH_DASH)) {
313 for (StringRef Val : A->getValues())
314 DAL->append(MakeInputArg(*DAL, *Opts, Val));
321 // Enforce -static if -miamcu is present.
322 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
323 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
325 // Add a default value of -mlinker-version=, if one was given and the user
326 // didn't specify one.
327 #if defined(HOST_LINK_VERSION)
328 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
329 strlen(HOST_LINK_VERSION) > 0) {
330 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
332 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
339 /// \brief Compute target triple from args.
341 /// This routine provides the logic to compute a target triple from various
342 /// args passed to the driver and the default triple string.
343 static llvm::Triple computeTargetTriple(const Driver &D,
344 StringRef DefaultTargetTriple,
346 StringRef DarwinArchName = "") {
347 // FIXME: Already done in Compilation *Driver::BuildCompilation
348 if (const Arg *A = Args.getLastArg(options::OPT_target))
349 DefaultTargetTriple = A->getValue();
351 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
353 // Handle Apple-specific options available here.
354 if (Target.isOSBinFormatMachO()) {
355 // If an explict Darwin arch name is given, that trumps all.
356 if (!DarwinArchName.empty()) {
357 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
361 // Handle the Darwin '-arch' flag.
362 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
363 StringRef ArchName = A->getValue();
364 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
368 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
369 // '-mbig-endian'/'-EB'.
370 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
371 options::OPT_mbig_endian)) {
372 if (A->getOption().matches(options::OPT_mlittle_endian)) {
373 llvm::Triple LE = Target.getLittleEndianArchVariant();
374 if (LE.getArch() != llvm::Triple::UnknownArch)
375 Target = std::move(LE);
377 llvm::Triple BE = Target.getBigEndianArchVariant();
378 if (BE.getArch() != llvm::Triple::UnknownArch)
379 Target = std::move(BE);
383 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
384 if (Target.getArch() == llvm::Triple::tce ||
385 Target.getOS() == llvm::Triple::Minix)
388 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
389 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
390 options::OPT_m32, options::OPT_m16);
392 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
394 if (A->getOption().matches(options::OPT_m64)) {
395 AT = Target.get64BitArchVariant().getArch();
396 if (Target.getEnvironment() == llvm::Triple::GNUX32)
397 Target.setEnvironment(llvm::Triple::GNU);
398 } else if (A->getOption().matches(options::OPT_mx32) &&
399 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
400 AT = llvm::Triple::x86_64;
401 Target.setEnvironment(llvm::Triple::GNUX32);
402 } else if (A->getOption().matches(options::OPT_m32)) {
403 AT = Target.get32BitArchVariant().getArch();
404 if (Target.getEnvironment() == llvm::Triple::GNUX32)
405 Target.setEnvironment(llvm::Triple::GNU);
406 } else if (A->getOption().matches(options::OPT_m16) &&
407 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
408 AT = llvm::Triple::x86;
409 Target.setEnvironment(llvm::Triple::CODE16);
412 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
416 // Handle -miamcu flag.
417 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
418 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
419 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
422 if (A && !A->getOption().matches(options::OPT_m32))
423 D.Diag(diag::err_drv_argument_not_allowed_with)
424 << "-miamcu" << A->getBaseArg().getAsString(Args);
426 Target.setArch(llvm::Triple::x86);
427 Target.setArchName("i586");
428 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
429 Target.setEnvironmentName("");
430 Target.setOS(llvm::Triple::ELFIAMCU);
431 Target.setVendor(llvm::Triple::UnknownVendor);
432 Target.setVendorName("intel");
438 // \brief Parse the LTO options and record the type of LTO compilation
439 // based on which -f(no-)?lto(=.*)? option occurs last.
440 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
442 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
443 options::OPT_fno_lto, false))
446 StringRef LTOName("full");
448 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
450 LTOName = A->getValue();
452 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
453 .Case("full", LTOK_Full)
454 .Case("thin", LTOK_Thin)
455 .Default(LTOK_Unknown);
457 if (LTOMode == LTOK_Unknown) {
459 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
464 /// Compute the desired OpenMP runtime from the flags provided.
465 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
466 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
468 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
470 RuntimeName = A->getValue();
472 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
473 .Case("libomp", OMPRT_OMP)
474 .Case("libgomp", OMPRT_GOMP)
475 .Case("libiomp5", OMPRT_IOMP5)
476 .Default(OMPRT_Unknown);
478 if (RT == OMPRT_Unknown) {
480 Diag(diag::err_drv_unsupported_option_argument)
481 << A->getOption().getName() << A->getValue();
483 // FIXME: We could use a nicer diagnostic here.
484 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
490 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
496 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
497 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
498 return types::isCuda(I.first);
500 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
501 const llvm::Triple &HostTriple = HostTC->getTriple();
502 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
503 : "nvptx-nvidia-cuda");
504 // Use the CUDA and host triples as the key into the ToolChains map, because
505 // the device toolchain we create depends on both.
506 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
508 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
509 *this, CudaTriple, *HostTC, C.getInputArgs());
511 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
517 // We need to generate an OpenMP toolchain if the user specified targets with
518 // the -fopenmp-targets option.
519 if (Arg *OpenMPTargets =
520 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
521 if (OpenMPTargets->getNumValues()) {
522 // We expect that -fopenmp-targets is always used in conjunction with the
523 // option -fopenmp specifying a valid runtime with offloading support,
524 // i.e. libomp or libiomp.
525 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
526 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
527 options::OPT_fno_openmp, false);
528 if (HasValidOpenMPRuntime) {
529 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
530 HasValidOpenMPRuntime =
531 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
534 if (HasValidOpenMPRuntime) {
535 llvm::StringMap<const char *> FoundNormalizedTriples;
536 for (const char *Val : OpenMPTargets->getValues()) {
537 llvm::Triple TT(Val);
538 std::string NormalizedName = TT.normalize();
540 // Make sure we don't have a duplicate triple.
541 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
542 if (Duplicate != FoundNormalizedTriples.end()) {
543 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
544 << Val << Duplicate->second;
548 // Store the current triple so that we can check for duplicates in the
549 // following iterations.
550 FoundNormalizedTriples[NormalizedName] = Val;
552 // If the specified target is invalid, emit a diagnostic.
553 if (TT.getArch() == llvm::Triple::UnknownArch)
554 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
556 const ToolChain &TC = getToolChain(C.getInputArgs(), TT);
557 C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP);
561 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
563 Diag(clang::diag::warn_drv_empty_joined_argument)
564 << OpenMPTargets->getAsString(C.getInputArgs());
568 // TODO: Add support for other offloading programming models here.
574 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
575 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
577 // FIXME: Handle environment options which affect driver behavior, somewhere
578 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
580 if (Optional<std::string> CompilerPathValue =
581 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
582 StringRef CompilerPath = *CompilerPathValue;
583 while (!CompilerPath.empty()) {
584 std::pair<StringRef, StringRef> Split =
585 CompilerPath.split(llvm::sys::EnvPathSeparator);
586 PrefixDirs.push_back(Split.first);
587 CompilerPath = Split.second;
591 // We look for the driver mode option early, because the mode can affect
592 // how other options are parsed.
593 ParseDriverMode(ClangExecutable, ArgList.slice(1));
595 // FIXME: What are we going to do with -V and -b?
597 // FIXME: This stuff needs to go into the Compilation, not the driver.
600 InputArgList Args = ParseArgStrings(ArgList.slice(1));
602 // Silence driver warnings if requested
603 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
605 // -no-canonical-prefixes is used very early in main.
606 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
609 Args.ClaimAllArgs(options::OPT_pipe);
611 // Extract -ccc args.
613 // FIXME: We need to figure out where this behavior should live. Most of it
614 // should be outside in the client; the parts that aren't should have proper
615 // options, either by introducing new ones or by overloading gcc ones like -V
617 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
618 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
619 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
620 CCCGenericGCCName = A->getValue();
622 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
623 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
624 options::OPT_fno_crash_diagnostics,
625 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
626 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
627 // and getToolChain is const.
629 // clang-cl targets MSVC-style Win32.
630 llvm::Triple T(DefaultTargetTriple);
631 T.setOS(llvm::Triple::Win32);
632 T.setVendor(llvm::Triple::PC);
633 T.setEnvironment(llvm::Triple::MSVC);
634 DefaultTargetTriple = T.str();
636 if (const Arg *A = Args.getLastArg(options::OPT_target))
637 DefaultTargetTriple = A->getValue();
638 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
639 Dir = InstalledDir = A->getValue();
640 for (const Arg *A : Args.filtered(options::OPT_B)) {
642 PrefixDirs.push_back(A->getValue(0));
644 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
645 SysRoot = A->getValue();
646 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
647 DyldPrefix = A->getValue();
648 if (Args.hasArg(options::OPT_nostdlib))
651 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
652 ResourceDir = A->getValue();
654 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
655 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
656 .Case("cwd", SaveTempsCwd)
657 .Case("obj", SaveTempsObj)
658 .Default(SaveTempsCwd);
663 // Process -fembed-bitcode= flags.
664 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
665 StringRef Name = A->getValue();
666 unsigned Model = llvm::StringSwitch<unsigned>(Name)
667 .Case("off", EmbedNone)
668 .Case("all", EmbedBitcode)
669 .Case("bitcode", EmbedBitcode)
670 .Case("marker", EmbedMarker)
673 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
676 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
679 std::unique_ptr<llvm::opt::InputArgList> UArgs =
680 llvm::make_unique<InputArgList>(std::move(Args));
682 // Perform the default argument translations.
683 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
685 // Owned by the host.
686 const ToolChain &TC = getToolChain(
687 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
689 // The compilation takes ownership of Args.
690 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
692 if (!HandleImmediateArgs(*C))
695 // Construct the list of inputs.
697 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
699 // Populate the tool chains for the offloading devices, if any.
700 CreateOffloadingDeviceToolChains(*C, Inputs);
702 // Construct the list of abstract actions to perform for this compilation. On
703 // MachO targets this uses the driver-driver and universal actions.
704 if (TC.getTriple().isOSBinFormatMachO())
705 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
707 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
709 if (CCCPrintPhases) {
719 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
720 llvm::opt::ArgStringList ASL;
721 for (const auto *A : Args)
722 A->render(Args, ASL);
724 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
725 if (I != ASL.begin())
727 Command::printArg(OS, *I, true);
732 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
733 SmallString<128> &CrashDiagDir) {
734 using namespace llvm::sys;
735 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
736 "Only knows about .crash files on Darwin");
738 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
739 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
740 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
741 path::home_directory(CrashDiagDir);
742 if (CrashDiagDir.startswith("/var/root"))
744 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
752 fs::file_status FileStatus;
753 TimePoint<> LastAccessTime;
754 SmallString<128> CrashFilePath;
755 // Lookup the .crash files and get the one generated by a subprocess spawned
756 // by this driver invocation.
757 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
758 File != FileEnd && !EC; File.increment(EC)) {
759 StringRef FileName = path::filename(File->path());
760 if (!FileName.startswith(Name))
762 if (fs::status(File->path(), FileStatus))
764 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
765 llvm::MemoryBuffer::getFile(File->path());
768 // The first line should start with "Process:", otherwise this isn't a real
770 StringRef Data = CrashFile.get()->getBuffer();
771 if (!Data.startswith("Process:"))
773 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
774 size_t ParentProcPos = Data.find("Parent Process:");
775 if (ParentProcPos == StringRef::npos)
777 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
778 if (LineEnd == StringRef::npos)
780 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
781 int OpenBracket = -1, CloseBracket = -1;
782 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
783 if (ParentProcess[i] == '[')
785 if (ParentProcess[i] == ']')
788 // Extract the parent process PID from the .crash file and check whether
789 // it matches this driver invocation pid.
791 if (OpenBracket < 0 || CloseBracket < 0 ||
792 ParentProcess.slice(OpenBracket + 1, CloseBracket)
793 .getAsInteger(10, CrashPID) || CrashPID != PID) {
797 // Found a .crash file matching the driver pid. To avoid getting an older
798 // and misleading crash file, continue looking for the most recent.
799 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
800 // multiple crashes poiting to the same parent process. Since the driver
801 // does not collect pid information for the dispatched invocation there's
802 // currently no way to distinguish among them.
803 const auto FileAccessTime = FileStatus.getLastModificationTime();
804 if (FileAccessTime > LastAccessTime) {
805 CrashFilePath.assign(File->path());
806 LastAccessTime = FileAccessTime;
810 // If found, copy it over to the location of other reproducer files.
811 if (!CrashFilePath.empty()) {
812 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
821 // When clang crashes, produce diagnostic information including the fully
822 // preprocessed source file(s). Request that the developer attach the
823 // diagnostic information to a bug report.
824 void Driver::generateCompilationDiagnostics(Compilation &C,
825 const Command &FailingCommand) {
826 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
829 // Don't try to generate diagnostics for link or dsymutil jobs.
830 if (FailingCommand.getCreator().isLinkJob() ||
831 FailingCommand.getCreator().isDsymutilJob())
834 // Print the version of the compiler.
835 PrintVersion(C, llvm::errs());
837 Diag(clang::diag::note_drv_command_failed_diag_msg)
838 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
839 "crash backtrace, preprocessed source, and associated run script.";
841 // Suppress driver output and emit preprocessor output to temp file.
843 CCGenDiagnostics = true;
845 // Save the original job command(s).
846 Command Cmd = FailingCommand;
848 // Keep track of whether we produce any errors while trying to produce
849 // preprocessed sources.
850 DiagnosticErrorTrap Trap(Diags);
852 // Suppress tool output.
853 C.initCompilationForDiagnostics();
855 // Construct the list of inputs.
857 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
859 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
860 bool IgnoreInput = false;
862 // Ignore input from stdin or any inputs that cannot be preprocessed.
863 // Check type first as not all linker inputs have a value.
864 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
866 } else if (!strcmp(it->second->getValue(), "-")) {
867 Diag(clang::diag::note_drv_command_failed_diag_msg)
868 << "Error generating preprocessed source(s) - "
869 "ignoring input from stdin.";
874 it = Inputs.erase(it);
881 if (Inputs.empty()) {
882 Diag(clang::diag::note_drv_command_failed_diag_msg)
883 << "Error generating preprocessed source(s) - "
884 "no preprocessable inputs.";
888 // Don't attempt to generate preprocessed files if multiple -arch options are
889 // used, unless they're all duplicates.
890 llvm::StringSet<> ArchNames;
891 for (const Arg *A : C.getArgs()) {
892 if (A->getOption().matches(options::OPT_arch)) {
893 StringRef ArchName = A->getValue();
894 ArchNames.insert(ArchName);
897 if (ArchNames.size() > 1) {
898 Diag(clang::diag::note_drv_command_failed_diag_msg)
899 << "Error generating preprocessed source(s) - cannot generate "
900 "preprocessed source with multiple -arch options.";
904 // Construct the list of abstract actions to perform for this compilation. On
905 // Darwin OSes this uses the driver-driver and builds universal actions.
906 const ToolChain &TC = C.getDefaultToolChain();
907 if (TC.getTriple().isOSBinFormatMachO())
908 BuildUniversalActions(C, TC, Inputs);
910 BuildActions(C, C.getArgs(), Inputs, C.getActions());
914 // If there were errors building the compilation, quit now.
915 if (Trap.hasErrorOccurred()) {
916 Diag(clang::diag::note_drv_command_failed_diag_msg)
917 << "Error generating preprocessed source(s).";
921 // Generate preprocessed output.
922 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
923 C.ExecuteJobs(C.getJobs(), FailingCommands);
925 // If any of the preprocessing commands failed, clean up and exit.
926 if (!FailingCommands.empty()) {
927 if (!isSaveTempsEnabled())
928 C.CleanupFileList(C.getTempFiles(), true);
930 Diag(clang::diag::note_drv_command_failed_diag_msg)
931 << "Error generating preprocessed source(s).";
935 const ArgStringList &TempFiles = C.getTempFiles();
936 if (TempFiles.empty()) {
937 Diag(clang::diag::note_drv_command_failed_diag_msg)
938 << "Error generating preprocessed source(s).";
942 Diag(clang::diag::note_drv_command_failed_diag_msg)
943 << "\n********************\n\n"
944 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
945 "Preprocessed source(s) and associated run script(s) are located at:";
947 SmallString<128> VFS;
948 SmallString<128> ReproCrashFilename;
949 for (const char *TempFile : TempFiles) {
950 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
951 if (ReproCrashFilename.empty()) {
952 ReproCrashFilename = TempFile;
953 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
955 if (StringRef(TempFile).endswith(".cache")) {
956 // In some cases (modules) we'll dump extra data to help with reproducing
957 // the crash into a directory next to the output.
958 VFS = llvm::sys::path::filename(TempFile);
959 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
963 // Assume associated files are based off of the first temporary file.
964 CrashReportInfo CrashInfo(TempFiles[0], VFS);
966 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
968 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
970 Diag(clang::diag::note_drv_command_failed_diag_msg)
971 << "Error generating run script: " + Script + " " + EC.message();
973 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
974 << "# Driver args: ";
975 printArgList(ScriptOS, C.getInputArgs());
976 ScriptOS << "# Original command: ";
977 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
978 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
979 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
982 // On darwin, provide information about the .crash diagnostic report.
983 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
984 SmallString<128> CrashDiagDir;
985 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
986 Diag(clang::diag::note_drv_command_failed_diag_msg)
987 << ReproCrashFilename.str();
988 } else { // Suggest a directory for the user to look for .crash files.
989 llvm::sys::path::append(CrashDiagDir, Name);
990 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
991 Diag(clang::diag::note_drv_command_failed_diag_msg)
992 << "Crash backtrace is located in";
993 Diag(clang::diag::note_drv_command_failed_diag_msg)
994 << CrashDiagDir.str();
995 Diag(clang::diag::note_drv_command_failed_diag_msg)
996 << "(choose the .crash file that corresponds to your crash)";
1000 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1001 options::OPT_frewrite_map_file_EQ))
1002 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1004 Diag(clang::diag::note_drv_command_failed_diag_msg)
1005 << "\n\n********************";
1008 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1009 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
1010 // if the tool does not support response files, there is a chance/ that things
1011 // will just work without a response file, so we silently just skip it.
1012 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1013 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
1016 std::string TmpName = GetTemporaryPath("response", "txt");
1017 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1020 int Driver::ExecuteCompilation(
1022 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1023 // Just print if -### was present.
1024 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1025 C.getJobs().Print(llvm::errs(), "\n", true);
1029 // If there were errors building the compilation, quit now.
1030 if (Diags.hasErrorOccurred())
1033 // Set up response file names for each command, if necessary
1034 for (auto &Job : C.getJobs())
1035 setUpResponseFiles(C, Job);
1037 C.ExecuteJobs(C.getJobs(), FailingCommands);
1039 // Remove temp files.
1040 C.CleanupFileList(C.getTempFiles());
1042 // If the command succeeded, we are done.
1043 if (FailingCommands.empty())
1046 // Otherwise, remove result files and print extra information about abnormal
1048 for (const auto &CmdPair : FailingCommands) {
1049 int Res = CmdPair.first;
1050 const Command *FailingCommand = CmdPair.second;
1052 // Remove result files if we're not saving temps.
1053 if (!isSaveTempsEnabled()) {
1054 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1055 C.CleanupFileMap(C.getResultFiles(), JA, true);
1057 // Failure result files are valid unless we crashed.
1059 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1062 // Print extra information about abnormal failures, if possible.
1064 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1065 // status was 1, assume the command failed normally. In particular, if it
1066 // was the compiler then assume it gave a reasonable error code. Failures
1067 // in other tools are less common, and they generally have worse
1068 // diagnostics, so always print the diagnostic there.
1069 const Tool &FailingTool = FailingCommand->getCreator();
1071 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1072 // FIXME: See FIXME above regarding result code interpretation.
1074 Diag(clang::diag::err_drv_command_signalled)
1075 << FailingTool.getShortName();
1077 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1084 void Driver::PrintHelp(bool ShowHidden) const {
1085 unsigned IncludedFlagsBitmask;
1086 unsigned ExcludedFlagsBitmask;
1087 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1088 getIncludeExcludeOptionFlagMasks();
1090 ExcludedFlagsBitmask |= options::NoDriverOption;
1092 ExcludedFlagsBitmask |= HelpHidden;
1094 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1095 IncludedFlagsBitmask, ExcludedFlagsBitmask);
1098 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1099 // FIXME: The following handlers should use a callback mechanism, we don't
1100 // know what the client would like to do.
1101 OS << getClangFullVersion() << '\n';
1102 const ToolChain &TC = C.getDefaultToolChain();
1103 OS << "Target: " << TC.getTripleString() << '\n';
1105 // Print the threading model.
1106 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1107 // Don't print if the ToolChain would have barfed on it already
1108 if (TC.isThreadModelSupported(A->getValue()))
1109 OS << "Thread model: " << A->getValue();
1111 OS << "Thread model: " << TC.getThreadModel();
1114 // Print out the install directory.
1115 OS << "InstalledDir: " << InstalledDir << '\n';
1118 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1120 static void PrintDiagnosticCategories(raw_ostream &OS) {
1121 // Skip the empty category.
1122 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1124 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1127 bool Driver::HandleImmediateArgs(const Compilation &C) {
1128 // The order these options are handled in gcc is all over the place, but we
1129 // don't expect inconsistencies w.r.t. that to matter in practice.
1131 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1132 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1136 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1137 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1138 // return an answer which matches our definition of __VERSION__.
1140 // If we want to return a more correct answer some day, then we should
1141 // introduce a non-pedantically GCC compatible mode to Clang in which we
1142 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1143 llvm::outs() << "4.2.1\n";
1147 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1148 PrintDiagnosticCategories(llvm::outs());
1152 if (C.getArgs().hasArg(options::OPT_help) ||
1153 C.getArgs().hasArg(options::OPT__help_hidden)) {
1154 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1158 if (C.getArgs().hasArg(options::OPT__version)) {
1159 // Follow gcc behavior and use stdout for --version and stderr for -v.
1160 PrintVersion(C, llvm::outs());
1164 if (C.getArgs().hasArg(options::OPT_v) ||
1165 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1166 PrintVersion(C, llvm::errs());
1167 SuppressMissingInputWarning = true;
1170 const ToolChain &TC = C.getDefaultToolChain();
1172 if (C.getArgs().hasArg(options::OPT_v))
1173 TC.printVerboseInfo(llvm::errs());
1175 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1176 llvm::outs() << ResourceDir << '\n';
1180 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1181 llvm::outs() << "programs: =";
1182 bool separator = false;
1183 for (const std::string &Path : TC.getProgramPaths()) {
1185 llvm::outs() << ':';
1186 llvm::outs() << Path;
1189 llvm::outs() << "\n";
1190 llvm::outs() << "libraries: =" << ResourceDir;
1192 StringRef sysroot = C.getSysRoot();
1194 for (const std::string &Path : TC.getFilePaths()) {
1195 // Always print a separator. ResourceDir was the first item shown.
1196 llvm::outs() << ':';
1197 // Interpretation of leading '=' is needed only for NetBSD.
1199 llvm::outs() << sysroot << Path.substr(1);
1201 llvm::outs() << Path;
1203 llvm::outs() << "\n";
1207 // FIXME: The following handlers should use a callback mechanism, we don't
1208 // know what the client would like to do.
1209 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1210 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1214 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1215 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
1219 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1220 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1222 case ToolChain::RLT_CompilerRT:
1223 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1225 case ToolChain::RLT_Libgcc:
1226 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1232 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1233 for (const Multilib &Multilib : TC.getMultilibs())
1234 llvm::outs() << Multilib << "\n";
1238 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1239 for (const Multilib &Multilib : TC.getMultilibs()) {
1240 if (Multilib.gccSuffix().empty())
1241 llvm::outs() << ".\n";
1243 StringRef Suffix(Multilib.gccSuffix());
1244 assert(Suffix.front() == '/');
1245 llvm::outs() << Suffix.substr(1) << "\n";
1253 // Display an action graph human-readably. Action A is the "sink" node
1254 // and latest-occuring action. Traversal is in pre-order, visiting the
1255 // inputs to each action before printing the action itself.
1256 static unsigned PrintActions1(const Compilation &C, Action *A,
1257 std::map<Action *, unsigned> &Ids) {
1258 if (Ids.count(A)) // A was already visited.
1262 llvm::raw_string_ostream os(str);
1264 os << Action::getClassName(A->getKind()) << ", ";
1265 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1266 os << "\"" << IA->getInputArg().getValue() << "\"";
1267 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1268 os << '"' << BIA->getArchName() << '"' << ", {"
1269 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1270 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1271 bool IsFirst = true;
1272 OA->doOnEachDependence(
1273 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1274 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1275 // sm_35 this will generate:
1276 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1277 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1282 os << A->getOffloadingKindPrefix();
1286 os << TC->getTriple().normalize();
1289 os << ":" << BoundArch;
1292 os << " {" << PrintActions1(C, A, Ids) << "}";
1296 const ActionList *AL = &A->getInputs();
1299 const char *Prefix = "{";
1300 for (Action *PreRequisite : *AL) {
1301 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1309 // Append offload info for all options other than the offloading action
1310 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1311 std::string offload_str;
1312 llvm::raw_string_ostream offload_os(offload_str);
1313 if (!isa<OffloadAction>(A)) {
1314 auto S = A->getOffloadingKindPrefix();
1316 offload_os << ", (" << S;
1317 if (A->getOffloadingArch())
1318 offload_os << ", " << A->getOffloadingArch();
1323 unsigned Id = Ids.size();
1325 llvm::errs() << Id << ": " << os.str() << ", "
1326 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1331 // Print the action graphs in a compilation C.
1332 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1333 void Driver::PrintActions(const Compilation &C) const {
1334 std::map<Action *, unsigned> Ids;
1335 for (Action *A : C.getActions())
1336 PrintActions1(C, A, Ids);
1339 /// \brief Check whether the given input tree contains any compilation or
1340 /// assembly actions.
1341 static bool ContainsCompileOrAssembleAction(const Action *A) {
1342 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1343 isa<AssembleJobAction>(A))
1346 for (const Action *Input : A->inputs())
1347 if (ContainsCompileOrAssembleAction(Input))
1353 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1354 const InputList &BAInputs) const {
1355 DerivedArgList &Args = C.getArgs();
1356 ActionList &Actions = C.getActions();
1357 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1358 // Collect the list of architectures. Duplicates are allowed, but should only
1359 // be handled once (in the order seen).
1360 llvm::StringSet<> ArchNames;
1361 SmallVector<const char *, 4> Archs;
1362 for (Arg *A : Args) {
1363 if (A->getOption().matches(options::OPT_arch)) {
1364 // Validate the option here; we don't save the type here because its
1365 // particular spelling may participate in other driver choices.
1366 llvm::Triple::ArchType Arch =
1367 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1368 if (Arch == llvm::Triple::UnknownArch) {
1369 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1374 if (ArchNames.insert(A->getValue()).second)
1375 Archs.push_back(A->getValue());
1379 // When there is no explicit arch for this platform, make sure we still bind
1380 // the architecture (to the default) so that -Xarch_ is handled correctly.
1382 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1384 ActionList SingleActions;
1385 BuildActions(C, Args, BAInputs, SingleActions);
1387 // Add in arch bindings for every top level action, as well as lipo and
1388 // dsymutil steps if needed.
1389 for (Action* Act : SingleActions) {
1390 // Make sure we can lipo this kind of output. If not (and it is an actual
1391 // output) then we disallow, since we can't create an output file with the
1392 // right name without overwriting it. We could remove this oddity by just
1393 // changing the output names to include the arch, which would also fix
1394 // -save-temps. Compatibility wins for now.
1396 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1397 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1398 << types::getTypeName(Act->getType());
1401 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1402 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1404 // Lipo if necessary, we do it this way because we need to set the arch flag
1405 // so that -Xarch_ gets overwritten.
1406 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1407 Actions.append(Inputs.begin(), Inputs.end());
1409 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1411 // Handle debug info queries.
1412 Arg *A = Args.getLastArg(options::OPT_g_Group);
1413 if (A && !A->getOption().matches(options::OPT_g0) &&
1414 !A->getOption().matches(options::OPT_gstabs) &&
1415 ContainsCompileOrAssembleAction(Actions.back())) {
1417 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1418 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1419 // because the debug info will refer to a temporary object file which
1420 // will be removed at the end of the compilation process.
1421 if (Act->getType() == types::TY_Image) {
1423 Inputs.push_back(Actions.back());
1426 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1429 // Verify the debug info output.
1430 if (Args.hasArg(options::OPT_verify_debug_info)) {
1431 Action* LastAction = Actions.back();
1433 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1434 LastAction, types::TY_Nothing));
1440 /// \brief Check that the file referenced by Value exists. If it doesn't,
1441 /// issue a diagnostic and return false.
1442 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1443 StringRef Value, types::ID Ty) {
1444 if (!D.getCheckInputsExist())
1447 // stdin always exists.
1451 SmallString<64> Path(Value);
1452 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1453 if (!llvm::sys::path::is_absolute(Path)) {
1454 SmallString<64> Directory(WorkDir->getValue());
1455 llvm::sys::path::append(Directory, Value);
1456 Path.assign(Directory);
1460 if (llvm::sys::fs::exists(Twine(Path)))
1464 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1465 llvm::sys::Process::FindInEnvPath("LIB", Value))
1468 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1469 // Arguments to the /link flag might cause the linker to search for object
1470 // and library files in paths we don't know about. Don't error in such
1476 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1480 // Construct a the list of inputs and their types.
1481 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1482 InputList &Inputs) const {
1483 // Track the current user specified (-x) input. We also explicitly track the
1484 // argument used to set the type; we only want to claim the type when we
1485 // actually use it, so we warn about unused -x arguments.
1486 types::ID InputType = types::TY_Nothing;
1487 Arg *InputTypeArg = nullptr;
1489 // The last /TC or /TP option sets the input type to C or C++ globally.
1490 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1491 options::OPT__SLASH_TP)) {
1492 InputTypeArg = TCTP;
1493 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1497 Arg *Previous = nullptr;
1498 bool ShowNote = false;
1499 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1501 Diag(clang::diag::warn_drv_overriding_flag_option)
1502 << Previous->getSpelling() << A->getSpelling();
1508 Diag(clang::diag::note_drv_t_option_is_global);
1510 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1511 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1514 for (Arg *A : Args) {
1515 if (A->getOption().getKind() == Option::InputClass) {
1516 const char *Value = A->getValue();
1517 types::ID Ty = types::TY_INVALID;
1519 // Infer the input type if necessary.
1520 if (InputType == types::TY_Nothing) {
1521 // If there was an explicit arg for this, claim it.
1523 InputTypeArg->claim();
1525 // stdin must be handled specially.
1526 if (memcmp(Value, "-", 2) == 0) {
1527 // If running with -E, treat as a C input (this changes the builtin
1528 // macros, for example). This may be overridden by -ObjC below.
1530 // Otherwise emit an error but still use a valid type to avoid
1531 // spurious errors (e.g., no inputs).
1532 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1533 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1534 : clang::diag::err_drv_unknown_stdin_type);
1537 // Otherwise lookup by extension.
1538 // Fallback is C if invoked as C preprocessor or Object otherwise.
1539 // We use a host hook here because Darwin at least has its own
1540 // idea of what .s is.
1541 if (const char *Ext = strrchr(Value, '.'))
1542 Ty = TC.LookupTypeForExtension(Ext + 1);
1544 if (Ty == types::TY_INVALID) {
1548 Ty = types::TY_Object;
1551 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1552 // should autodetect some input files as C++ for g++ compatibility.
1554 types::ID OldTy = Ty;
1555 Ty = types::lookupCXXTypeForCType(Ty);
1558 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1559 << getTypeName(OldTy) << getTypeName(Ty);
1563 // -ObjC and -ObjC++ override the default language, but only for "source
1564 // files". We just treat everything that isn't a linker input as a
1567 // FIXME: Clean this up if we move the phase sequence into the type.
1568 if (Ty != types::TY_Object) {
1569 if (Args.hasArg(options::OPT_ObjC))
1570 Ty = types::TY_ObjC;
1571 else if (Args.hasArg(options::OPT_ObjCXX))
1572 Ty = types::TY_ObjCXX;
1575 assert(InputTypeArg && "InputType set w/o InputTypeArg");
1576 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1577 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1579 const char *Ext = strrchr(Value, '.');
1580 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1581 Ty = types::TY_Object;
1583 if (Ty == types::TY_INVALID) {
1585 InputTypeArg->claim();
1589 if (DiagnoseInputExistence(*this, Args, Value, Ty))
1590 Inputs.push_back(std::make_pair(Ty, A));
1592 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1593 StringRef Value = A->getValue();
1594 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1595 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1596 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1599 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1600 StringRef Value = A->getValue();
1601 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1602 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1603 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1606 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1607 // Just treat as object type, we could make a special type for this if
1609 Inputs.push_back(std::make_pair(types::TY_Object, A));
1611 } else if (A->getOption().matches(options::OPT_x)) {
1613 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1616 // Follow gcc behavior and treat as linker input for invalid -x
1617 // options. Its not clear why we shouldn't just revert to unknown; but
1618 // this isn't very important, we might as well be bug compatible.
1620 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1621 InputType = types::TY_Object;
1623 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1624 assert(A->getNumValues() == 1 && "The /U option has one value.");
1625 StringRef Val = A->getValue(0);
1626 if (Val.find_first_of("/\\") != StringRef::npos) {
1627 // Warn about e.g. "/Users/me/myfile.c".
1628 Diag(diag::warn_slash_u_filename) << Val;
1629 Diag(diag::note_use_dashdash);
1633 if (CCCIsCPP() && Inputs.empty()) {
1634 // If called as standalone preprocessor, stdin is processed
1635 // if no other input is present.
1636 Arg *A = MakeInputArg(Args, *Opts, "-");
1637 Inputs.push_back(std::make_pair(types::TY_C, A));
1642 /// Provides a convenient interface for different programming models to generate
1643 /// the required device actions.
1644 class OffloadingActionBuilder final {
1645 /// Flag used to trace errors in the builder.
1646 bool IsValid = false;
1648 /// The compilation that is using this builder.
1651 /// Map between an input argument and the offload kinds used to process it.
1652 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1654 /// Builder interface. It doesn't build anything or keep any state.
1655 class DeviceActionBuilder {
1657 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1659 enum ActionBuilderReturnCode {
1660 // The builder acted successfully on the current action.
1662 // The builder didn't have to act on the current action.
1664 // The builder was successful and requested the host action to not be
1670 /// Compilation associated with this builder.
1673 /// Tool chains associated with this builder. The same programming
1674 /// model may have associated one or more tool chains.
1675 SmallVector<const ToolChain *, 2> ToolChains;
1677 /// The derived arguments associated with this builder.
1678 DerivedArgList &Args;
1680 /// The inputs associated with this builder.
1681 const Driver::InputList &Inputs;
1683 /// The associated offload kind.
1684 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1687 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1688 const Driver::InputList &Inputs,
1689 Action::OffloadKind AssociatedOffloadKind)
1690 : C(C), Args(Args), Inputs(Inputs),
1691 AssociatedOffloadKind(AssociatedOffloadKind) {}
1692 virtual ~DeviceActionBuilder() {}
1694 /// Fill up the array \a DA with all the device dependences that should be
1695 /// added to the provided host action \a HostAction. By default it is
1697 virtual ActionBuilderReturnCode
1698 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1699 phases::ID CurPhase, phases::ID FinalPhase,
1701 return ABRT_Inactive;
1704 /// Update the state to include the provided host action \a HostAction as a
1705 /// dependency of the current device action. By default it is inactive.
1706 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1707 return ABRT_Inactive;
1710 /// Append top level actions generated by the builder. Return true if errors
1712 virtual void appendTopLevelActions(ActionList &AL) {}
1714 /// Append linker actions generated by the builder. Return true if errors
1716 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1718 /// Initialize the builder. Return true if any initialization errors are
1720 virtual bool initialize() { return false; }
1722 /// Return true if the builder can use bundling/unbundling.
1723 virtual bool canUseBundlerUnbundler() const { return false; }
1725 /// Return true if this builder is valid. We have a valid builder if we have
1726 /// associated device tool chains.
1727 bool isValid() { return !ToolChains.empty(); }
1729 /// Return the associated offload kind.
1730 Action::OffloadKind getAssociatedOffloadKind() {
1731 return AssociatedOffloadKind;
1735 /// \brief CUDA action builder. It injects device code in the host backend
1737 class CudaActionBuilder final : public DeviceActionBuilder {
1738 /// Flags to signal if the user requested host-only or device-only
1740 bool CompileHostOnly = false;
1741 bool CompileDeviceOnly = false;
1743 /// List of GPU architectures to use in this compilation.
1744 SmallVector<CudaArch, 4> GpuArchList;
1746 /// The CUDA actions for the current input.
1747 ActionList CudaDeviceActions;
1749 /// The CUDA fat binary if it was generated for the current input.
1750 Action *CudaFatBinary = nullptr;
1752 /// Flag that is set to true if this builder acted on the current input.
1753 bool IsActive = false;
1756 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1757 const Driver::InputList &Inputs)
1758 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1760 ActionBuilderReturnCode
1761 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1762 phases::ID CurPhase, phases::ID FinalPhase,
1763 PhasesTy &Phases) override {
1765 return ABRT_Inactive;
1767 // If we don't have more CUDA actions, we don't have any dependences to
1768 // create for the host.
1769 if (CudaDeviceActions.empty())
1770 return ABRT_Success;
1772 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1773 "Expecting one action per GPU architecture.");
1774 assert(!CompileHostOnly &&
1775 "Not expecting CUDA actions in host-only compilation.");
1777 // If we are generating code for the device or we are in a backend phase,
1778 // we attempt to generate the fat binary. We compile each arch to ptx and
1779 // assemble to cubin, then feed the cubin *and* the ptx into a device
1780 // "link" action, which uses fatbinary to combine these cubins into one
1781 // fatbin. The fatbin is then an input to the host action if not in
1782 // device-only mode.
1783 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1784 ActionList DeviceActions;
1785 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1786 // Produce the device action from the current phase up to the assemble
1788 for (auto Ph : Phases) {
1789 // Skip the phases that were already dealt with.
1792 // We have to be consistent with the host final phase.
1793 if (Ph > FinalPhase)
1796 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1797 C, Args, Ph, CudaDeviceActions[I]);
1799 if (Ph == phases::Assemble)
1803 // If we didn't reach the assemble phase, we can't generate the fat
1804 // binary. We don't need to generate the fat binary if we are not in
1805 // device-only mode.
1806 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1810 Action *AssembleAction = CudaDeviceActions[I];
1811 assert(AssembleAction->getType() == types::TY_Object);
1812 assert(AssembleAction->getInputs().size() == 1);
1814 Action *BackendAction = AssembleAction->getInputs()[0];
1815 assert(BackendAction->getType() == types::TY_PP_Asm);
1817 for (auto &A : {AssembleAction, BackendAction}) {
1818 OffloadAction::DeviceDependences DDep;
1819 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1821 DeviceActions.push_back(
1822 C.MakeAction<OffloadAction>(DDep, A->getType()));
1826 // We generate the fat binary if we have device input actions.
1827 if (!DeviceActions.empty()) {
1829 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1831 if (!CompileDeviceOnly) {
1832 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1834 // Clear the fat binary, it is already a dependence to an host
1836 CudaFatBinary = nullptr;
1839 // Remove the CUDA actions as they are already connected to an host
1840 // action or fat binary.
1841 CudaDeviceActions.clear();
1844 // We avoid creating host action in device-only mode.
1845 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
1846 } else if (CurPhase > phases::Backend) {
1847 // If we are past the backend phase and still have a device action, we
1848 // don't have to do anything as this action is already a device
1849 // top-level action.
1850 return ABRT_Success;
1853 assert(CurPhase < phases::Backend && "Generating single CUDA "
1854 "instructions should only occur "
1855 "before the backend phase!");
1857 // By default, we produce an action for each device arch.
1858 for (Action *&A : CudaDeviceActions)
1859 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1861 return ABRT_Success;
1864 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1865 // While generating code for CUDA, we only depend on the host input action
1866 // to trigger the creation of all the CUDA device actions.
1868 // If we are dealing with an input action, replicate it for each GPU
1869 // architecture. If we are in host-only mode we return 'success' so that
1870 // the host uses the CUDA offload kind.
1871 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1872 assert(!GpuArchList.empty() &&
1873 "We should have at least one GPU architecture.");
1875 // If the host input is not CUDA, we don't need to bother about this
1877 if (IA->getType() != types::TY_CUDA) {
1878 // The builder will ignore this input.
1880 return ABRT_Inactive;
1883 // Set the flag to true, so that the builder acts on the current input.
1886 if (CompileHostOnly)
1887 return ABRT_Success;
1889 // Replicate inputs for each GPU architecture.
1890 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1891 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1892 IA->getInputArg(), types::TY_CUDA_DEVICE));
1894 return ABRT_Success;
1897 return IsActive ? ABRT_Success : ABRT_Inactive;
1900 void appendTopLevelActions(ActionList &AL) override {
1901 // Utility to append actions to the top level list.
1902 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1903 OffloadAction::DeviceDependences Dep;
1904 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1906 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1909 // If we have a fat binary, add it to the list.
1910 if (CudaFatBinary) {
1911 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1912 CudaDeviceActions.clear();
1913 CudaFatBinary = nullptr;
1917 if (CudaDeviceActions.empty())
1920 // If we have CUDA actions at this point, that's because we have a have
1921 // partial compilation, so we should have an action for each GPU
1923 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1924 "Expecting one action per GPU architecture.");
1925 assert(ToolChains.size() == 1 &&
1926 "Expecting to have a sing CUDA toolchain.");
1927 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1928 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1930 CudaDeviceActions.clear();
1933 bool initialize() override {
1934 // We don't need to support CUDA.
1935 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1938 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1939 assert(HostTC && "No toolchain for host compilation.");
1940 if (HostTC->getTriple().isNVPTX()) {
1941 // We do not support targeting NVPTX for host compilation. Throw
1942 // an error and abort pipeline construction early so we don't trip
1943 // asserts that assume device-side compilation.
1944 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1948 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1950 Arg *PartialCompilationArg = Args.getLastArg(
1951 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1952 options::OPT_cuda_compile_host_device);
1953 CompileHostOnly = PartialCompilationArg &&
1954 PartialCompilationArg->getOption().matches(
1955 options::OPT_cuda_host_only);
1956 CompileDeviceOnly = PartialCompilationArg &&
1957 PartialCompilationArg->getOption().matches(
1958 options::OPT_cuda_device_only);
1960 // Collect all cuda_gpu_arch parameters, removing duplicates.
1961 std::set<CudaArch> GpuArchs;
1963 for (Arg *A : Args) {
1964 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
1965 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
1969 const StringRef ArchStr = A->getValue();
1970 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
1975 CudaArch Arch = StringToCudaArch(ArchStr);
1976 if (Arch == CudaArch::UNKNOWN) {
1977 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1979 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1980 GpuArchs.insert(Arch);
1981 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
1982 GpuArchs.erase(Arch);
1984 llvm_unreachable("Unexpected option.");
1987 // Collect list of GPUs remaining in the set.
1988 for (CudaArch Arch : GpuArchs)
1989 GpuArchList.push_back(Arch);
1991 // Default to sm_20 which is the lowest common denominator for
1992 // supported GPUs. sm_20 code should work correctly, if
1993 // suboptimally, on all newer GPUs.
1994 if (GpuArchList.empty())
1995 GpuArchList.push_back(CudaArch::SM_20);
2001 /// OpenMP action builder. The host bitcode is passed to the device frontend
2002 /// and all the device linked images are passed to the host link phase.
2003 class OpenMPActionBuilder final : public DeviceActionBuilder {
2004 /// The OpenMP actions for the current input.
2005 ActionList OpenMPDeviceActions;
2007 /// The linker inputs obtained for each toolchain.
2008 SmallVector<ActionList, 8> DeviceLinkerInputs;
2011 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2012 const Driver::InputList &Inputs)
2013 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2015 ActionBuilderReturnCode
2016 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2017 phases::ID CurPhase, phases::ID FinalPhase,
2018 PhasesTy &Phases) override {
2020 // We should always have an action for each input.
2021 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2022 "Number of OpenMP actions and toolchains do not match.");
2024 // The host only depends on device action in the linking phase, when all
2025 // the device images have to be embedded in the host image.
2026 if (CurPhase == phases::Link) {
2027 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2028 "Toolchains and linker inputs sizes do not match.");
2029 auto LI = DeviceLinkerInputs.begin();
2030 for (auto *A : OpenMPDeviceActions) {
2035 // We passed the device action as a host dependence, so we don't need to
2036 // do anything else with them.
2037 OpenMPDeviceActions.clear();
2038 return ABRT_Success;
2041 // By default, we produce an action for each device arch.
2042 for (Action *&A : OpenMPDeviceActions)
2043 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2045 return ABRT_Success;
2048 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2050 // If this is an input action replicate it for each OpenMP toolchain.
2051 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2052 OpenMPDeviceActions.clear();
2053 for (unsigned I = 0; I < ToolChains.size(); ++I)
2054 OpenMPDeviceActions.push_back(
2055 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2056 return ABRT_Success;
2059 // If this is an unbundling action use it as is for each OpenMP toolchain.
2060 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2061 OpenMPDeviceActions.clear();
2062 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2063 OpenMPDeviceActions.push_back(UA);
2064 UA->registerDependentActionInfo(
2065 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2067 return ABRT_Success;
2070 // When generating code for OpenMP we use the host compile phase result as
2071 // a dependence to the device compile phase so that it can learn what
2072 // declarations should be emitted. However, this is not the only use for
2073 // the host action, so we prevent it from being collapsed.
2074 if (isa<CompileJobAction>(HostAction)) {
2075 HostAction->setCannotBeCollapsedWithNextDependentAction();
2076 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2077 "Toolchains and device action sizes do not match.");
2078 OffloadAction::HostDependence HDep(
2079 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2080 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2081 auto TC = ToolChains.begin();
2082 for (Action *&A : OpenMPDeviceActions) {
2083 assert(isa<CompileJobAction>(A));
2084 OffloadAction::DeviceDependences DDep;
2085 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2086 A = C.MakeAction<OffloadAction>(HDep, DDep);
2090 return ABRT_Success;
2093 void appendTopLevelActions(ActionList &AL) override {
2094 if (OpenMPDeviceActions.empty())
2097 // We should always have an action for each input.
2098 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2099 "Number of OpenMP actions and toolchains do not match.");
2101 // Append all device actions followed by the proper offload action.
2102 auto TI = ToolChains.begin();
2103 for (auto *A : OpenMPDeviceActions) {
2104 OffloadAction::DeviceDependences Dep;
2105 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2106 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2109 // We no longer need the action stored in this builder.
2110 OpenMPDeviceActions.clear();
2113 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2114 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2115 "Toolchains and linker inputs sizes do not match.");
2117 // Append a new link action for each device.
2118 auto TC = ToolChains.begin();
2119 for (auto &LI : DeviceLinkerInputs) {
2120 auto *DeviceLinkAction =
2121 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2122 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2123 Action::OFK_OpenMP);
2128 bool initialize() override {
2129 // Get the OpenMP toolchains. If we don't get any, the action builder will
2130 // know there is nothing to do related to OpenMP offloading.
2131 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2132 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2134 ToolChains.push_back(TI->second);
2136 DeviceLinkerInputs.resize(ToolChains.size());
2140 bool canUseBundlerUnbundler() const override {
2141 // OpenMP should use bundled files whenever possible.
2147 /// TODO: Add the implementation for other specialized builders here.
2150 /// Specialized builders being used by this offloading action builder.
2151 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2153 /// Flag set to true if all valid builders allow file bundling/unbundling.
2157 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2158 const Driver::InputList &Inputs)
2160 // Create a specialized builder for each device toolchain.
2164 // Create a specialized builder for CUDA.
2165 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2167 // Create a specialized builder for OpenMP.
2168 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2171 // TODO: Build other specialized builders here.
2174 // Initialize all the builders, keeping track of errors. If all valid
2175 // builders agree that we can use bundling, set the flag to true.
2176 unsigned ValidBuilders = 0u;
2177 unsigned ValidBuildersSupportingBundling = 0u;
2178 for (auto *SB : SpecializedBuilders) {
2179 IsValid = IsValid && !SB->initialize();
2181 // Update the counters if the builder is valid.
2182 if (SB->isValid()) {
2184 if (SB->canUseBundlerUnbundler())
2185 ++ValidBuildersSupportingBundling;
2189 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2192 ~OffloadingActionBuilder() {
2193 for (auto *SB : SpecializedBuilders)
2197 /// Generate an action that adds device dependences (if any) to a host action.
2198 /// If no device dependence actions exist, just return the host action \a
2199 /// HostAction. If an error is found or if no builder requires the host action
2200 /// to be generated, return nullptr.
2202 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2203 phases::ID CurPhase, phases::ID FinalPhase,
2204 DeviceActionBuilder::PhasesTy &Phases) {
2208 if (SpecializedBuilders.empty())
2211 assert(HostAction && "Invalid host action!");
2213 OffloadAction::DeviceDependences DDeps;
2214 // Check if all the programming models agree we should not emit the host
2215 // action. Also, keep track of the offloading kinds employed.
2216 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2217 unsigned InactiveBuilders = 0u;
2218 unsigned IgnoringBuilders = 0u;
2219 for (auto *SB : SpecializedBuilders) {
2220 if (!SB->isValid()) {
2226 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2228 // If the builder explicitly says the host action should be ignored,
2229 // we need to increment the variable that tracks the builders that request
2230 // the host object to be ignored.
2231 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2234 // Unless the builder was inactive for this action, we have to record the
2235 // offload kind because the host will have to use it.
2236 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2237 OffloadKind |= SB->getAssociatedOffloadKind();
2240 // If all builders agree that the host object should be ignored, just return
2242 if (IgnoringBuilders &&
2243 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2246 if (DDeps.getActions().empty())
2249 // We have dependences we need to bundle together. We use an offload action
2251 OffloadAction::HostDependence HDep(
2252 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2253 /*BoundArch=*/nullptr, DDeps);
2254 return C.MakeAction<OffloadAction>(HDep, DDeps);
2257 /// Generate an action that adds a host dependence to a device action. The
2258 /// results will be kept in this action builder. Return true if an error was
2260 bool addHostDependenceToDeviceActions(Action *&HostAction,
2261 const Arg *InputArg) {
2265 // If we are supporting bundling/unbundling and the current action is an
2266 // input action of non-source file, we replace the host action by the
2267 // unbundling action. The bundler tool has the logic to detect if an input
2268 // is a bundle or not and if the input is not a bundle it assumes it is a
2269 // host file. Therefore it is safe to create an unbundling action even if
2270 // the input is not a bundle.
2271 if (CanUseBundler && isa<InputAction>(HostAction) &&
2272 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2273 !types::isSrcFile(HostAction->getType())) {
2274 auto UnbundlingHostAction =
2275 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2276 UnbundlingHostAction->registerDependentActionInfo(
2277 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2278 /*BoundArch=*/StringRef(), Action::OFK_Host);
2279 HostAction = UnbundlingHostAction;
2282 assert(HostAction && "Invalid host action!");
2284 // Register the offload kinds that are used.
2285 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2286 for (auto *SB : SpecializedBuilders) {
2290 auto RetCode = SB->addDeviceDepences(HostAction);
2292 // Host dependences for device actions are not compatible with that same
2293 // action being ignored.
2294 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2295 "Host dependence not expected to be ignored.!");
2297 // Unless the builder was inactive for this action, we have to record the
2298 // offload kind because the host will have to use it.
2299 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2300 OffloadKind |= SB->getAssociatedOffloadKind();
2306 /// Add the offloading top level actions to the provided action list. This
2307 /// function can replace the host action by a bundling action if the
2308 /// programming models allow it.
2309 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2310 const Arg *InputArg) {
2311 // Get the device actions to be appended.
2312 ActionList OffloadAL;
2313 for (auto *SB : SpecializedBuilders) {
2316 SB->appendTopLevelActions(OffloadAL);
2319 // If we can use the bundler, replace the host action by the bundling one in
2320 // the resulting list. Otherwise, just append the device actions.
2321 if (CanUseBundler && !OffloadAL.empty()) {
2322 // Add the host action to the list in order to create the bundling action.
2323 OffloadAL.push_back(HostAction);
2325 // We expect that the host action was just appended to the action list
2326 // before this method was called.
2327 assert(HostAction == AL.back() && "Host action not in the list??");
2328 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2329 AL.back() = HostAction;
2331 AL.append(OffloadAL.begin(), OffloadAL.end());
2333 // Propagate to the current host action (if any) the offload information
2334 // associated with the current input.
2336 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2337 /*BoundArch=*/nullptr);
2341 /// Processes the host linker action. This currently consists of replacing it
2342 /// with an offload action if there are device link objects and propagate to
2343 /// the host action all the offload kinds used in the current compilation. The
2344 /// resulting action is returned.
2345 Action *processHostLinkAction(Action *HostAction) {
2346 // Add all the dependences from the device linking actions.
2347 OffloadAction::DeviceDependences DDeps;
2348 for (auto *SB : SpecializedBuilders) {
2352 SB->appendLinkDependences(DDeps);
2355 // Calculate all the offload kinds used in the current compilation.
2356 unsigned ActiveOffloadKinds = 0u;
2357 for (auto &I : InputArgToOffloadKindMap)
2358 ActiveOffloadKinds |= I.second;
2360 // If we don't have device dependencies, we don't have to create an offload
2362 if (DDeps.getActions().empty()) {
2363 // Propagate all the active kinds to host action. Given that it is a link
2364 // action it is assumed to depend on all actions generated so far.
2365 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2366 /*BoundArch=*/nullptr);
2370 // Create the offload action with all dependences. When an offload action
2371 // is created the kinds are propagated to the host action, so we don't have
2372 // to do that explicitly here.
2373 OffloadAction::HostDependence HDep(
2374 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2375 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2376 return C.MakeAction<OffloadAction>(HDep, DDeps);
2379 } // anonymous namespace.
2381 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2382 const InputList &Inputs, ActionList &Actions) const {
2383 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
2385 if (!SuppressMissingInputWarning && Inputs.empty()) {
2386 Diag(clang::diag::err_drv_no_input_files);
2391 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
2393 if (FinalPhase == phases::Link) {
2394 if (Args.hasArg(options::OPT_emit_llvm))
2395 Diag(clang::diag::err_drv_emit_llvm_link);
2396 if (IsCLMode() && LTOMode != LTOK_None &&
2397 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2398 Diag(clang::diag::err_drv_lto_without_lld);
2401 // Reject -Z* at the top level, these options should never have been exposed
2403 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
2404 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
2406 // Diagnose misuse of /Fo.
2407 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
2408 StringRef V = A->getValue();
2409 if (Inputs.size() > 1 && !V.empty() &&
2410 !llvm::sys::path::is_separator(V.back())) {
2411 // Check whether /Fo tries to name an output file for multiple inputs.
2412 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2413 << A->getSpelling() << V;
2414 Args.eraseArg(options::OPT__SLASH_Fo);
2418 // Diagnose misuse of /Fa.
2419 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2420 StringRef V = A->getValue();
2421 if (Inputs.size() > 1 && !V.empty() &&
2422 !llvm::sys::path::is_separator(V.back())) {
2423 // Check whether /Fa tries to name an asm file for multiple inputs.
2424 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2425 << A->getSpelling() << V;
2426 Args.eraseArg(options::OPT__SLASH_Fa);
2430 // Diagnose misuse of /o.
2431 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2432 if (A->getValue()[0] == '\0') {
2433 // It has to have a value.
2434 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2435 Args.eraseArg(options::OPT__SLASH_o);
2439 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2440 // * no filename after it
2441 // * both /Yc and /Yu passed but with different filenames
2442 // * corresponding file not also passed as /FI
2443 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2444 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2445 if (YcArg && YcArg->getValue()[0] == '\0') {
2446 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2447 Args.eraseArg(options::OPT__SLASH_Yc);
2450 if (YuArg && YuArg->getValue()[0] == '\0') {
2451 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2452 Args.eraseArg(options::OPT__SLASH_Yu);
2455 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2456 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2457 Args.eraseArg(options::OPT__SLASH_Yc);
2458 Args.eraseArg(options::OPT__SLASH_Yu);
2459 YcArg = YuArg = nullptr;
2461 if (YcArg || YuArg) {
2462 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2463 bool FoundMatchingInclude = false;
2464 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2465 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2466 if (Inc->getValue() == Val)
2467 FoundMatchingInclude = true;
2469 if (!FoundMatchingInclude) {
2470 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2471 << (YcArg ? YcArg : YuArg)->getSpelling();
2472 Args.eraseArg(options::OPT__SLASH_Yc);
2473 Args.eraseArg(options::OPT__SLASH_Yu);
2474 YcArg = YuArg = nullptr;
2477 if (YcArg && Inputs.size() > 1) {
2478 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2479 Args.eraseArg(options::OPT__SLASH_Yc);
2482 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2483 // /Y- disables all pch handling. Rather than check for it everywhere,
2484 // just remove clang-cl pch-related flags here.
2485 Args.eraseArg(options::OPT__SLASH_Fp);
2486 Args.eraseArg(options::OPT__SLASH_Yc);
2487 Args.eraseArg(options::OPT__SLASH_Yu);
2488 YcArg = YuArg = nullptr;
2491 // Builder to be used to build offloading actions.
2492 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
2494 // Construct the actions to perform.
2495 ActionList LinkerInputs;
2497 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
2498 for (auto &I : Inputs) {
2499 types::ID InputType = I.first;
2500 const Arg *InputArg = I.second;
2503 types::getCompilationPhases(InputType, PL);
2505 // If the first step comes after the final phase we are doing as part of
2506 // this compilation, warn the user about it.
2507 phases::ID InitialPhase = PL[0];
2508 if (InitialPhase > FinalPhase) {
2509 // Claim here to avoid the more general unused warning.
2512 // Suppress all unused style warnings with -Qunused-arguments
2513 if (Args.hasArg(options::OPT_Qunused_arguments))
2516 // Special case when final phase determined by binary name, rather than
2517 // by a command-line argument with a corresponding Arg.
2519 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
2520 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
2521 // Special case '-E' warning on a previously preprocessed file to make
2523 else if (InitialPhase == phases::Compile &&
2524 FinalPhase == phases::Preprocess &&
2525 getPreprocessedType(InputType) == types::TY_INVALID)
2526 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
2527 << InputArg->getAsString(Args) << !!FinalPhaseArg
2528 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2530 Diag(clang::diag::warn_drv_input_file_unused)
2531 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2533 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2538 // Add a separate precompile phase for the compile phase.
2539 if (FinalPhase >= phases::Compile) {
2540 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
2541 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
2542 types::getCompilationPhases(HeaderType, PCHPL);
2543 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
2545 // Build the pipeline for the pch file.
2546 Action *ClangClPch =
2547 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
2548 for (phases::ID Phase : PCHPL)
2549 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2551 Actions.push_back(ClangClPch);
2552 // The driver currently exits after the first failed command. This
2553 // relies on that behavior, to make sure if the pch generation fails,
2554 // the main compilation won't run.
2558 // Build the pipeline for this file.
2559 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
2561 // Use the current host action in any of the offloading actions, if
2563 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2566 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2568 phases::ID Phase = *i;
2570 // We are done if this step is past what the user requested.
2571 if (Phase > FinalPhase)
2574 // Add any offload action the host action depends on.
2575 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2576 Current, InputArg, Phase, FinalPhase, PL);
2580 // Queue linker inputs.
2581 if (Phase == phases::Link) {
2582 assert((i + 1) == e && "linking must be final compilation step.");
2583 LinkerInputs.push_back(Current);
2588 // Otherwise construct the appropriate action.
2589 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2591 // We didn't create a new action, so we will just move to the next phase.
2592 if (NewCurrent == Current)
2595 Current = NewCurrent;
2597 // Use the current host action in any of the offloading actions, if
2599 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2602 if (Current->getType() == types::TY_Nothing)
2606 // If we ended with something, add to the output list.
2608 Actions.push_back(Current);
2610 // Add any top level actions generated for offloading.
2611 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
2614 // Add a link action if necessary.
2615 if (!LinkerInputs.empty()) {
2616 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2617 LA = OffloadBuilder.processHostLinkAction(LA);
2618 Actions.push_back(LA);
2621 // If we are linking, claim any options which are obviously only used for
2623 if (FinalPhase == phases::Link && PL.size() == 1) {
2624 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
2625 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2628 // Claim ignored clang-cl options.
2629 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
2631 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2632 // to non-CUDA compilations and should not trigger warnings there.
2633 Args.ClaimAllArgs(options::OPT_cuda_host_only);
2634 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
2637 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2638 phases::ID Phase, Action *Input) const {
2639 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
2641 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2642 // encode this in the steps because the intermediate type depends on
2643 // arguments. Just special case here.
2644 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2647 // Build the appropriate action.
2650 llvm_unreachable("link action invalid here.");
2651 case phases::Preprocess: {
2653 // -{M, MM} alter the output type.
2654 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
2655 OutputTy = types::TY_Dependencies;
2657 OutputTy = Input->getType();
2658 if (!Args.hasFlag(options::OPT_frewrite_includes,
2659 options::OPT_fno_rewrite_includes, false) &&
2661 OutputTy = types::getPreprocessedType(OutputTy);
2662 assert(OutputTy != types::TY_INVALID &&
2663 "Cannot preprocess this input type!");
2665 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
2667 case phases::Precompile: {
2668 types::ID OutputTy = getPrecompiledType(Input->getType());
2669 assert(OutputTy != types::TY_INVALID &&
2670 "Cannot precompile this input type!");
2671 if (Args.hasArg(options::OPT_fsyntax_only)) {
2672 // Syntax checks should not emit a PCH file
2673 OutputTy = types::TY_Nothing;
2675 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
2677 case phases::Compile: {
2678 if (Args.hasArg(options::OPT_fsyntax_only))
2679 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
2680 if (Args.hasArg(options::OPT_rewrite_objc))
2681 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
2682 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
2683 return C.MakeAction<CompileJobAction>(Input,
2684 types::TY_RewrittenLegacyObjC);
2685 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
2686 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
2687 if (Args.hasArg(options::OPT__migrate))
2688 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
2689 if (Args.hasArg(options::OPT_emit_ast))
2690 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
2691 if (Args.hasArg(options::OPT_module_file_info))
2692 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
2693 if (Args.hasArg(options::OPT_verify_pch))
2694 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2695 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
2697 case phases::Backend: {
2700 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
2701 return C.MakeAction<BackendJobAction>(Input, Output);
2703 if (Args.hasArg(options::OPT_emit_llvm)) {
2705 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
2706 return C.MakeAction<BackendJobAction>(Input, Output);
2708 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
2710 case phases::Assemble:
2711 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
2714 llvm_unreachable("invalid phase in ConstructPhaseAction");
2717 void Driver::BuildJobs(Compilation &C) const {
2718 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2720 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2722 // It is an error to provide a -o option if we are making multiple output
2725 unsigned NumOutputs = 0;
2726 for (const Action *A : C.getActions())
2727 if (A->getType() != types::TY_Nothing)
2730 if (NumOutputs > 1) {
2731 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
2732 FinalOutput = nullptr;
2736 // Collect the list of architectures.
2737 llvm::StringSet<> ArchNames;
2738 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2739 for (const Arg *A : C.getArgs())
2740 if (A->getOption().matches(options::OPT_arch))
2741 ArchNames.insert(A->getValue());
2743 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2744 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
2745 for (Action *A : C.getActions()) {
2746 // If we are linking an image for multiple archs then the linker wants
2747 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2748 // doesn't fit in cleanly because we have to pass this information down.
2750 // FIXME: This is a hack; find a cleaner way to integrate this into the
2752 const char *LinkingOutput = nullptr;
2753 if (isa<LipoJobAction>(A)) {
2755 LinkingOutput = FinalOutput->getValue();
2757 LinkingOutput = getDefaultImageName();
2760 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
2761 /*BoundArch*/ StringRef(),
2762 /*AtTopLevel*/ true,
2763 /*MultipleArchs*/ ArchNames.size() > 1,
2764 /*LinkingOutput*/ LinkingOutput, CachedResults,
2765 /*TargetDeviceOffloadKind*/ Action::OFK_None);
2768 // If the user passed -Qunused-arguments or there were errors, don't warn
2769 // about any unused arguments.
2770 if (Diags.hasErrorOccurred() ||
2771 C.getArgs().hasArg(options::OPT_Qunused_arguments))
2775 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
2777 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
2778 (void)C.getArgs().hasArg(options::OPT_driver_mode);
2779 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
2781 for (Arg *A : C.getArgs()) {
2782 // FIXME: It would be nice to be able to send the argument to the
2783 // DiagnosticsEngine, so that extra values, position, and so on could be
2785 if (!A->isClaimed()) {
2786 if (A->getOption().hasFlag(options::NoArgumentUnused))
2789 // Suppress the warning automatically if this is just a flag, and it is an
2790 // instance of an argument we already claimed.
2791 const Option &Opt = A->getOption();
2792 if (Opt.getKind() == Option::FlagClass) {
2793 bool DuplicateClaimed = false;
2795 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2796 if (AA->isClaimed()) {
2797 DuplicateClaimed = true;
2802 if (DuplicateClaimed)
2806 // In clang-cl, don't mention unknown arguments here since they have
2807 // already been warned about.
2808 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2809 Diag(clang::diag::warn_drv_unused_argument)
2810 << A->getAsString(C.getArgs());
2816 /// Utility class to control the collapse of dependent actions and select the
2817 /// tools accordingly.
2818 class ToolSelector final {
2819 /// The tool chain this selector refers to.
2820 const ToolChain &TC;
2822 /// The compilation this selector refers to.
2823 const Compilation &C;
2825 /// The base action this selector refers to.
2826 const JobAction *BaseAction;
2828 /// Set to true if the current toolchain refers to host actions.
2829 bool IsHostSelector;
2831 /// Set to true if save-temps and embed-bitcode functionalities are active.
2835 /// Get previous dependent action or null if that does not exist. If
2836 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2837 /// null will be returned.
2838 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2839 ActionList &SavedOffloadAction,
2840 bool CanBeCollapsed = true) {
2841 // An option can be collapsed only if it has a single input.
2842 if (Inputs.size() != 1)
2845 Action *CurAction = *Inputs.begin();
2846 if (CanBeCollapsed &&
2847 !CurAction->isCollapsingWithNextDependentActionLegal())
2850 // If the input action is an offload action. Look through it and save any
2851 // offload action that can be dropped in the event of a collapse.
2852 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2853 // If the dependent action is a device action, we will attempt to collapse
2854 // only with other device actions. Otherwise, we would do the same but
2855 // with host actions only.
2856 if (!IsHostSelector) {
2857 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2859 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2860 if (CanBeCollapsed &&
2861 !CurAction->isCollapsingWithNextDependentActionLegal())
2863 SavedOffloadAction.push_back(OA);
2864 return dyn_cast<JobAction>(CurAction);
2866 } else if (OA->hasHostDependence()) {
2867 CurAction = OA->getHostDependence();
2868 if (CanBeCollapsed &&
2869 !CurAction->isCollapsingWithNextDependentActionLegal())
2871 SavedOffloadAction.push_back(OA);
2872 return dyn_cast<JobAction>(CurAction);
2877 return dyn_cast<JobAction>(CurAction);
2880 /// Return true if an assemble action can be collapsed.
2881 bool canCollapseAssembleAction() const {
2882 return TC.useIntegratedAs() && !SaveTemps &&
2883 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2884 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2885 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2888 /// Return true if a preprocessor action can be collapsed.
2889 bool canCollapsePreprocessorAction() const {
2890 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2891 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2892 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2895 /// Struct that relates an action with the offload actions that would be
2896 /// collapsed with it.
2897 struct JobActionInfo final {
2898 /// The action this info refers to.
2899 const JobAction *JA = nullptr;
2900 /// The offload actions we need to take care off if this action is
2902 ActionList SavedOffloadAction;
2905 /// Append collapsed offload actions from the give nnumber of elements in the
2906 /// action info array.
2907 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2908 ArrayRef<JobActionInfo> &ActionInfo,
2909 unsigned ElementNum) {
2910 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2911 for (unsigned I = 0; I < ElementNum; ++I)
2912 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2913 ActionInfo[I].SavedOffloadAction.end());
2916 /// Functions that attempt to perform the combining. They detect if that is
2917 /// legal, and if so they update the inputs \a Inputs and the offload action
2918 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
2919 /// the combined action is returned. If the combining is not legal or if the
2920 /// tool does not exist, null is returned.
2921 /// Currently three kinds of collapsing are supported:
2922 /// - Assemble + Backend + Compile;
2923 /// - Assemble + Backend ;
2924 /// - Backend + Compile.
2926 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2927 const ActionList *&Inputs,
2928 ActionList &CollapsedOffloadAction) {
2929 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
2931 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2932 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2933 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
2934 if (!AJ || !BJ || !CJ)
2937 // Get compiler tool.
2938 const Tool *T = TC.SelectTool(*CJ);
2942 // When using -fembed-bitcode, it is required to have the same tool (clang)
2943 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2945 const Tool *BT = TC.SelectTool(*BJ);
2950 if (!T->hasIntegratedAssembler())
2953 Inputs = &CJ->getInputs();
2954 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2958 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
2959 const ActionList *&Inputs,
2960 ActionList &CollapsedOffloadAction) {
2961 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
2963 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2964 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2968 // Retrieve the compile job, backend action must always be preceded by one.
2969 ActionList CompileJobOffloadActions;
2970 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
2971 /*CanBeCollapsed=*/false);
2972 if (!AJ || !BJ || !CJ)
2975 assert(isa<CompileJobAction>(CJ) &&
2976 "Expecting compile job preceding backend job.");
2978 // Get compiler tool.
2979 const Tool *T = TC.SelectTool(*CJ);
2983 if (!T->hasIntegratedAssembler())
2986 Inputs = &BJ->getInputs();
2987 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2991 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2992 const ActionList *&Inputs,
2993 ActionList &CollapsedOffloadAction) {
2994 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
2996 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
2997 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3001 // Get compiler tool.
3002 const Tool *T = TC.SelectTool(*CJ);
3006 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3009 Inputs = &CJ->getInputs();
3010 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3015 /// Updates the inputs if the obtained tool supports combining with
3016 /// preprocessor action, and the current input is indeed a preprocessor
3017 /// action. If combining results in the collapse of offloading actions, those
3018 /// are appended to \a CollapsedOffloadAction.
3019 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3020 ActionList &CollapsedOffloadAction) {
3021 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3024 // Attempt to get a preprocessor action dependence.
3025 ActionList PreprocessJobOffloadActions;
3026 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3027 if (!PJ || !isa<PreprocessJobAction>(PJ))
3030 // This is legal to combine. Append any offload action we found and set the
3031 // current inputs to preprocessor inputs.
3032 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3033 PreprocessJobOffloadActions.end());
3034 Inputs = &PJ->getInputs();
3038 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3039 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3040 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3041 EmbedBitcode(EmbedBitcode) {
3042 assert(BaseAction && "Invalid base action.");
3043 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3046 /// Check if a chain of actions can be combined and return the tool that can
3047 /// handle the combination of actions. The pointer to the current inputs \a
3048 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3049 /// connected to collapsed actions are updated accordingly. The latter enables
3050 /// the caller of the selector to process them afterwards instead of just
3051 /// dropping them. If no suitable tool is found, null will be returned.
3052 const Tool *getTool(const ActionList *&Inputs,
3053 ActionList &CollapsedOffloadAction) {
3055 // Get the largest chain of actions that we could combine.
3058 SmallVector<JobActionInfo, 5> ActionChain(1);
3059 ActionChain.back().JA = BaseAction;
3060 while (ActionChain.back().JA) {
3061 const Action *CurAction = ActionChain.back().JA;
3063 // Grow the chain by one element.
3064 ActionChain.resize(ActionChain.size() + 1);
3065 JobActionInfo &AI = ActionChain.back();
3067 // Attempt to fill it with the
3069 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3072 // Pop the last action info as it could not be filled.
3073 ActionChain.pop_back();
3076 // Attempt to combine actions. If all combining attempts failed, just return
3077 // the tool of the provided action. At the end we attempt to combine the
3078 // action with any preprocessor action it may depend on.
3081 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3082 CollapsedOffloadAction);
3084 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3086 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3088 Inputs = &BaseAction->getInputs();
3089 T = TC.SelectTool(*BaseAction);
3092 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3098 /// Return a string that uniquely identifies the result of a job. The bound arch
3099 /// is not necessarily represented in the toolchain's triple -- for example,
3100 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
3101 /// Also, we need to add the offloading device kind, as the same tool chain can
3102 /// be used for host and device for some programming models, e.g. OpenMP.
3103 static std::string GetTriplePlusArchString(const ToolChain *TC,
3104 StringRef BoundArch,
3105 Action::OffloadKind OffloadKind) {
3106 std::string TriplePlusArch = TC->getTriple().normalize();
3107 if (!BoundArch.empty()) {
3108 TriplePlusArch += "-";
3109 TriplePlusArch += BoundArch;
3111 TriplePlusArch += "-";
3112 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3113 return TriplePlusArch;
3116 InputInfo Driver::BuildJobsForAction(
3117 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3118 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3119 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3120 Action::OffloadKind TargetDeviceOffloadKind) const {
3121 std::pair<const Action *, std::string> ActionTC = {
3122 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3123 auto CachedResult = CachedResults.find(ActionTC);
3124 if (CachedResult != CachedResults.end()) {
3125 return CachedResult->second;
3127 InputInfo Result = BuildJobsForActionNoCache(
3128 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3129 CachedResults, TargetDeviceOffloadKind);
3130 CachedResults[ActionTC] = Result;
3134 InputInfo Driver::BuildJobsForActionNoCache(
3135 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3136 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3137 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3138 Action::OffloadKind TargetDeviceOffloadKind) const {
3139 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3141 InputInfoList OffloadDependencesInputInfo;
3142 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3143 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3144 // The offload action is expected to be used in four different situations.
3146 // a) Set a toolchain/architecture/kind for a host action:
3147 // Host Action 1 -> OffloadAction -> Host Action 2
3149 // b) Set a toolchain/architecture/kind for a device action;
3150 // Device Action 1 -> OffloadAction -> Device Action 2
3152 // c) Specify a device dependence to a host action;
3153 // Device Action 1 _
3155 // Host Action 1 ---> OffloadAction -> Host Action 2
3157 // d) Specify a host dependence to a device action.
3160 // Device Action 1 ---> OffloadAction -> Device Action 2
3162 // For a) and b), we just return the job generated for the dependence. For
3163 // c) and d) we override the current action with the host/device dependence
3164 // if the current toolchain is host/device and set the offload dependences
3165 // info with the jobs obtained from the device/host dependence(s).
3167 // If there is a single device option, just generate the job for it.
3168 if (OA->hasSingleDeviceDependence()) {
3170 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3171 const char *DepBoundArch) {
3173 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3174 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3175 CachedResults, DepA->getOffloadingDeviceKind());
3180 // If 'Action 2' is host, we generate jobs for the device dependences and
3181 // override the current action with the host dependence. Otherwise, we
3182 // generate the host dependences and override the action with the device
3183 // dependence. The dependences can't therefore be a top-level action.
3184 OA->doOnEachDependence(
3185 /*IsHostDependence=*/BuildingForOffloadDevice,
3186 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3187 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3188 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3189 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3190 DepA->getOffloadingDeviceKind()));
3193 A = BuildingForOffloadDevice
3194 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3195 : OA->getHostDependence();
3198 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3199 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3200 // just using Args was better?
3201 const Arg &Input = IA->getInputArg();
3203 if (Input.getOption().matches(options::OPT_INPUT)) {
3204 const char *Name = Input.getValue();
3205 return InputInfo(A, Name, /* BaseInput = */ Name);
3207 return InputInfo(A, &Input, /* BaseInput = */ "");
3210 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
3211 const ToolChain *TC;
3212 StringRef ArchName = BAA->getArchName();
3214 if (!ArchName.empty())
3215 TC = &getToolChain(C.getArgs(),
3216 computeTargetTriple(*this, DefaultTargetTriple,
3217 C.getArgs(), ArchName));
3219 TC = &C.getDefaultToolChain();
3221 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
3222 MultipleArchs, LinkingOutput, CachedResults,
3223 TargetDeviceOffloadKind);
3227 const ActionList *Inputs = &A->getInputs();
3229 const JobAction *JA = cast<JobAction>(A);
3230 ActionList CollapsedOffloadActions;
3232 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3233 embedBitcodeInObject() && !isUsingLTO());
3234 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3239 // If we've collapsed action list that contained OffloadAction we
3240 // need to build jobs for host/device-side inputs it may have held.
3241 for (const auto *OA : CollapsedOffloadActions)
3242 cast<OffloadAction>(OA)->doOnEachDependence(
3243 /*IsHostDependence=*/BuildingForOffloadDevice,
3244 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3245 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3246 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
3247 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
3248 DepA->getOffloadingDeviceKind()));
3251 // Only use pipes when there is exactly one input.
3252 InputInfoList InputInfos;
3253 for (const Action *Input : *Inputs) {
3254 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3255 // shouldn't get temporary output names.
3256 // FIXME: Clean this up.
3257 bool SubJobAtTopLevel =
3258 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
3259 InputInfos.push_back(BuildJobsForAction(
3260 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
3261 CachedResults, A->getOffloadingDeviceKind()));
3264 // Always use the first input as the base input.
3265 const char *BaseInput = InputInfos[0].getBaseInput();
3267 // ... except dsymutil actions, which use their actual input as the base
3269 if (JA->getType() == types::TY_dSYM)
3270 BaseInput = InputInfos[0].getFilename();
3272 // Append outputs of offload device jobs to the input list
3273 if (!OffloadDependencesInputInfo.empty())
3274 InputInfos.append(OffloadDependencesInputInfo.begin(),
3275 OffloadDependencesInputInfo.end());
3277 // Set the effective triple of the toolchain for the duration of this job.
3278 llvm::Triple EffectiveTriple;
3279 const ToolChain &ToolTC = T->getToolChain();
3280 const ArgList &Args =
3281 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
3282 if (InputInfos.size() != 1) {
3283 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3285 // Pass along the input type if it can be unambiguously determined.
3286 EffectiveTriple = llvm::Triple(
3287 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3289 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3291 // Determine the place to write output to, if any.
3293 InputInfoList UnbundlingResults;
3294 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3295 // If we have an unbundling job, we need to create results for all the
3296 // outputs. We also update the results cache so that other actions using
3297 // this unbundling action can get the right results.
3298 for (auto &UI : UA->getDependentActionsInfo()) {
3299 assert(UI.DependentOffloadKind != Action::OFK_None &&
3300 "Unbundling with no offloading??");
3302 // Unbundling actions are never at the top level. When we generate the
3303 // offloading prefix, we also do that for the host file because the
3304 // unbundling action does not change the type of the output which can
3305 // cause a overwrite.
3306 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3307 UI.DependentOffloadKind,
3308 UI.DependentToolChain->getTriple().normalize(),
3309 /*CreatePrefixForHost=*/true);
3310 auto CurI = InputInfo(
3311 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3312 /*AtTopLevel=*/false, MultipleArchs,
3315 // Save the unbundling result.
3316 UnbundlingResults.push_back(CurI);
3318 // Get the unique string identifier for this dependence and cache the
3320 CachedResults[{A, GetTriplePlusArchString(
3321 UI.DependentToolChain, UI.DependentBoundArch,
3322 UI.DependentOffloadKind)}] = CurI;
3325 // Now that we have all the results generated, select the one that should be
3326 // returned for the current depending action.
3327 std::pair<const Action *, std::string> ActionTC = {
3328 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3329 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3330 "Result does not exist??");
3331 Result = CachedResults[ActionTC];
3332 } else if (JA->getType() == types::TY_Nothing)
3333 Result = InputInfo(A, BaseInput);
3335 // We only have to generate a prefix for the host if this is not a top-level
3337 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3338 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3339 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3341 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
3342 AtTopLevel, MultipleArchs,
3347 if (CCCPrintBindings && !CCGenDiagnostics) {
3348 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3349 << " - \"" << T->getName() << "\", inputs: [";
3350 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3351 llvm::errs() << InputInfos[i].getAsString();
3353 llvm::errs() << ", ";
3355 if (UnbundlingResults.empty())
3356 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3358 llvm::errs() << "], outputs: [";
3359 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3360 llvm::errs() << UnbundlingResults[i].getAsString();
3362 llvm::errs() << ", ";
3364 llvm::errs() << "] \n";
3367 if (UnbundlingResults.empty())
3369 C, *JA, Result, InputInfos,
3370 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3373 T->ConstructJobMultipleOutputs(
3374 C, *JA, UnbundlingResults, InputInfos,
3375 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3381 const char *Driver::getDefaultImageName() const {
3382 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3383 return Target.isOSWindows() ? "a.exe" : "a.out";
3386 /// \brief Create output filename based on ArgValue, which could either be a
3387 /// full filename, filename without extension, or a directory. If ArgValue
3388 /// does not provide a filename, then use BaseName, and use the extension
3389 /// suitable for FileType.
3390 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
3392 types::ID FileType) {
3393 SmallString<128> Filename = ArgValue;
3395 if (ArgValue.empty()) {
3396 // If the argument is empty, output to BaseName in the current dir.
3397 Filename = BaseName;
3398 } else if (llvm::sys::path::is_separator(Filename.back())) {
3399 // If the argument is a directory, output to BaseName in that dir.
3400 llvm::sys::path::append(Filename, BaseName);
3403 if (!llvm::sys::path::has_extension(ArgValue)) {
3404 // If the argument didn't provide an extension, then set it.
3405 const char *Extension = types::getTypeTempSuffix(FileType, true);
3407 if (FileType == types::TY_Image &&
3408 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3409 // The output file is a dll.
3413 llvm::sys::path::replace_extension(Filename, Extension);
3416 return Args.MakeArgString(Filename.c_str());
3419 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
3420 const char *BaseInput,
3421 StringRef BoundArch, bool AtTopLevel,
3423 StringRef OffloadingPrefix) const {
3424 llvm::PrettyStackTraceString CrashInfo("Computing output path");
3425 // Output to a user requested destination?
3426 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
3427 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
3428 return C.addResultFile(FinalOutput->getValue(), &JA);
3431 // For /P, preprocess to file named after BaseInput.
3432 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3433 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3434 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3436 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
3437 NameArg = A->getValue();
3438 return C.addResultFile(
3439 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3443 // Default to writing to stdout?
3444 if (AtTopLevel && !CCGenDiagnostics &&
3445 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
3448 // Is this the assembly listing for /FA?
3449 if (JA.getType() == types::TY_PP_Asm &&
3450 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3451 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3452 // Use /Fa and the input filename to determine the asm file name.
3453 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3454 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
3455 return C.addResultFile(
3456 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3460 // Output to a temporary file?
3461 if ((!AtTopLevel && !isSaveTempsEnabled() &&
3462 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
3464 StringRef Name = llvm::sys::path::filename(BaseInput);
3465 std::pair<StringRef, StringRef> Split = Name.split('.');
3466 std::string TmpName = GetTemporaryPath(
3467 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3468 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3471 SmallString<128> BasePath(BaseInput);
3474 // Dsymutil actions should use the full path.
3475 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
3476 BaseName = BasePath;
3478 BaseName = llvm::sys::path::filename(BasePath);
3480 // Determine what the derived output name should be.
3481 const char *NamedOutput;
3483 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
3484 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3485 // The /Fo or /o flag decides the object filename.
3488 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3491 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
3492 } else if (JA.getType() == types::TY_Image &&
3493 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3494 options::OPT__SLASH_o)) {
3495 // The /Fe or /o flag names the linked file.
3498 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3501 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
3502 } else if (JA.getType() == types::TY_Image) {
3504 // clang-cl uses BaseName for the executable name.
3506 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
3508 SmallString<128> Output(getDefaultImageName());
3509 Output += OffloadingPrefix;
3510 if (MultipleArchs && !BoundArch.empty()) {
3512 Output.append(BoundArch);
3514 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
3516 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
3517 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
3519 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
3520 assert(Suffix && "All types used for output should have a suffix.");
3522 std::string::size_type End = std::string::npos;
3523 if (!types::appendSuffixForType(JA.getType()))
3524 End = BaseName.rfind('.');
3525 SmallString<128> Suffixed(BaseName.substr(0, End));
3526 Suffixed += OffloadingPrefix;
3527 if (MultipleArchs && !BoundArch.empty()) {
3529 Suffixed.append(BoundArch);
3531 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3532 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3533 // optimized bitcode output.
3534 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3535 JA.getType() == types::TY_LLVM_BC)
3539 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3542 // Prepend object file path if -save-temps=obj
3543 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3544 JA.getType() != types::TY_PCH) {
3545 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3546 SmallString<128> TempPath(FinalOutput->getValue());
3547 llvm::sys::path::remove_filename(TempPath);
3548 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3549 llvm::sys::path::append(TempPath, OutputFileName);
3550 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3553 // If we're saving temps and the temp file conflicts with the input file,
3554 // then avoid overwriting input file.
3555 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
3556 bool SameFile = false;
3557 SmallString<256> Result;
3558 llvm::sys::fs::current_path(Result);
3559 llvm::sys::path::append(Result, BaseName);
3560 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3561 // Must share the same path to conflict.
3563 StringRef Name = llvm::sys::path::filename(BaseInput);
3564 std::pair<StringRef, StringRef> Split = Name.split('.');
3565 std::string TmpName = GetTemporaryPath(
3566 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3567 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3571 // As an annoying special case, PCH generation doesn't strip the pathname.
3572 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
3573 llvm::sys::path::remove_filename(BasePath);
3574 if (BasePath.empty())
3575 BasePath = NamedOutput;
3577 llvm::sys::path::append(BasePath, NamedOutput);
3578 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
3580 return C.addResultFile(NamedOutput, &JA);
3584 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
3585 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3586 // attempting to use this prefix when looking for file paths.
3587 for (const std::string &Dir : PrefixDirs) {
3590 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3591 llvm::sys::path::append(P, Name);
3592 if (llvm::sys::fs::exists(Twine(P)))
3596 SmallString<128> P(ResourceDir);
3597 llvm::sys::path::append(P, Name);
3598 if (llvm::sys::fs::exists(Twine(P)))
3601 for (const std::string &Dir : TC.getFilePaths()) {
3604 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3605 llvm::sys::path::append(P, Name);
3606 if (llvm::sys::fs::exists(Twine(P)))
3613 void Driver::generatePrefixedToolNames(
3614 StringRef Tool, const ToolChain &TC,
3615 SmallVectorImpl<std::string> &Names) const {
3616 // FIXME: Needs a better variable than DefaultTargetTriple
3617 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
3618 Names.emplace_back(Tool);
3620 // Allow the discovery of tools prefixed with LLVM's default target triple.
3621 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3622 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
3623 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
3626 static bool ScanDirForExecutable(SmallString<128> &Dir,
3627 ArrayRef<std::string> Names) {
3628 for (const auto &Name : Names) {
3629 llvm::sys::path::append(Dir, Name);
3630 if (llvm::sys::fs::can_execute(Twine(Dir)))
3632 llvm::sys::path::remove_filename(Dir);
3637 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
3638 SmallVector<std::string, 2> TargetSpecificExecutables;
3639 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3641 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3642 // attempting to use this prefix when looking for program paths.
3643 for (const auto &PrefixDir : PrefixDirs) {
3644 if (llvm::sys::fs::is_directory(PrefixDir)) {
3645 SmallString<128> P(PrefixDir);
3646 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3649 SmallString<128> P((PrefixDir + Name).str());
3650 if (llvm::sys::fs::can_execute(Twine(P)))
3655 const ToolChain::path_list &List = TC.getProgramPaths();
3656 for (const auto &Path : List) {
3657 SmallString<128> P(Path);
3658 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3662 // If all else failed, search the path.
3663 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3664 if (llvm::ErrorOr<std::string> P =
3665 llvm::sys::findProgramByName(TargetSpecificExecutable))
3671 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
3672 SmallString<128> Path;
3673 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
3675 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
3682 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3683 SmallString<128> Output;
3684 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3685 // FIXME: If anybody needs it, implement this obscure rule:
3686 // "If you specify a directory without a file name, the default file name
3687 // is VCx0.pch., where x is the major version of Visual C++ in use."
3688 Output = FpArg->getValue();
3690 // "If you do not specify an extension as part of the path name, an
3691 // extension of .pch is assumed. "
3692 if (!llvm::sys::path::has_extension(Output))
3696 llvm::sys::path::replace_extension(Output, ".pch");
3698 return Output.str();
3701 const ToolChain &Driver::getToolChain(const ArgList &Args,
3702 const llvm::Triple &Target) const {
3704 auto &TC = ToolChains[Target.str()];
3706 switch (Target.getOS()) {
3707 case llvm::Triple::Haiku:
3708 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
3710 case llvm::Triple::CloudABI:
3711 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
3713 case llvm::Triple::Darwin:
3714 case llvm::Triple::MacOSX:
3715 case llvm::Triple::IOS:
3716 case llvm::Triple::TvOS:
3717 case llvm::Triple::WatchOS:
3718 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
3720 case llvm::Triple::DragonFly:
3721 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
3723 case llvm::Triple::OpenBSD:
3724 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
3726 case llvm::Triple::Bitrig:
3727 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
3729 case llvm::Triple::NetBSD:
3730 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
3732 case llvm::Triple::FreeBSD:
3733 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
3735 case llvm::Triple::Minix:
3736 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
3738 case llvm::Triple::Linux:
3739 case llvm::Triple::ELFIAMCU:
3740 if (Target.getArch() == llvm::Triple::hexagon)
3741 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3743 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3744 !Target.hasEnvironment())
3745 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3748 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
3750 case llvm::Triple::NaCl:
3751 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
3753 case llvm::Triple::Fuchsia:
3754 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
3756 case llvm::Triple::Solaris:
3757 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
3759 case llvm::Triple::AMDHSA:
3760 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
3762 case llvm::Triple::Win32:
3763 switch (Target.getEnvironment()) {
3765 if (Target.isOSBinFormatELF())
3766 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3767 else if (Target.isOSBinFormatMachO())
3768 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3770 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3772 case llvm::Triple::GNU:
3773 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
3775 case llvm::Triple::Itanium:
3776 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3779 case llvm::Triple::MSVC:
3780 case llvm::Triple::UnknownEnvironment:
3781 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
3785 case llvm::Triple::PS4:
3786 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
3788 case llvm::Triple::Contiki:
3789 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
3792 // Of these targets, Hexagon is the only one that might have
3793 // an OS of Linux, in which case it got handled above already.
3794 switch (Target.getArch()) {
3795 case llvm::Triple::tce:
3796 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
3798 case llvm::Triple::tcele:
3799 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
3801 case llvm::Triple::hexagon:
3802 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3805 case llvm::Triple::lanai:
3806 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
3808 case llvm::Triple::xcore:
3809 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
3811 case llvm::Triple::wasm32:
3812 case llvm::Triple::wasm64:
3813 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
3815 case llvm::Triple::avr:
3816 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
3819 if (Target.getVendor() == llvm::Triple::Myriad)
3820 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3822 else if (Target.isOSBinFormatELF())
3823 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3824 else if (Target.isOSBinFormatMachO())
3825 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3827 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3832 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3833 // compiles always need two toolchains, the CUDA toolchain and the host
3834 // toolchain. So the only valid way to create a CUDA toolchain is via
3835 // CreateOffloadingDeviceToolChains.
3840 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
3841 // Say "no" if there is not exactly one input of a type clang understands.
3842 if (JA.size() != 1 ||
3843 !types::isAcceptedByClang((*JA.input_begin())->getType()))
3846 // And say "no" if this is not a kind of action clang understands.
3847 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
3848 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
3854 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3855 /// grouped values as integers. Numbers which are not provided are set to 0.
3857 /// \return True if the entire string was parsed (9.2), or all groups were
3858 /// parsed (10.3.5extrastuff).
3859 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3860 unsigned &Micro, bool &HadExtra) {
3863 Major = Minor = Micro = 0;
3867 if (Str.consumeInteger(10, Major))
3874 Str = Str.drop_front(1);
3876 if (Str.consumeInteger(10, Minor))
3882 Str = Str.drop_front(1);
3884 if (Str.consumeInteger(10, Micro))
3891 /// Parse digits from a string \p Str and fulfill \p Digits with
3892 /// the parsed numbers. This method assumes that the max number of
3893 /// digits to look for is equal to Digits.size().
3895 /// \return True if the entire string was parsed and there are
3896 /// no extra characters remaining at the end.
3897 bool Driver::GetReleaseVersion(StringRef Str,
3898 MutableArrayRef<unsigned> Digits) {
3902 unsigned CurDigit = 0;
3903 while (CurDigit < Digits.size()) {
3905 if (Str.consumeInteger(10, Digit))
3907 Digits[CurDigit] = Digit;
3912 Str = Str.drop_front(1);
3916 // More digits than requested, bail out...
3920 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3921 unsigned IncludedFlagsBitmask = 0;
3922 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
3924 if (Mode == CLMode) {
3925 // Include CL and Core options.
3926 IncludedFlagsBitmask |= options::CLOption;
3927 IncludedFlagsBitmask |= options::CoreOption;
3929 ExcludedFlagsBitmask |= options::CLOption;
3932 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3935 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
3936 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);