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/Ananas.h"
15 #include "ToolChains/Bitrig.h"
16 #include "ToolChains/Clang.h"
17 #include "ToolChains/CloudABI.h"
18 #include "ToolChains/Contiki.h"
19 #include "ToolChains/CrossWindows.h"
20 #include "ToolChains/Cuda.h"
21 #include "ToolChains/Darwin.h"
22 #include "ToolChains/DragonFly.h"
23 #include "ToolChains/FreeBSD.h"
24 #include "ToolChains/Fuchsia.h"
25 #include "ToolChains/Gnu.h"
26 #include "ToolChains/BareMetal.h"
27 #include "ToolChains/Haiku.h"
28 #include "ToolChains/Hexagon.h"
29 #include "ToolChains/Lanai.h"
30 #include "ToolChains/Linux.h"
31 #include "ToolChains/MinGW.h"
32 #include "ToolChains/Minix.h"
33 #include "ToolChains/MipsLinux.h"
34 #include "ToolChains/MSVC.h"
35 #include "ToolChains/Myriad.h"
36 #include "ToolChains/NaCl.h"
37 #include "ToolChains/NetBSD.h"
38 #include "ToolChains/OpenBSD.h"
39 #include "ToolChains/PS4CPU.h"
40 #include "ToolChains/Solaris.h"
41 #include "ToolChains/TCE.h"
42 #include "ToolChains/WebAssembly.h"
43 #include "ToolChains/XCore.h"
44 #include "clang/Basic/Version.h"
45 #include "clang/Basic/VirtualFileSystem.h"
46 #include "clang/Config/config.h"
47 #include "clang/Driver/Action.h"
48 #include "clang/Driver/Compilation.h"
49 #include "clang/Driver/DriverDiagnostic.h"
50 #include "clang/Driver/Job.h"
51 #include "clang/Driver/Options.h"
52 #include "clang/Driver/SanitizerArgs.h"
53 #include "clang/Driver/Tool.h"
54 #include "clang/Driver/ToolChain.h"
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallSet.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/ADT/StringSet.h"
60 #include "llvm/ADT/StringSwitch.h"
61 #include "llvm/Option/Arg.h"
62 #include "llvm/Option/ArgList.h"
63 #include "llvm/Option/OptSpecifier.h"
64 #include "llvm/Option/OptTable.h"
65 #include "llvm/Option/Option.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/FileSystem.h"
68 #include "llvm/Support/Path.h"
69 #include "llvm/Support/PrettyStackTrace.h"
70 #include "llvm/Support/Process.h"
71 #include "llvm/Support/Program.h"
72 #include "llvm/Support/TargetRegistry.h"
73 #include "llvm/Support/raw_ostream.h"
78 #include <unistd.h> // getpid
81 using namespace clang::driver;
82 using namespace clang;
83 using namespace llvm::opt;
85 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
86 DiagnosticsEngine &Diags,
87 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
88 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
89 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
90 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
91 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
92 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
93 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
94 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
95 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
96 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
97 GenReproducer(false), SuppressMissingInputWarning(false) {
99 // Provide a sane fallback if no VFS is specified.
101 this->VFS = vfs::getRealFileSystem();
103 Name = llvm::sys::path::filename(ClangExecutable);
104 Dir = llvm::sys::path::parent_path(ClangExecutable);
105 InstalledDir = Dir; // Provide a sensible default installed dir.
107 // Compute the path to the resource directory.
108 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
109 SmallString<128> P(Dir);
110 if (ClangResourceDir != "") {
111 llvm::sys::path::append(P, ClangResourceDir);
113 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
114 P = llvm::sys::path::parent_path(Dir);
115 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
116 CLANG_VERSION_STRING);
118 ResourceDir = P.str();
121 void Driver::ParseDriverMode(StringRef ProgramName,
122 ArrayRef<const char *> Args) {
123 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
124 StringRef DefaultMode(Default.second);
125 setDriverModeFromOption(DefaultMode);
127 for (const char *ArgPtr : Args) {
128 // Ingore nullptrs, they are response file's EOL markers
129 if (ArgPtr == nullptr)
131 const StringRef Arg = ArgPtr;
132 setDriverModeFromOption(Arg);
136 void Driver::setDriverModeFromOption(StringRef Opt) {
137 const std::string OptName =
138 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
139 if (!Opt.startswith(OptName))
141 StringRef Value = Opt.drop_front(OptName.size());
143 const unsigned M = llvm::StringSwitch<unsigned>(Value)
144 .Case("gcc", GCCMode)
145 .Case("g++", GXXMode)
146 .Case("cpp", CPPMode)
151 Mode = static_cast<DriverMode>(M);
153 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
156 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
157 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
159 unsigned IncludedFlagsBitmask;
160 unsigned ExcludedFlagsBitmask;
161 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
162 getIncludeExcludeOptionFlagMasks();
164 unsigned MissingArgIndex, MissingArgCount;
166 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
167 IncludedFlagsBitmask, ExcludedFlagsBitmask);
169 // Check for missing argument error.
171 Diag(clang::diag::err_drv_missing_argument)
172 << Args.getArgString(MissingArgIndex) << MissingArgCount;
174 // Check for unsupported options.
175 for (const Arg *A : Args) {
176 if (A->getOption().hasFlag(options::Unsupported)) {
177 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
181 // Warn about -mcpu= without an argument.
182 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
183 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
187 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
188 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
189 diag::err_drv_unknown_argument)
190 << A->getAsString(Args);
195 // Determine which compilation mode we are in. We look for options which
196 // affect the phase, starting with the earliest phases, and record which
197 // option we used to determine the final phase.
198 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
199 Arg **FinalPhaseArg) const {
200 Arg *PhaseArg = nullptr;
201 phases::ID FinalPhase;
203 // -{E,EP,P,M,MM} only run the preprocessor.
204 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
205 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
206 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
207 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
208 FinalPhase = phases::Preprocess;
210 // --precompile only runs up to precompilation.
211 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
212 FinalPhase = phases::Precompile;
214 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
215 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
216 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
217 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
218 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
219 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
220 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
221 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
222 options::OPT__analyze_auto)) ||
223 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
224 FinalPhase = phases::Compile;
226 // -S only runs up to the backend.
227 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
228 FinalPhase = phases::Backend;
230 // -c compilation only runs up to the assembler.
231 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
232 FinalPhase = phases::Assemble;
234 // Otherwise do everything.
236 FinalPhase = phases::Link;
239 *FinalPhaseArg = PhaseArg;
244 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
246 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
247 Args.getBaseArgs().MakeIndex(Value), Value.data());
248 Args.AddSynthesizedArg(A);
253 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
254 DerivedArgList *DAL = new DerivedArgList(Args);
256 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
257 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
258 for (Arg *A : Args) {
259 // Unfortunately, we have to parse some forwarding options (-Xassembler,
260 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
261 // (assembler and preprocessor), or bypass a previous driver ('collect2').
263 // Rewrite linker options, to replace --no-demangle with a custom internal
265 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
266 A->getOption().matches(options::OPT_Xlinker)) &&
267 A->containsValue("--no-demangle")) {
268 // Add the rewritten no-demangle argument.
269 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
271 // Add the remaining values as Xlinker arguments.
272 for (StringRef Val : A->getValues())
273 if (Val != "--no-demangle")
274 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
279 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
280 // some build systems. We don't try to be complete here because we don't
281 // care to encourage this usage model.
282 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
283 (A->getValue(0) == StringRef("-MD") ||
284 A->getValue(0) == StringRef("-MMD"))) {
285 // Rewrite to -MD/-MMD along with -MF.
286 if (A->getValue(0) == StringRef("-MD"))
287 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
289 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
290 if (A->getNumValues() == 2)
291 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
296 // Rewrite reserved library names.
297 if (A->getOption().matches(options::OPT_l)) {
298 StringRef Value = A->getValue();
300 // Rewrite unless -nostdlib is present.
301 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
302 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
306 // Rewrite unconditionally.
307 if (Value == "cc_kext") {
308 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
313 // Pick up inputs via the -- option.
314 if (A->getOption().matches(options::OPT__DASH_DASH)) {
316 for (StringRef Val : A->getValues())
317 DAL->append(MakeInputArg(*DAL, *Opts, Val));
324 // Enforce -static if -miamcu is present.
325 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
326 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
328 // Add a default value of -mlinker-version=, if one was given and the user
329 // didn't specify one.
330 #if defined(HOST_LINK_VERSION)
331 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
332 strlen(HOST_LINK_VERSION) > 0) {
333 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
335 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
342 /// \brief Compute target triple from args.
344 /// This routine provides the logic to compute a target triple from various
345 /// args passed to the driver and the default triple string.
346 static llvm::Triple computeTargetTriple(const Driver &D,
347 StringRef DefaultTargetTriple,
349 StringRef DarwinArchName = "") {
350 // FIXME: Already done in Compilation *Driver::BuildCompilation
351 if (const Arg *A = Args.getLastArg(options::OPT_target))
352 DefaultTargetTriple = A->getValue();
354 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
356 // Handle Apple-specific options available here.
357 if (Target.isOSBinFormatMachO()) {
358 // If an explict Darwin arch name is given, that trumps all.
359 if (!DarwinArchName.empty()) {
360 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
364 // Handle the Darwin '-arch' flag.
365 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
366 StringRef ArchName = A->getValue();
367 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
371 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
372 // '-mbig-endian'/'-EB'.
373 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
374 options::OPT_mbig_endian)) {
375 if (A->getOption().matches(options::OPT_mlittle_endian)) {
376 llvm::Triple LE = Target.getLittleEndianArchVariant();
377 if (LE.getArch() != llvm::Triple::UnknownArch)
378 Target = std::move(LE);
380 llvm::Triple BE = Target.getBigEndianArchVariant();
381 if (BE.getArch() != llvm::Triple::UnknownArch)
382 Target = std::move(BE);
386 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
387 if (Target.getArch() == llvm::Triple::tce ||
388 Target.getOS() == llvm::Triple::Minix)
391 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
392 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
393 options::OPT_m32, options::OPT_m16);
395 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
397 if (A->getOption().matches(options::OPT_m64)) {
398 AT = Target.get64BitArchVariant().getArch();
399 if (Target.getEnvironment() == llvm::Triple::GNUX32)
400 Target.setEnvironment(llvm::Triple::GNU);
401 } else if (A->getOption().matches(options::OPT_mx32) &&
402 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
403 AT = llvm::Triple::x86_64;
404 Target.setEnvironment(llvm::Triple::GNUX32);
405 } else if (A->getOption().matches(options::OPT_m32)) {
406 AT = Target.get32BitArchVariant().getArch();
407 if (Target.getEnvironment() == llvm::Triple::GNUX32)
408 Target.setEnvironment(llvm::Triple::GNU);
409 } else if (A->getOption().matches(options::OPT_m16) &&
410 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
411 AT = llvm::Triple::x86;
412 Target.setEnvironment(llvm::Triple::CODE16);
415 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
419 // Handle -miamcu flag.
420 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
421 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
422 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
425 if (A && !A->getOption().matches(options::OPT_m32))
426 D.Diag(diag::err_drv_argument_not_allowed_with)
427 << "-miamcu" << A->getBaseArg().getAsString(Args);
429 Target.setArch(llvm::Triple::x86);
430 Target.setArchName("i586");
431 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
432 Target.setEnvironmentName("");
433 Target.setOS(llvm::Triple::ELFIAMCU);
434 Target.setVendor(llvm::Triple::UnknownVendor);
435 Target.setVendorName("intel");
441 // \brief Parse the LTO options and record the type of LTO compilation
442 // based on which -f(no-)?lto(=.*)? option occurs last.
443 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
445 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
446 options::OPT_fno_lto, false))
449 StringRef LTOName("full");
451 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
453 LTOName = A->getValue();
455 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
456 .Case("full", LTOK_Full)
457 .Case("thin", LTOK_Thin)
458 .Default(LTOK_Unknown);
460 if (LTOMode == LTOK_Unknown) {
462 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
467 /// Compute the desired OpenMP runtime from the flags provided.
468 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
469 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
471 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
473 RuntimeName = A->getValue();
475 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
476 .Case("libomp", OMPRT_OMP)
477 .Case("libgomp", OMPRT_GOMP)
478 .Case("libiomp5", OMPRT_IOMP5)
479 .Default(OMPRT_Unknown);
481 if (RT == OMPRT_Unknown) {
483 Diag(diag::err_drv_unsupported_option_argument)
484 << A->getOption().getName() << A->getValue();
486 // FIXME: We could use a nicer diagnostic here.
487 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
493 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
499 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
500 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
501 return types::isCuda(I.first);
503 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
504 const llvm::Triple &HostTriple = HostTC->getTriple();
505 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
506 : "nvptx-nvidia-cuda");
507 // Use the CUDA and host triples as the key into the ToolChains map, because
508 // the device toolchain we create depends on both.
509 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
511 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
512 *this, CudaTriple, *HostTC, C.getInputArgs());
514 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
520 // We need to generate an OpenMP toolchain if the user specified targets with
521 // the -fopenmp-targets option.
522 if (Arg *OpenMPTargets =
523 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
524 if (OpenMPTargets->getNumValues()) {
525 // We expect that -fopenmp-targets is always used in conjunction with the
526 // option -fopenmp specifying a valid runtime with offloading support,
527 // i.e. libomp or libiomp.
528 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
529 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
530 options::OPT_fno_openmp, false);
531 if (HasValidOpenMPRuntime) {
532 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
533 HasValidOpenMPRuntime =
534 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
537 if (HasValidOpenMPRuntime) {
538 llvm::StringMap<const char *> FoundNormalizedTriples;
539 for (const char *Val : OpenMPTargets->getValues()) {
540 llvm::Triple TT(Val);
541 std::string NormalizedName = TT.normalize();
543 // Make sure we don't have a duplicate triple.
544 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
545 if (Duplicate != FoundNormalizedTriples.end()) {
546 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
547 << Val << Duplicate->second;
551 // Store the current triple so that we can check for duplicates in the
552 // following iterations.
553 FoundNormalizedTriples[NormalizedName] = Val;
555 // If the specified target is invalid, emit a diagnostic.
556 if (TT.getArch() == llvm::Triple::UnknownArch)
557 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
559 const ToolChain &TC = getToolChain(C.getInputArgs(), TT);
560 C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP);
564 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
566 Diag(clang::diag::warn_drv_empty_joined_argument)
567 << OpenMPTargets->getAsString(C.getInputArgs());
571 // TODO: Add support for other offloading programming models here.
577 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
578 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
580 // FIXME: Handle environment options which affect driver behavior, somewhere
581 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
583 if (Optional<std::string> CompilerPathValue =
584 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
585 StringRef CompilerPath = *CompilerPathValue;
586 while (!CompilerPath.empty()) {
587 std::pair<StringRef, StringRef> Split =
588 CompilerPath.split(llvm::sys::EnvPathSeparator);
589 PrefixDirs.push_back(Split.first);
590 CompilerPath = Split.second;
594 // We look for the driver mode option early, because the mode can affect
595 // how other options are parsed.
596 ParseDriverMode(ClangExecutable, ArgList.slice(1));
598 // FIXME: What are we going to do with -V and -b?
600 // FIXME: This stuff needs to go into the Compilation, not the driver.
603 InputArgList Args = ParseArgStrings(ArgList.slice(1));
604 if (Diags.hasErrorOccurred())
607 // Silence driver warnings if requested
608 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
610 // -no-canonical-prefixes is used very early in main.
611 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
614 Args.ClaimAllArgs(options::OPT_pipe);
616 // Extract -ccc args.
618 // FIXME: We need to figure out where this behavior should live. Most of it
619 // should be outside in the client; the parts that aren't should have proper
620 // options, either by introducing new ones or by overloading gcc ones like -V
622 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
623 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
624 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
625 CCCGenericGCCName = A->getValue();
627 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
628 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
629 options::OPT_fno_crash_diagnostics,
630 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
631 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
632 // and getToolChain is const.
634 // clang-cl targets MSVC-style Win32.
635 llvm::Triple T(DefaultTargetTriple);
636 T.setOS(llvm::Triple::Win32);
637 T.setVendor(llvm::Triple::PC);
638 T.setEnvironment(llvm::Triple::MSVC);
639 DefaultTargetTriple = T.str();
641 if (const Arg *A = Args.getLastArg(options::OPT_target))
642 DefaultTargetTriple = A->getValue();
643 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
644 Dir = InstalledDir = A->getValue();
645 for (const Arg *A : Args.filtered(options::OPT_B)) {
647 PrefixDirs.push_back(A->getValue(0));
649 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
650 SysRoot = A->getValue();
651 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
652 DyldPrefix = A->getValue();
653 if (Args.hasArg(options::OPT_nostdlib))
656 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
657 ResourceDir = A->getValue();
659 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
660 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
661 .Case("cwd", SaveTempsCwd)
662 .Case("obj", SaveTempsObj)
663 .Default(SaveTempsCwd);
668 // Process -fembed-bitcode= flags.
669 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
670 StringRef Name = A->getValue();
671 unsigned Model = llvm::StringSwitch<unsigned>(Name)
672 .Case("off", EmbedNone)
673 .Case("all", EmbedBitcode)
674 .Case("bitcode", EmbedBitcode)
675 .Case("marker", EmbedMarker)
678 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
681 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
684 std::unique_ptr<llvm::opt::InputArgList> UArgs =
685 llvm::make_unique<InputArgList>(std::move(Args));
687 // Perform the default argument translations.
688 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
690 // Owned by the host.
691 const ToolChain &TC = getToolChain(
692 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
694 // The compilation takes ownership of Args.
695 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
697 if (!HandleImmediateArgs(*C))
700 // Construct the list of inputs.
702 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
704 // Populate the tool chains for the offloading devices, if any.
705 CreateOffloadingDeviceToolChains(*C, Inputs);
707 // Construct the list of abstract actions to perform for this compilation. On
708 // MachO targets this uses the driver-driver and universal actions.
709 if (TC.getTriple().isOSBinFormatMachO())
710 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
712 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
714 if (CCCPrintPhases) {
724 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
725 llvm::opt::ArgStringList ASL;
726 for (const auto *A : Args)
727 A->render(Args, ASL);
729 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
730 if (I != ASL.begin())
732 Command::printArg(OS, *I, true);
737 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
738 SmallString<128> &CrashDiagDir) {
739 using namespace llvm::sys;
740 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
741 "Only knows about .crash files on Darwin");
743 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
744 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
745 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
746 path::home_directory(CrashDiagDir);
747 if (CrashDiagDir.startswith("/var/root"))
749 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
757 fs::file_status FileStatus;
758 TimePoint<> LastAccessTime;
759 SmallString<128> CrashFilePath;
760 // Lookup the .crash files and get the one generated by a subprocess spawned
761 // by this driver invocation.
762 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
763 File != FileEnd && !EC; File.increment(EC)) {
764 StringRef FileName = path::filename(File->path());
765 if (!FileName.startswith(Name))
767 if (fs::status(File->path(), FileStatus))
769 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
770 llvm::MemoryBuffer::getFile(File->path());
773 // The first line should start with "Process:", otherwise this isn't a real
775 StringRef Data = CrashFile.get()->getBuffer();
776 if (!Data.startswith("Process:"))
778 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
779 size_t ParentProcPos = Data.find("Parent Process:");
780 if (ParentProcPos == StringRef::npos)
782 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
783 if (LineEnd == StringRef::npos)
785 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
786 int OpenBracket = -1, CloseBracket = -1;
787 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
788 if (ParentProcess[i] == '[')
790 if (ParentProcess[i] == ']')
793 // Extract the parent process PID from the .crash file and check whether
794 // it matches this driver invocation pid.
796 if (OpenBracket < 0 || CloseBracket < 0 ||
797 ParentProcess.slice(OpenBracket + 1, CloseBracket)
798 .getAsInteger(10, CrashPID) || CrashPID != PID) {
802 // Found a .crash file matching the driver pid. To avoid getting an older
803 // and misleading crash file, continue looking for the most recent.
804 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
805 // multiple crashes poiting to the same parent process. Since the driver
806 // does not collect pid information for the dispatched invocation there's
807 // currently no way to distinguish among them.
808 const auto FileAccessTime = FileStatus.getLastModificationTime();
809 if (FileAccessTime > LastAccessTime) {
810 CrashFilePath.assign(File->path());
811 LastAccessTime = FileAccessTime;
815 // If found, copy it over to the location of other reproducer files.
816 if (!CrashFilePath.empty()) {
817 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
826 // When clang crashes, produce diagnostic information including the fully
827 // preprocessed source file(s). Request that the developer attach the
828 // diagnostic information to a bug report.
829 void Driver::generateCompilationDiagnostics(Compilation &C,
830 const Command &FailingCommand) {
831 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
834 // Don't try to generate diagnostics for link or dsymutil jobs.
835 if (FailingCommand.getCreator().isLinkJob() ||
836 FailingCommand.getCreator().isDsymutilJob())
839 // Print the version of the compiler.
840 PrintVersion(C, llvm::errs());
842 Diag(clang::diag::note_drv_command_failed_diag_msg)
843 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
844 "crash backtrace, preprocessed source, and associated run script.";
846 // Suppress driver output and emit preprocessor output to temp file.
848 CCGenDiagnostics = true;
850 // Save the original job command(s).
851 Command Cmd = FailingCommand;
853 // Keep track of whether we produce any errors while trying to produce
854 // preprocessed sources.
855 DiagnosticErrorTrap Trap(Diags);
857 // Suppress tool output.
858 C.initCompilationForDiagnostics();
860 // Construct the list of inputs.
862 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
864 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
865 bool IgnoreInput = false;
867 // Ignore input from stdin or any inputs that cannot be preprocessed.
868 // Check type first as not all linker inputs have a value.
869 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
871 } else if (!strcmp(it->second->getValue(), "-")) {
872 Diag(clang::diag::note_drv_command_failed_diag_msg)
873 << "Error generating preprocessed source(s) - "
874 "ignoring input from stdin.";
879 it = Inputs.erase(it);
886 if (Inputs.empty()) {
887 Diag(clang::diag::note_drv_command_failed_diag_msg)
888 << "Error generating preprocessed source(s) - "
889 "no preprocessable inputs.";
893 // Don't attempt to generate preprocessed files if multiple -arch options are
894 // used, unless they're all duplicates.
895 llvm::StringSet<> ArchNames;
896 for (const Arg *A : C.getArgs()) {
897 if (A->getOption().matches(options::OPT_arch)) {
898 StringRef ArchName = A->getValue();
899 ArchNames.insert(ArchName);
902 if (ArchNames.size() > 1) {
903 Diag(clang::diag::note_drv_command_failed_diag_msg)
904 << "Error generating preprocessed source(s) - cannot generate "
905 "preprocessed source with multiple -arch options.";
909 // Construct the list of abstract actions to perform for this compilation. On
910 // Darwin OSes this uses the driver-driver and builds universal actions.
911 const ToolChain &TC = C.getDefaultToolChain();
912 if (TC.getTriple().isOSBinFormatMachO())
913 BuildUniversalActions(C, TC, Inputs);
915 BuildActions(C, C.getArgs(), Inputs, C.getActions());
919 // If there were errors building the compilation, quit now.
920 if (Trap.hasErrorOccurred()) {
921 Diag(clang::diag::note_drv_command_failed_diag_msg)
922 << "Error generating preprocessed source(s).";
926 // Generate preprocessed output.
927 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
928 C.ExecuteJobs(C.getJobs(), FailingCommands);
930 // If any of the preprocessing commands failed, clean up and exit.
931 if (!FailingCommands.empty()) {
932 if (!isSaveTempsEnabled())
933 C.CleanupFileList(C.getTempFiles(), true);
935 Diag(clang::diag::note_drv_command_failed_diag_msg)
936 << "Error generating preprocessed source(s).";
940 const ArgStringList &TempFiles = C.getTempFiles();
941 if (TempFiles.empty()) {
942 Diag(clang::diag::note_drv_command_failed_diag_msg)
943 << "Error generating preprocessed source(s).";
947 Diag(clang::diag::note_drv_command_failed_diag_msg)
948 << "\n********************\n\n"
949 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
950 "Preprocessed source(s) and associated run script(s) are located at:";
952 SmallString<128> VFS;
953 SmallString<128> ReproCrashFilename;
954 for (const char *TempFile : TempFiles) {
955 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
956 if (ReproCrashFilename.empty()) {
957 ReproCrashFilename = TempFile;
958 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
960 if (StringRef(TempFile).endswith(".cache")) {
961 // In some cases (modules) we'll dump extra data to help with reproducing
962 // the crash into a directory next to the output.
963 VFS = llvm::sys::path::filename(TempFile);
964 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
968 // Assume associated files are based off of the first temporary file.
969 CrashReportInfo CrashInfo(TempFiles[0], VFS);
971 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
973 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
975 Diag(clang::diag::note_drv_command_failed_diag_msg)
976 << "Error generating run script: " + Script + " " + EC.message();
978 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
979 << "# Driver args: ";
980 printArgList(ScriptOS, C.getInputArgs());
981 ScriptOS << "# Original command: ";
982 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
983 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
984 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
987 // On darwin, provide information about the .crash diagnostic report.
988 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
989 SmallString<128> CrashDiagDir;
990 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
991 Diag(clang::diag::note_drv_command_failed_diag_msg)
992 << ReproCrashFilename.str();
993 } else { // Suggest a directory for the user to look for .crash files.
994 llvm::sys::path::append(CrashDiagDir, Name);
995 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
996 Diag(clang::diag::note_drv_command_failed_diag_msg)
997 << "Crash backtrace is located in";
998 Diag(clang::diag::note_drv_command_failed_diag_msg)
999 << CrashDiagDir.str();
1000 Diag(clang::diag::note_drv_command_failed_diag_msg)
1001 << "(choose the .crash file that corresponds to your crash)";
1005 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1006 options::OPT_frewrite_map_file_EQ))
1007 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1009 Diag(clang::diag::note_drv_command_failed_diag_msg)
1010 << "\n\n********************";
1013 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1014 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
1015 // if the tool does not support response files, there is a chance/ that things
1016 // will just work without a response file, so we silently just skip it.
1017 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1018 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
1021 std::string TmpName = GetTemporaryPath("response", "txt");
1022 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1025 int Driver::ExecuteCompilation(
1027 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1028 // Just print if -### was present.
1029 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1030 C.getJobs().Print(llvm::errs(), "\n", true);
1034 // If there were errors building the compilation, quit now.
1035 if (Diags.hasErrorOccurred())
1038 // Set up response file names for each command, if necessary
1039 for (auto &Job : C.getJobs())
1040 setUpResponseFiles(C, Job);
1042 C.ExecuteJobs(C.getJobs(), FailingCommands);
1044 // Remove temp files.
1045 C.CleanupFileList(C.getTempFiles());
1047 // If the command succeeded, we are done.
1048 if (FailingCommands.empty())
1051 // Otherwise, remove result files and print extra information about abnormal
1053 for (const auto &CmdPair : FailingCommands) {
1054 int Res = CmdPair.first;
1055 const Command *FailingCommand = CmdPair.second;
1057 // Remove result files if we're not saving temps.
1058 if (!isSaveTempsEnabled()) {
1059 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1060 C.CleanupFileMap(C.getResultFiles(), JA, true);
1062 // Failure result files are valid unless we crashed.
1064 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1067 // Print extra information about abnormal failures, if possible.
1069 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1070 // status was 1, assume the command failed normally. In particular, if it
1071 // was the compiler then assume it gave a reasonable error code. Failures
1072 // in other tools are less common, and they generally have worse
1073 // diagnostics, so always print the diagnostic there.
1074 const Tool &FailingTool = FailingCommand->getCreator();
1076 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1077 // FIXME: See FIXME above regarding result code interpretation.
1079 Diag(clang::diag::err_drv_command_signalled)
1080 << FailingTool.getShortName();
1082 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1089 void Driver::PrintHelp(bool ShowHidden) const {
1090 unsigned IncludedFlagsBitmask;
1091 unsigned ExcludedFlagsBitmask;
1092 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1093 getIncludeExcludeOptionFlagMasks();
1095 ExcludedFlagsBitmask |= options::NoDriverOption;
1097 ExcludedFlagsBitmask |= HelpHidden;
1099 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1100 IncludedFlagsBitmask, ExcludedFlagsBitmask);
1103 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1104 // FIXME: The following handlers should use a callback mechanism, we don't
1105 // know what the client would like to do.
1106 OS << getClangFullVersion() << '\n';
1107 const ToolChain &TC = C.getDefaultToolChain();
1108 OS << "Target: " << TC.getTripleString() << '\n';
1110 // Print the threading model.
1111 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1112 // Don't print if the ToolChain would have barfed on it already
1113 if (TC.isThreadModelSupported(A->getValue()))
1114 OS << "Thread model: " << A->getValue();
1116 OS << "Thread model: " << TC.getThreadModel();
1119 // Print out the install directory.
1120 OS << "InstalledDir: " << InstalledDir << '\n';
1123 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1125 static void PrintDiagnosticCategories(raw_ostream &OS) {
1126 // Skip the empty category.
1127 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1129 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1132 bool Driver::HandleImmediateArgs(const Compilation &C) {
1133 // The order these options are handled in gcc is all over the place, but we
1134 // don't expect inconsistencies w.r.t. that to matter in practice.
1136 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1137 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1141 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1142 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1143 // return an answer which matches our definition of __VERSION__.
1145 // If we want to return a more correct answer some day, then we should
1146 // introduce a non-pedantically GCC compatible mode to Clang in which we
1147 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1148 llvm::outs() << "4.2.1\n";
1152 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1153 PrintDiagnosticCategories(llvm::outs());
1157 if (C.getArgs().hasArg(options::OPT_help) ||
1158 C.getArgs().hasArg(options::OPT__help_hidden)) {
1159 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1163 if (C.getArgs().hasArg(options::OPT__version)) {
1164 // Follow gcc behavior and use stdout for --version and stderr for -v.
1165 PrintVersion(C, llvm::outs());
1167 // Print registered targets.
1168 llvm::outs() << '\n';
1169 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
1173 if (C.getArgs().hasArg(options::OPT_v) ||
1174 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1175 PrintVersion(C, llvm::errs());
1176 SuppressMissingInputWarning = true;
1179 const ToolChain &TC = C.getDefaultToolChain();
1181 if (C.getArgs().hasArg(options::OPT_v))
1182 TC.printVerboseInfo(llvm::errs());
1184 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1185 llvm::outs() << ResourceDir << '\n';
1189 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1190 llvm::outs() << "programs: =";
1191 bool separator = false;
1192 for (const std::string &Path : TC.getProgramPaths()) {
1194 llvm::outs() << ':';
1195 llvm::outs() << Path;
1198 llvm::outs() << "\n";
1199 llvm::outs() << "libraries: =" << ResourceDir;
1201 StringRef sysroot = C.getSysRoot();
1203 for (const std::string &Path : TC.getFilePaths()) {
1204 // Always print a separator. ResourceDir was the first item shown.
1205 llvm::outs() << ':';
1206 // Interpretation of leading '=' is needed only for NetBSD.
1208 llvm::outs() << sysroot << Path.substr(1);
1210 llvm::outs() << Path;
1212 llvm::outs() << "\n";
1216 // FIXME: The following handlers should use a callback mechanism, we don't
1217 // know what the client would like to do.
1218 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1219 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1223 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1224 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
1228 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1229 // Print out all options that start with a given argument. This is used for
1230 // shell autocompletion.
1231 StringRef PassedFlags = A->getValue();
1232 std::vector<std::string> SuggestedCompletions;
1234 if (PassedFlags.find(',') == StringRef::npos) {
1235 // If the flag is in the form of "--autocomplete=-foo",
1236 // we were requested to print out all option names that start with "-foo".
1237 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1238 SuggestedCompletions = Opts->findByPrefix(PassedFlags);
1240 // If the flag is in the form of "--autocomplete=foo,bar", we were
1241 // requested to print out all option values for "-foo" that start with
1242 // "bar". For example,
1243 // "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
1244 StringRef Option, Arg;
1245 std::tie(Option, Arg) = PassedFlags.split(',');
1246 SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
1249 // Sort the autocomplete candidates so that shells print them out in a
1250 // deterministic order. We could sort in any way, but we chose
1251 // case-insensitive sorting for consistency with the -help option
1252 // which prints out options in the case-insensitive alphabetical order.
1253 std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1254 [](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
1256 llvm::outs() << llvm::join(SuggestedCompletions, " ") << '\n';
1260 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1261 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1263 case ToolChain::RLT_CompilerRT:
1264 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1266 case ToolChain::RLT_Libgcc:
1267 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1273 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1274 for (const Multilib &Multilib : TC.getMultilibs())
1275 llvm::outs() << Multilib << "\n";
1279 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1280 for (const Multilib &Multilib : TC.getMultilibs()) {
1281 if (Multilib.gccSuffix().empty())
1282 llvm::outs() << ".\n";
1284 StringRef Suffix(Multilib.gccSuffix());
1285 assert(Suffix.front() == '/');
1286 llvm::outs() << Suffix.substr(1) << "\n";
1294 // Display an action graph human-readably. Action A is the "sink" node
1295 // and latest-occuring action. Traversal is in pre-order, visiting the
1296 // inputs to each action before printing the action itself.
1297 static unsigned PrintActions1(const Compilation &C, Action *A,
1298 std::map<Action *, unsigned> &Ids) {
1299 if (Ids.count(A)) // A was already visited.
1303 llvm::raw_string_ostream os(str);
1305 os << Action::getClassName(A->getKind()) << ", ";
1306 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1307 os << "\"" << IA->getInputArg().getValue() << "\"";
1308 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1309 os << '"' << BIA->getArchName() << '"' << ", {"
1310 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1311 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1312 bool IsFirst = true;
1313 OA->doOnEachDependence(
1314 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1315 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1316 // sm_35 this will generate:
1317 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1318 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1323 os << A->getOffloadingKindPrefix();
1327 os << TC->getTriple().normalize();
1330 os << ":" << BoundArch;
1333 os << " {" << PrintActions1(C, A, Ids) << "}";
1337 const ActionList *AL = &A->getInputs();
1340 const char *Prefix = "{";
1341 for (Action *PreRequisite : *AL) {
1342 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1350 // Append offload info for all options other than the offloading action
1351 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1352 std::string offload_str;
1353 llvm::raw_string_ostream offload_os(offload_str);
1354 if (!isa<OffloadAction>(A)) {
1355 auto S = A->getOffloadingKindPrefix();
1357 offload_os << ", (" << S;
1358 if (A->getOffloadingArch())
1359 offload_os << ", " << A->getOffloadingArch();
1364 unsigned Id = Ids.size();
1366 llvm::errs() << Id << ": " << os.str() << ", "
1367 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1372 // Print the action graphs in a compilation C.
1373 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1374 void Driver::PrintActions(const Compilation &C) const {
1375 std::map<Action *, unsigned> Ids;
1376 for (Action *A : C.getActions())
1377 PrintActions1(C, A, Ids);
1380 /// \brief Check whether the given input tree contains any compilation or
1381 /// assembly actions.
1382 static bool ContainsCompileOrAssembleAction(const Action *A) {
1383 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1384 isa<AssembleJobAction>(A))
1387 for (const Action *Input : A->inputs())
1388 if (ContainsCompileOrAssembleAction(Input))
1394 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1395 const InputList &BAInputs) const {
1396 DerivedArgList &Args = C.getArgs();
1397 ActionList &Actions = C.getActions();
1398 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1399 // Collect the list of architectures. Duplicates are allowed, but should only
1400 // be handled once (in the order seen).
1401 llvm::StringSet<> ArchNames;
1402 SmallVector<const char *, 4> Archs;
1403 for (Arg *A : Args) {
1404 if (A->getOption().matches(options::OPT_arch)) {
1405 // Validate the option here; we don't save the type here because its
1406 // particular spelling may participate in other driver choices.
1407 llvm::Triple::ArchType Arch =
1408 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1409 if (Arch == llvm::Triple::UnknownArch) {
1410 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1415 if (ArchNames.insert(A->getValue()).second)
1416 Archs.push_back(A->getValue());
1420 // When there is no explicit arch for this platform, make sure we still bind
1421 // the architecture (to the default) so that -Xarch_ is handled correctly.
1423 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1425 ActionList SingleActions;
1426 BuildActions(C, Args, BAInputs, SingleActions);
1428 // Add in arch bindings for every top level action, as well as lipo and
1429 // dsymutil steps if needed.
1430 for (Action* Act : SingleActions) {
1431 // Make sure we can lipo this kind of output. If not (and it is an actual
1432 // output) then we disallow, since we can't create an output file with the
1433 // right name without overwriting it. We could remove this oddity by just
1434 // changing the output names to include the arch, which would also fix
1435 // -save-temps. Compatibility wins for now.
1437 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1438 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1439 << types::getTypeName(Act->getType());
1442 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1443 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1445 // Lipo if necessary, we do it this way because we need to set the arch flag
1446 // so that -Xarch_ gets overwritten.
1447 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1448 Actions.append(Inputs.begin(), Inputs.end());
1450 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1452 // Handle debug info queries.
1453 Arg *A = Args.getLastArg(options::OPT_g_Group);
1454 if (A && !A->getOption().matches(options::OPT_g0) &&
1455 !A->getOption().matches(options::OPT_gstabs) &&
1456 ContainsCompileOrAssembleAction(Actions.back())) {
1458 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1459 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1460 // because the debug info will refer to a temporary object file which
1461 // will be removed at the end of the compilation process.
1462 if (Act->getType() == types::TY_Image) {
1464 Inputs.push_back(Actions.back());
1467 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1470 // Verify the debug info output.
1471 if (Args.hasArg(options::OPT_verify_debug_info)) {
1472 Action* LastAction = Actions.back();
1474 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1475 LastAction, types::TY_Nothing));
1481 /// \brief Check that the file referenced by Value exists. If it doesn't,
1482 /// issue a diagnostic and return false.
1483 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1484 StringRef Value, types::ID Ty) {
1485 if (!D.getCheckInputsExist())
1488 // stdin always exists.
1492 SmallString<64> Path(Value);
1493 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1494 if (!llvm::sys::path::is_absolute(Path)) {
1495 SmallString<64> Directory(WorkDir->getValue());
1496 llvm::sys::path::append(Directory, Value);
1497 Path.assign(Directory);
1501 if (llvm::sys::fs::exists(Twine(Path)))
1505 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1506 llvm::sys::Process::FindInEnvPath("LIB", Value))
1509 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1510 // Arguments to the /link flag might cause the linker to search for object
1511 // and library files in paths we don't know about. Don't error in such
1517 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1521 // Construct a the list of inputs and their types.
1522 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1523 InputList &Inputs) const {
1524 // Track the current user specified (-x) input. We also explicitly track the
1525 // argument used to set the type; we only want to claim the type when we
1526 // actually use it, so we warn about unused -x arguments.
1527 types::ID InputType = types::TY_Nothing;
1528 Arg *InputTypeArg = nullptr;
1530 // The last /TC or /TP option sets the input type to C or C++ globally.
1531 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1532 options::OPT__SLASH_TP)) {
1533 InputTypeArg = TCTP;
1534 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1538 Arg *Previous = nullptr;
1539 bool ShowNote = false;
1540 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1542 Diag(clang::diag::warn_drv_overriding_flag_option)
1543 << Previous->getSpelling() << A->getSpelling();
1549 Diag(clang::diag::note_drv_t_option_is_global);
1551 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1552 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1555 for (Arg *A : Args) {
1556 if (A->getOption().getKind() == Option::InputClass) {
1557 const char *Value = A->getValue();
1558 types::ID Ty = types::TY_INVALID;
1560 // Infer the input type if necessary.
1561 if (InputType == types::TY_Nothing) {
1562 // If there was an explicit arg for this, claim it.
1564 InputTypeArg->claim();
1566 // stdin must be handled specially.
1567 if (memcmp(Value, "-", 2) == 0) {
1568 // If running with -E, treat as a C input (this changes the builtin
1569 // macros, for example). This may be overridden by -ObjC below.
1571 // Otherwise emit an error but still use a valid type to avoid
1572 // spurious errors (e.g., no inputs).
1573 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1574 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1575 : clang::diag::err_drv_unknown_stdin_type);
1578 // Otherwise lookup by extension.
1579 // Fallback is C if invoked as C preprocessor or Object otherwise.
1580 // We use a host hook here because Darwin at least has its own
1581 // idea of what .s is.
1582 if (const char *Ext = strrchr(Value, '.'))
1583 Ty = TC.LookupTypeForExtension(Ext + 1);
1585 if (Ty == types::TY_INVALID) {
1589 Ty = types::TY_Object;
1592 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1593 // should autodetect some input files as C++ for g++ compatibility.
1595 types::ID OldTy = Ty;
1596 Ty = types::lookupCXXTypeForCType(Ty);
1599 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1600 << getTypeName(OldTy) << getTypeName(Ty);
1604 // -ObjC and -ObjC++ override the default language, but only for "source
1605 // files". We just treat everything that isn't a linker input as a
1608 // FIXME: Clean this up if we move the phase sequence into the type.
1609 if (Ty != types::TY_Object) {
1610 if (Args.hasArg(options::OPT_ObjC))
1611 Ty = types::TY_ObjC;
1612 else if (Args.hasArg(options::OPT_ObjCXX))
1613 Ty = types::TY_ObjCXX;
1616 assert(InputTypeArg && "InputType set w/o InputTypeArg");
1617 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1618 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1620 const char *Ext = strrchr(Value, '.');
1621 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1622 Ty = types::TY_Object;
1624 if (Ty == types::TY_INVALID) {
1626 InputTypeArg->claim();
1630 if (DiagnoseInputExistence(*this, Args, Value, Ty))
1631 Inputs.push_back(std::make_pair(Ty, A));
1633 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1634 StringRef Value = A->getValue();
1635 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1636 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1637 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1640 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1641 StringRef Value = A->getValue();
1642 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1643 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1644 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1647 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1648 // Just treat as object type, we could make a special type for this if
1650 Inputs.push_back(std::make_pair(types::TY_Object, A));
1652 } else if (A->getOption().matches(options::OPT_x)) {
1654 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1657 // Follow gcc behavior and treat as linker input for invalid -x
1658 // options. Its not clear why we shouldn't just revert to unknown; but
1659 // this isn't very important, we might as well be bug compatible.
1661 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1662 InputType = types::TY_Object;
1664 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1665 assert(A->getNumValues() == 1 && "The /U option has one value.");
1666 StringRef Val = A->getValue(0);
1667 if (Val.find_first_of("/\\") != StringRef::npos) {
1668 // Warn about e.g. "/Users/me/myfile.c".
1669 Diag(diag::warn_slash_u_filename) << Val;
1670 Diag(diag::note_use_dashdash);
1674 if (CCCIsCPP() && Inputs.empty()) {
1675 // If called as standalone preprocessor, stdin is processed
1676 // if no other input is present.
1677 Arg *A = MakeInputArg(Args, *Opts, "-");
1678 Inputs.push_back(std::make_pair(types::TY_C, A));
1683 /// Provides a convenient interface for different programming models to generate
1684 /// the required device actions.
1685 class OffloadingActionBuilder final {
1686 /// Flag used to trace errors in the builder.
1687 bool IsValid = false;
1689 /// The compilation that is using this builder.
1692 /// Map between an input argument and the offload kinds used to process it.
1693 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1695 /// Builder interface. It doesn't build anything or keep any state.
1696 class DeviceActionBuilder {
1698 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1700 enum ActionBuilderReturnCode {
1701 // The builder acted successfully on the current action.
1703 // The builder didn't have to act on the current action.
1705 // The builder was successful and requested the host action to not be
1711 /// Compilation associated with this builder.
1714 /// Tool chains associated with this builder. The same programming
1715 /// model may have associated one or more tool chains.
1716 SmallVector<const ToolChain *, 2> ToolChains;
1718 /// The derived arguments associated with this builder.
1719 DerivedArgList &Args;
1721 /// The inputs associated with this builder.
1722 const Driver::InputList &Inputs;
1724 /// The associated offload kind.
1725 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1728 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1729 const Driver::InputList &Inputs,
1730 Action::OffloadKind AssociatedOffloadKind)
1731 : C(C), Args(Args), Inputs(Inputs),
1732 AssociatedOffloadKind(AssociatedOffloadKind) {}
1733 virtual ~DeviceActionBuilder() {}
1735 /// Fill up the array \a DA with all the device dependences that should be
1736 /// added to the provided host action \a HostAction. By default it is
1738 virtual ActionBuilderReturnCode
1739 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1740 phases::ID CurPhase, phases::ID FinalPhase,
1742 return ABRT_Inactive;
1745 /// Update the state to include the provided host action \a HostAction as a
1746 /// dependency of the current device action. By default it is inactive.
1747 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1748 return ABRT_Inactive;
1751 /// Append top level actions generated by the builder. Return true if errors
1753 virtual void appendTopLevelActions(ActionList &AL) {}
1755 /// Append linker actions generated by the builder. Return true if errors
1757 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1759 /// Initialize the builder. Return true if any initialization errors are
1761 virtual bool initialize() { return false; }
1763 /// Return true if the builder can use bundling/unbundling.
1764 virtual bool canUseBundlerUnbundler() const { return false; }
1766 /// Return true if this builder is valid. We have a valid builder if we have
1767 /// associated device tool chains.
1768 bool isValid() { return !ToolChains.empty(); }
1770 /// Return the associated offload kind.
1771 Action::OffloadKind getAssociatedOffloadKind() {
1772 return AssociatedOffloadKind;
1776 /// \brief CUDA action builder. It injects device code in the host backend
1778 class CudaActionBuilder final : public DeviceActionBuilder {
1779 /// Flags to signal if the user requested host-only or device-only
1781 bool CompileHostOnly = false;
1782 bool CompileDeviceOnly = false;
1784 /// List of GPU architectures to use in this compilation.
1785 SmallVector<CudaArch, 4> GpuArchList;
1787 /// The CUDA actions for the current input.
1788 ActionList CudaDeviceActions;
1790 /// The CUDA fat binary if it was generated for the current input.
1791 Action *CudaFatBinary = nullptr;
1793 /// Flag that is set to true if this builder acted on the current input.
1794 bool IsActive = false;
1797 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1798 const Driver::InputList &Inputs)
1799 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1801 ActionBuilderReturnCode
1802 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1803 phases::ID CurPhase, phases::ID FinalPhase,
1804 PhasesTy &Phases) override {
1806 return ABRT_Inactive;
1808 // If we don't have more CUDA actions, we don't have any dependences to
1809 // create for the host.
1810 if (CudaDeviceActions.empty())
1811 return ABRT_Success;
1813 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1814 "Expecting one action per GPU architecture.");
1815 assert(!CompileHostOnly &&
1816 "Not expecting CUDA actions in host-only compilation.");
1818 // If we are generating code for the device or we are in a backend phase,
1819 // we attempt to generate the fat binary. We compile each arch to ptx and
1820 // assemble to cubin, then feed the cubin *and* the ptx into a device
1821 // "link" action, which uses fatbinary to combine these cubins into one
1822 // fatbin. The fatbin is then an input to the host action if not in
1823 // device-only mode.
1824 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1825 ActionList DeviceActions;
1826 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1827 // Produce the device action from the current phase up to the assemble
1829 for (auto Ph : Phases) {
1830 // Skip the phases that were already dealt with.
1833 // We have to be consistent with the host final phase.
1834 if (Ph > FinalPhase)
1837 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1838 C, Args, Ph, CudaDeviceActions[I]);
1840 if (Ph == phases::Assemble)
1844 // If we didn't reach the assemble phase, we can't generate the fat
1845 // binary. We don't need to generate the fat binary if we are not in
1846 // device-only mode.
1847 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1851 Action *AssembleAction = CudaDeviceActions[I];
1852 assert(AssembleAction->getType() == types::TY_Object);
1853 assert(AssembleAction->getInputs().size() == 1);
1855 Action *BackendAction = AssembleAction->getInputs()[0];
1856 assert(BackendAction->getType() == types::TY_PP_Asm);
1858 for (auto &A : {AssembleAction, BackendAction}) {
1859 OffloadAction::DeviceDependences DDep;
1860 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1862 DeviceActions.push_back(
1863 C.MakeAction<OffloadAction>(DDep, A->getType()));
1867 // We generate the fat binary if we have device input actions.
1868 if (!DeviceActions.empty()) {
1870 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1872 if (!CompileDeviceOnly) {
1873 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1875 // Clear the fat binary, it is already a dependence to an host
1877 CudaFatBinary = nullptr;
1880 // Remove the CUDA actions as they are already connected to an host
1881 // action or fat binary.
1882 CudaDeviceActions.clear();
1885 // We avoid creating host action in device-only mode.
1886 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
1887 } else if (CurPhase > phases::Backend) {
1888 // If we are past the backend phase and still have a device action, we
1889 // don't have to do anything as this action is already a device
1890 // top-level action.
1891 return ABRT_Success;
1894 assert(CurPhase < phases::Backend && "Generating single CUDA "
1895 "instructions should only occur "
1896 "before the backend phase!");
1898 // By default, we produce an action for each device arch.
1899 for (Action *&A : CudaDeviceActions)
1900 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1902 return ABRT_Success;
1905 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1906 // While generating code for CUDA, we only depend on the host input action
1907 // to trigger the creation of all the CUDA device actions.
1909 // If we are dealing with an input action, replicate it for each GPU
1910 // architecture. If we are in host-only mode we return 'success' so that
1911 // the host uses the CUDA offload kind.
1912 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1913 assert(!GpuArchList.empty() &&
1914 "We should have at least one GPU architecture.");
1916 // If the host input is not CUDA, we don't need to bother about this
1918 if (IA->getType() != types::TY_CUDA) {
1919 // The builder will ignore this input.
1921 return ABRT_Inactive;
1924 // Set the flag to true, so that the builder acts on the current input.
1927 if (CompileHostOnly)
1928 return ABRT_Success;
1930 // Replicate inputs for each GPU architecture.
1931 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1932 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1933 IA->getInputArg(), types::TY_CUDA_DEVICE));
1935 return ABRT_Success;
1938 return IsActive ? ABRT_Success : ABRT_Inactive;
1941 void appendTopLevelActions(ActionList &AL) override {
1942 // Utility to append actions to the top level list.
1943 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1944 OffloadAction::DeviceDependences Dep;
1945 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1947 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1950 // If we have a fat binary, add it to the list.
1951 if (CudaFatBinary) {
1952 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1953 CudaDeviceActions.clear();
1954 CudaFatBinary = nullptr;
1958 if (CudaDeviceActions.empty())
1961 // If we have CUDA actions at this point, that's because we have a have
1962 // partial compilation, so we should have an action for each GPU
1964 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1965 "Expecting one action per GPU architecture.");
1966 assert(ToolChains.size() == 1 &&
1967 "Expecting to have a sing CUDA toolchain.");
1968 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1969 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1971 CudaDeviceActions.clear();
1974 bool initialize() override {
1975 // We don't need to support CUDA.
1976 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1979 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1980 assert(HostTC && "No toolchain for host compilation.");
1981 if (HostTC->getTriple().isNVPTX()) {
1982 // We do not support targeting NVPTX for host compilation. Throw
1983 // an error and abort pipeline construction early so we don't trip
1984 // asserts that assume device-side compilation.
1985 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1989 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1991 Arg *PartialCompilationArg = Args.getLastArg(
1992 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1993 options::OPT_cuda_compile_host_device);
1994 CompileHostOnly = PartialCompilationArg &&
1995 PartialCompilationArg->getOption().matches(
1996 options::OPT_cuda_host_only);
1997 CompileDeviceOnly = PartialCompilationArg &&
1998 PartialCompilationArg->getOption().matches(
1999 options::OPT_cuda_device_only);
2001 // Collect all cuda_gpu_arch parameters, removing duplicates.
2002 std::set<CudaArch> GpuArchs;
2004 for (Arg *A : Args) {
2005 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2006 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2010 const StringRef ArchStr = A->getValue();
2011 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2016 CudaArch Arch = StringToCudaArch(ArchStr);
2017 if (Arch == CudaArch::UNKNOWN) {
2018 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2020 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2021 GpuArchs.insert(Arch);
2022 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2023 GpuArchs.erase(Arch);
2025 llvm_unreachable("Unexpected option.");
2028 // Collect list of GPUs remaining in the set.
2029 for (CudaArch Arch : GpuArchs)
2030 GpuArchList.push_back(Arch);
2032 // Default to sm_20 which is the lowest common denominator for
2033 // supported GPUs. sm_20 code should work correctly, if
2034 // suboptimally, on all newer GPUs.
2035 if (GpuArchList.empty())
2036 GpuArchList.push_back(CudaArch::SM_20);
2042 /// OpenMP action builder. The host bitcode is passed to the device frontend
2043 /// and all the device linked images are passed to the host link phase.
2044 class OpenMPActionBuilder final : public DeviceActionBuilder {
2045 /// The OpenMP actions for the current input.
2046 ActionList OpenMPDeviceActions;
2048 /// The linker inputs obtained for each toolchain.
2049 SmallVector<ActionList, 8> DeviceLinkerInputs;
2052 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2053 const Driver::InputList &Inputs)
2054 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2056 ActionBuilderReturnCode
2057 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2058 phases::ID CurPhase, phases::ID FinalPhase,
2059 PhasesTy &Phases) override {
2061 // We should always have an action for each input.
2062 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2063 "Number of OpenMP actions and toolchains do not match.");
2065 // The host only depends on device action in the linking phase, when all
2066 // the device images have to be embedded in the host image.
2067 if (CurPhase == phases::Link) {
2068 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2069 "Toolchains and linker inputs sizes do not match.");
2070 auto LI = DeviceLinkerInputs.begin();
2071 for (auto *A : OpenMPDeviceActions) {
2076 // We passed the device action as a host dependence, so we don't need to
2077 // do anything else with them.
2078 OpenMPDeviceActions.clear();
2079 return ABRT_Success;
2082 // By default, we produce an action for each device arch.
2083 for (Action *&A : OpenMPDeviceActions)
2084 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2086 return ABRT_Success;
2089 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2091 // If this is an input action replicate it for each OpenMP toolchain.
2092 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2093 OpenMPDeviceActions.clear();
2094 for (unsigned I = 0; I < ToolChains.size(); ++I)
2095 OpenMPDeviceActions.push_back(
2096 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2097 return ABRT_Success;
2100 // If this is an unbundling action use it as is for each OpenMP toolchain.
2101 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2102 OpenMPDeviceActions.clear();
2103 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2104 OpenMPDeviceActions.push_back(UA);
2105 UA->registerDependentActionInfo(
2106 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2108 return ABRT_Success;
2111 // When generating code for OpenMP we use the host compile phase result as
2112 // a dependence to the device compile phase so that it can learn what
2113 // declarations should be emitted. However, this is not the only use for
2114 // the host action, so we prevent it from being collapsed.
2115 if (isa<CompileJobAction>(HostAction)) {
2116 HostAction->setCannotBeCollapsedWithNextDependentAction();
2117 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2118 "Toolchains and device action sizes do not match.");
2119 OffloadAction::HostDependence HDep(
2120 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2121 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2122 auto TC = ToolChains.begin();
2123 for (Action *&A : OpenMPDeviceActions) {
2124 assert(isa<CompileJobAction>(A));
2125 OffloadAction::DeviceDependences DDep;
2126 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2127 A = C.MakeAction<OffloadAction>(HDep, DDep);
2131 return ABRT_Success;
2134 void appendTopLevelActions(ActionList &AL) override {
2135 if (OpenMPDeviceActions.empty())
2138 // We should always have an action for each input.
2139 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2140 "Number of OpenMP actions and toolchains do not match.");
2142 // Append all device actions followed by the proper offload action.
2143 auto TI = ToolChains.begin();
2144 for (auto *A : OpenMPDeviceActions) {
2145 OffloadAction::DeviceDependences Dep;
2146 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2147 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2150 // We no longer need the action stored in this builder.
2151 OpenMPDeviceActions.clear();
2154 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2155 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2156 "Toolchains and linker inputs sizes do not match.");
2158 // Append a new link action for each device.
2159 auto TC = ToolChains.begin();
2160 for (auto &LI : DeviceLinkerInputs) {
2161 auto *DeviceLinkAction =
2162 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2163 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2164 Action::OFK_OpenMP);
2169 bool initialize() override {
2170 // Get the OpenMP toolchains. If we don't get any, the action builder will
2171 // know there is nothing to do related to OpenMP offloading.
2172 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2173 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2175 ToolChains.push_back(TI->second);
2177 DeviceLinkerInputs.resize(ToolChains.size());
2181 bool canUseBundlerUnbundler() const override {
2182 // OpenMP should use bundled files whenever possible.
2188 /// TODO: Add the implementation for other specialized builders here.
2191 /// Specialized builders being used by this offloading action builder.
2192 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2194 /// Flag set to true if all valid builders allow file bundling/unbundling.
2198 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2199 const Driver::InputList &Inputs)
2201 // Create a specialized builder for each device toolchain.
2205 // Create a specialized builder for CUDA.
2206 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2208 // Create a specialized builder for OpenMP.
2209 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2212 // TODO: Build other specialized builders here.
2215 // Initialize all the builders, keeping track of errors. If all valid
2216 // builders agree that we can use bundling, set the flag to true.
2217 unsigned ValidBuilders = 0u;
2218 unsigned ValidBuildersSupportingBundling = 0u;
2219 for (auto *SB : SpecializedBuilders) {
2220 IsValid = IsValid && !SB->initialize();
2222 // Update the counters if the builder is valid.
2223 if (SB->isValid()) {
2225 if (SB->canUseBundlerUnbundler())
2226 ++ValidBuildersSupportingBundling;
2230 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2233 ~OffloadingActionBuilder() {
2234 for (auto *SB : SpecializedBuilders)
2238 /// Generate an action that adds device dependences (if any) to a host action.
2239 /// If no device dependence actions exist, just return the host action \a
2240 /// HostAction. If an error is found or if no builder requires the host action
2241 /// to be generated, return nullptr.
2243 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2244 phases::ID CurPhase, phases::ID FinalPhase,
2245 DeviceActionBuilder::PhasesTy &Phases) {
2249 if (SpecializedBuilders.empty())
2252 assert(HostAction && "Invalid host action!");
2254 OffloadAction::DeviceDependences DDeps;
2255 // Check if all the programming models agree we should not emit the host
2256 // action. Also, keep track of the offloading kinds employed.
2257 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2258 unsigned InactiveBuilders = 0u;
2259 unsigned IgnoringBuilders = 0u;
2260 for (auto *SB : SpecializedBuilders) {
2261 if (!SB->isValid()) {
2267 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2269 // If the builder explicitly says the host action should be ignored,
2270 // we need to increment the variable that tracks the builders that request
2271 // the host object to be ignored.
2272 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2275 // Unless the builder was inactive for this action, we have to record the
2276 // offload kind because the host will have to use it.
2277 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2278 OffloadKind |= SB->getAssociatedOffloadKind();
2281 // If all builders agree that the host object should be ignored, just return
2283 if (IgnoringBuilders &&
2284 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2287 if (DDeps.getActions().empty())
2290 // We have dependences we need to bundle together. We use an offload action
2292 OffloadAction::HostDependence HDep(
2293 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2294 /*BoundArch=*/nullptr, DDeps);
2295 return C.MakeAction<OffloadAction>(HDep, DDeps);
2298 /// Generate an action that adds a host dependence to a device action. The
2299 /// results will be kept in this action builder. Return true if an error was
2301 bool addHostDependenceToDeviceActions(Action *&HostAction,
2302 const Arg *InputArg) {
2306 // If we are supporting bundling/unbundling and the current action is an
2307 // input action of non-source file, we replace the host action by the
2308 // unbundling action. The bundler tool has the logic to detect if an input
2309 // is a bundle or not and if the input is not a bundle it assumes it is a
2310 // host file. Therefore it is safe to create an unbundling action even if
2311 // the input is not a bundle.
2312 if (CanUseBundler && isa<InputAction>(HostAction) &&
2313 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2314 !types::isSrcFile(HostAction->getType())) {
2315 auto UnbundlingHostAction =
2316 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2317 UnbundlingHostAction->registerDependentActionInfo(
2318 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2319 /*BoundArch=*/StringRef(), Action::OFK_Host);
2320 HostAction = UnbundlingHostAction;
2323 assert(HostAction && "Invalid host action!");
2325 // Register the offload kinds that are used.
2326 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2327 for (auto *SB : SpecializedBuilders) {
2331 auto RetCode = SB->addDeviceDepences(HostAction);
2333 // Host dependences for device actions are not compatible with that same
2334 // action being ignored.
2335 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2336 "Host dependence not expected to be ignored.!");
2338 // Unless the builder was inactive for this action, we have to record the
2339 // offload kind because the host will have to use it.
2340 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2341 OffloadKind |= SB->getAssociatedOffloadKind();
2347 /// Add the offloading top level actions to the provided action list. This
2348 /// function can replace the host action by a bundling action if the
2349 /// programming models allow it.
2350 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2351 const Arg *InputArg) {
2352 // Get the device actions to be appended.
2353 ActionList OffloadAL;
2354 for (auto *SB : SpecializedBuilders) {
2357 SB->appendTopLevelActions(OffloadAL);
2360 // If we can use the bundler, replace the host action by the bundling one in
2361 // the resulting list. Otherwise, just append the device actions.
2362 if (CanUseBundler && !OffloadAL.empty()) {
2363 // Add the host action to the list in order to create the bundling action.
2364 OffloadAL.push_back(HostAction);
2366 // We expect that the host action was just appended to the action list
2367 // before this method was called.
2368 assert(HostAction == AL.back() && "Host action not in the list??");
2369 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2370 AL.back() = HostAction;
2372 AL.append(OffloadAL.begin(), OffloadAL.end());
2374 // Propagate to the current host action (if any) the offload information
2375 // associated with the current input.
2377 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2378 /*BoundArch=*/nullptr);
2382 /// Processes the host linker action. This currently consists of replacing it
2383 /// with an offload action if there are device link objects and propagate to
2384 /// the host action all the offload kinds used in the current compilation. The
2385 /// resulting action is returned.
2386 Action *processHostLinkAction(Action *HostAction) {
2387 // Add all the dependences from the device linking actions.
2388 OffloadAction::DeviceDependences DDeps;
2389 for (auto *SB : SpecializedBuilders) {
2393 SB->appendLinkDependences(DDeps);
2396 // Calculate all the offload kinds used in the current compilation.
2397 unsigned ActiveOffloadKinds = 0u;
2398 for (auto &I : InputArgToOffloadKindMap)
2399 ActiveOffloadKinds |= I.second;
2401 // If we don't have device dependencies, we don't have to create an offload
2403 if (DDeps.getActions().empty()) {
2404 // Propagate all the active kinds to host action. Given that it is a link
2405 // action it is assumed to depend on all actions generated so far.
2406 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2407 /*BoundArch=*/nullptr);
2411 // Create the offload action with all dependences. When an offload action
2412 // is created the kinds are propagated to the host action, so we don't have
2413 // to do that explicitly here.
2414 OffloadAction::HostDependence HDep(
2415 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2416 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2417 return C.MakeAction<OffloadAction>(HDep, DDeps);
2420 } // anonymous namespace.
2422 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2423 const InputList &Inputs, ActionList &Actions) const {
2424 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
2426 if (!SuppressMissingInputWarning && Inputs.empty()) {
2427 Diag(clang::diag::err_drv_no_input_files);
2432 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
2434 if (FinalPhase == phases::Link) {
2435 if (Args.hasArg(options::OPT_emit_llvm))
2436 Diag(clang::diag::err_drv_emit_llvm_link);
2437 if (IsCLMode() && LTOMode != LTOK_None &&
2438 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2439 Diag(clang::diag::err_drv_lto_without_lld);
2442 // Reject -Z* at the top level, these options should never have been exposed
2444 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
2445 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
2447 // Diagnose misuse of /Fo.
2448 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
2449 StringRef V = A->getValue();
2450 if (Inputs.size() > 1 && !V.empty() &&
2451 !llvm::sys::path::is_separator(V.back())) {
2452 // Check whether /Fo tries to name an output file for multiple inputs.
2453 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2454 << A->getSpelling() << V;
2455 Args.eraseArg(options::OPT__SLASH_Fo);
2459 // Diagnose misuse of /Fa.
2460 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2461 StringRef V = A->getValue();
2462 if (Inputs.size() > 1 && !V.empty() &&
2463 !llvm::sys::path::is_separator(V.back())) {
2464 // Check whether /Fa tries to name an asm file for multiple inputs.
2465 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2466 << A->getSpelling() << V;
2467 Args.eraseArg(options::OPT__SLASH_Fa);
2471 // Diagnose misuse of /o.
2472 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2473 if (A->getValue()[0] == '\0') {
2474 // It has to have a value.
2475 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2476 Args.eraseArg(options::OPT__SLASH_o);
2480 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2481 // * no filename after it
2482 // * both /Yc and /Yu passed but with different filenames
2483 // * corresponding file not also passed as /FI
2484 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2485 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2486 if (YcArg && YcArg->getValue()[0] == '\0') {
2487 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2488 Args.eraseArg(options::OPT__SLASH_Yc);
2491 if (YuArg && YuArg->getValue()[0] == '\0') {
2492 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2493 Args.eraseArg(options::OPT__SLASH_Yu);
2496 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2497 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2498 Args.eraseArg(options::OPT__SLASH_Yc);
2499 Args.eraseArg(options::OPT__SLASH_Yu);
2500 YcArg = YuArg = nullptr;
2502 if (YcArg || YuArg) {
2503 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2504 bool FoundMatchingInclude = false;
2505 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2506 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2507 if (Inc->getValue() == Val)
2508 FoundMatchingInclude = true;
2510 if (!FoundMatchingInclude) {
2511 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2512 << (YcArg ? YcArg : YuArg)->getSpelling();
2513 Args.eraseArg(options::OPT__SLASH_Yc);
2514 Args.eraseArg(options::OPT__SLASH_Yu);
2515 YcArg = YuArg = nullptr;
2518 if (YcArg && Inputs.size() > 1) {
2519 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2520 Args.eraseArg(options::OPT__SLASH_Yc);
2523 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2524 // /Y- disables all pch handling. Rather than check for it everywhere,
2525 // just remove clang-cl pch-related flags here.
2526 Args.eraseArg(options::OPT__SLASH_Fp);
2527 Args.eraseArg(options::OPT__SLASH_Yc);
2528 Args.eraseArg(options::OPT__SLASH_Yu);
2529 YcArg = YuArg = nullptr;
2532 // Builder to be used to build offloading actions.
2533 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
2535 // Construct the actions to perform.
2536 ActionList LinkerInputs;
2538 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
2539 for (auto &I : Inputs) {
2540 types::ID InputType = I.first;
2541 const Arg *InputArg = I.second;
2544 types::getCompilationPhases(InputType, PL);
2546 // If the first step comes after the final phase we are doing as part of
2547 // this compilation, warn the user about it.
2548 phases::ID InitialPhase = PL[0];
2549 if (InitialPhase > FinalPhase) {
2550 // Claim here to avoid the more general unused warning.
2553 // Suppress all unused style warnings with -Qunused-arguments
2554 if (Args.hasArg(options::OPT_Qunused_arguments))
2557 // Special case when final phase determined by binary name, rather than
2558 // by a command-line argument with a corresponding Arg.
2560 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
2561 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
2562 // Special case '-E' warning on a previously preprocessed file to make
2564 else if (InitialPhase == phases::Compile &&
2565 FinalPhase == phases::Preprocess &&
2566 getPreprocessedType(InputType) == types::TY_INVALID)
2567 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
2568 << InputArg->getAsString(Args) << !!FinalPhaseArg
2569 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2571 Diag(clang::diag::warn_drv_input_file_unused)
2572 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2574 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2579 // Add a separate precompile phase for the compile phase.
2580 if (FinalPhase >= phases::Compile) {
2581 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
2582 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
2583 types::getCompilationPhases(HeaderType, PCHPL);
2584 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
2586 // Build the pipeline for the pch file.
2587 Action *ClangClPch =
2588 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
2589 for (phases::ID Phase : PCHPL)
2590 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2592 Actions.push_back(ClangClPch);
2593 // The driver currently exits after the first failed command. This
2594 // relies on that behavior, to make sure if the pch generation fails,
2595 // the main compilation won't run.
2599 // Build the pipeline for this file.
2600 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
2602 // Use the current host action in any of the offloading actions, if
2604 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2607 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2609 phases::ID Phase = *i;
2611 // We are done if this step is past what the user requested.
2612 if (Phase > FinalPhase)
2615 // Add any offload action the host action depends on.
2616 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2617 Current, InputArg, Phase, FinalPhase, PL);
2621 // Queue linker inputs.
2622 if (Phase == phases::Link) {
2623 assert((i + 1) == e && "linking must be final compilation step.");
2624 LinkerInputs.push_back(Current);
2629 // Otherwise construct the appropriate action.
2630 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2632 // We didn't create a new action, so we will just move to the next phase.
2633 if (NewCurrent == Current)
2636 Current = NewCurrent;
2638 // Use the current host action in any of the offloading actions, if
2640 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2643 if (Current->getType() == types::TY_Nothing)
2647 // If we ended with something, add to the output list.
2649 Actions.push_back(Current);
2651 // Add any top level actions generated for offloading.
2652 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
2655 // Add a link action if necessary.
2656 if (!LinkerInputs.empty()) {
2657 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2658 LA = OffloadBuilder.processHostLinkAction(LA);
2659 Actions.push_back(LA);
2662 // If we are linking, claim any options which are obviously only used for
2664 if (FinalPhase == phases::Link && PL.size() == 1) {
2665 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
2666 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2669 // Claim ignored clang-cl options.
2670 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
2672 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2673 // to non-CUDA compilations and should not trigger warnings there.
2674 Args.ClaimAllArgs(options::OPT_cuda_host_only);
2675 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
2678 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2679 phases::ID Phase, Action *Input) const {
2680 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
2682 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2683 // encode this in the steps because the intermediate type depends on
2684 // arguments. Just special case here.
2685 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2688 // Build the appropriate action.
2691 llvm_unreachable("link action invalid here.");
2692 case phases::Preprocess: {
2694 // -{M, MM} alter the output type.
2695 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
2696 OutputTy = types::TY_Dependencies;
2698 OutputTy = Input->getType();
2699 if (!Args.hasFlag(options::OPT_frewrite_includes,
2700 options::OPT_fno_rewrite_includes, false) &&
2701 !Args.hasFlag(options::OPT_frewrite_imports,
2702 options::OPT_fno_rewrite_imports, false) &&
2704 OutputTy = types::getPreprocessedType(OutputTy);
2705 assert(OutputTy != types::TY_INVALID &&
2706 "Cannot preprocess this input type!");
2708 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
2710 case phases::Precompile: {
2711 types::ID OutputTy = getPrecompiledType(Input->getType());
2712 assert(OutputTy != types::TY_INVALID &&
2713 "Cannot precompile this input type!");
2714 if (Args.hasArg(options::OPT_fsyntax_only)) {
2715 // Syntax checks should not emit a PCH file
2716 OutputTy = types::TY_Nothing;
2718 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
2720 case phases::Compile: {
2721 if (Args.hasArg(options::OPT_fsyntax_only))
2722 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
2723 if (Args.hasArg(options::OPT_rewrite_objc))
2724 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
2725 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
2726 return C.MakeAction<CompileJobAction>(Input,
2727 types::TY_RewrittenLegacyObjC);
2728 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
2729 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
2730 if (Args.hasArg(options::OPT__migrate))
2731 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
2732 if (Args.hasArg(options::OPT_emit_ast))
2733 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
2734 if (Args.hasArg(options::OPT_module_file_info))
2735 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
2736 if (Args.hasArg(options::OPT_verify_pch))
2737 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2738 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
2740 case phases::Backend: {
2743 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
2744 return C.MakeAction<BackendJobAction>(Input, Output);
2746 if (Args.hasArg(options::OPT_emit_llvm)) {
2748 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
2749 return C.MakeAction<BackendJobAction>(Input, Output);
2751 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
2753 case phases::Assemble:
2754 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
2757 llvm_unreachable("invalid phase in ConstructPhaseAction");
2760 void Driver::BuildJobs(Compilation &C) const {
2761 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2763 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2765 // It is an error to provide a -o option if we are making multiple output
2768 unsigned NumOutputs = 0;
2769 for (const Action *A : C.getActions())
2770 if (A->getType() != types::TY_Nothing)
2773 if (NumOutputs > 1) {
2774 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
2775 FinalOutput = nullptr;
2779 // Collect the list of architectures.
2780 llvm::StringSet<> ArchNames;
2781 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2782 for (const Arg *A : C.getArgs())
2783 if (A->getOption().matches(options::OPT_arch))
2784 ArchNames.insert(A->getValue());
2786 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2787 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
2788 for (Action *A : C.getActions()) {
2789 // If we are linking an image for multiple archs then the linker wants
2790 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2791 // doesn't fit in cleanly because we have to pass this information down.
2793 // FIXME: This is a hack; find a cleaner way to integrate this into the
2795 const char *LinkingOutput = nullptr;
2796 if (isa<LipoJobAction>(A)) {
2798 LinkingOutput = FinalOutput->getValue();
2800 LinkingOutput = getDefaultImageName();
2803 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
2804 /*BoundArch*/ StringRef(),
2805 /*AtTopLevel*/ true,
2806 /*MultipleArchs*/ ArchNames.size() > 1,
2807 /*LinkingOutput*/ LinkingOutput, CachedResults,
2808 /*TargetDeviceOffloadKind*/ Action::OFK_None);
2811 // If the user passed -Qunused-arguments or there were errors, don't warn
2812 // about any unused arguments.
2813 if (Diags.hasErrorOccurred() ||
2814 C.getArgs().hasArg(options::OPT_Qunused_arguments))
2818 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
2820 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
2821 (void)C.getArgs().hasArg(options::OPT_driver_mode);
2822 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
2824 for (Arg *A : C.getArgs()) {
2825 // FIXME: It would be nice to be able to send the argument to the
2826 // DiagnosticsEngine, so that extra values, position, and so on could be
2828 if (!A->isClaimed()) {
2829 if (A->getOption().hasFlag(options::NoArgumentUnused))
2832 // Suppress the warning automatically if this is just a flag, and it is an
2833 // instance of an argument we already claimed.
2834 const Option &Opt = A->getOption();
2835 if (Opt.getKind() == Option::FlagClass) {
2836 bool DuplicateClaimed = false;
2838 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2839 if (AA->isClaimed()) {
2840 DuplicateClaimed = true;
2845 if (DuplicateClaimed)
2849 // In clang-cl, don't mention unknown arguments here since they have
2850 // already been warned about.
2851 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2852 Diag(clang::diag::warn_drv_unused_argument)
2853 << A->getAsString(C.getArgs());
2859 /// Utility class to control the collapse of dependent actions and select the
2860 /// tools accordingly.
2861 class ToolSelector final {
2862 /// The tool chain this selector refers to.
2863 const ToolChain &TC;
2865 /// The compilation this selector refers to.
2866 const Compilation &C;
2868 /// The base action this selector refers to.
2869 const JobAction *BaseAction;
2871 /// Set to true if the current toolchain refers to host actions.
2872 bool IsHostSelector;
2874 /// Set to true if save-temps and embed-bitcode functionalities are active.
2878 /// Get previous dependent action or null if that does not exist. If
2879 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2880 /// null will be returned.
2881 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2882 ActionList &SavedOffloadAction,
2883 bool CanBeCollapsed = true) {
2884 // An option can be collapsed only if it has a single input.
2885 if (Inputs.size() != 1)
2888 Action *CurAction = *Inputs.begin();
2889 if (CanBeCollapsed &&
2890 !CurAction->isCollapsingWithNextDependentActionLegal())
2893 // If the input action is an offload action. Look through it and save any
2894 // offload action that can be dropped in the event of a collapse.
2895 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2896 // If the dependent action is a device action, we will attempt to collapse
2897 // only with other device actions. Otherwise, we would do the same but
2898 // with host actions only.
2899 if (!IsHostSelector) {
2900 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2902 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2903 if (CanBeCollapsed &&
2904 !CurAction->isCollapsingWithNextDependentActionLegal())
2906 SavedOffloadAction.push_back(OA);
2907 return dyn_cast<JobAction>(CurAction);
2909 } else if (OA->hasHostDependence()) {
2910 CurAction = OA->getHostDependence();
2911 if (CanBeCollapsed &&
2912 !CurAction->isCollapsingWithNextDependentActionLegal())
2914 SavedOffloadAction.push_back(OA);
2915 return dyn_cast<JobAction>(CurAction);
2920 return dyn_cast<JobAction>(CurAction);
2923 /// Return true if an assemble action can be collapsed.
2924 bool canCollapseAssembleAction() const {
2925 return TC.useIntegratedAs() && !SaveTemps &&
2926 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2927 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2928 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2931 /// Return true if a preprocessor action can be collapsed.
2932 bool canCollapsePreprocessorAction() const {
2933 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2934 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2935 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2938 /// Struct that relates an action with the offload actions that would be
2939 /// collapsed with it.
2940 struct JobActionInfo final {
2941 /// The action this info refers to.
2942 const JobAction *JA = nullptr;
2943 /// The offload actions we need to take care off if this action is
2945 ActionList SavedOffloadAction;
2948 /// Append collapsed offload actions from the give nnumber of elements in the
2949 /// action info array.
2950 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2951 ArrayRef<JobActionInfo> &ActionInfo,
2952 unsigned ElementNum) {
2953 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2954 for (unsigned I = 0; I < ElementNum; ++I)
2955 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2956 ActionInfo[I].SavedOffloadAction.end());
2959 /// Functions that attempt to perform the combining. They detect if that is
2960 /// legal, and if so they update the inputs \a Inputs and the offload action
2961 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
2962 /// the combined action is returned. If the combining is not legal or if the
2963 /// tool does not exist, null is returned.
2964 /// Currently three kinds of collapsing are supported:
2965 /// - Assemble + Backend + Compile;
2966 /// - Assemble + Backend ;
2967 /// - Backend + Compile.
2969 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2970 const ActionList *&Inputs,
2971 ActionList &CollapsedOffloadAction) {
2972 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
2974 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2975 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2976 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
2977 if (!AJ || !BJ || !CJ)
2980 // Get compiler tool.
2981 const Tool *T = TC.SelectTool(*CJ);
2985 // When using -fembed-bitcode, it is required to have the same tool (clang)
2986 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2988 const Tool *BT = TC.SelectTool(*BJ);
2993 if (!T->hasIntegratedAssembler())
2996 Inputs = &CJ->getInputs();
2997 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3001 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3002 const ActionList *&Inputs,
3003 ActionList &CollapsedOffloadAction) {
3004 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3006 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3007 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3011 // Retrieve the compile job, backend action must always be preceded by one.
3012 ActionList CompileJobOffloadActions;
3013 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3014 /*CanBeCollapsed=*/false);
3015 if (!AJ || !BJ || !CJ)
3018 assert(isa<CompileJobAction>(CJ) &&
3019 "Expecting compile job preceding backend job.");
3021 // Get compiler tool.
3022 const Tool *T = TC.SelectTool(*CJ);
3026 if (!T->hasIntegratedAssembler())
3029 Inputs = &BJ->getInputs();
3030 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3034 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3035 const ActionList *&Inputs,
3036 ActionList &CollapsedOffloadAction) {
3037 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3039 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3040 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3044 // Get compiler tool.
3045 const Tool *T = TC.SelectTool(*CJ);
3049 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3052 Inputs = &CJ->getInputs();
3053 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3058 /// Updates the inputs if the obtained tool supports combining with
3059 /// preprocessor action, and the current input is indeed a preprocessor
3060 /// action. If combining results in the collapse of offloading actions, those
3061 /// are appended to \a CollapsedOffloadAction.
3062 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3063 ActionList &CollapsedOffloadAction) {
3064 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3067 // Attempt to get a preprocessor action dependence.
3068 ActionList PreprocessJobOffloadActions;
3069 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3070 if (!PJ || !isa<PreprocessJobAction>(PJ))
3073 // This is legal to combine. Append any offload action we found and set the
3074 // current inputs to preprocessor inputs.
3075 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3076 PreprocessJobOffloadActions.end());
3077 Inputs = &PJ->getInputs();
3081 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3082 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3083 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3084 EmbedBitcode(EmbedBitcode) {
3085 assert(BaseAction && "Invalid base action.");
3086 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3089 /// Check if a chain of actions can be combined and return the tool that can
3090 /// handle the combination of actions. The pointer to the current inputs \a
3091 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3092 /// connected to collapsed actions are updated accordingly. The latter enables
3093 /// the caller of the selector to process them afterwards instead of just
3094 /// dropping them. If no suitable tool is found, null will be returned.
3095 const Tool *getTool(const ActionList *&Inputs,
3096 ActionList &CollapsedOffloadAction) {
3098 // Get the largest chain of actions that we could combine.
3101 SmallVector<JobActionInfo, 5> ActionChain(1);
3102 ActionChain.back().JA = BaseAction;
3103 while (ActionChain.back().JA) {
3104 const Action *CurAction = ActionChain.back().JA;
3106 // Grow the chain by one element.
3107 ActionChain.resize(ActionChain.size() + 1);
3108 JobActionInfo &AI = ActionChain.back();
3110 // Attempt to fill it with the
3112 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3115 // Pop the last action info as it could not be filled.
3116 ActionChain.pop_back();
3119 // Attempt to combine actions. If all combining attempts failed, just return
3120 // the tool of the provided action. At the end we attempt to combine the
3121 // action with any preprocessor action it may depend on.
3124 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3125 CollapsedOffloadAction);
3127 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3129 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3131 Inputs = &BaseAction->getInputs();
3132 T = TC.SelectTool(*BaseAction);
3135 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3141 /// Return a string that uniquely identifies the result of a job. The bound arch
3142 /// is not necessarily represented in the toolchain's triple -- for example,
3143 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
3144 /// Also, we need to add the offloading device kind, as the same tool chain can
3145 /// be used for host and device for some programming models, e.g. OpenMP.
3146 static std::string GetTriplePlusArchString(const ToolChain *TC,
3147 StringRef BoundArch,
3148 Action::OffloadKind OffloadKind) {
3149 std::string TriplePlusArch = TC->getTriple().normalize();
3150 if (!BoundArch.empty()) {
3151 TriplePlusArch += "-";
3152 TriplePlusArch += BoundArch;
3154 TriplePlusArch += "-";
3155 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3156 return TriplePlusArch;
3159 InputInfo Driver::BuildJobsForAction(
3160 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3161 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3162 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3163 Action::OffloadKind TargetDeviceOffloadKind) const {
3164 std::pair<const Action *, std::string> ActionTC = {
3165 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3166 auto CachedResult = CachedResults.find(ActionTC);
3167 if (CachedResult != CachedResults.end()) {
3168 return CachedResult->second;
3170 InputInfo Result = BuildJobsForActionNoCache(
3171 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3172 CachedResults, TargetDeviceOffloadKind);
3173 CachedResults[ActionTC] = Result;
3177 InputInfo Driver::BuildJobsForActionNoCache(
3178 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3179 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3180 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3181 Action::OffloadKind TargetDeviceOffloadKind) const {
3182 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3184 InputInfoList OffloadDependencesInputInfo;
3185 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3186 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3187 // The offload action is expected to be used in four different situations.
3189 // a) Set a toolchain/architecture/kind for a host action:
3190 // Host Action 1 -> OffloadAction -> Host Action 2
3192 // b) Set a toolchain/architecture/kind for a device action;
3193 // Device Action 1 -> OffloadAction -> Device Action 2
3195 // c) Specify a device dependence to a host action;
3196 // Device Action 1 _
3198 // Host Action 1 ---> OffloadAction -> Host Action 2
3200 // d) Specify a host dependence to a device action.
3203 // Device Action 1 ---> OffloadAction -> Device Action 2
3205 // For a) and b), we just return the job generated for the dependence. For
3206 // c) and d) we override the current action with the host/device dependence
3207 // if the current toolchain is host/device and set the offload dependences
3208 // info with the jobs obtained from the device/host dependence(s).
3210 // If there is a single device option, just generate the job for it.
3211 if (OA->hasSingleDeviceDependence()) {
3213 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3214 const char *DepBoundArch) {
3216 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3217 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3218 CachedResults, DepA->getOffloadingDeviceKind());
3223 // If 'Action 2' is host, we generate jobs for the device dependences and
3224 // override the current action with the host dependence. Otherwise, we
3225 // generate the host dependences and override the action with the device
3226 // dependence. The dependences can't therefore be a top-level action.
3227 OA->doOnEachDependence(
3228 /*IsHostDependence=*/BuildingForOffloadDevice,
3229 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3230 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3231 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3232 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3233 DepA->getOffloadingDeviceKind()));
3236 A = BuildingForOffloadDevice
3237 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3238 : OA->getHostDependence();
3241 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3242 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3243 // just using Args was better?
3244 const Arg &Input = IA->getInputArg();
3246 if (Input.getOption().matches(options::OPT_INPUT)) {
3247 const char *Name = Input.getValue();
3248 return InputInfo(A, Name, /* BaseInput = */ Name);
3250 return InputInfo(A, &Input, /* BaseInput = */ "");
3253 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
3254 const ToolChain *TC;
3255 StringRef ArchName = BAA->getArchName();
3257 if (!ArchName.empty())
3258 TC = &getToolChain(C.getArgs(),
3259 computeTargetTriple(*this, DefaultTargetTriple,
3260 C.getArgs(), ArchName));
3262 TC = &C.getDefaultToolChain();
3264 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
3265 MultipleArchs, LinkingOutput, CachedResults,
3266 TargetDeviceOffloadKind);
3270 const ActionList *Inputs = &A->getInputs();
3272 const JobAction *JA = cast<JobAction>(A);
3273 ActionList CollapsedOffloadActions;
3275 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3276 embedBitcodeInObject() && !isUsingLTO());
3277 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3282 // If we've collapsed action list that contained OffloadAction we
3283 // need to build jobs for host/device-side inputs it may have held.
3284 for (const auto *OA : CollapsedOffloadActions)
3285 cast<OffloadAction>(OA)->doOnEachDependence(
3286 /*IsHostDependence=*/BuildingForOffloadDevice,
3287 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3288 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3289 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
3290 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
3291 DepA->getOffloadingDeviceKind()));
3294 // Only use pipes when there is exactly one input.
3295 InputInfoList InputInfos;
3296 for (const Action *Input : *Inputs) {
3297 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3298 // shouldn't get temporary output names.
3299 // FIXME: Clean this up.
3300 bool SubJobAtTopLevel =
3301 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
3302 InputInfos.push_back(BuildJobsForAction(
3303 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
3304 CachedResults, A->getOffloadingDeviceKind()));
3307 // Always use the first input as the base input.
3308 const char *BaseInput = InputInfos[0].getBaseInput();
3310 // ... except dsymutil actions, which use their actual input as the base
3312 if (JA->getType() == types::TY_dSYM)
3313 BaseInput = InputInfos[0].getFilename();
3315 // Append outputs of offload device jobs to the input list
3316 if (!OffloadDependencesInputInfo.empty())
3317 InputInfos.append(OffloadDependencesInputInfo.begin(),
3318 OffloadDependencesInputInfo.end());
3320 // Set the effective triple of the toolchain for the duration of this job.
3321 llvm::Triple EffectiveTriple;
3322 const ToolChain &ToolTC = T->getToolChain();
3323 const ArgList &Args =
3324 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
3325 if (InputInfos.size() != 1) {
3326 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3328 // Pass along the input type if it can be unambiguously determined.
3329 EffectiveTriple = llvm::Triple(
3330 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3332 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3334 // Determine the place to write output to, if any.
3336 InputInfoList UnbundlingResults;
3337 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3338 // If we have an unbundling job, we need to create results for all the
3339 // outputs. We also update the results cache so that other actions using
3340 // this unbundling action can get the right results.
3341 for (auto &UI : UA->getDependentActionsInfo()) {
3342 assert(UI.DependentOffloadKind != Action::OFK_None &&
3343 "Unbundling with no offloading??");
3345 // Unbundling actions are never at the top level. When we generate the
3346 // offloading prefix, we also do that for the host file because the
3347 // unbundling action does not change the type of the output which can
3348 // cause a overwrite.
3349 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3350 UI.DependentOffloadKind,
3351 UI.DependentToolChain->getTriple().normalize(),
3352 /*CreatePrefixForHost=*/true);
3353 auto CurI = InputInfo(
3354 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3355 /*AtTopLevel=*/false, MultipleArchs,
3358 // Save the unbundling result.
3359 UnbundlingResults.push_back(CurI);
3361 // Get the unique string identifier for this dependence and cache the
3363 CachedResults[{A, GetTriplePlusArchString(
3364 UI.DependentToolChain, UI.DependentBoundArch,
3365 UI.DependentOffloadKind)}] = CurI;
3368 // Now that we have all the results generated, select the one that should be
3369 // returned for the current depending action.
3370 std::pair<const Action *, std::string> ActionTC = {
3371 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3372 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3373 "Result does not exist??");
3374 Result = CachedResults[ActionTC];
3375 } else if (JA->getType() == types::TY_Nothing)
3376 Result = InputInfo(A, BaseInput);
3378 // We only have to generate a prefix for the host if this is not a top-level
3380 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3381 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3382 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3384 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
3385 AtTopLevel, MultipleArchs,
3390 if (CCCPrintBindings && !CCGenDiagnostics) {
3391 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3392 << " - \"" << T->getName() << "\", inputs: [";
3393 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3394 llvm::errs() << InputInfos[i].getAsString();
3396 llvm::errs() << ", ";
3398 if (UnbundlingResults.empty())
3399 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3401 llvm::errs() << "], outputs: [";
3402 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3403 llvm::errs() << UnbundlingResults[i].getAsString();
3405 llvm::errs() << ", ";
3407 llvm::errs() << "] \n";
3410 if (UnbundlingResults.empty())
3412 C, *JA, Result, InputInfos,
3413 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3416 T->ConstructJobMultipleOutputs(
3417 C, *JA, UnbundlingResults, InputInfos,
3418 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3424 const char *Driver::getDefaultImageName() const {
3425 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3426 return Target.isOSWindows() ? "a.exe" : "a.out";
3429 /// \brief Create output filename based on ArgValue, which could either be a
3430 /// full filename, filename without extension, or a directory. If ArgValue
3431 /// does not provide a filename, then use BaseName, and use the extension
3432 /// suitable for FileType.
3433 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
3435 types::ID FileType) {
3436 SmallString<128> Filename = ArgValue;
3438 if (ArgValue.empty()) {
3439 // If the argument is empty, output to BaseName in the current dir.
3440 Filename = BaseName;
3441 } else if (llvm::sys::path::is_separator(Filename.back())) {
3442 // If the argument is a directory, output to BaseName in that dir.
3443 llvm::sys::path::append(Filename, BaseName);
3446 if (!llvm::sys::path::has_extension(ArgValue)) {
3447 // If the argument didn't provide an extension, then set it.
3448 const char *Extension = types::getTypeTempSuffix(FileType, true);
3450 if (FileType == types::TY_Image &&
3451 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3452 // The output file is a dll.
3456 llvm::sys::path::replace_extension(Filename, Extension);
3459 return Args.MakeArgString(Filename.c_str());
3462 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
3463 const char *BaseInput,
3464 StringRef BoundArch, bool AtTopLevel,
3466 StringRef OffloadingPrefix) const {
3467 llvm::PrettyStackTraceString CrashInfo("Computing output path");
3468 // Output to a user requested destination?
3469 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
3470 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
3471 return C.addResultFile(FinalOutput->getValue(), &JA);
3474 // For /P, preprocess to file named after BaseInput.
3475 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3476 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3477 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3479 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
3480 NameArg = A->getValue();
3481 return C.addResultFile(
3482 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3486 // Default to writing to stdout?
3487 if (AtTopLevel && !CCGenDiagnostics &&
3488 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
3491 // Is this the assembly listing for /FA?
3492 if (JA.getType() == types::TY_PP_Asm &&
3493 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3494 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3495 // Use /Fa and the input filename to determine the asm file name.
3496 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3497 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
3498 return C.addResultFile(
3499 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3503 // Output to a temporary file?
3504 if ((!AtTopLevel && !isSaveTempsEnabled() &&
3505 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
3507 StringRef Name = llvm::sys::path::filename(BaseInput);
3508 std::pair<StringRef, StringRef> Split = Name.split('.');
3509 std::string TmpName = GetTemporaryPath(
3510 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3511 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3514 SmallString<128> BasePath(BaseInput);
3517 // Dsymutil actions should use the full path.
3518 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
3519 BaseName = BasePath;
3521 BaseName = llvm::sys::path::filename(BasePath);
3523 // Determine what the derived output name should be.
3524 const char *NamedOutput;
3526 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
3527 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3528 // The /Fo or /o flag decides the object filename.
3531 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3534 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
3535 } else if (JA.getType() == types::TY_Image &&
3536 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3537 options::OPT__SLASH_o)) {
3538 // The /Fe or /o flag names the linked file.
3541 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3544 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
3545 } else if (JA.getType() == types::TY_Image) {
3547 // clang-cl uses BaseName for the executable name.
3549 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
3551 SmallString<128> Output(getDefaultImageName());
3552 Output += OffloadingPrefix;
3553 if (MultipleArchs && !BoundArch.empty()) {
3555 Output.append(BoundArch);
3557 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
3559 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
3560 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
3562 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
3563 assert(Suffix && "All types used for output should have a suffix.");
3565 std::string::size_type End = std::string::npos;
3566 if (!types::appendSuffixForType(JA.getType()))
3567 End = BaseName.rfind('.');
3568 SmallString<128> Suffixed(BaseName.substr(0, End));
3569 Suffixed += OffloadingPrefix;
3570 if (MultipleArchs && !BoundArch.empty()) {
3572 Suffixed.append(BoundArch);
3574 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3575 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3576 // optimized bitcode output.
3577 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3578 JA.getType() == types::TY_LLVM_BC)
3582 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3585 // Prepend object file path if -save-temps=obj
3586 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3587 JA.getType() != types::TY_PCH) {
3588 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3589 SmallString<128> TempPath(FinalOutput->getValue());
3590 llvm::sys::path::remove_filename(TempPath);
3591 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3592 llvm::sys::path::append(TempPath, OutputFileName);
3593 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3596 // If we're saving temps and the temp file conflicts with the input file,
3597 // then avoid overwriting input file.
3598 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
3599 bool SameFile = false;
3600 SmallString<256> Result;
3601 llvm::sys::fs::current_path(Result);
3602 llvm::sys::path::append(Result, BaseName);
3603 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3604 // Must share the same path to conflict.
3606 StringRef Name = llvm::sys::path::filename(BaseInput);
3607 std::pair<StringRef, StringRef> Split = Name.split('.');
3608 std::string TmpName = GetTemporaryPath(
3609 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3610 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3614 // As an annoying special case, PCH generation doesn't strip the pathname.
3615 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
3616 llvm::sys::path::remove_filename(BasePath);
3617 if (BasePath.empty())
3618 BasePath = NamedOutput;
3620 llvm::sys::path::append(BasePath, NamedOutput);
3621 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
3623 return C.addResultFile(NamedOutput, &JA);
3627 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
3628 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3629 // attempting to use this prefix when looking for file paths.
3630 for (const std::string &Dir : PrefixDirs) {
3633 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3634 llvm::sys::path::append(P, Name);
3635 if (llvm::sys::fs::exists(Twine(P)))
3639 SmallString<128> P(ResourceDir);
3640 llvm::sys::path::append(P, Name);
3641 if (llvm::sys::fs::exists(Twine(P)))
3644 for (const std::string &Dir : TC.getFilePaths()) {
3647 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3648 llvm::sys::path::append(P, Name);
3649 if (llvm::sys::fs::exists(Twine(P)))
3656 void Driver::generatePrefixedToolNames(
3657 StringRef Tool, const ToolChain &TC,
3658 SmallVectorImpl<std::string> &Names) const {
3659 // FIXME: Needs a better variable than DefaultTargetTriple
3660 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
3661 Names.emplace_back(Tool);
3663 // Allow the discovery of tools prefixed with LLVM's default target triple.
3664 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3665 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
3666 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
3669 static bool ScanDirForExecutable(SmallString<128> &Dir,
3670 ArrayRef<std::string> Names) {
3671 for (const auto &Name : Names) {
3672 llvm::sys::path::append(Dir, Name);
3673 if (llvm::sys::fs::can_execute(Twine(Dir)))
3675 llvm::sys::path::remove_filename(Dir);
3680 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
3681 SmallVector<std::string, 2> TargetSpecificExecutables;
3682 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3684 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3685 // attempting to use this prefix when looking for program paths.
3686 for (const auto &PrefixDir : PrefixDirs) {
3687 if (llvm::sys::fs::is_directory(PrefixDir)) {
3688 SmallString<128> P(PrefixDir);
3689 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3692 SmallString<128> P((PrefixDir + Name).str());
3693 if (llvm::sys::fs::can_execute(Twine(P)))
3698 const ToolChain::path_list &List = TC.getProgramPaths();
3699 for (const auto &Path : List) {
3700 SmallString<128> P(Path);
3701 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3705 // If all else failed, search the path.
3706 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3707 if (llvm::ErrorOr<std::string> P =
3708 llvm::sys::findProgramByName(TargetSpecificExecutable))
3714 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
3715 SmallString<128> Path;
3716 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
3718 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
3725 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3726 SmallString<128> Output;
3727 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3728 // FIXME: If anybody needs it, implement this obscure rule:
3729 // "If you specify a directory without a file name, the default file name
3730 // is VCx0.pch., where x is the major version of Visual C++ in use."
3731 Output = FpArg->getValue();
3733 // "If you do not specify an extension as part of the path name, an
3734 // extension of .pch is assumed. "
3735 if (!llvm::sys::path::has_extension(Output))
3739 llvm::sys::path::replace_extension(Output, ".pch");
3741 return Output.str();
3744 const ToolChain &Driver::getToolChain(const ArgList &Args,
3745 const llvm::Triple &Target) const {
3747 auto &TC = ToolChains[Target.str()];
3749 switch (Target.getOS()) {
3750 case llvm::Triple::Haiku:
3751 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
3753 case llvm::Triple::Ananas:
3754 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
3756 case llvm::Triple::CloudABI:
3757 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
3759 case llvm::Triple::Darwin:
3760 case llvm::Triple::MacOSX:
3761 case llvm::Triple::IOS:
3762 case llvm::Triple::TvOS:
3763 case llvm::Triple::WatchOS:
3764 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
3766 case llvm::Triple::DragonFly:
3767 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
3769 case llvm::Triple::OpenBSD:
3770 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
3772 case llvm::Triple::Bitrig:
3773 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
3775 case llvm::Triple::NetBSD:
3776 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
3778 case llvm::Triple::FreeBSD:
3779 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
3781 case llvm::Triple::Minix:
3782 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
3784 case llvm::Triple::Linux:
3785 case llvm::Triple::ELFIAMCU:
3786 if (Target.getArch() == llvm::Triple::hexagon)
3787 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3789 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3790 !Target.hasEnvironment())
3791 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3794 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
3796 case llvm::Triple::NaCl:
3797 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
3799 case llvm::Triple::Fuchsia:
3800 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
3802 case llvm::Triple::Solaris:
3803 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
3805 case llvm::Triple::AMDHSA:
3806 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
3808 case llvm::Triple::Win32:
3809 switch (Target.getEnvironment()) {
3811 if (Target.isOSBinFormatELF())
3812 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3813 else if (Target.isOSBinFormatMachO())
3814 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3816 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3818 case llvm::Triple::GNU:
3819 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
3821 case llvm::Triple::Itanium:
3822 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3825 case llvm::Triple::MSVC:
3826 case llvm::Triple::UnknownEnvironment:
3827 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
3831 case llvm::Triple::PS4:
3832 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
3834 case llvm::Triple::Contiki:
3835 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
3838 // Of these targets, Hexagon is the only one that might have
3839 // an OS of Linux, in which case it got handled above already.
3840 switch (Target.getArch()) {
3841 case llvm::Triple::tce:
3842 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
3844 case llvm::Triple::tcele:
3845 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
3847 case llvm::Triple::hexagon:
3848 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3851 case llvm::Triple::lanai:
3852 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
3854 case llvm::Triple::xcore:
3855 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
3857 case llvm::Triple::wasm32:
3858 case llvm::Triple::wasm64:
3859 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
3861 case llvm::Triple::avr:
3862 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
3865 if (Target.getVendor() == llvm::Triple::Myriad)
3866 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3868 else if (toolchains::BareMetal::handlesTarget(Target))
3869 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
3870 else if (Target.isOSBinFormatELF())
3871 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3872 else if (Target.isOSBinFormatMachO())
3873 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3875 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3880 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3881 // compiles always need two toolchains, the CUDA toolchain and the host
3882 // toolchain. So the only valid way to create a CUDA toolchain is via
3883 // CreateOffloadingDeviceToolChains.
3888 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
3889 // Say "no" if there is not exactly one input of a type clang understands.
3890 if (JA.size() != 1 ||
3891 !types::isAcceptedByClang((*JA.input_begin())->getType()))
3894 // And say "no" if this is not a kind of action clang understands.
3895 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
3896 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
3902 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3903 /// grouped values as integers. Numbers which are not provided are set to 0.
3905 /// \return True if the entire string was parsed (9.2), or all groups were
3906 /// parsed (10.3.5extrastuff).
3907 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3908 unsigned &Micro, bool &HadExtra) {
3911 Major = Minor = Micro = 0;
3915 if (Str.consumeInteger(10, Major))
3922 Str = Str.drop_front(1);
3924 if (Str.consumeInteger(10, Minor))
3930 Str = Str.drop_front(1);
3932 if (Str.consumeInteger(10, Micro))
3939 /// Parse digits from a string \p Str and fulfill \p Digits with
3940 /// the parsed numbers. This method assumes that the max number of
3941 /// digits to look for is equal to Digits.size().
3943 /// \return True if the entire string was parsed and there are
3944 /// no extra characters remaining at the end.
3945 bool Driver::GetReleaseVersion(StringRef Str,
3946 MutableArrayRef<unsigned> Digits) {
3950 unsigned CurDigit = 0;
3951 while (CurDigit < Digits.size()) {
3953 if (Str.consumeInteger(10, Digit))
3955 Digits[CurDigit] = Digit;
3960 Str = Str.drop_front(1);
3964 // More digits than requested, bail out...
3968 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3969 unsigned IncludedFlagsBitmask = 0;
3970 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
3972 if (Mode == CLMode) {
3973 // Include CL and Core options.
3974 IncludedFlagsBitmask |= options::CLOption;
3975 IncludedFlagsBitmask |= options::CoreOption;
3977 ExcludedFlagsBitmask |= options::CLOption;
3980 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3983 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
3984 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);