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/raw_ostream.h"
77 #include <unistd.h> // getpid
80 using namespace clang::driver;
81 using namespace clang;
82 using namespace llvm::opt;
84 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
85 DiagnosticsEngine &Diags,
86 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
87 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
88 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
89 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
90 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
91 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
92 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
93 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
94 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
95 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
96 GenReproducer(false), SuppressMissingInputWarning(false) {
98 // Provide a sane fallback if no VFS is specified.
100 this->VFS = vfs::getRealFileSystem();
102 Name = llvm::sys::path::filename(ClangExecutable);
103 Dir = llvm::sys::path::parent_path(ClangExecutable);
104 InstalledDir = Dir; // Provide a sensible default installed dir.
106 // Compute the path to the resource directory.
107 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
108 SmallString<128> P(Dir);
109 if (ClangResourceDir != "") {
110 llvm::sys::path::append(P, ClangResourceDir);
112 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
113 P = llvm::sys::path::parent_path(Dir);
114 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
115 CLANG_VERSION_STRING);
117 ResourceDir = P.str();
120 void Driver::ParseDriverMode(StringRef ProgramName,
121 ArrayRef<const char *> Args) {
122 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
123 StringRef DefaultMode(Default.second);
124 setDriverModeFromOption(DefaultMode);
126 for (const char *ArgPtr : Args) {
127 // Ingore nullptrs, they are response file's EOL markers
128 if (ArgPtr == nullptr)
130 const StringRef Arg = ArgPtr;
131 setDriverModeFromOption(Arg);
135 void Driver::setDriverModeFromOption(StringRef Opt) {
136 const std::string OptName =
137 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
138 if (!Opt.startswith(OptName))
140 StringRef Value = Opt.drop_front(OptName.size());
142 const unsigned M = llvm::StringSwitch<unsigned>(Value)
143 .Case("gcc", GCCMode)
144 .Case("g++", GXXMode)
145 .Case("cpp", CPPMode)
150 Mode = static_cast<DriverMode>(M);
152 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
155 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
156 bool &ContainsError) {
157 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
158 ContainsError = false;
160 unsigned IncludedFlagsBitmask;
161 unsigned ExcludedFlagsBitmask;
162 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
163 getIncludeExcludeOptionFlagMasks();
165 unsigned MissingArgIndex, MissingArgCount;
167 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
168 IncludedFlagsBitmask, ExcludedFlagsBitmask);
170 // Check for missing argument error.
171 if (MissingArgCount) {
172 Diag(diag::err_drv_missing_argument)
173 << Args.getArgString(MissingArgIndex) << MissingArgCount;
175 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
176 SourceLocation()) > DiagnosticsEngine::Warning;
179 // Check for unsupported options.
180 for (const Arg *A : Args) {
181 if (A->getOption().hasFlag(options::Unsupported)) {
182 Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
183 ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt,
185 DiagnosticsEngine::Warning;
189 // Warn about -mcpu= without an argument.
190 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
191 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
192 ContainsError |= Diags.getDiagnosticLevel(
193 diag::warn_drv_empty_joined_argument,
194 SourceLocation()) > DiagnosticsEngine::Warning;
198 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
199 auto ID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
200 : diag::err_drv_unknown_argument;
202 Diags.Report(ID) << A->getAsString(Args);
203 ContainsError |= Diags.getDiagnosticLevel(ID, SourceLocation()) >
204 DiagnosticsEngine::Warning;
210 // Determine which compilation mode we are in. We look for options which
211 // affect the phase, starting with the earliest phases, and record which
212 // option we used to determine the final phase.
213 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
214 Arg **FinalPhaseArg) const {
215 Arg *PhaseArg = nullptr;
216 phases::ID FinalPhase;
218 // -{E,EP,P,M,MM} only run the preprocessor.
219 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
220 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
221 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
222 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
223 FinalPhase = phases::Preprocess;
225 // --precompile only runs up to precompilation.
226 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
227 FinalPhase = phases::Precompile;
229 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
230 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
231 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
232 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
233 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
234 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
235 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
236 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
237 options::OPT__analyze_auto)) ||
238 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
239 FinalPhase = phases::Compile;
241 // -S only runs up to the backend.
242 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
243 FinalPhase = phases::Backend;
245 // -c compilation only runs up to the assembler.
246 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
247 FinalPhase = phases::Assemble;
249 // Otherwise do everything.
251 FinalPhase = phases::Link;
254 *FinalPhaseArg = PhaseArg;
259 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
261 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
262 Args.getBaseArgs().MakeIndex(Value), Value.data());
263 Args.AddSynthesizedArg(A);
268 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
269 DerivedArgList *DAL = new DerivedArgList(Args);
271 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
272 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
273 for (Arg *A : Args) {
274 // Unfortunately, we have to parse some forwarding options (-Xassembler,
275 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
276 // (assembler and preprocessor), or bypass a previous driver ('collect2').
278 // Rewrite linker options, to replace --no-demangle with a custom internal
280 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
281 A->getOption().matches(options::OPT_Xlinker)) &&
282 A->containsValue("--no-demangle")) {
283 // Add the rewritten no-demangle argument.
284 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
286 // Add the remaining values as Xlinker arguments.
287 for (StringRef Val : A->getValues())
288 if (Val != "--no-demangle")
289 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
294 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
295 // some build systems. We don't try to be complete here because we don't
296 // care to encourage this usage model.
297 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
298 (A->getValue(0) == StringRef("-MD") ||
299 A->getValue(0) == StringRef("-MMD"))) {
300 // Rewrite to -MD/-MMD along with -MF.
301 if (A->getValue(0) == StringRef("-MD"))
302 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
304 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
305 if (A->getNumValues() == 2)
306 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
311 // Rewrite reserved library names.
312 if (A->getOption().matches(options::OPT_l)) {
313 StringRef Value = A->getValue();
315 // Rewrite unless -nostdlib is present.
316 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
317 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
321 // Rewrite unconditionally.
322 if (Value == "cc_kext") {
323 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
328 // Pick up inputs via the -- option.
329 if (A->getOption().matches(options::OPT__DASH_DASH)) {
331 for (StringRef Val : A->getValues())
332 DAL->append(MakeInputArg(*DAL, *Opts, Val));
339 // Enforce -static if -miamcu is present.
340 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
341 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
343 // Add a default value of -mlinker-version=, if one was given and the user
344 // didn't specify one.
345 #if defined(HOST_LINK_VERSION)
346 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
347 strlen(HOST_LINK_VERSION) > 0) {
348 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
350 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
357 /// \brief Compute target triple from args.
359 /// This routine provides the logic to compute a target triple from various
360 /// args passed to the driver and the default triple string.
361 static llvm::Triple computeTargetTriple(const Driver &D,
362 StringRef DefaultTargetTriple,
364 StringRef DarwinArchName = "") {
365 // FIXME: Already done in Compilation *Driver::BuildCompilation
366 if (const Arg *A = Args.getLastArg(options::OPT_target))
367 DefaultTargetTriple = A->getValue();
369 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
371 // Handle Apple-specific options available here.
372 if (Target.isOSBinFormatMachO()) {
373 // If an explict Darwin arch name is given, that trumps all.
374 if (!DarwinArchName.empty()) {
375 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
379 // Handle the Darwin '-arch' flag.
380 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
381 StringRef ArchName = A->getValue();
382 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
386 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
387 // '-mbig-endian'/'-EB'.
388 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
389 options::OPT_mbig_endian)) {
390 if (A->getOption().matches(options::OPT_mlittle_endian)) {
391 llvm::Triple LE = Target.getLittleEndianArchVariant();
392 if (LE.getArch() != llvm::Triple::UnknownArch)
393 Target = std::move(LE);
395 llvm::Triple BE = Target.getBigEndianArchVariant();
396 if (BE.getArch() != llvm::Triple::UnknownArch)
397 Target = std::move(BE);
401 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
402 if (Target.getArch() == llvm::Triple::tce ||
403 Target.getOS() == llvm::Triple::Minix)
406 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
407 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
408 options::OPT_m32, options::OPT_m16);
410 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
412 if (A->getOption().matches(options::OPT_m64)) {
413 AT = Target.get64BitArchVariant().getArch();
414 if (Target.getEnvironment() == llvm::Triple::GNUX32)
415 Target.setEnvironment(llvm::Triple::GNU);
416 } else if (A->getOption().matches(options::OPT_mx32) &&
417 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
418 AT = llvm::Triple::x86_64;
419 Target.setEnvironment(llvm::Triple::GNUX32);
420 } else if (A->getOption().matches(options::OPT_m32)) {
421 AT = Target.get32BitArchVariant().getArch();
422 if (Target.getEnvironment() == llvm::Triple::GNUX32)
423 Target.setEnvironment(llvm::Triple::GNU);
424 } else if (A->getOption().matches(options::OPT_m16) &&
425 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
426 AT = llvm::Triple::x86;
427 Target.setEnvironment(llvm::Triple::CODE16);
430 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
434 // Handle -miamcu flag.
435 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
436 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
437 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
440 if (A && !A->getOption().matches(options::OPT_m32))
441 D.Diag(diag::err_drv_argument_not_allowed_with)
442 << "-miamcu" << A->getBaseArg().getAsString(Args);
444 Target.setArch(llvm::Triple::x86);
445 Target.setArchName("i586");
446 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
447 Target.setEnvironmentName("");
448 Target.setOS(llvm::Triple::ELFIAMCU);
449 Target.setVendor(llvm::Triple::UnknownVendor);
450 Target.setVendorName("intel");
456 // \brief Parse the LTO options and record the type of LTO compilation
457 // based on which -f(no-)?lto(=.*)? option occurs last.
458 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
460 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
461 options::OPT_fno_lto, false))
464 StringRef LTOName("full");
466 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
468 LTOName = A->getValue();
470 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
471 .Case("full", LTOK_Full)
472 .Case("thin", LTOK_Thin)
473 .Default(LTOK_Unknown);
475 if (LTOMode == LTOK_Unknown) {
477 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
482 /// Compute the desired OpenMP runtime from the flags provided.
483 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
484 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
486 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
488 RuntimeName = A->getValue();
490 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
491 .Case("libomp", OMPRT_OMP)
492 .Case("libgomp", OMPRT_GOMP)
493 .Case("libiomp5", OMPRT_IOMP5)
494 .Default(OMPRT_Unknown);
496 if (RT == OMPRT_Unknown) {
498 Diag(diag::err_drv_unsupported_option_argument)
499 << A->getOption().getName() << A->getValue();
501 // FIXME: We could use a nicer diagnostic here.
502 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
508 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
514 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
515 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
516 return types::isCuda(I.first);
518 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
519 const llvm::Triple &HostTriple = HostTC->getTriple();
520 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
521 : "nvptx-nvidia-cuda");
522 // Use the CUDA and host triples as the key into the ToolChains map, because
523 // the device toolchain we create depends on both.
524 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
526 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
527 *this, CudaTriple, *HostTC, C.getInputArgs());
529 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
535 // We need to generate an OpenMP toolchain if the user specified targets with
536 // the -fopenmp-targets option.
537 if (Arg *OpenMPTargets =
538 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
539 if (OpenMPTargets->getNumValues()) {
540 // We expect that -fopenmp-targets is always used in conjunction with the
541 // option -fopenmp specifying a valid runtime with offloading support,
542 // i.e. libomp or libiomp.
543 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
544 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
545 options::OPT_fno_openmp, false);
546 if (HasValidOpenMPRuntime) {
547 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
548 HasValidOpenMPRuntime =
549 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
552 if (HasValidOpenMPRuntime) {
553 llvm::StringMap<const char *> FoundNormalizedTriples;
554 for (const char *Val : OpenMPTargets->getValues()) {
555 llvm::Triple TT(Val);
556 std::string NormalizedName = TT.normalize();
558 // Make sure we don't have a duplicate triple.
559 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
560 if (Duplicate != FoundNormalizedTriples.end()) {
561 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
562 << Val << Duplicate->second;
566 // Store the current triple so that we can check for duplicates in the
567 // following iterations.
568 FoundNormalizedTriples[NormalizedName] = Val;
570 // If the specified target is invalid, emit a diagnostic.
571 if (TT.getArch() == llvm::Triple::UnknownArch)
572 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
575 // CUDA toolchains have to be selected differently. They pair host
576 // and device in their implementation.
578 const ToolChain *HostTC =
579 C.getSingleOffloadToolChain<Action::OFK_Host>();
580 assert(HostTC && "Host toolchain should be always defined.");
582 ToolChains[TT.str() + "/" + HostTC->getTriple().str()];
584 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
585 *this, TT, *HostTC, C.getInputArgs());
588 TC = &getToolChain(C.getInputArgs(), TT);
589 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
593 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
595 Diag(clang::diag::warn_drv_empty_joined_argument)
596 << OpenMPTargets->getAsString(C.getInputArgs());
600 // TODO: Add support for other offloading programming models here.
606 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
607 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
609 // FIXME: Handle environment options which affect driver behavior, somewhere
610 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
612 if (Optional<std::string> CompilerPathValue =
613 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
614 StringRef CompilerPath = *CompilerPathValue;
615 while (!CompilerPath.empty()) {
616 std::pair<StringRef, StringRef> Split =
617 CompilerPath.split(llvm::sys::EnvPathSeparator);
618 PrefixDirs.push_back(Split.first);
619 CompilerPath = Split.second;
623 // We look for the driver mode option early, because the mode can affect
624 // how other options are parsed.
625 ParseDriverMode(ClangExecutable, ArgList.slice(1));
627 // FIXME: What are we going to do with -V and -b?
629 // FIXME: This stuff needs to go into the Compilation, not the driver.
633 InputArgList Args = ParseArgStrings(ArgList.slice(1), ContainsError);
635 // Silence driver warnings if requested
636 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
638 // -no-canonical-prefixes is used very early in main.
639 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
642 Args.ClaimAllArgs(options::OPT_pipe);
644 // Extract -ccc args.
646 // FIXME: We need to figure out where this behavior should live. Most of it
647 // should be outside in the client; the parts that aren't should have proper
648 // options, either by introducing new ones or by overloading gcc ones like -V
650 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
651 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
652 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
653 CCCGenericGCCName = A->getValue();
655 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
656 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
657 options::OPT_fno_crash_diagnostics,
658 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
659 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
660 // and getToolChain is const.
662 // clang-cl targets MSVC-style Win32.
663 llvm::Triple T(DefaultTargetTriple);
664 T.setOS(llvm::Triple::Win32);
665 T.setVendor(llvm::Triple::PC);
666 T.setEnvironment(llvm::Triple::MSVC);
667 DefaultTargetTriple = T.str();
669 if (const Arg *A = Args.getLastArg(options::OPT_target))
670 DefaultTargetTriple = A->getValue();
671 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
672 Dir = InstalledDir = A->getValue();
673 for (const Arg *A : Args.filtered(options::OPT_B)) {
675 PrefixDirs.push_back(A->getValue(0));
677 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
678 SysRoot = A->getValue();
679 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
680 DyldPrefix = A->getValue();
681 if (Args.hasArg(options::OPT_nostdlib))
684 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
685 ResourceDir = A->getValue();
687 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
688 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
689 .Case("cwd", SaveTempsCwd)
690 .Case("obj", SaveTempsObj)
691 .Default(SaveTempsCwd);
696 // Process -fembed-bitcode= flags.
697 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
698 StringRef Name = A->getValue();
699 unsigned Model = llvm::StringSwitch<unsigned>(Name)
700 .Case("off", EmbedNone)
701 .Case("all", EmbedBitcode)
702 .Case("bitcode", EmbedBitcode)
703 .Case("marker", EmbedMarker)
706 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
709 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
712 std::unique_ptr<llvm::opt::InputArgList> UArgs =
713 llvm::make_unique<InputArgList>(std::move(Args));
715 // Perform the default argument translations.
716 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
718 // Owned by the host.
719 const ToolChain &TC = getToolChain(
720 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
722 // The compilation takes ownership of Args.
723 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
726 if (!HandleImmediateArgs(*C))
729 // Construct the list of inputs.
731 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
733 // Populate the tool chains for the offloading devices, if any.
734 CreateOffloadingDeviceToolChains(*C, Inputs);
736 // Construct the list of abstract actions to perform for this compilation. On
737 // MachO targets this uses the driver-driver and universal actions.
738 if (TC.getTriple().isOSBinFormatMachO())
739 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
741 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
743 if (CCCPrintPhases) {
753 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
754 llvm::opt::ArgStringList ASL;
755 for (const auto *A : Args)
756 A->render(Args, ASL);
758 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
759 if (I != ASL.begin())
761 Command::printArg(OS, *I, true);
766 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
767 SmallString<128> &CrashDiagDir) {
768 using namespace llvm::sys;
769 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
770 "Only knows about .crash files on Darwin");
772 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
773 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
774 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
775 path::home_directory(CrashDiagDir);
776 if (CrashDiagDir.startswith("/var/root"))
778 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
786 fs::file_status FileStatus;
787 TimePoint<> LastAccessTime;
788 SmallString<128> CrashFilePath;
789 // Lookup the .crash files and get the one generated by a subprocess spawned
790 // by this driver invocation.
791 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
792 File != FileEnd && !EC; File.increment(EC)) {
793 StringRef FileName = path::filename(File->path());
794 if (!FileName.startswith(Name))
796 if (fs::status(File->path(), FileStatus))
798 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
799 llvm::MemoryBuffer::getFile(File->path());
802 // The first line should start with "Process:", otherwise this isn't a real
804 StringRef Data = CrashFile.get()->getBuffer();
805 if (!Data.startswith("Process:"))
807 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
808 size_t ParentProcPos = Data.find("Parent Process:");
809 if (ParentProcPos == StringRef::npos)
811 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
812 if (LineEnd == StringRef::npos)
814 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
815 int OpenBracket = -1, CloseBracket = -1;
816 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
817 if (ParentProcess[i] == '[')
819 if (ParentProcess[i] == ']')
822 // Extract the parent process PID from the .crash file and check whether
823 // it matches this driver invocation pid.
825 if (OpenBracket < 0 || CloseBracket < 0 ||
826 ParentProcess.slice(OpenBracket + 1, CloseBracket)
827 .getAsInteger(10, CrashPID) || CrashPID != PID) {
831 // Found a .crash file matching the driver pid. To avoid getting an older
832 // and misleading crash file, continue looking for the most recent.
833 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
834 // multiple crashes poiting to the same parent process. Since the driver
835 // does not collect pid information for the dispatched invocation there's
836 // currently no way to distinguish among them.
837 const auto FileAccessTime = FileStatus.getLastModificationTime();
838 if (FileAccessTime > LastAccessTime) {
839 CrashFilePath.assign(File->path());
840 LastAccessTime = FileAccessTime;
844 // If found, copy it over to the location of other reproducer files.
845 if (!CrashFilePath.empty()) {
846 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
855 // When clang crashes, produce diagnostic information including the fully
856 // preprocessed source file(s). Request that the developer attach the
857 // diagnostic information to a bug report.
858 void Driver::generateCompilationDiagnostics(Compilation &C,
859 const Command &FailingCommand) {
860 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
863 // Don't try to generate diagnostics for link or dsymutil jobs.
864 if (FailingCommand.getCreator().isLinkJob() ||
865 FailingCommand.getCreator().isDsymutilJob())
868 // Print the version of the compiler.
869 PrintVersion(C, llvm::errs());
871 Diag(clang::diag::note_drv_command_failed_diag_msg)
872 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
873 "crash backtrace, preprocessed source, and associated run script.";
875 // Suppress driver output and emit preprocessor output to temp file.
877 CCGenDiagnostics = true;
879 // Save the original job command(s).
880 Command Cmd = FailingCommand;
882 // Keep track of whether we produce any errors while trying to produce
883 // preprocessed sources.
884 DiagnosticErrorTrap Trap(Diags);
886 // Suppress tool output.
887 C.initCompilationForDiagnostics();
889 // Construct the list of inputs.
891 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
893 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
894 bool IgnoreInput = false;
896 // Ignore input from stdin or any inputs that cannot be preprocessed.
897 // Check type first as not all linker inputs have a value.
898 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
900 } else if (!strcmp(it->second->getValue(), "-")) {
901 Diag(clang::diag::note_drv_command_failed_diag_msg)
902 << "Error generating preprocessed source(s) - "
903 "ignoring input from stdin.";
908 it = Inputs.erase(it);
915 if (Inputs.empty()) {
916 Diag(clang::diag::note_drv_command_failed_diag_msg)
917 << "Error generating preprocessed source(s) - "
918 "no preprocessable inputs.";
922 // Don't attempt to generate preprocessed files if multiple -arch options are
923 // used, unless they're all duplicates.
924 llvm::StringSet<> ArchNames;
925 for (const Arg *A : C.getArgs()) {
926 if (A->getOption().matches(options::OPT_arch)) {
927 StringRef ArchName = A->getValue();
928 ArchNames.insert(ArchName);
931 if (ArchNames.size() > 1) {
932 Diag(clang::diag::note_drv_command_failed_diag_msg)
933 << "Error generating preprocessed source(s) - cannot generate "
934 "preprocessed source with multiple -arch options.";
938 // Construct the list of abstract actions to perform for this compilation. On
939 // Darwin OSes this uses the driver-driver and builds universal actions.
940 const ToolChain &TC = C.getDefaultToolChain();
941 if (TC.getTriple().isOSBinFormatMachO())
942 BuildUniversalActions(C, TC, Inputs);
944 BuildActions(C, C.getArgs(), Inputs, C.getActions());
948 // If there were errors building the compilation, quit now.
949 if (Trap.hasErrorOccurred()) {
950 Diag(clang::diag::note_drv_command_failed_diag_msg)
951 << "Error generating preprocessed source(s).";
955 // Generate preprocessed output.
956 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
957 C.ExecuteJobs(C.getJobs(), FailingCommands);
959 // If any of the preprocessing commands failed, clean up and exit.
960 if (!FailingCommands.empty()) {
961 if (!isSaveTempsEnabled())
962 C.CleanupFileList(C.getTempFiles(), true);
964 Diag(clang::diag::note_drv_command_failed_diag_msg)
965 << "Error generating preprocessed source(s).";
969 const ArgStringList &TempFiles = C.getTempFiles();
970 if (TempFiles.empty()) {
971 Diag(clang::diag::note_drv_command_failed_diag_msg)
972 << "Error generating preprocessed source(s).";
976 Diag(clang::diag::note_drv_command_failed_diag_msg)
977 << "\n********************\n\n"
978 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
979 "Preprocessed source(s) and associated run script(s) are located at:";
981 SmallString<128> VFS;
982 SmallString<128> ReproCrashFilename;
983 for (const char *TempFile : TempFiles) {
984 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
985 if (ReproCrashFilename.empty()) {
986 ReproCrashFilename = TempFile;
987 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
989 if (StringRef(TempFile).endswith(".cache")) {
990 // In some cases (modules) we'll dump extra data to help with reproducing
991 // the crash into a directory next to the output.
992 VFS = llvm::sys::path::filename(TempFile);
993 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
997 // Assume associated files are based off of the first temporary file.
998 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1000 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
1002 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
1004 Diag(clang::diag::note_drv_command_failed_diag_msg)
1005 << "Error generating run script: " + Script + " " + EC.message();
1007 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1008 << "# Driver args: ";
1009 printArgList(ScriptOS, C.getInputArgs());
1010 ScriptOS << "# Original command: ";
1011 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1012 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1013 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1016 // On darwin, provide information about the .crash diagnostic report.
1017 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1018 SmallString<128> CrashDiagDir;
1019 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1020 Diag(clang::diag::note_drv_command_failed_diag_msg)
1021 << ReproCrashFilename.str();
1022 } else { // Suggest a directory for the user to look for .crash files.
1023 llvm::sys::path::append(CrashDiagDir, Name);
1024 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1025 Diag(clang::diag::note_drv_command_failed_diag_msg)
1026 << "Crash backtrace is located in";
1027 Diag(clang::diag::note_drv_command_failed_diag_msg)
1028 << CrashDiagDir.str();
1029 Diag(clang::diag::note_drv_command_failed_diag_msg)
1030 << "(choose the .crash file that corresponds to your crash)";
1034 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1035 options::OPT_frewrite_map_file_EQ))
1036 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1038 Diag(clang::diag::note_drv_command_failed_diag_msg)
1039 << "\n\n********************";
1042 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1043 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
1044 // if the tool does not support response files, there is a chance/ that things
1045 // will just work without a response file, so we silently just skip it.
1046 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1047 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
1050 std::string TmpName = GetTemporaryPath("response", "txt");
1051 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1054 int Driver::ExecuteCompilation(
1056 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1057 // Just print if -### was present.
1058 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1059 C.getJobs().Print(llvm::errs(), "\n", true);
1063 // If there were errors building the compilation, quit now.
1064 if (Diags.hasErrorOccurred())
1067 // Set up response file names for each command, if necessary
1068 for (auto &Job : C.getJobs())
1069 setUpResponseFiles(C, Job);
1071 C.ExecuteJobs(C.getJobs(), FailingCommands);
1073 // Remove temp files.
1074 C.CleanupFileList(C.getTempFiles());
1076 // If the command succeeded, we are done.
1077 if (FailingCommands.empty())
1080 // Otherwise, remove result files and print extra information about abnormal
1082 for (const auto &CmdPair : FailingCommands) {
1083 int Res = CmdPair.first;
1084 const Command *FailingCommand = CmdPair.second;
1086 // Remove result files if we're not saving temps.
1087 if (!isSaveTempsEnabled()) {
1088 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1089 C.CleanupFileMap(C.getResultFiles(), JA, true);
1091 // Failure result files are valid unless we crashed.
1093 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1096 // Print extra information about abnormal failures, if possible.
1098 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1099 // status was 1, assume the command failed normally. In particular, if it
1100 // was the compiler then assume it gave a reasonable error code. Failures
1101 // in other tools are less common, and they generally have worse
1102 // diagnostics, so always print the diagnostic there.
1103 const Tool &FailingTool = FailingCommand->getCreator();
1105 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1106 // FIXME: See FIXME above regarding result code interpretation.
1108 Diag(clang::diag::err_drv_command_signalled)
1109 << FailingTool.getShortName();
1111 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1118 void Driver::PrintHelp(bool ShowHidden) const {
1119 unsigned IncludedFlagsBitmask;
1120 unsigned ExcludedFlagsBitmask;
1121 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1122 getIncludeExcludeOptionFlagMasks();
1124 ExcludedFlagsBitmask |= options::NoDriverOption;
1126 ExcludedFlagsBitmask |= HelpHidden;
1128 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1129 IncludedFlagsBitmask, ExcludedFlagsBitmask);
1132 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1133 // FIXME: The following handlers should use a callback mechanism, we don't
1134 // know what the client would like to do.
1135 OS << getClangFullVersion() << '\n';
1136 const ToolChain &TC = C.getDefaultToolChain();
1137 OS << "Target: " << TC.getTripleString() << '\n';
1139 // Print the threading model.
1140 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1141 // Don't print if the ToolChain would have barfed on it already
1142 if (TC.isThreadModelSupported(A->getValue()))
1143 OS << "Thread model: " << A->getValue();
1145 OS << "Thread model: " << TC.getThreadModel();
1148 // Print out the install directory.
1149 OS << "InstalledDir: " << InstalledDir << '\n';
1152 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1154 static void PrintDiagnosticCategories(raw_ostream &OS) {
1155 // Skip the empty category.
1156 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1158 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1161 bool Driver::HandleImmediateArgs(const Compilation &C) {
1162 // The order these options are handled in gcc is all over the place, but we
1163 // don't expect inconsistencies w.r.t. that to matter in practice.
1165 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1166 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1170 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1171 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1172 // return an answer which matches our definition of __VERSION__.
1174 // If we want to return a more correct answer some day, then we should
1175 // introduce a non-pedantically GCC compatible mode to Clang in which we
1176 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1177 llvm::outs() << "4.2.1\n";
1181 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1182 PrintDiagnosticCategories(llvm::outs());
1186 if (C.getArgs().hasArg(options::OPT_help) ||
1187 C.getArgs().hasArg(options::OPT__help_hidden)) {
1188 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1192 if (C.getArgs().hasArg(options::OPT__version)) {
1193 // Follow gcc behavior and use stdout for --version and stderr for -v.
1194 PrintVersion(C, llvm::outs());
1198 if (C.getArgs().hasArg(options::OPT_v) ||
1199 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1200 PrintVersion(C, llvm::errs());
1201 SuppressMissingInputWarning = true;
1204 const ToolChain &TC = C.getDefaultToolChain();
1206 if (C.getArgs().hasArg(options::OPT_v))
1207 TC.printVerboseInfo(llvm::errs());
1209 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1210 llvm::outs() << ResourceDir << '\n';
1214 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1215 llvm::outs() << "programs: =";
1216 bool separator = false;
1217 for (const std::string &Path : TC.getProgramPaths()) {
1219 llvm::outs() << ':';
1220 llvm::outs() << Path;
1223 llvm::outs() << "\n";
1224 llvm::outs() << "libraries: =" << ResourceDir;
1226 StringRef sysroot = C.getSysRoot();
1228 for (const std::string &Path : TC.getFilePaths()) {
1229 // Always print a separator. ResourceDir was the first item shown.
1230 llvm::outs() << ':';
1231 // Interpretation of leading '=' is needed only for NetBSD.
1233 llvm::outs() << sysroot << Path.substr(1);
1235 llvm::outs() << Path;
1237 llvm::outs() << "\n";
1241 // FIXME: The following handlers should use a callback mechanism, we don't
1242 // know what the client would like to do.
1243 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1244 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1248 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1249 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
1253 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1254 // Print out all options that start with a given argument. This is used for
1255 // shell autocompletion.
1256 StringRef PassedFlags = A->getValue();
1257 std::vector<std::string> SuggestedCompletions;
1259 unsigned short DisableFlags = options::NoDriverOption | options::Unsupported | options::Ignored;
1260 // We want to show cc1-only options only when clang is invoked as "clang -cc1".
1261 // When clang is invoked as "clang -cc1", we add "#" to the beginning of an --autocomplete
1262 // option so that the clang driver can distinguish whether it is requested to show cc1-only options or not.
1263 if (PassedFlags[0] == '#') {
1264 DisableFlags &= ~options::NoDriverOption;
1265 PassedFlags = PassedFlags.substr(1);
1268 if (PassedFlags.find(',') == StringRef::npos) {
1269 // If the flag is in the form of "--autocomplete=-foo",
1270 // we were requested to print out all option names that start with "-foo".
1271 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1272 SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
1274 // We have to query the -W flags manually as they're not in the OptTable.
1275 // TODO: Find a good way to add them to OptTable instead and them remove
1277 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1278 if (S.startswith(PassedFlags))
1279 SuggestedCompletions.push_back(S);
1281 // If the flag is in the form of "--autocomplete=foo,bar", we were
1282 // requested to print out all option values for "-foo" that start with
1283 // "bar". For example,
1284 // "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
1285 StringRef Option, Arg;
1286 std::tie(Option, Arg) = PassedFlags.split(',');
1287 SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
1290 // Sort the autocomplete candidates so that shells print them out in a
1291 // deterministic order. We could sort in any way, but we chose
1292 // case-insensitive sorting for consistency with the -help option
1293 // which prints out options in the case-insensitive alphabetical order.
1294 std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1295 [](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
1297 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1301 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1302 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1304 case ToolChain::RLT_CompilerRT:
1305 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1307 case ToolChain::RLT_Libgcc:
1308 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1314 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1315 for (const Multilib &Multilib : TC.getMultilibs())
1316 llvm::outs() << Multilib << "\n";
1320 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1321 for (const Multilib &Multilib : TC.getMultilibs()) {
1322 if (Multilib.gccSuffix().empty())
1323 llvm::outs() << ".\n";
1325 StringRef Suffix(Multilib.gccSuffix());
1326 assert(Suffix.front() == '/');
1327 llvm::outs() << Suffix.substr(1) << "\n";
1335 // Display an action graph human-readably. Action A is the "sink" node
1336 // and latest-occuring action. Traversal is in pre-order, visiting the
1337 // inputs to each action before printing the action itself.
1338 static unsigned PrintActions1(const Compilation &C, Action *A,
1339 std::map<Action *, unsigned> &Ids) {
1340 if (Ids.count(A)) // A was already visited.
1344 llvm::raw_string_ostream os(str);
1346 os << Action::getClassName(A->getKind()) << ", ";
1347 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1348 os << "\"" << IA->getInputArg().getValue() << "\"";
1349 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1350 os << '"' << BIA->getArchName() << '"' << ", {"
1351 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1352 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1353 bool IsFirst = true;
1354 OA->doOnEachDependence(
1355 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1356 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1357 // sm_35 this will generate:
1358 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1359 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1364 os << A->getOffloadingKindPrefix();
1368 os << TC->getTriple().normalize();
1371 os << ":" << BoundArch;
1374 os << " {" << PrintActions1(C, A, Ids) << "}";
1378 const ActionList *AL = &A->getInputs();
1381 const char *Prefix = "{";
1382 for (Action *PreRequisite : *AL) {
1383 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1391 // Append offload info for all options other than the offloading action
1392 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1393 std::string offload_str;
1394 llvm::raw_string_ostream offload_os(offload_str);
1395 if (!isa<OffloadAction>(A)) {
1396 auto S = A->getOffloadingKindPrefix();
1398 offload_os << ", (" << S;
1399 if (A->getOffloadingArch())
1400 offload_os << ", " << A->getOffloadingArch();
1405 unsigned Id = Ids.size();
1407 llvm::errs() << Id << ": " << os.str() << ", "
1408 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1413 // Print the action graphs in a compilation C.
1414 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1415 void Driver::PrintActions(const Compilation &C) const {
1416 std::map<Action *, unsigned> Ids;
1417 for (Action *A : C.getActions())
1418 PrintActions1(C, A, Ids);
1421 /// \brief Check whether the given input tree contains any compilation or
1422 /// assembly actions.
1423 static bool ContainsCompileOrAssembleAction(const Action *A) {
1424 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1425 isa<AssembleJobAction>(A))
1428 for (const Action *Input : A->inputs())
1429 if (ContainsCompileOrAssembleAction(Input))
1435 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1436 const InputList &BAInputs) const {
1437 DerivedArgList &Args = C.getArgs();
1438 ActionList &Actions = C.getActions();
1439 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1440 // Collect the list of architectures. Duplicates are allowed, but should only
1441 // be handled once (in the order seen).
1442 llvm::StringSet<> ArchNames;
1443 SmallVector<const char *, 4> Archs;
1444 for (Arg *A : Args) {
1445 if (A->getOption().matches(options::OPT_arch)) {
1446 // Validate the option here; we don't save the type here because its
1447 // particular spelling may participate in other driver choices.
1448 llvm::Triple::ArchType Arch =
1449 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1450 if (Arch == llvm::Triple::UnknownArch) {
1451 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1456 if (ArchNames.insert(A->getValue()).second)
1457 Archs.push_back(A->getValue());
1461 // When there is no explicit arch for this platform, make sure we still bind
1462 // the architecture (to the default) so that -Xarch_ is handled correctly.
1464 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1466 ActionList SingleActions;
1467 BuildActions(C, Args, BAInputs, SingleActions);
1469 // Add in arch bindings for every top level action, as well as lipo and
1470 // dsymutil steps if needed.
1471 for (Action* Act : SingleActions) {
1472 // Make sure we can lipo this kind of output. If not (and it is an actual
1473 // output) then we disallow, since we can't create an output file with the
1474 // right name without overwriting it. We could remove this oddity by just
1475 // changing the output names to include the arch, which would also fix
1476 // -save-temps. Compatibility wins for now.
1478 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1479 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1480 << types::getTypeName(Act->getType());
1483 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1484 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1486 // Lipo if necessary, we do it this way because we need to set the arch flag
1487 // so that -Xarch_ gets overwritten.
1488 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1489 Actions.append(Inputs.begin(), Inputs.end());
1491 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1493 // Handle debug info queries.
1494 Arg *A = Args.getLastArg(options::OPT_g_Group);
1495 if (A && !A->getOption().matches(options::OPT_g0) &&
1496 !A->getOption().matches(options::OPT_gstabs) &&
1497 ContainsCompileOrAssembleAction(Actions.back())) {
1499 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1500 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1501 // because the debug info will refer to a temporary object file which
1502 // will be removed at the end of the compilation process.
1503 if (Act->getType() == types::TY_Image) {
1505 Inputs.push_back(Actions.back());
1508 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1511 // Verify the debug info output.
1512 if (Args.hasArg(options::OPT_verify_debug_info)) {
1513 Action* LastAction = Actions.back();
1515 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1516 LastAction, types::TY_Nothing));
1522 /// \brief Check that the file referenced by Value exists. If it doesn't,
1523 /// issue a diagnostic and return false.
1524 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1525 StringRef Value, types::ID Ty) {
1526 if (!D.getCheckInputsExist())
1529 // stdin always exists.
1533 SmallString<64> Path(Value);
1534 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1535 if (!llvm::sys::path::is_absolute(Path)) {
1536 SmallString<64> Directory(WorkDir->getValue());
1537 llvm::sys::path::append(Directory, Value);
1538 Path.assign(Directory);
1542 if (llvm::sys::fs::exists(Twine(Path)))
1546 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1547 llvm::sys::Process::FindInEnvPath("LIB", Value))
1550 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1551 // Arguments to the /link flag might cause the linker to search for object
1552 // and library files in paths we don't know about. Don't error in such
1558 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1562 // Construct a the list of inputs and their types.
1563 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1564 InputList &Inputs) const {
1565 // Track the current user specified (-x) input. We also explicitly track the
1566 // argument used to set the type; we only want to claim the type when we
1567 // actually use it, so we warn about unused -x arguments.
1568 types::ID InputType = types::TY_Nothing;
1569 Arg *InputTypeArg = nullptr;
1571 // The last /TC or /TP option sets the input type to C or C++ globally.
1572 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1573 options::OPT__SLASH_TP)) {
1574 InputTypeArg = TCTP;
1575 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1579 Arg *Previous = nullptr;
1580 bool ShowNote = false;
1581 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1583 Diag(clang::diag::warn_drv_overriding_flag_option)
1584 << Previous->getSpelling() << A->getSpelling();
1590 Diag(clang::diag::note_drv_t_option_is_global);
1592 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1593 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1596 for (Arg *A : Args) {
1597 if (A->getOption().getKind() == Option::InputClass) {
1598 const char *Value = A->getValue();
1599 types::ID Ty = types::TY_INVALID;
1601 // Infer the input type if necessary.
1602 if (InputType == types::TY_Nothing) {
1603 // If there was an explicit arg for this, claim it.
1605 InputTypeArg->claim();
1607 // stdin must be handled specially.
1608 if (memcmp(Value, "-", 2) == 0) {
1609 // If running with -E, treat as a C input (this changes the builtin
1610 // macros, for example). This may be overridden by -ObjC below.
1612 // Otherwise emit an error but still use a valid type to avoid
1613 // spurious errors (e.g., no inputs).
1614 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1615 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1616 : clang::diag::err_drv_unknown_stdin_type);
1619 // Otherwise lookup by extension.
1620 // Fallback is C if invoked as C preprocessor or Object otherwise.
1621 // We use a host hook here because Darwin at least has its own
1622 // idea of what .s is.
1623 if (const char *Ext = strrchr(Value, '.'))
1624 Ty = TC.LookupTypeForExtension(Ext + 1);
1626 if (Ty == types::TY_INVALID) {
1630 Ty = types::TY_Object;
1633 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1634 // should autodetect some input files as C++ for g++ compatibility.
1636 types::ID OldTy = Ty;
1637 Ty = types::lookupCXXTypeForCType(Ty);
1640 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1641 << getTypeName(OldTy) << getTypeName(Ty);
1645 // -ObjC and -ObjC++ override the default language, but only for "source
1646 // files". We just treat everything that isn't a linker input as a
1649 // FIXME: Clean this up if we move the phase sequence into the type.
1650 if (Ty != types::TY_Object) {
1651 if (Args.hasArg(options::OPT_ObjC))
1652 Ty = types::TY_ObjC;
1653 else if (Args.hasArg(options::OPT_ObjCXX))
1654 Ty = types::TY_ObjCXX;
1657 assert(InputTypeArg && "InputType set w/o InputTypeArg");
1658 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1659 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1661 const char *Ext = strrchr(Value, '.');
1662 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1663 Ty = types::TY_Object;
1665 if (Ty == types::TY_INVALID) {
1667 InputTypeArg->claim();
1671 if (DiagnoseInputExistence(*this, Args, Value, Ty))
1672 Inputs.push_back(std::make_pair(Ty, A));
1674 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1675 StringRef Value = A->getValue();
1676 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1677 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1678 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1681 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1682 StringRef Value = A->getValue();
1683 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1684 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1685 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1688 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1689 // Just treat as object type, we could make a special type for this if
1691 Inputs.push_back(std::make_pair(types::TY_Object, A));
1693 } else if (A->getOption().matches(options::OPT_x)) {
1695 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1698 // Follow gcc behavior and treat as linker input for invalid -x
1699 // options. Its not clear why we shouldn't just revert to unknown; but
1700 // this isn't very important, we might as well be bug compatible.
1702 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1703 InputType = types::TY_Object;
1705 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1706 assert(A->getNumValues() == 1 && "The /U option has one value.");
1707 StringRef Val = A->getValue(0);
1708 if (Val.find_first_of("/\\") != StringRef::npos) {
1709 // Warn about e.g. "/Users/me/myfile.c".
1710 Diag(diag::warn_slash_u_filename) << Val;
1711 Diag(diag::note_use_dashdash);
1715 if (CCCIsCPP() && Inputs.empty()) {
1716 // If called as standalone preprocessor, stdin is processed
1717 // if no other input is present.
1718 Arg *A = MakeInputArg(Args, *Opts, "-");
1719 Inputs.push_back(std::make_pair(types::TY_C, A));
1724 /// Provides a convenient interface for different programming models to generate
1725 /// the required device actions.
1726 class OffloadingActionBuilder final {
1727 /// Flag used to trace errors in the builder.
1728 bool IsValid = false;
1730 /// The compilation that is using this builder.
1733 /// Map between an input argument and the offload kinds used to process it.
1734 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1736 /// Builder interface. It doesn't build anything or keep any state.
1737 class DeviceActionBuilder {
1739 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1741 enum ActionBuilderReturnCode {
1742 // The builder acted successfully on the current action.
1744 // The builder didn't have to act on the current action.
1746 // The builder was successful and requested the host action to not be
1752 /// Compilation associated with this builder.
1755 /// Tool chains associated with this builder. The same programming
1756 /// model may have associated one or more tool chains.
1757 SmallVector<const ToolChain *, 2> ToolChains;
1759 /// The derived arguments associated with this builder.
1760 DerivedArgList &Args;
1762 /// The inputs associated with this builder.
1763 const Driver::InputList &Inputs;
1765 /// The associated offload kind.
1766 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1769 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1770 const Driver::InputList &Inputs,
1771 Action::OffloadKind AssociatedOffloadKind)
1772 : C(C), Args(Args), Inputs(Inputs),
1773 AssociatedOffloadKind(AssociatedOffloadKind) {}
1774 virtual ~DeviceActionBuilder() {}
1776 /// Fill up the array \a DA with all the device dependences that should be
1777 /// added to the provided host action \a HostAction. By default it is
1779 virtual ActionBuilderReturnCode
1780 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1781 phases::ID CurPhase, phases::ID FinalPhase,
1783 return ABRT_Inactive;
1786 /// Update the state to include the provided host action \a HostAction as a
1787 /// dependency of the current device action. By default it is inactive.
1788 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1789 return ABRT_Inactive;
1792 /// Append top level actions generated by the builder. Return true if errors
1794 virtual void appendTopLevelActions(ActionList &AL) {}
1796 /// Append linker actions generated by the builder. Return true if errors
1798 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1800 /// Initialize the builder. Return true if any initialization errors are
1802 virtual bool initialize() { return false; }
1804 /// Return true if the builder can use bundling/unbundling.
1805 virtual bool canUseBundlerUnbundler() const { return false; }
1807 /// Return true if this builder is valid. We have a valid builder if we have
1808 /// associated device tool chains.
1809 bool isValid() { return !ToolChains.empty(); }
1811 /// Return the associated offload kind.
1812 Action::OffloadKind getAssociatedOffloadKind() {
1813 return AssociatedOffloadKind;
1817 /// \brief CUDA action builder. It injects device code in the host backend
1819 class CudaActionBuilder final : public DeviceActionBuilder {
1820 /// Flags to signal if the user requested host-only or device-only
1822 bool CompileHostOnly = false;
1823 bool CompileDeviceOnly = false;
1825 /// List of GPU architectures to use in this compilation.
1826 SmallVector<CudaArch, 4> GpuArchList;
1828 /// The CUDA actions for the current input.
1829 ActionList CudaDeviceActions;
1831 /// The CUDA fat binary if it was generated for the current input.
1832 Action *CudaFatBinary = nullptr;
1834 /// Flag that is set to true if this builder acted on the current input.
1835 bool IsActive = false;
1838 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1839 const Driver::InputList &Inputs)
1840 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1842 ActionBuilderReturnCode
1843 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1844 phases::ID CurPhase, phases::ID FinalPhase,
1845 PhasesTy &Phases) override {
1847 return ABRT_Inactive;
1849 // If we don't have more CUDA actions, we don't have any dependences to
1850 // create for the host.
1851 if (CudaDeviceActions.empty())
1852 return ABRT_Success;
1854 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1855 "Expecting one action per GPU architecture.");
1856 assert(!CompileHostOnly &&
1857 "Not expecting CUDA actions in host-only compilation.");
1859 // If we are generating code for the device or we are in a backend phase,
1860 // we attempt to generate the fat binary. We compile each arch to ptx and
1861 // assemble to cubin, then feed the cubin *and* the ptx into a device
1862 // "link" action, which uses fatbinary to combine these cubins into one
1863 // fatbin. The fatbin is then an input to the host action if not in
1864 // device-only mode.
1865 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1866 ActionList DeviceActions;
1867 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1868 // Produce the device action from the current phase up to the assemble
1870 for (auto Ph : Phases) {
1871 // Skip the phases that were already dealt with.
1874 // We have to be consistent with the host final phase.
1875 if (Ph > FinalPhase)
1878 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1879 C, Args, Ph, CudaDeviceActions[I]);
1881 if (Ph == phases::Assemble)
1885 // If we didn't reach the assemble phase, we can't generate the fat
1886 // binary. We don't need to generate the fat binary if we are not in
1887 // device-only mode.
1888 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1892 Action *AssembleAction = CudaDeviceActions[I];
1893 assert(AssembleAction->getType() == types::TY_Object);
1894 assert(AssembleAction->getInputs().size() == 1);
1896 Action *BackendAction = AssembleAction->getInputs()[0];
1897 assert(BackendAction->getType() == types::TY_PP_Asm);
1899 for (auto &A : {AssembleAction, BackendAction}) {
1900 OffloadAction::DeviceDependences DDep;
1901 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1903 DeviceActions.push_back(
1904 C.MakeAction<OffloadAction>(DDep, A->getType()));
1908 // We generate the fat binary if we have device input actions.
1909 if (!DeviceActions.empty()) {
1911 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1913 if (!CompileDeviceOnly) {
1914 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1916 // Clear the fat binary, it is already a dependence to an host
1918 CudaFatBinary = nullptr;
1921 // Remove the CUDA actions as they are already connected to an host
1922 // action or fat binary.
1923 CudaDeviceActions.clear();
1926 // We avoid creating host action in device-only mode.
1927 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
1928 } else if (CurPhase > phases::Backend) {
1929 // If we are past the backend phase and still have a device action, we
1930 // don't have to do anything as this action is already a device
1931 // top-level action.
1932 return ABRT_Success;
1935 assert(CurPhase < phases::Backend && "Generating single CUDA "
1936 "instructions should only occur "
1937 "before the backend phase!");
1939 // By default, we produce an action for each device arch.
1940 for (Action *&A : CudaDeviceActions)
1941 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1943 return ABRT_Success;
1946 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1947 // While generating code for CUDA, we only depend on the host input action
1948 // to trigger the creation of all the CUDA device actions.
1950 // If we are dealing with an input action, replicate it for each GPU
1951 // architecture. If we are in host-only mode we return 'success' so that
1952 // the host uses the CUDA offload kind.
1953 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1954 assert(!GpuArchList.empty() &&
1955 "We should have at least one GPU architecture.");
1957 // If the host input is not CUDA, we don't need to bother about this
1959 if (IA->getType() != types::TY_CUDA) {
1960 // The builder will ignore this input.
1962 return ABRT_Inactive;
1965 // Set the flag to true, so that the builder acts on the current input.
1968 if (CompileHostOnly)
1969 return ABRT_Success;
1971 // Replicate inputs for each GPU architecture.
1972 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1973 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1974 IA->getInputArg(), types::TY_CUDA_DEVICE));
1976 return ABRT_Success;
1979 return IsActive ? ABRT_Success : ABRT_Inactive;
1982 void appendTopLevelActions(ActionList &AL) override {
1983 // Utility to append actions to the top level list.
1984 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1985 OffloadAction::DeviceDependences Dep;
1986 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1988 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1991 // If we have a fat binary, add it to the list.
1992 if (CudaFatBinary) {
1993 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1994 CudaDeviceActions.clear();
1995 CudaFatBinary = nullptr;
1999 if (CudaDeviceActions.empty())
2002 // If we have CUDA actions at this point, that's because we have a have
2003 // partial compilation, so we should have an action for each GPU
2005 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2006 "Expecting one action per GPU architecture.");
2007 assert(ToolChains.size() == 1 &&
2008 "Expecting to have a sing CUDA toolchain.");
2009 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2010 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2012 CudaDeviceActions.clear();
2015 bool initialize() override {
2016 // We don't need to support CUDA.
2017 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
2020 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2021 assert(HostTC && "No toolchain for host compilation.");
2022 if (HostTC->getTriple().isNVPTX()) {
2023 // We do not support targeting NVPTX for host compilation. Throw
2024 // an error and abort pipeline construction early so we don't trip
2025 // asserts that assume device-side compilation.
2026 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
2030 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
2032 Arg *PartialCompilationArg = Args.getLastArg(
2033 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2034 options::OPT_cuda_compile_host_device);
2035 CompileHostOnly = PartialCompilationArg &&
2036 PartialCompilationArg->getOption().matches(
2037 options::OPT_cuda_host_only);
2038 CompileDeviceOnly = PartialCompilationArg &&
2039 PartialCompilationArg->getOption().matches(
2040 options::OPT_cuda_device_only);
2042 // Collect all cuda_gpu_arch parameters, removing duplicates.
2043 std::set<CudaArch> GpuArchs;
2045 for (Arg *A : Args) {
2046 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2047 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2051 const StringRef ArchStr = A->getValue();
2052 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2057 CudaArch Arch = StringToCudaArch(ArchStr);
2058 if (Arch == CudaArch::UNKNOWN) {
2059 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2061 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2062 GpuArchs.insert(Arch);
2063 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2064 GpuArchs.erase(Arch);
2066 llvm_unreachable("Unexpected option.");
2069 // Collect list of GPUs remaining in the set.
2070 for (CudaArch Arch : GpuArchs)
2071 GpuArchList.push_back(Arch);
2073 // Default to sm_20 which is the lowest common denominator for
2074 // supported GPUs. sm_20 code should work correctly, if
2075 // suboptimally, on all newer GPUs.
2076 if (GpuArchList.empty())
2077 GpuArchList.push_back(CudaArch::SM_20);
2083 /// OpenMP action builder. The host bitcode is passed to the device frontend
2084 /// and all the device linked images are passed to the host link phase.
2085 class OpenMPActionBuilder final : public DeviceActionBuilder {
2086 /// The OpenMP actions for the current input.
2087 ActionList OpenMPDeviceActions;
2089 /// The linker inputs obtained for each toolchain.
2090 SmallVector<ActionList, 8> DeviceLinkerInputs;
2093 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2094 const Driver::InputList &Inputs)
2095 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2097 ActionBuilderReturnCode
2098 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2099 phases::ID CurPhase, phases::ID FinalPhase,
2100 PhasesTy &Phases) override {
2102 // We should always have an action for each input.
2103 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2104 "Number of OpenMP actions and toolchains do not match.");
2106 // The host only depends on device action in the linking phase, when all
2107 // the device images have to be embedded in the host image.
2108 if (CurPhase == phases::Link) {
2109 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2110 "Toolchains and linker inputs sizes do not match.");
2111 auto LI = DeviceLinkerInputs.begin();
2112 for (auto *A : OpenMPDeviceActions) {
2117 // We passed the device action as a host dependence, so we don't need to
2118 // do anything else with them.
2119 OpenMPDeviceActions.clear();
2120 return ABRT_Success;
2123 // By default, we produce an action for each device arch.
2124 for (Action *&A : OpenMPDeviceActions)
2125 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2127 return ABRT_Success;
2130 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2132 // If this is an input action replicate it for each OpenMP toolchain.
2133 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2134 OpenMPDeviceActions.clear();
2135 for (unsigned I = 0; I < ToolChains.size(); ++I)
2136 OpenMPDeviceActions.push_back(
2137 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2138 return ABRT_Success;
2141 // If this is an unbundling action use it as is for each OpenMP toolchain.
2142 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2143 OpenMPDeviceActions.clear();
2144 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2145 OpenMPDeviceActions.push_back(UA);
2146 UA->registerDependentActionInfo(
2147 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2149 return ABRT_Success;
2152 // When generating code for OpenMP we use the host compile phase result as
2153 // a dependence to the device compile phase so that it can learn what
2154 // declarations should be emitted. However, this is not the only use for
2155 // the host action, so we prevent it from being collapsed.
2156 if (isa<CompileJobAction>(HostAction)) {
2157 HostAction->setCannotBeCollapsedWithNextDependentAction();
2158 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2159 "Toolchains and device action sizes do not match.");
2160 OffloadAction::HostDependence HDep(
2161 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2162 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2163 auto TC = ToolChains.begin();
2164 for (Action *&A : OpenMPDeviceActions) {
2165 assert(isa<CompileJobAction>(A));
2166 OffloadAction::DeviceDependences DDep;
2167 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2168 A = C.MakeAction<OffloadAction>(HDep, DDep);
2172 return ABRT_Success;
2175 void appendTopLevelActions(ActionList &AL) override {
2176 if (OpenMPDeviceActions.empty())
2179 // We should always have an action for each input.
2180 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2181 "Number of OpenMP actions and toolchains do not match.");
2183 // Append all device actions followed by the proper offload action.
2184 auto TI = ToolChains.begin();
2185 for (auto *A : OpenMPDeviceActions) {
2186 OffloadAction::DeviceDependences Dep;
2187 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2188 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2191 // We no longer need the action stored in this builder.
2192 OpenMPDeviceActions.clear();
2195 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2196 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2197 "Toolchains and linker inputs sizes do not match.");
2199 // Append a new link action for each device.
2200 auto TC = ToolChains.begin();
2201 for (auto &LI : DeviceLinkerInputs) {
2202 auto *DeviceLinkAction =
2203 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2204 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2205 Action::OFK_OpenMP);
2210 bool initialize() override {
2211 // Get the OpenMP toolchains. If we don't get any, the action builder will
2212 // know there is nothing to do related to OpenMP offloading.
2213 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2214 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2216 ToolChains.push_back(TI->second);
2218 DeviceLinkerInputs.resize(ToolChains.size());
2222 bool canUseBundlerUnbundler() const override {
2223 // OpenMP should use bundled files whenever possible.
2229 /// TODO: Add the implementation for other specialized builders here.
2232 /// Specialized builders being used by this offloading action builder.
2233 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2235 /// Flag set to true if all valid builders allow file bundling/unbundling.
2239 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2240 const Driver::InputList &Inputs)
2242 // Create a specialized builder for each device toolchain.
2246 // Create a specialized builder for CUDA.
2247 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2249 // Create a specialized builder for OpenMP.
2250 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2253 // TODO: Build other specialized builders here.
2256 // Initialize all the builders, keeping track of errors. If all valid
2257 // builders agree that we can use bundling, set the flag to true.
2258 unsigned ValidBuilders = 0u;
2259 unsigned ValidBuildersSupportingBundling = 0u;
2260 for (auto *SB : SpecializedBuilders) {
2261 IsValid = IsValid && !SB->initialize();
2263 // Update the counters if the builder is valid.
2264 if (SB->isValid()) {
2266 if (SB->canUseBundlerUnbundler())
2267 ++ValidBuildersSupportingBundling;
2271 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2274 ~OffloadingActionBuilder() {
2275 for (auto *SB : SpecializedBuilders)
2279 /// Generate an action that adds device dependences (if any) to a host action.
2280 /// If no device dependence actions exist, just return the host action \a
2281 /// HostAction. If an error is found or if no builder requires the host action
2282 /// to be generated, return nullptr.
2284 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2285 phases::ID CurPhase, phases::ID FinalPhase,
2286 DeviceActionBuilder::PhasesTy &Phases) {
2290 if (SpecializedBuilders.empty())
2293 assert(HostAction && "Invalid host action!");
2295 OffloadAction::DeviceDependences DDeps;
2296 // Check if all the programming models agree we should not emit the host
2297 // action. Also, keep track of the offloading kinds employed.
2298 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2299 unsigned InactiveBuilders = 0u;
2300 unsigned IgnoringBuilders = 0u;
2301 for (auto *SB : SpecializedBuilders) {
2302 if (!SB->isValid()) {
2308 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2310 // If the builder explicitly says the host action should be ignored,
2311 // we need to increment the variable that tracks the builders that request
2312 // the host object to be ignored.
2313 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2316 // Unless the builder was inactive for this action, we have to record the
2317 // offload kind because the host will have to use it.
2318 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2319 OffloadKind |= SB->getAssociatedOffloadKind();
2322 // If all builders agree that the host object should be ignored, just return
2324 if (IgnoringBuilders &&
2325 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2328 if (DDeps.getActions().empty())
2331 // We have dependences we need to bundle together. We use an offload action
2333 OffloadAction::HostDependence HDep(
2334 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2335 /*BoundArch=*/nullptr, DDeps);
2336 return C.MakeAction<OffloadAction>(HDep, DDeps);
2339 /// Generate an action that adds a host dependence to a device action. The
2340 /// results will be kept in this action builder. Return true if an error was
2342 bool addHostDependenceToDeviceActions(Action *&HostAction,
2343 const Arg *InputArg) {
2347 // If we are supporting bundling/unbundling and the current action is an
2348 // input action of non-source file, we replace the host action by the
2349 // unbundling action. The bundler tool has the logic to detect if an input
2350 // is a bundle or not and if the input is not a bundle it assumes it is a
2351 // host file. Therefore it is safe to create an unbundling action even if
2352 // the input is not a bundle.
2353 if (CanUseBundler && isa<InputAction>(HostAction) &&
2354 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2355 !types::isSrcFile(HostAction->getType())) {
2356 auto UnbundlingHostAction =
2357 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2358 UnbundlingHostAction->registerDependentActionInfo(
2359 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2360 /*BoundArch=*/StringRef(), Action::OFK_Host);
2361 HostAction = UnbundlingHostAction;
2364 assert(HostAction && "Invalid host action!");
2366 // Register the offload kinds that are used.
2367 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2368 for (auto *SB : SpecializedBuilders) {
2372 auto RetCode = SB->addDeviceDepences(HostAction);
2374 // Host dependences for device actions are not compatible with that same
2375 // action being ignored.
2376 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2377 "Host dependence not expected to be ignored.!");
2379 // Unless the builder was inactive for this action, we have to record the
2380 // offload kind because the host will have to use it.
2381 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2382 OffloadKind |= SB->getAssociatedOffloadKind();
2388 /// Add the offloading top level actions to the provided action list. This
2389 /// function can replace the host action by a bundling action if the
2390 /// programming models allow it.
2391 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2392 const Arg *InputArg) {
2393 // Get the device actions to be appended.
2394 ActionList OffloadAL;
2395 for (auto *SB : SpecializedBuilders) {
2398 SB->appendTopLevelActions(OffloadAL);
2401 // If we can use the bundler, replace the host action by the bundling one in
2402 // the resulting list. Otherwise, just append the device actions.
2403 if (CanUseBundler && !OffloadAL.empty()) {
2404 // Add the host action to the list in order to create the bundling action.
2405 OffloadAL.push_back(HostAction);
2407 // We expect that the host action was just appended to the action list
2408 // before this method was called.
2409 assert(HostAction == AL.back() && "Host action not in the list??");
2410 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2411 AL.back() = HostAction;
2413 AL.append(OffloadAL.begin(), OffloadAL.end());
2415 // Propagate to the current host action (if any) the offload information
2416 // associated with the current input.
2418 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2419 /*BoundArch=*/nullptr);
2423 /// Processes the host linker action. This currently consists of replacing it
2424 /// with an offload action if there are device link objects and propagate to
2425 /// the host action all the offload kinds used in the current compilation. The
2426 /// resulting action is returned.
2427 Action *processHostLinkAction(Action *HostAction) {
2428 // Add all the dependences from the device linking actions.
2429 OffloadAction::DeviceDependences DDeps;
2430 for (auto *SB : SpecializedBuilders) {
2434 SB->appendLinkDependences(DDeps);
2437 // Calculate all the offload kinds used in the current compilation.
2438 unsigned ActiveOffloadKinds = 0u;
2439 for (auto &I : InputArgToOffloadKindMap)
2440 ActiveOffloadKinds |= I.second;
2442 // If we don't have device dependencies, we don't have to create an offload
2444 if (DDeps.getActions().empty()) {
2445 // Propagate all the active kinds to host action. Given that it is a link
2446 // action it is assumed to depend on all actions generated so far.
2447 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2448 /*BoundArch=*/nullptr);
2452 // Create the offload action with all dependences. When an offload action
2453 // is created the kinds are propagated to the host action, so we don't have
2454 // to do that explicitly here.
2455 OffloadAction::HostDependence HDep(
2456 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2457 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2458 return C.MakeAction<OffloadAction>(HDep, DDeps);
2461 } // anonymous namespace.
2463 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2464 const InputList &Inputs, ActionList &Actions) const {
2465 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
2467 if (!SuppressMissingInputWarning && Inputs.empty()) {
2468 Diag(clang::diag::err_drv_no_input_files);
2473 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
2475 if (FinalPhase == phases::Link) {
2476 if (Args.hasArg(options::OPT_emit_llvm))
2477 Diag(clang::diag::err_drv_emit_llvm_link);
2478 if (IsCLMode() && LTOMode != LTOK_None &&
2479 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2480 Diag(clang::diag::err_drv_lto_without_lld);
2483 // Reject -Z* at the top level, these options should never have been exposed
2485 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
2486 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
2488 // Diagnose misuse of /Fo.
2489 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
2490 StringRef V = A->getValue();
2491 if (Inputs.size() > 1 && !V.empty() &&
2492 !llvm::sys::path::is_separator(V.back())) {
2493 // Check whether /Fo tries to name an output file for multiple inputs.
2494 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2495 << A->getSpelling() << V;
2496 Args.eraseArg(options::OPT__SLASH_Fo);
2500 // Diagnose misuse of /Fa.
2501 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2502 StringRef V = A->getValue();
2503 if (Inputs.size() > 1 && !V.empty() &&
2504 !llvm::sys::path::is_separator(V.back())) {
2505 // Check whether /Fa tries to name an asm file for multiple inputs.
2506 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2507 << A->getSpelling() << V;
2508 Args.eraseArg(options::OPT__SLASH_Fa);
2512 // Diagnose misuse of /o.
2513 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2514 if (A->getValue()[0] == '\0') {
2515 // It has to have a value.
2516 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2517 Args.eraseArg(options::OPT__SLASH_o);
2521 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2522 // * no filename after it
2523 // * both /Yc and /Yu passed but with different filenames
2524 // * corresponding file not also passed as /FI
2525 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2526 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2527 if (YcArg && YcArg->getValue()[0] == '\0') {
2528 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2529 Args.eraseArg(options::OPT__SLASH_Yc);
2532 if (YuArg && YuArg->getValue()[0] == '\0') {
2533 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2534 Args.eraseArg(options::OPT__SLASH_Yu);
2537 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2538 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2539 Args.eraseArg(options::OPT__SLASH_Yc);
2540 Args.eraseArg(options::OPT__SLASH_Yu);
2541 YcArg = YuArg = nullptr;
2543 if (YcArg || YuArg) {
2544 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2545 bool FoundMatchingInclude = false;
2546 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2547 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2548 if (Inc->getValue() == Val)
2549 FoundMatchingInclude = true;
2551 if (!FoundMatchingInclude) {
2552 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2553 << (YcArg ? YcArg : YuArg)->getSpelling();
2554 Args.eraseArg(options::OPT__SLASH_Yc);
2555 Args.eraseArg(options::OPT__SLASH_Yu);
2556 YcArg = YuArg = nullptr;
2559 if (YcArg && Inputs.size() > 1) {
2560 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2561 Args.eraseArg(options::OPT__SLASH_Yc);
2564 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2565 // /Y- disables all pch handling. Rather than check for it everywhere,
2566 // just remove clang-cl pch-related flags here.
2567 Args.eraseArg(options::OPT__SLASH_Fp);
2568 Args.eraseArg(options::OPT__SLASH_Yc);
2569 Args.eraseArg(options::OPT__SLASH_Yu);
2570 YcArg = YuArg = nullptr;
2573 // Builder to be used to build offloading actions.
2574 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
2576 // Construct the actions to perform.
2577 ActionList LinkerInputs;
2579 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
2580 for (auto &I : Inputs) {
2581 types::ID InputType = I.first;
2582 const Arg *InputArg = I.second;
2585 types::getCompilationPhases(InputType, PL);
2587 // If the first step comes after the final phase we are doing as part of
2588 // this compilation, warn the user about it.
2589 phases::ID InitialPhase = PL[0];
2590 if (InitialPhase > FinalPhase) {
2591 // Claim here to avoid the more general unused warning.
2594 // Suppress all unused style warnings with -Qunused-arguments
2595 if (Args.hasArg(options::OPT_Qunused_arguments))
2598 // Special case when final phase determined by binary name, rather than
2599 // by a command-line argument with a corresponding Arg.
2601 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
2602 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
2603 // Special case '-E' warning on a previously preprocessed file to make
2605 else if (InitialPhase == phases::Compile &&
2606 FinalPhase == phases::Preprocess &&
2607 getPreprocessedType(InputType) == types::TY_INVALID)
2608 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
2609 << InputArg->getAsString(Args) << !!FinalPhaseArg
2610 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2612 Diag(clang::diag::warn_drv_input_file_unused)
2613 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2615 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2620 // Add a separate precompile phase for the compile phase.
2621 if (FinalPhase >= phases::Compile) {
2622 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
2623 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
2624 types::getCompilationPhases(HeaderType, PCHPL);
2625 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
2627 // Build the pipeline for the pch file.
2628 Action *ClangClPch =
2629 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
2630 for (phases::ID Phase : PCHPL)
2631 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2633 Actions.push_back(ClangClPch);
2634 // The driver currently exits after the first failed command. This
2635 // relies on that behavior, to make sure if the pch generation fails,
2636 // the main compilation won't run.
2640 // Build the pipeline for this file.
2641 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
2643 // Use the current host action in any of the offloading actions, if
2645 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2648 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2650 phases::ID Phase = *i;
2652 // We are done if this step is past what the user requested.
2653 if (Phase > FinalPhase)
2656 // Add any offload action the host action depends on.
2657 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2658 Current, InputArg, Phase, FinalPhase, PL);
2662 // Queue linker inputs.
2663 if (Phase == phases::Link) {
2664 assert((i + 1) == e && "linking must be final compilation step.");
2665 LinkerInputs.push_back(Current);
2670 // Otherwise construct the appropriate action.
2671 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2673 // We didn't create a new action, so we will just move to the next phase.
2674 if (NewCurrent == Current)
2677 Current = NewCurrent;
2679 // Use the current host action in any of the offloading actions, if
2681 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2684 if (Current->getType() == types::TY_Nothing)
2688 // If we ended with something, add to the output list.
2690 Actions.push_back(Current);
2692 // Add any top level actions generated for offloading.
2693 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
2696 // Add a link action if necessary.
2697 if (!LinkerInputs.empty()) {
2698 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2699 LA = OffloadBuilder.processHostLinkAction(LA);
2700 Actions.push_back(LA);
2703 // If we are linking, claim any options which are obviously only used for
2705 if (FinalPhase == phases::Link && PL.size() == 1) {
2706 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
2707 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2710 // Claim ignored clang-cl options.
2711 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
2713 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2714 // to non-CUDA compilations and should not trigger warnings there.
2715 Args.ClaimAllArgs(options::OPT_cuda_host_only);
2716 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
2719 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2720 phases::ID Phase, Action *Input) const {
2721 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
2723 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2724 // encode this in the steps because the intermediate type depends on
2725 // arguments. Just special case here.
2726 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2729 // Build the appropriate action.
2732 llvm_unreachable("link action invalid here.");
2733 case phases::Preprocess: {
2735 // -{M, MM} alter the output type.
2736 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
2737 OutputTy = types::TY_Dependencies;
2739 OutputTy = Input->getType();
2740 if (!Args.hasFlag(options::OPT_frewrite_includes,
2741 options::OPT_fno_rewrite_includes, false) &&
2742 !Args.hasFlag(options::OPT_frewrite_imports,
2743 options::OPT_fno_rewrite_imports, false) &&
2745 OutputTy = types::getPreprocessedType(OutputTy);
2746 assert(OutputTy != types::TY_INVALID &&
2747 "Cannot preprocess this input type!");
2749 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
2751 case phases::Precompile: {
2752 types::ID OutputTy = getPrecompiledType(Input->getType());
2753 assert(OutputTy != types::TY_INVALID &&
2754 "Cannot precompile this input type!");
2755 if (Args.hasArg(options::OPT_fsyntax_only)) {
2756 // Syntax checks should not emit a PCH file
2757 OutputTy = types::TY_Nothing;
2759 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
2761 case phases::Compile: {
2762 if (Args.hasArg(options::OPT_fsyntax_only))
2763 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
2764 if (Args.hasArg(options::OPT_rewrite_objc))
2765 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
2766 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
2767 return C.MakeAction<CompileJobAction>(Input,
2768 types::TY_RewrittenLegacyObjC);
2769 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
2770 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
2771 if (Args.hasArg(options::OPT__migrate))
2772 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
2773 if (Args.hasArg(options::OPT_emit_ast))
2774 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
2775 if (Args.hasArg(options::OPT_module_file_info))
2776 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
2777 if (Args.hasArg(options::OPT_verify_pch))
2778 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2779 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
2781 case phases::Backend: {
2784 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
2785 return C.MakeAction<BackendJobAction>(Input, Output);
2787 if (Args.hasArg(options::OPT_emit_llvm)) {
2789 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
2790 return C.MakeAction<BackendJobAction>(Input, Output);
2792 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
2794 case phases::Assemble:
2795 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
2798 llvm_unreachable("invalid phase in ConstructPhaseAction");
2801 void Driver::BuildJobs(Compilation &C) const {
2802 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2804 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2806 // It is an error to provide a -o option if we are making multiple output
2809 unsigned NumOutputs = 0;
2810 for (const Action *A : C.getActions())
2811 if (A->getType() != types::TY_Nothing)
2814 if (NumOutputs > 1) {
2815 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
2816 FinalOutput = nullptr;
2820 // Collect the list of architectures.
2821 llvm::StringSet<> ArchNames;
2822 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2823 for (const Arg *A : C.getArgs())
2824 if (A->getOption().matches(options::OPT_arch))
2825 ArchNames.insert(A->getValue());
2827 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2828 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
2829 for (Action *A : C.getActions()) {
2830 // If we are linking an image for multiple archs then the linker wants
2831 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2832 // doesn't fit in cleanly because we have to pass this information down.
2834 // FIXME: This is a hack; find a cleaner way to integrate this into the
2836 const char *LinkingOutput = nullptr;
2837 if (isa<LipoJobAction>(A)) {
2839 LinkingOutput = FinalOutput->getValue();
2841 LinkingOutput = getDefaultImageName();
2844 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
2845 /*BoundArch*/ StringRef(),
2846 /*AtTopLevel*/ true,
2847 /*MultipleArchs*/ ArchNames.size() > 1,
2848 /*LinkingOutput*/ LinkingOutput, CachedResults,
2849 /*TargetDeviceOffloadKind*/ Action::OFK_None);
2852 // If the user passed -Qunused-arguments or there were errors, don't warn
2853 // about any unused arguments.
2854 if (Diags.hasErrorOccurred() ||
2855 C.getArgs().hasArg(options::OPT_Qunused_arguments))
2859 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
2861 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
2862 (void)C.getArgs().hasArg(options::OPT_driver_mode);
2863 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
2865 for (Arg *A : C.getArgs()) {
2866 // FIXME: It would be nice to be able to send the argument to the
2867 // DiagnosticsEngine, so that extra values, position, and so on could be
2869 if (!A->isClaimed()) {
2870 if (A->getOption().hasFlag(options::NoArgumentUnused))
2873 // Suppress the warning automatically if this is just a flag, and it is an
2874 // instance of an argument we already claimed.
2875 const Option &Opt = A->getOption();
2876 if (Opt.getKind() == Option::FlagClass) {
2877 bool DuplicateClaimed = false;
2879 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2880 if (AA->isClaimed()) {
2881 DuplicateClaimed = true;
2886 if (DuplicateClaimed)
2890 // In clang-cl, don't mention unknown arguments here since they have
2891 // already been warned about.
2892 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2893 Diag(clang::diag::warn_drv_unused_argument)
2894 << A->getAsString(C.getArgs());
2900 /// Utility class to control the collapse of dependent actions and select the
2901 /// tools accordingly.
2902 class ToolSelector final {
2903 /// The tool chain this selector refers to.
2904 const ToolChain &TC;
2906 /// The compilation this selector refers to.
2907 const Compilation &C;
2909 /// The base action this selector refers to.
2910 const JobAction *BaseAction;
2912 /// Set to true if the current toolchain refers to host actions.
2913 bool IsHostSelector;
2915 /// Set to true if save-temps and embed-bitcode functionalities are active.
2919 /// Get previous dependent action or null if that does not exist. If
2920 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2921 /// null will be returned.
2922 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2923 ActionList &SavedOffloadAction,
2924 bool CanBeCollapsed = true) {
2925 // An option can be collapsed only if it has a single input.
2926 if (Inputs.size() != 1)
2929 Action *CurAction = *Inputs.begin();
2930 if (CanBeCollapsed &&
2931 !CurAction->isCollapsingWithNextDependentActionLegal())
2934 // If the input action is an offload action. Look through it and save any
2935 // offload action that can be dropped in the event of a collapse.
2936 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2937 // If the dependent action is a device action, we will attempt to collapse
2938 // only with other device actions. Otherwise, we would do the same but
2939 // with host actions only.
2940 if (!IsHostSelector) {
2941 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2943 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2944 if (CanBeCollapsed &&
2945 !CurAction->isCollapsingWithNextDependentActionLegal())
2947 SavedOffloadAction.push_back(OA);
2948 return dyn_cast<JobAction>(CurAction);
2950 } else if (OA->hasHostDependence()) {
2951 CurAction = OA->getHostDependence();
2952 if (CanBeCollapsed &&
2953 !CurAction->isCollapsingWithNextDependentActionLegal())
2955 SavedOffloadAction.push_back(OA);
2956 return dyn_cast<JobAction>(CurAction);
2961 return dyn_cast<JobAction>(CurAction);
2964 /// Return true if an assemble action can be collapsed.
2965 bool canCollapseAssembleAction() const {
2966 return TC.useIntegratedAs() && !SaveTemps &&
2967 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2968 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2969 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2972 /// Return true if a preprocessor action can be collapsed.
2973 bool canCollapsePreprocessorAction() const {
2974 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2975 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2976 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2979 /// Struct that relates an action with the offload actions that would be
2980 /// collapsed with it.
2981 struct JobActionInfo final {
2982 /// The action this info refers to.
2983 const JobAction *JA = nullptr;
2984 /// The offload actions we need to take care off if this action is
2986 ActionList SavedOffloadAction;
2989 /// Append collapsed offload actions from the give nnumber of elements in the
2990 /// action info array.
2991 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2992 ArrayRef<JobActionInfo> &ActionInfo,
2993 unsigned ElementNum) {
2994 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2995 for (unsigned I = 0; I < ElementNum; ++I)
2996 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2997 ActionInfo[I].SavedOffloadAction.end());
3000 /// Functions that attempt to perform the combining. They detect if that is
3001 /// legal, and if so they update the inputs \a Inputs and the offload action
3002 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3003 /// the combined action is returned. If the combining is not legal or if the
3004 /// tool does not exist, null is returned.
3005 /// Currently three kinds of collapsing are supported:
3006 /// - Assemble + Backend + Compile;
3007 /// - Assemble + Backend ;
3008 /// - Backend + Compile.
3010 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3011 const ActionList *&Inputs,
3012 ActionList &CollapsedOffloadAction) {
3013 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3015 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3016 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3017 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3018 if (!AJ || !BJ || !CJ)
3021 // Get compiler tool.
3022 const Tool *T = TC.SelectTool(*CJ);
3026 // When using -fembed-bitcode, it is required to have the same tool (clang)
3027 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3029 const Tool *BT = TC.SelectTool(*BJ);
3034 if (!T->hasIntegratedAssembler())
3037 Inputs = &CJ->getInputs();
3038 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3042 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3043 const ActionList *&Inputs,
3044 ActionList &CollapsedOffloadAction) {
3045 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3047 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3048 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3052 // Retrieve the compile job, backend action must always be preceded by one.
3053 ActionList CompileJobOffloadActions;
3054 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3055 /*CanBeCollapsed=*/false);
3056 if (!AJ || !BJ || !CJ)
3059 assert(isa<CompileJobAction>(CJ) &&
3060 "Expecting compile job preceding backend job.");
3062 // Get compiler tool.
3063 const Tool *T = TC.SelectTool(*CJ);
3067 if (!T->hasIntegratedAssembler())
3070 Inputs = &BJ->getInputs();
3071 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3075 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3076 const ActionList *&Inputs,
3077 ActionList &CollapsedOffloadAction) {
3078 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3080 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3081 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3085 // Get compiler tool.
3086 const Tool *T = TC.SelectTool(*CJ);
3090 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3093 Inputs = &CJ->getInputs();
3094 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3099 /// Updates the inputs if the obtained tool supports combining with
3100 /// preprocessor action, and the current input is indeed a preprocessor
3101 /// action. If combining results in the collapse of offloading actions, those
3102 /// are appended to \a CollapsedOffloadAction.
3103 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3104 ActionList &CollapsedOffloadAction) {
3105 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3108 // Attempt to get a preprocessor action dependence.
3109 ActionList PreprocessJobOffloadActions;
3110 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3111 if (!PJ || !isa<PreprocessJobAction>(PJ))
3114 // This is legal to combine. Append any offload action we found and set the
3115 // current inputs to preprocessor inputs.
3116 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3117 PreprocessJobOffloadActions.end());
3118 Inputs = &PJ->getInputs();
3122 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3123 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3124 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3125 EmbedBitcode(EmbedBitcode) {
3126 assert(BaseAction && "Invalid base action.");
3127 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3130 /// Check if a chain of actions can be combined and return the tool that can
3131 /// handle the combination of actions. The pointer to the current inputs \a
3132 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3133 /// connected to collapsed actions are updated accordingly. The latter enables
3134 /// the caller of the selector to process them afterwards instead of just
3135 /// dropping them. If no suitable tool is found, null will be returned.
3136 const Tool *getTool(const ActionList *&Inputs,
3137 ActionList &CollapsedOffloadAction) {
3139 // Get the largest chain of actions that we could combine.
3142 SmallVector<JobActionInfo, 5> ActionChain(1);
3143 ActionChain.back().JA = BaseAction;
3144 while (ActionChain.back().JA) {
3145 const Action *CurAction = ActionChain.back().JA;
3147 // Grow the chain by one element.
3148 ActionChain.resize(ActionChain.size() + 1);
3149 JobActionInfo &AI = ActionChain.back();
3151 // Attempt to fill it with the
3153 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3156 // Pop the last action info as it could not be filled.
3157 ActionChain.pop_back();
3160 // Attempt to combine actions. If all combining attempts failed, just return
3161 // the tool of the provided action. At the end we attempt to combine the
3162 // action with any preprocessor action it may depend on.
3165 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3166 CollapsedOffloadAction);
3168 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3170 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3172 Inputs = &BaseAction->getInputs();
3173 T = TC.SelectTool(*BaseAction);
3176 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3182 /// Return a string that uniquely identifies the result of a job. The bound arch
3183 /// is not necessarily represented in the toolchain's triple -- for example,
3184 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
3185 /// Also, we need to add the offloading device kind, as the same tool chain can
3186 /// be used for host and device for some programming models, e.g. OpenMP.
3187 static std::string GetTriplePlusArchString(const ToolChain *TC,
3188 StringRef BoundArch,
3189 Action::OffloadKind OffloadKind) {
3190 std::string TriplePlusArch = TC->getTriple().normalize();
3191 if (!BoundArch.empty()) {
3192 TriplePlusArch += "-";
3193 TriplePlusArch += BoundArch;
3195 TriplePlusArch += "-";
3196 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3197 return TriplePlusArch;
3200 InputInfo Driver::BuildJobsForAction(
3201 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3202 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3203 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3204 Action::OffloadKind TargetDeviceOffloadKind) const {
3205 std::pair<const Action *, std::string> ActionTC = {
3206 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3207 auto CachedResult = CachedResults.find(ActionTC);
3208 if (CachedResult != CachedResults.end()) {
3209 return CachedResult->second;
3211 InputInfo Result = BuildJobsForActionNoCache(
3212 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3213 CachedResults, TargetDeviceOffloadKind);
3214 CachedResults[ActionTC] = Result;
3218 InputInfo Driver::BuildJobsForActionNoCache(
3219 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3220 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3221 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3222 Action::OffloadKind TargetDeviceOffloadKind) const {
3223 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3225 InputInfoList OffloadDependencesInputInfo;
3226 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3227 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3228 // The offload action is expected to be used in four different situations.
3230 // a) Set a toolchain/architecture/kind for a host action:
3231 // Host Action 1 -> OffloadAction -> Host Action 2
3233 // b) Set a toolchain/architecture/kind for a device action;
3234 // Device Action 1 -> OffloadAction -> Device Action 2
3236 // c) Specify a device dependence to a host action;
3237 // Device Action 1 _
3239 // Host Action 1 ---> OffloadAction -> Host Action 2
3241 // d) Specify a host dependence to a device action.
3244 // Device Action 1 ---> OffloadAction -> Device Action 2
3246 // For a) and b), we just return the job generated for the dependence. For
3247 // c) and d) we override the current action with the host/device dependence
3248 // if the current toolchain is host/device and set the offload dependences
3249 // info with the jobs obtained from the device/host dependence(s).
3251 // If there is a single device option, just generate the job for it.
3252 if (OA->hasSingleDeviceDependence()) {
3254 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3255 const char *DepBoundArch) {
3257 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3258 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3259 CachedResults, DepA->getOffloadingDeviceKind());
3264 // If 'Action 2' is host, we generate jobs for the device dependences and
3265 // override the current action with the host dependence. Otherwise, we
3266 // generate the host dependences and override the action with the device
3267 // dependence. The dependences can't therefore be a top-level action.
3268 OA->doOnEachDependence(
3269 /*IsHostDependence=*/BuildingForOffloadDevice,
3270 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3271 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3272 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3273 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3274 DepA->getOffloadingDeviceKind()));
3277 A = BuildingForOffloadDevice
3278 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3279 : OA->getHostDependence();
3282 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3283 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3284 // just using Args was better?
3285 const Arg &Input = IA->getInputArg();
3287 if (Input.getOption().matches(options::OPT_INPUT)) {
3288 const char *Name = Input.getValue();
3289 return InputInfo(A, Name, /* BaseInput = */ Name);
3291 return InputInfo(A, &Input, /* BaseInput = */ "");
3294 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
3295 const ToolChain *TC;
3296 StringRef ArchName = BAA->getArchName();
3298 if (!ArchName.empty())
3299 TC = &getToolChain(C.getArgs(),
3300 computeTargetTriple(*this, DefaultTargetTriple,
3301 C.getArgs(), ArchName));
3303 TC = &C.getDefaultToolChain();
3305 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
3306 MultipleArchs, LinkingOutput, CachedResults,
3307 TargetDeviceOffloadKind);
3311 const ActionList *Inputs = &A->getInputs();
3313 const JobAction *JA = cast<JobAction>(A);
3314 ActionList CollapsedOffloadActions;
3316 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3317 embedBitcodeInObject() && !isUsingLTO());
3318 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3323 // If we've collapsed action list that contained OffloadAction we
3324 // need to build jobs for host/device-side inputs it may have held.
3325 for (const auto *OA : CollapsedOffloadActions)
3326 cast<OffloadAction>(OA)->doOnEachDependence(
3327 /*IsHostDependence=*/BuildingForOffloadDevice,
3328 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3329 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3330 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
3331 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
3332 DepA->getOffloadingDeviceKind()));
3335 // Only use pipes when there is exactly one input.
3336 InputInfoList InputInfos;
3337 for (const Action *Input : *Inputs) {
3338 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3339 // shouldn't get temporary output names.
3340 // FIXME: Clean this up.
3341 bool SubJobAtTopLevel =
3342 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
3343 InputInfos.push_back(BuildJobsForAction(
3344 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
3345 CachedResults, A->getOffloadingDeviceKind()));
3348 // Always use the first input as the base input.
3349 const char *BaseInput = InputInfos[0].getBaseInput();
3351 // ... except dsymutil actions, which use their actual input as the base
3353 if (JA->getType() == types::TY_dSYM)
3354 BaseInput = InputInfos[0].getFilename();
3356 // Append outputs of offload device jobs to the input list
3357 if (!OffloadDependencesInputInfo.empty())
3358 InputInfos.append(OffloadDependencesInputInfo.begin(),
3359 OffloadDependencesInputInfo.end());
3361 // Set the effective triple of the toolchain for the duration of this job.
3362 llvm::Triple EffectiveTriple;
3363 const ToolChain &ToolTC = T->getToolChain();
3364 const ArgList &Args =
3365 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
3366 if (InputInfos.size() != 1) {
3367 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3369 // Pass along the input type if it can be unambiguously determined.
3370 EffectiveTriple = llvm::Triple(
3371 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3373 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3375 // Determine the place to write output to, if any.
3377 InputInfoList UnbundlingResults;
3378 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3379 // If we have an unbundling job, we need to create results for all the
3380 // outputs. We also update the results cache so that other actions using
3381 // this unbundling action can get the right results.
3382 for (auto &UI : UA->getDependentActionsInfo()) {
3383 assert(UI.DependentOffloadKind != Action::OFK_None &&
3384 "Unbundling with no offloading??");
3386 // Unbundling actions are never at the top level. When we generate the
3387 // offloading prefix, we also do that for the host file because the
3388 // unbundling action does not change the type of the output which can
3389 // cause a overwrite.
3390 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3391 UI.DependentOffloadKind,
3392 UI.DependentToolChain->getTriple().normalize(),
3393 /*CreatePrefixForHost=*/true);
3394 auto CurI = InputInfo(
3395 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3396 /*AtTopLevel=*/false, MultipleArchs,
3399 // Save the unbundling result.
3400 UnbundlingResults.push_back(CurI);
3402 // Get the unique string identifier for this dependence and cache the
3404 CachedResults[{A, GetTriplePlusArchString(
3405 UI.DependentToolChain, UI.DependentBoundArch,
3406 UI.DependentOffloadKind)}] = CurI;
3409 // Now that we have all the results generated, select the one that should be
3410 // returned for the current depending action.
3411 std::pair<const Action *, std::string> ActionTC = {
3412 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3413 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3414 "Result does not exist??");
3415 Result = CachedResults[ActionTC];
3416 } else if (JA->getType() == types::TY_Nothing)
3417 Result = InputInfo(A, BaseInput);
3419 // We only have to generate a prefix for the host if this is not a top-level
3421 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3422 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3423 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3425 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
3426 AtTopLevel, MultipleArchs,
3431 if (CCCPrintBindings && !CCGenDiagnostics) {
3432 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3433 << " - \"" << T->getName() << "\", inputs: [";
3434 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3435 llvm::errs() << InputInfos[i].getAsString();
3437 llvm::errs() << ", ";
3439 if (UnbundlingResults.empty())
3440 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3442 llvm::errs() << "], outputs: [";
3443 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3444 llvm::errs() << UnbundlingResults[i].getAsString();
3446 llvm::errs() << ", ";
3448 llvm::errs() << "] \n";
3451 if (UnbundlingResults.empty())
3453 C, *JA, Result, InputInfos,
3454 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3457 T->ConstructJobMultipleOutputs(
3458 C, *JA, UnbundlingResults, InputInfos,
3459 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3465 const char *Driver::getDefaultImageName() const {
3466 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3467 return Target.isOSWindows() ? "a.exe" : "a.out";
3470 /// \brief Create output filename based on ArgValue, which could either be a
3471 /// full filename, filename without extension, or a directory. If ArgValue
3472 /// does not provide a filename, then use BaseName, and use the extension
3473 /// suitable for FileType.
3474 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
3476 types::ID FileType) {
3477 SmallString<128> Filename = ArgValue;
3479 if (ArgValue.empty()) {
3480 // If the argument is empty, output to BaseName in the current dir.
3481 Filename = BaseName;
3482 } else if (llvm::sys::path::is_separator(Filename.back())) {
3483 // If the argument is a directory, output to BaseName in that dir.
3484 llvm::sys::path::append(Filename, BaseName);
3487 if (!llvm::sys::path::has_extension(ArgValue)) {
3488 // If the argument didn't provide an extension, then set it.
3489 const char *Extension = types::getTypeTempSuffix(FileType, true);
3491 if (FileType == types::TY_Image &&
3492 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3493 // The output file is a dll.
3497 llvm::sys::path::replace_extension(Filename, Extension);
3500 return Args.MakeArgString(Filename.c_str());
3503 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
3504 const char *BaseInput,
3505 StringRef BoundArch, bool AtTopLevel,
3507 StringRef OffloadingPrefix) const {
3508 llvm::PrettyStackTraceString CrashInfo("Computing output path");
3509 // Output to a user requested destination?
3510 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
3511 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
3512 return C.addResultFile(FinalOutput->getValue(), &JA);
3515 // For /P, preprocess to file named after BaseInput.
3516 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3517 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3518 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3520 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
3521 NameArg = A->getValue();
3522 return C.addResultFile(
3523 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3527 // Default to writing to stdout?
3528 if (AtTopLevel && !CCGenDiagnostics &&
3529 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
3532 // Is this the assembly listing for /FA?
3533 if (JA.getType() == types::TY_PP_Asm &&
3534 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3535 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3536 // Use /Fa and the input filename to determine the asm file name.
3537 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3538 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
3539 return C.addResultFile(
3540 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3544 // Output to a temporary file?
3545 if ((!AtTopLevel && !isSaveTempsEnabled() &&
3546 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
3548 StringRef Name = llvm::sys::path::filename(BaseInput);
3549 std::pair<StringRef, StringRef> Split = Name.split('.');
3550 std::string TmpName = GetTemporaryPath(
3551 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3552 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3555 SmallString<128> BasePath(BaseInput);
3558 // Dsymutil actions should use the full path.
3559 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
3560 BaseName = BasePath;
3562 BaseName = llvm::sys::path::filename(BasePath);
3564 // Determine what the derived output name should be.
3565 const char *NamedOutput;
3567 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
3568 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3569 // The /Fo or /o flag decides the object filename.
3572 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3575 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
3576 } else if (JA.getType() == types::TY_Image &&
3577 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3578 options::OPT__SLASH_o)) {
3579 // The /Fe or /o flag names the linked file.
3582 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3585 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
3586 } else if (JA.getType() == types::TY_Image) {
3588 // clang-cl uses BaseName for the executable name.
3590 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
3592 SmallString<128> Output(getDefaultImageName());
3593 Output += OffloadingPrefix;
3594 if (MultipleArchs && !BoundArch.empty()) {
3596 Output.append(BoundArch);
3598 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
3600 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
3601 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
3603 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
3604 assert(Suffix && "All types used for output should have a suffix.");
3606 std::string::size_type End = std::string::npos;
3607 if (!types::appendSuffixForType(JA.getType()))
3608 End = BaseName.rfind('.');
3609 SmallString<128> Suffixed(BaseName.substr(0, End));
3610 Suffixed += OffloadingPrefix;
3611 if (MultipleArchs && !BoundArch.empty()) {
3613 Suffixed.append(BoundArch);
3615 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3616 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3617 // optimized bitcode output.
3618 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3619 JA.getType() == types::TY_LLVM_BC)
3623 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3626 // Prepend object file path if -save-temps=obj
3627 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3628 JA.getType() != types::TY_PCH) {
3629 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3630 SmallString<128> TempPath(FinalOutput->getValue());
3631 llvm::sys::path::remove_filename(TempPath);
3632 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3633 llvm::sys::path::append(TempPath, OutputFileName);
3634 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3637 // If we're saving temps and the temp file conflicts with the input file,
3638 // then avoid overwriting input file.
3639 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
3640 bool SameFile = false;
3641 SmallString<256> Result;
3642 llvm::sys::fs::current_path(Result);
3643 llvm::sys::path::append(Result, BaseName);
3644 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3645 // Must share the same path to conflict.
3647 StringRef Name = llvm::sys::path::filename(BaseInput);
3648 std::pair<StringRef, StringRef> Split = Name.split('.');
3649 std::string TmpName = GetTemporaryPath(
3650 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3651 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3655 // As an annoying special case, PCH generation doesn't strip the pathname.
3656 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
3657 llvm::sys::path::remove_filename(BasePath);
3658 if (BasePath.empty())
3659 BasePath = NamedOutput;
3661 llvm::sys::path::append(BasePath, NamedOutput);
3662 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
3664 return C.addResultFile(NamedOutput, &JA);
3668 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
3669 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3670 // attempting to use this prefix when looking for file paths.
3671 for (const std::string &Dir : PrefixDirs) {
3674 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3675 llvm::sys::path::append(P, Name);
3676 if (llvm::sys::fs::exists(Twine(P)))
3680 SmallString<128> P(ResourceDir);
3681 llvm::sys::path::append(P, Name);
3682 if (llvm::sys::fs::exists(Twine(P)))
3685 for (const std::string &Dir : TC.getFilePaths()) {
3688 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3689 llvm::sys::path::append(P, Name);
3690 if (llvm::sys::fs::exists(Twine(P)))
3697 void Driver::generatePrefixedToolNames(
3698 StringRef Tool, const ToolChain &TC,
3699 SmallVectorImpl<std::string> &Names) const {
3700 // FIXME: Needs a better variable than DefaultTargetTriple
3701 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
3702 Names.emplace_back(Tool);
3704 // Allow the discovery of tools prefixed with LLVM's default target triple.
3705 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3706 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
3707 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
3710 static bool ScanDirForExecutable(SmallString<128> &Dir,
3711 ArrayRef<std::string> Names) {
3712 for (const auto &Name : Names) {
3713 llvm::sys::path::append(Dir, Name);
3714 if (llvm::sys::fs::can_execute(Twine(Dir)))
3716 llvm::sys::path::remove_filename(Dir);
3721 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
3722 SmallVector<std::string, 2> TargetSpecificExecutables;
3723 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3725 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3726 // attempting to use this prefix when looking for program paths.
3727 for (const auto &PrefixDir : PrefixDirs) {
3728 if (llvm::sys::fs::is_directory(PrefixDir)) {
3729 SmallString<128> P(PrefixDir);
3730 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3733 SmallString<128> P((PrefixDir + Name).str());
3734 if (llvm::sys::fs::can_execute(Twine(P)))
3739 const ToolChain::path_list &List = TC.getProgramPaths();
3740 for (const auto &Path : List) {
3741 SmallString<128> P(Path);
3742 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3746 // If all else failed, search the path.
3747 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3748 if (llvm::ErrorOr<std::string> P =
3749 llvm::sys::findProgramByName(TargetSpecificExecutable))
3755 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
3756 SmallString<128> Path;
3757 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
3759 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
3766 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3767 SmallString<128> Output;
3768 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3769 // FIXME: If anybody needs it, implement this obscure rule:
3770 // "If you specify a directory without a file name, the default file name
3771 // is VCx0.pch., where x is the major version of Visual C++ in use."
3772 Output = FpArg->getValue();
3774 // "If you do not specify an extension as part of the path name, an
3775 // extension of .pch is assumed. "
3776 if (!llvm::sys::path::has_extension(Output))
3780 llvm::sys::path::replace_extension(Output, ".pch");
3782 return Output.str();
3785 const ToolChain &Driver::getToolChain(const ArgList &Args,
3786 const llvm::Triple &Target) const {
3788 auto &TC = ToolChains[Target.str()];
3790 switch (Target.getOS()) {
3791 case llvm::Triple::Haiku:
3792 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
3794 case llvm::Triple::Ananas:
3795 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
3797 case llvm::Triple::CloudABI:
3798 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
3800 case llvm::Triple::Darwin:
3801 case llvm::Triple::MacOSX:
3802 case llvm::Triple::IOS:
3803 case llvm::Triple::TvOS:
3804 case llvm::Triple::WatchOS:
3805 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
3807 case llvm::Triple::DragonFly:
3808 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
3810 case llvm::Triple::OpenBSD:
3811 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
3813 case llvm::Triple::Bitrig:
3814 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
3816 case llvm::Triple::NetBSD:
3817 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
3819 case llvm::Triple::FreeBSD:
3820 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
3822 case llvm::Triple::Minix:
3823 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
3825 case llvm::Triple::Linux:
3826 case llvm::Triple::ELFIAMCU:
3827 if (Target.getArch() == llvm::Triple::hexagon)
3828 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3830 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3831 !Target.hasEnvironment())
3832 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3835 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
3837 case llvm::Triple::NaCl:
3838 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
3840 case llvm::Triple::Fuchsia:
3841 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
3843 case llvm::Triple::Solaris:
3844 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
3846 case llvm::Triple::AMDHSA:
3847 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
3849 case llvm::Triple::Win32:
3850 switch (Target.getEnvironment()) {
3852 if (Target.isOSBinFormatELF())
3853 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3854 else if (Target.isOSBinFormatMachO())
3855 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3857 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3859 case llvm::Triple::GNU:
3860 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
3862 case llvm::Triple::Itanium:
3863 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3866 case llvm::Triple::MSVC:
3867 case llvm::Triple::UnknownEnvironment:
3868 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
3872 case llvm::Triple::PS4:
3873 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
3875 case llvm::Triple::Contiki:
3876 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
3879 // Of these targets, Hexagon is the only one that might have
3880 // an OS of Linux, in which case it got handled above already.
3881 switch (Target.getArch()) {
3882 case llvm::Triple::tce:
3883 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
3885 case llvm::Triple::tcele:
3886 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
3888 case llvm::Triple::hexagon:
3889 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3892 case llvm::Triple::lanai:
3893 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
3895 case llvm::Triple::xcore:
3896 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
3898 case llvm::Triple::wasm32:
3899 case llvm::Triple::wasm64:
3900 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
3902 case llvm::Triple::avr:
3903 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
3906 if (Target.getVendor() == llvm::Triple::Myriad)
3907 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3909 else if (toolchains::BareMetal::handlesTarget(Target))
3910 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
3911 else if (Target.isOSBinFormatELF())
3912 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3913 else if (Target.isOSBinFormatMachO())
3914 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3916 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3921 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3922 // compiles always need two toolchains, the CUDA toolchain and the host
3923 // toolchain. So the only valid way to create a CUDA toolchain is via
3924 // CreateOffloadingDeviceToolChains.
3929 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
3930 // Say "no" if there is not exactly one input of a type clang understands.
3931 if (JA.size() != 1 ||
3932 !types::isAcceptedByClang((*JA.input_begin())->getType()))
3935 // And say "no" if this is not a kind of action clang understands.
3936 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
3937 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
3943 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3944 /// grouped values as integers. Numbers which are not provided are set to 0.
3946 /// \return True if the entire string was parsed (9.2), or all groups were
3947 /// parsed (10.3.5extrastuff).
3948 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3949 unsigned &Micro, bool &HadExtra) {
3952 Major = Minor = Micro = 0;
3956 if (Str.consumeInteger(10, Major))
3963 Str = Str.drop_front(1);
3965 if (Str.consumeInteger(10, Minor))
3971 Str = Str.drop_front(1);
3973 if (Str.consumeInteger(10, Micro))
3980 /// Parse digits from a string \p Str and fulfill \p Digits with
3981 /// the parsed numbers. This method assumes that the max number of
3982 /// digits to look for is equal to Digits.size().
3984 /// \return True if the entire string was parsed and there are
3985 /// no extra characters remaining at the end.
3986 bool Driver::GetReleaseVersion(StringRef Str,
3987 MutableArrayRef<unsigned> Digits) {
3991 unsigned CurDigit = 0;
3992 while (CurDigit < Digits.size()) {
3994 if (Str.consumeInteger(10, Digit))
3996 Digits[CurDigit] = Digit;
4001 Str = Str.drop_front(1);
4005 // More digits than requested, bail out...
4009 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4010 unsigned IncludedFlagsBitmask = 0;
4011 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
4013 if (Mode == CLMode) {
4014 // Include CL and Core options.
4015 IncludedFlagsBitmask |= options::CLOption;
4016 IncludedFlagsBitmask |= options::CoreOption;
4018 ExcludedFlagsBitmask |= options::CLOption;
4021 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4024 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
4025 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);