1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Driver/Driver.h"
11 #include "InputInfo.h"
12 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/Bitrig.h"
16 #include "ToolChains/Clang.h"
17 #include "ToolChains/CloudABI.h"
18 #include "ToolChains/Contiki.h"
19 #include "ToolChains/CrossWindows.h"
20 #include "ToolChains/Cuda.h"
21 #include "ToolChains/Darwin.h"
22 #include "ToolChains/DragonFly.h"
23 #include "ToolChains/FreeBSD.h"
24 #include "ToolChains/Fuchsia.h"
25 #include "ToolChains/Gnu.h"
26 #include "ToolChains/BareMetal.h"
27 #include "ToolChains/Haiku.h"
28 #include "ToolChains/Hexagon.h"
29 #include "ToolChains/Lanai.h"
30 #include "ToolChains/Linux.h"
31 #include "ToolChains/MinGW.h"
32 #include "ToolChains/Minix.h"
33 #include "ToolChains/MipsLinux.h"
34 #include "ToolChains/MSVC.h"
35 #include "ToolChains/Myriad.h"
36 #include "ToolChains/NaCl.h"
37 #include "ToolChains/NetBSD.h"
38 #include "ToolChains/OpenBSD.h"
39 #include "ToolChains/PS4CPU.h"
40 #include "ToolChains/Solaris.h"
41 #include "ToolChains/TCE.h"
42 #include "ToolChains/WebAssembly.h"
43 #include "ToolChains/XCore.h"
44 #include "clang/Basic/Version.h"
45 #include "clang/Basic/VirtualFileSystem.h"
46 #include "clang/Config/config.h"
47 #include "clang/Driver/Action.h"
48 #include "clang/Driver/Compilation.h"
49 #include "clang/Driver/DriverDiagnostic.h"
50 #include "clang/Driver/Job.h"
51 #include "clang/Driver/Options.h"
52 #include "clang/Driver/SanitizerArgs.h"
53 #include "clang/Driver/Tool.h"
54 #include "clang/Driver/ToolChain.h"
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallSet.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/ADT/StringSet.h"
60 #include "llvm/ADT/StringSwitch.h"
61 #include "llvm/Option/Arg.h"
62 #include "llvm/Option/ArgList.h"
63 #include "llvm/Option/OptSpecifier.h"
64 #include "llvm/Option/OptTable.h"
65 #include "llvm/Option/Option.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/FileSystem.h"
68 #include "llvm/Support/Path.h"
69 #include "llvm/Support/PrettyStackTrace.h"
70 #include "llvm/Support/Process.h"
71 #include "llvm/Support/Program.h"
72 #include "llvm/Support/TargetRegistry.h"
73 #include "llvm/Support/raw_ostream.h"
78 #include <unistd.h> // getpid
81 using namespace clang::driver;
82 using namespace clang;
83 using namespace llvm::opt;
85 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
86 DiagnosticsEngine &Diags,
87 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
88 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
89 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
90 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
91 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
92 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
93 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
94 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
95 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
96 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
97 GenReproducer(false), SuppressMissingInputWarning(false) {
99 // Provide a sane fallback if no VFS is specified.
101 this->VFS = vfs::getRealFileSystem();
103 Name = llvm::sys::path::filename(ClangExecutable);
104 Dir = llvm::sys::path::parent_path(ClangExecutable);
105 InstalledDir = Dir; // Provide a sensible default installed dir.
107 // Compute the path to the resource directory.
108 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
109 SmallString<128> P(Dir);
110 if (ClangResourceDir != "") {
111 llvm::sys::path::append(P, ClangResourceDir);
113 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
114 P = llvm::sys::path::parent_path(Dir);
115 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
116 CLANG_VERSION_STRING);
118 ResourceDir = P.str();
121 void Driver::ParseDriverMode(StringRef ProgramName,
122 ArrayRef<const char *> Args) {
123 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
124 StringRef DefaultMode(Default.second);
125 setDriverModeFromOption(DefaultMode);
127 for (const char *ArgPtr : Args) {
128 // Ingore nullptrs, they are response file's EOL markers
129 if (ArgPtr == nullptr)
131 const StringRef Arg = ArgPtr;
132 setDriverModeFromOption(Arg);
136 void Driver::setDriverModeFromOption(StringRef Opt) {
137 const std::string OptName =
138 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
139 if (!Opt.startswith(OptName))
141 StringRef Value = Opt.drop_front(OptName.size());
143 const unsigned M = llvm::StringSwitch<unsigned>(Value)
144 .Case("gcc", GCCMode)
145 .Case("g++", GXXMode)
146 .Case("cpp", CPPMode)
151 Mode = static_cast<DriverMode>(M);
153 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
156 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
157 bool &ContainsError) {
158 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
159 ContainsError = false;
161 unsigned IncludedFlagsBitmask;
162 unsigned ExcludedFlagsBitmask;
163 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
164 getIncludeExcludeOptionFlagMasks();
166 unsigned MissingArgIndex, MissingArgCount;
168 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
169 IncludedFlagsBitmask, ExcludedFlagsBitmask);
171 // Check for missing argument error.
172 if (MissingArgCount) {
173 Diag(diag::err_drv_missing_argument)
174 << Args.getArgString(MissingArgIndex) << MissingArgCount;
176 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
177 SourceLocation()) > DiagnosticsEngine::Warning;
180 // Check for unsupported options.
181 for (const Arg *A : Args) {
182 if (A->getOption().hasFlag(options::Unsupported)) {
183 Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
184 ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt,
186 DiagnosticsEngine::Warning;
190 // Warn about -mcpu= without an argument.
191 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
192 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
193 ContainsError |= Diags.getDiagnosticLevel(
194 diag::warn_drv_empty_joined_argument,
195 SourceLocation()) > DiagnosticsEngine::Warning;
199 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
200 auto ID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
201 : diag::err_drv_unknown_argument;
203 Diags.Report(ID) << A->getAsString(Args);
204 ContainsError |= Diags.getDiagnosticLevel(ID, SourceLocation()) >
205 DiagnosticsEngine::Warning;
211 // Determine which compilation mode we are in. We look for options which
212 // affect the phase, starting with the earliest phases, and record which
213 // option we used to determine the final phase.
214 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
215 Arg **FinalPhaseArg) const {
216 Arg *PhaseArg = nullptr;
217 phases::ID FinalPhase;
219 // -{E,EP,P,M,MM} only run the preprocessor.
220 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
221 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
222 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
223 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
224 FinalPhase = phases::Preprocess;
226 // --precompile only runs up to precompilation.
227 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
228 FinalPhase = phases::Precompile;
230 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
231 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
232 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
233 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
234 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
235 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
236 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
237 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
238 options::OPT__analyze_auto)) ||
239 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
240 FinalPhase = phases::Compile;
242 // -S only runs up to the backend.
243 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
244 FinalPhase = phases::Backend;
246 // -c compilation only runs up to the assembler.
247 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
248 FinalPhase = phases::Assemble;
250 // Otherwise do everything.
252 FinalPhase = phases::Link;
255 *FinalPhaseArg = PhaseArg;
260 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
262 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
263 Args.getBaseArgs().MakeIndex(Value), Value.data());
264 Args.AddSynthesizedArg(A);
269 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
270 DerivedArgList *DAL = new DerivedArgList(Args);
272 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
273 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
274 for (Arg *A : Args) {
275 // Unfortunately, we have to parse some forwarding options (-Xassembler,
276 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
277 // (assembler and preprocessor), or bypass a previous driver ('collect2').
279 // Rewrite linker options, to replace --no-demangle with a custom internal
281 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
282 A->getOption().matches(options::OPT_Xlinker)) &&
283 A->containsValue("--no-demangle")) {
284 // Add the rewritten no-demangle argument.
285 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
287 // Add the remaining values as Xlinker arguments.
288 for (StringRef Val : A->getValues())
289 if (Val != "--no-demangle")
290 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
295 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
296 // some build systems. We don't try to be complete here because we don't
297 // care to encourage this usage model.
298 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
299 (A->getValue(0) == StringRef("-MD") ||
300 A->getValue(0) == StringRef("-MMD"))) {
301 // Rewrite to -MD/-MMD along with -MF.
302 if (A->getValue(0) == StringRef("-MD"))
303 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
305 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
306 if (A->getNumValues() == 2)
307 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
312 // Rewrite reserved library names.
313 if (A->getOption().matches(options::OPT_l)) {
314 StringRef Value = A->getValue();
316 // Rewrite unless -nostdlib is present.
317 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
318 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
322 // Rewrite unconditionally.
323 if (Value == "cc_kext") {
324 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
329 // Pick up inputs via the -- option.
330 if (A->getOption().matches(options::OPT__DASH_DASH)) {
332 for (StringRef Val : A->getValues())
333 DAL->append(MakeInputArg(*DAL, *Opts, Val));
340 // Enforce -static if -miamcu is present.
341 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
342 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
344 // Add a default value of -mlinker-version=, if one was given and the user
345 // didn't specify one.
346 #if defined(HOST_LINK_VERSION)
347 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
348 strlen(HOST_LINK_VERSION) > 0) {
349 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
351 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
358 /// \brief Compute target triple from args.
360 /// This routine provides the logic to compute a target triple from various
361 /// args passed to the driver and the default triple string.
362 static llvm::Triple computeTargetTriple(const Driver &D,
363 StringRef DefaultTargetTriple,
365 StringRef DarwinArchName = "") {
366 // FIXME: Already done in Compilation *Driver::BuildCompilation
367 if (const Arg *A = Args.getLastArg(options::OPT_target))
368 DefaultTargetTriple = A->getValue();
370 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
372 // Handle Apple-specific options available here.
373 if (Target.isOSBinFormatMachO()) {
374 // If an explict Darwin arch name is given, that trumps all.
375 if (!DarwinArchName.empty()) {
376 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
380 // Handle the Darwin '-arch' flag.
381 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
382 StringRef ArchName = A->getValue();
383 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
387 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
388 // '-mbig-endian'/'-EB'.
389 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
390 options::OPT_mbig_endian)) {
391 if (A->getOption().matches(options::OPT_mlittle_endian)) {
392 llvm::Triple LE = Target.getLittleEndianArchVariant();
393 if (LE.getArch() != llvm::Triple::UnknownArch)
394 Target = std::move(LE);
396 llvm::Triple BE = Target.getBigEndianArchVariant();
397 if (BE.getArch() != llvm::Triple::UnknownArch)
398 Target = std::move(BE);
402 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
403 if (Target.getArch() == llvm::Triple::tce ||
404 Target.getOS() == llvm::Triple::Minix)
407 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
408 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
409 options::OPT_m32, options::OPT_m16);
411 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
413 if (A->getOption().matches(options::OPT_m64)) {
414 AT = Target.get64BitArchVariant().getArch();
415 if (Target.getEnvironment() == llvm::Triple::GNUX32)
416 Target.setEnvironment(llvm::Triple::GNU);
417 } else if (A->getOption().matches(options::OPT_mx32) &&
418 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
419 AT = llvm::Triple::x86_64;
420 Target.setEnvironment(llvm::Triple::GNUX32);
421 } else if (A->getOption().matches(options::OPT_m32)) {
422 AT = Target.get32BitArchVariant().getArch();
423 if (Target.getEnvironment() == llvm::Triple::GNUX32)
424 Target.setEnvironment(llvm::Triple::GNU);
425 } else if (A->getOption().matches(options::OPT_m16) &&
426 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
427 AT = llvm::Triple::x86;
428 Target.setEnvironment(llvm::Triple::CODE16);
431 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
435 // Handle -miamcu flag.
436 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
437 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
438 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
441 if (A && !A->getOption().matches(options::OPT_m32))
442 D.Diag(diag::err_drv_argument_not_allowed_with)
443 << "-miamcu" << A->getBaseArg().getAsString(Args);
445 Target.setArch(llvm::Triple::x86);
446 Target.setArchName("i586");
447 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
448 Target.setEnvironmentName("");
449 Target.setOS(llvm::Triple::ELFIAMCU);
450 Target.setVendor(llvm::Triple::UnknownVendor);
451 Target.setVendorName("intel");
457 // \brief Parse the LTO options and record the type of LTO compilation
458 // based on which -f(no-)?lto(=.*)? option occurs last.
459 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
461 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
462 options::OPT_fno_lto, false))
465 StringRef LTOName("full");
467 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
469 LTOName = A->getValue();
471 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
472 .Case("full", LTOK_Full)
473 .Case("thin", LTOK_Thin)
474 .Default(LTOK_Unknown);
476 if (LTOMode == LTOK_Unknown) {
478 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
483 /// Compute the desired OpenMP runtime from the flags provided.
484 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
485 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
487 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
489 RuntimeName = A->getValue();
491 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
492 .Case("libomp", OMPRT_OMP)
493 .Case("libgomp", OMPRT_GOMP)
494 .Case("libiomp5", OMPRT_IOMP5)
495 .Default(OMPRT_Unknown);
497 if (RT == OMPRT_Unknown) {
499 Diag(diag::err_drv_unsupported_option_argument)
500 << A->getOption().getName() << A->getValue();
502 // FIXME: We could use a nicer diagnostic here.
503 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
509 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
515 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
516 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
517 return types::isCuda(I.first);
519 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
520 const llvm::Triple &HostTriple = HostTC->getTriple();
521 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
522 : "nvptx-nvidia-cuda");
523 // Use the CUDA and host triples as the key into the ToolChains map, because
524 // the device toolchain we create depends on both.
525 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
527 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
528 *this, CudaTriple, *HostTC, C.getInputArgs());
530 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
536 // We need to generate an OpenMP toolchain if the user specified targets with
537 // the -fopenmp-targets option.
538 if (Arg *OpenMPTargets =
539 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
540 if (OpenMPTargets->getNumValues()) {
541 // We expect that -fopenmp-targets is always used in conjunction with the
542 // option -fopenmp specifying a valid runtime with offloading support,
543 // i.e. libomp or libiomp.
544 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
545 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
546 options::OPT_fno_openmp, false);
547 if (HasValidOpenMPRuntime) {
548 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
549 HasValidOpenMPRuntime =
550 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
553 if (HasValidOpenMPRuntime) {
554 llvm::StringMap<const char *> FoundNormalizedTriples;
555 for (const char *Val : OpenMPTargets->getValues()) {
556 llvm::Triple TT(Val);
557 std::string NormalizedName = TT.normalize();
559 // Make sure we don't have a duplicate triple.
560 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
561 if (Duplicate != FoundNormalizedTriples.end()) {
562 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
563 << Val << Duplicate->second;
567 // Store the current triple so that we can check for duplicates in the
568 // following iterations.
569 FoundNormalizedTriples[NormalizedName] = Val;
571 // If the specified target is invalid, emit a diagnostic.
572 if (TT.getArch() == llvm::Triple::UnknownArch)
573 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
576 // CUDA toolchains have to be selected differently. They pair host
577 // and device in their implementation.
579 const ToolChain *HostTC =
580 C.getSingleOffloadToolChain<Action::OFK_Host>();
581 assert(HostTC && "Host toolchain should be always defined.");
583 ToolChains[TT.str() + "/" + HostTC->getTriple().str()];
585 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
586 *this, TT, *HostTC, C.getInputArgs());
589 TC = &getToolChain(C.getInputArgs(), TT);
590 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
594 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
596 Diag(clang::diag::warn_drv_empty_joined_argument)
597 << OpenMPTargets->getAsString(C.getInputArgs());
601 // TODO: Add support for other offloading programming models here.
607 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
608 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
610 // FIXME: Handle environment options which affect driver behavior, somewhere
611 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
613 if (Optional<std::string> CompilerPathValue =
614 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
615 StringRef CompilerPath = *CompilerPathValue;
616 while (!CompilerPath.empty()) {
617 std::pair<StringRef, StringRef> Split =
618 CompilerPath.split(llvm::sys::EnvPathSeparator);
619 PrefixDirs.push_back(Split.first);
620 CompilerPath = Split.second;
624 // We look for the driver mode option early, because the mode can affect
625 // how other options are parsed.
626 ParseDriverMode(ClangExecutable, ArgList.slice(1));
628 // FIXME: What are we going to do with -V and -b?
630 // FIXME: This stuff needs to go into the Compilation, not the driver.
634 InputArgList Args = ParseArgStrings(ArgList.slice(1), ContainsError);
636 // Silence driver warnings if requested
637 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
639 // -no-canonical-prefixes is used very early in main.
640 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
643 Args.ClaimAllArgs(options::OPT_pipe);
645 // Extract -ccc args.
647 // FIXME: We need to figure out where this behavior should live. Most of it
648 // should be outside in the client; the parts that aren't should have proper
649 // options, either by introducing new ones or by overloading gcc ones like -V
651 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
652 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
653 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
654 CCCGenericGCCName = A->getValue();
656 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
657 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
658 options::OPT_fno_crash_diagnostics,
659 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
660 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
661 // and getToolChain is const.
663 // clang-cl targets MSVC-style Win32.
664 llvm::Triple T(DefaultTargetTriple);
665 T.setOS(llvm::Triple::Win32);
666 T.setVendor(llvm::Triple::PC);
667 T.setEnvironment(llvm::Triple::MSVC);
668 DefaultTargetTriple = T.str();
670 if (const Arg *A = Args.getLastArg(options::OPT_target))
671 DefaultTargetTriple = A->getValue();
672 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
673 Dir = InstalledDir = A->getValue();
674 for (const Arg *A : Args.filtered(options::OPT_B)) {
676 PrefixDirs.push_back(A->getValue(0));
678 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
679 SysRoot = A->getValue();
680 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
681 DyldPrefix = A->getValue();
682 if (Args.hasArg(options::OPT_nostdlib))
685 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
686 ResourceDir = A->getValue();
688 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
689 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
690 .Case("cwd", SaveTempsCwd)
691 .Case("obj", SaveTempsObj)
692 .Default(SaveTempsCwd);
697 // Process -fembed-bitcode= flags.
698 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
699 StringRef Name = A->getValue();
700 unsigned Model = llvm::StringSwitch<unsigned>(Name)
701 .Case("off", EmbedNone)
702 .Case("all", EmbedBitcode)
703 .Case("bitcode", EmbedBitcode)
704 .Case("marker", EmbedMarker)
707 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
710 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
713 std::unique_ptr<llvm::opt::InputArgList> UArgs =
714 llvm::make_unique<InputArgList>(std::move(Args));
716 // Perform the default argument translations.
717 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
719 // Owned by the host.
720 const ToolChain &TC = getToolChain(
721 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
723 // The compilation takes ownership of Args.
724 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
727 if (!HandleImmediateArgs(*C))
730 // Construct the list of inputs.
732 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
734 // Populate the tool chains for the offloading devices, if any.
735 CreateOffloadingDeviceToolChains(*C, Inputs);
737 // Construct the list of abstract actions to perform for this compilation. On
738 // MachO targets this uses the driver-driver and universal actions.
739 if (TC.getTriple().isOSBinFormatMachO())
740 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
742 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
744 if (CCCPrintPhases) {
754 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
755 llvm::opt::ArgStringList ASL;
756 for (const auto *A : Args)
757 A->render(Args, ASL);
759 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
760 if (I != ASL.begin())
762 Command::printArg(OS, *I, true);
767 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
768 SmallString<128> &CrashDiagDir) {
769 using namespace llvm::sys;
770 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
771 "Only knows about .crash files on Darwin");
773 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
774 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
775 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
776 path::home_directory(CrashDiagDir);
777 if (CrashDiagDir.startswith("/var/root"))
779 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
787 fs::file_status FileStatus;
788 TimePoint<> LastAccessTime;
789 SmallString<128> CrashFilePath;
790 // Lookup the .crash files and get the one generated by a subprocess spawned
791 // by this driver invocation.
792 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
793 File != FileEnd && !EC; File.increment(EC)) {
794 StringRef FileName = path::filename(File->path());
795 if (!FileName.startswith(Name))
797 if (fs::status(File->path(), FileStatus))
799 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
800 llvm::MemoryBuffer::getFile(File->path());
803 // The first line should start with "Process:", otherwise this isn't a real
805 StringRef Data = CrashFile.get()->getBuffer();
806 if (!Data.startswith("Process:"))
808 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
809 size_t ParentProcPos = Data.find("Parent Process:");
810 if (ParentProcPos == StringRef::npos)
812 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
813 if (LineEnd == StringRef::npos)
815 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
816 int OpenBracket = -1, CloseBracket = -1;
817 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
818 if (ParentProcess[i] == '[')
820 if (ParentProcess[i] == ']')
823 // Extract the parent process PID from the .crash file and check whether
824 // it matches this driver invocation pid.
826 if (OpenBracket < 0 || CloseBracket < 0 ||
827 ParentProcess.slice(OpenBracket + 1, CloseBracket)
828 .getAsInteger(10, CrashPID) || CrashPID != PID) {
832 // Found a .crash file matching the driver pid. To avoid getting an older
833 // and misleading crash file, continue looking for the most recent.
834 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
835 // multiple crashes poiting to the same parent process. Since the driver
836 // does not collect pid information for the dispatched invocation there's
837 // currently no way to distinguish among them.
838 const auto FileAccessTime = FileStatus.getLastModificationTime();
839 if (FileAccessTime > LastAccessTime) {
840 CrashFilePath.assign(File->path());
841 LastAccessTime = FileAccessTime;
845 // If found, copy it over to the location of other reproducer files.
846 if (!CrashFilePath.empty()) {
847 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
856 // When clang crashes, produce diagnostic information including the fully
857 // preprocessed source file(s). Request that the developer attach the
858 // diagnostic information to a bug report.
859 void Driver::generateCompilationDiagnostics(Compilation &C,
860 const Command &FailingCommand) {
861 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
864 // Don't try to generate diagnostics for link or dsymutil jobs.
865 if (FailingCommand.getCreator().isLinkJob() ||
866 FailingCommand.getCreator().isDsymutilJob())
869 // Print the version of the compiler.
870 PrintVersion(C, llvm::errs());
872 Diag(clang::diag::note_drv_command_failed_diag_msg)
873 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
874 "crash backtrace, preprocessed source, and associated run script.";
876 // Suppress driver output and emit preprocessor output to temp file.
878 CCGenDiagnostics = true;
880 // Save the original job command(s).
881 Command Cmd = FailingCommand;
883 // Keep track of whether we produce any errors while trying to produce
884 // preprocessed sources.
885 DiagnosticErrorTrap Trap(Diags);
887 // Suppress tool output.
888 C.initCompilationForDiagnostics();
890 // Construct the list of inputs.
892 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
894 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
895 bool IgnoreInput = false;
897 // Ignore input from stdin or any inputs that cannot be preprocessed.
898 // Check type first as not all linker inputs have a value.
899 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
901 } else if (!strcmp(it->second->getValue(), "-")) {
902 Diag(clang::diag::note_drv_command_failed_diag_msg)
903 << "Error generating preprocessed source(s) - "
904 "ignoring input from stdin.";
909 it = Inputs.erase(it);
916 if (Inputs.empty()) {
917 Diag(clang::diag::note_drv_command_failed_diag_msg)
918 << "Error generating preprocessed source(s) - "
919 "no preprocessable inputs.";
923 // Don't attempt to generate preprocessed files if multiple -arch options are
924 // used, unless they're all duplicates.
925 llvm::StringSet<> ArchNames;
926 for (const Arg *A : C.getArgs()) {
927 if (A->getOption().matches(options::OPT_arch)) {
928 StringRef ArchName = A->getValue();
929 ArchNames.insert(ArchName);
932 if (ArchNames.size() > 1) {
933 Diag(clang::diag::note_drv_command_failed_diag_msg)
934 << "Error generating preprocessed source(s) - cannot generate "
935 "preprocessed source with multiple -arch options.";
939 // Construct the list of abstract actions to perform for this compilation. On
940 // Darwin OSes this uses the driver-driver and builds universal actions.
941 const ToolChain &TC = C.getDefaultToolChain();
942 if (TC.getTriple().isOSBinFormatMachO())
943 BuildUniversalActions(C, TC, Inputs);
945 BuildActions(C, C.getArgs(), Inputs, C.getActions());
949 // If there were errors building the compilation, quit now.
950 if (Trap.hasErrorOccurred()) {
951 Diag(clang::diag::note_drv_command_failed_diag_msg)
952 << "Error generating preprocessed source(s).";
956 // Generate preprocessed output.
957 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
958 C.ExecuteJobs(C.getJobs(), FailingCommands);
960 // If any of the preprocessing commands failed, clean up and exit.
961 if (!FailingCommands.empty()) {
962 if (!isSaveTempsEnabled())
963 C.CleanupFileList(C.getTempFiles(), true);
965 Diag(clang::diag::note_drv_command_failed_diag_msg)
966 << "Error generating preprocessed source(s).";
970 const ArgStringList &TempFiles = C.getTempFiles();
971 if (TempFiles.empty()) {
972 Diag(clang::diag::note_drv_command_failed_diag_msg)
973 << "Error generating preprocessed source(s).";
977 Diag(clang::diag::note_drv_command_failed_diag_msg)
978 << "\n********************\n\n"
979 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
980 "Preprocessed source(s) and associated run script(s) are located at:";
982 SmallString<128> VFS;
983 SmallString<128> ReproCrashFilename;
984 for (const char *TempFile : TempFiles) {
985 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
986 if (ReproCrashFilename.empty()) {
987 ReproCrashFilename = TempFile;
988 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
990 if (StringRef(TempFile).endswith(".cache")) {
991 // In some cases (modules) we'll dump extra data to help with reproducing
992 // the crash into a directory next to the output.
993 VFS = llvm::sys::path::filename(TempFile);
994 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
998 // Assume associated files are based off of the first temporary file.
999 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1001 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
1003 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
1005 Diag(clang::diag::note_drv_command_failed_diag_msg)
1006 << "Error generating run script: " + Script + " " + EC.message();
1008 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1009 << "# Driver args: ";
1010 printArgList(ScriptOS, C.getInputArgs());
1011 ScriptOS << "# Original command: ";
1012 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1013 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1014 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1017 // On darwin, provide information about the .crash diagnostic report.
1018 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1019 SmallString<128> CrashDiagDir;
1020 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1021 Diag(clang::diag::note_drv_command_failed_diag_msg)
1022 << ReproCrashFilename.str();
1023 } else { // Suggest a directory for the user to look for .crash files.
1024 llvm::sys::path::append(CrashDiagDir, Name);
1025 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1026 Diag(clang::diag::note_drv_command_failed_diag_msg)
1027 << "Crash backtrace is located in";
1028 Diag(clang::diag::note_drv_command_failed_diag_msg)
1029 << CrashDiagDir.str();
1030 Diag(clang::diag::note_drv_command_failed_diag_msg)
1031 << "(choose the .crash file that corresponds to your crash)";
1035 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1036 options::OPT_frewrite_map_file_EQ))
1037 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1039 Diag(clang::diag::note_drv_command_failed_diag_msg)
1040 << "\n\n********************";
1043 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1044 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
1045 // if the tool does not support response files, there is a chance/ that things
1046 // will just work without a response file, so we silently just skip it.
1047 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1048 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
1051 std::string TmpName = GetTemporaryPath("response", "txt");
1052 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1055 int Driver::ExecuteCompilation(
1057 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1058 // Just print if -### was present.
1059 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1060 C.getJobs().Print(llvm::errs(), "\n", true);
1064 // If there were errors building the compilation, quit now.
1065 if (Diags.hasErrorOccurred())
1068 // Set up response file names for each command, if necessary
1069 for (auto &Job : C.getJobs())
1070 setUpResponseFiles(C, Job);
1072 C.ExecuteJobs(C.getJobs(), FailingCommands);
1074 // Remove temp files.
1075 C.CleanupFileList(C.getTempFiles());
1077 // If the command succeeded, we are done.
1078 if (FailingCommands.empty())
1081 // Otherwise, remove result files and print extra information about abnormal
1083 for (const auto &CmdPair : FailingCommands) {
1084 int Res = CmdPair.first;
1085 const Command *FailingCommand = CmdPair.second;
1087 // Remove result files if we're not saving temps.
1088 if (!isSaveTempsEnabled()) {
1089 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1090 C.CleanupFileMap(C.getResultFiles(), JA, true);
1092 // Failure result files are valid unless we crashed.
1094 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1097 // Print extra information about abnormal failures, if possible.
1099 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1100 // status was 1, assume the command failed normally. In particular, if it
1101 // was the compiler then assume it gave a reasonable error code. Failures
1102 // in other tools are less common, and they generally have worse
1103 // diagnostics, so always print the diagnostic there.
1104 const Tool &FailingTool = FailingCommand->getCreator();
1106 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1107 // FIXME: See FIXME above regarding result code interpretation.
1109 Diag(clang::diag::err_drv_command_signalled)
1110 << FailingTool.getShortName();
1112 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1119 void Driver::PrintHelp(bool ShowHidden) const {
1120 unsigned IncludedFlagsBitmask;
1121 unsigned ExcludedFlagsBitmask;
1122 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1123 getIncludeExcludeOptionFlagMasks();
1125 ExcludedFlagsBitmask |= options::NoDriverOption;
1127 ExcludedFlagsBitmask |= HelpHidden;
1129 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1130 IncludedFlagsBitmask, ExcludedFlagsBitmask);
1133 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1134 // FIXME: The following handlers should use a callback mechanism, we don't
1135 // know what the client would like to do.
1136 OS << getClangFullVersion() << '\n';
1137 const ToolChain &TC = C.getDefaultToolChain();
1138 OS << "Target: " << TC.getTripleString() << '\n';
1140 // Print the threading model.
1141 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1142 // Don't print if the ToolChain would have barfed on it already
1143 if (TC.isThreadModelSupported(A->getValue()))
1144 OS << "Thread model: " << A->getValue();
1146 OS << "Thread model: " << TC.getThreadModel();
1149 // Print out the install directory.
1150 OS << "InstalledDir: " << InstalledDir << '\n';
1153 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1155 static void PrintDiagnosticCategories(raw_ostream &OS) {
1156 // Skip the empty category.
1157 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1159 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1162 bool Driver::HandleImmediateArgs(const Compilation &C) {
1163 // The order these options are handled in gcc is all over the place, but we
1164 // don't expect inconsistencies w.r.t. that to matter in practice.
1166 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1167 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1171 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1172 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1173 // return an answer which matches our definition of __VERSION__.
1175 // If we want to return a more correct answer some day, then we should
1176 // introduce a non-pedantically GCC compatible mode to Clang in which we
1177 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1178 llvm::outs() << "4.2.1\n";
1182 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1183 PrintDiagnosticCategories(llvm::outs());
1187 if (C.getArgs().hasArg(options::OPT_help) ||
1188 C.getArgs().hasArg(options::OPT__help_hidden)) {
1189 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1193 if (C.getArgs().hasArg(options::OPT__version)) {
1194 // Follow gcc behavior and use stdout for --version and stderr for -v.
1195 PrintVersion(C, llvm::outs());
1197 // Print registered targets.
1198 llvm::outs() << '\n';
1199 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
1203 if (C.getArgs().hasArg(options::OPT_v) ||
1204 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1205 PrintVersion(C, llvm::errs());
1206 SuppressMissingInputWarning = true;
1209 const ToolChain &TC = C.getDefaultToolChain();
1211 if (C.getArgs().hasArg(options::OPT_v))
1212 TC.printVerboseInfo(llvm::errs());
1214 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1215 llvm::outs() << ResourceDir << '\n';
1219 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1220 llvm::outs() << "programs: =";
1221 bool separator = false;
1222 for (const std::string &Path : TC.getProgramPaths()) {
1224 llvm::outs() << ':';
1225 llvm::outs() << Path;
1228 llvm::outs() << "\n";
1229 llvm::outs() << "libraries: =" << ResourceDir;
1231 StringRef sysroot = C.getSysRoot();
1233 for (const std::string &Path : TC.getFilePaths()) {
1234 // Always print a separator. ResourceDir was the first item shown.
1235 llvm::outs() << ':';
1236 // Interpretation of leading '=' is needed only for NetBSD.
1238 llvm::outs() << sysroot << Path.substr(1);
1240 llvm::outs() << Path;
1242 llvm::outs() << "\n";
1246 // FIXME: The following handlers should use a callback mechanism, we don't
1247 // know what the client would like to do.
1248 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1249 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1253 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1254 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
1258 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1259 // Print out all options that start with a given argument. This is used for
1260 // shell autocompletion.
1261 StringRef PassedFlags = A->getValue();
1262 std::vector<std::string> SuggestedCompletions;
1264 unsigned short DisableFlags = options::NoDriverOption | options::Unsupported | options::Ignored;
1265 // We want to show cc1-only options only when clang is invoked as "clang -cc1".
1266 // When clang is invoked as "clang -cc1", we add "#" to the beginning of an --autocomplete
1267 // option so that the clang driver can distinguish whether it is requested to show cc1-only options or not.
1268 if (PassedFlags[0] == '#') {
1269 DisableFlags &= ~options::NoDriverOption;
1270 PassedFlags = PassedFlags.substr(1);
1273 if (PassedFlags.find(',') == StringRef::npos) {
1274 // If the flag is in the form of "--autocomplete=-foo",
1275 // we were requested to print out all option names that start with "-foo".
1276 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1277 SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
1279 // If the flag is in the form of "--autocomplete=foo,bar", we were
1280 // requested to print out all option values for "-foo" that start with
1281 // "bar". For example,
1282 // "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
1283 StringRef Option, Arg;
1284 std::tie(Option, Arg) = PassedFlags.split(',');
1285 SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
1288 // Sort the autocomplete candidates so that shells print them out in a
1289 // deterministic order. We could sort in any way, but we chose
1290 // case-insensitive sorting for consistency with the -help option
1291 // which prints out options in the case-insensitive alphabetical order.
1292 std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1293 [](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
1295 llvm::outs() << llvm::join(SuggestedCompletions, " ") << '\n';
1299 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1300 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1302 case ToolChain::RLT_CompilerRT:
1303 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1305 case ToolChain::RLT_Libgcc:
1306 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1312 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1313 for (const Multilib &Multilib : TC.getMultilibs())
1314 llvm::outs() << Multilib << "\n";
1318 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1319 for (const Multilib &Multilib : TC.getMultilibs()) {
1320 if (Multilib.gccSuffix().empty())
1321 llvm::outs() << ".\n";
1323 StringRef Suffix(Multilib.gccSuffix());
1324 assert(Suffix.front() == '/');
1325 llvm::outs() << Suffix.substr(1) << "\n";
1333 // Display an action graph human-readably. Action A is the "sink" node
1334 // and latest-occuring action. Traversal is in pre-order, visiting the
1335 // inputs to each action before printing the action itself.
1336 static unsigned PrintActions1(const Compilation &C, Action *A,
1337 std::map<Action *, unsigned> &Ids) {
1338 if (Ids.count(A)) // A was already visited.
1342 llvm::raw_string_ostream os(str);
1344 os << Action::getClassName(A->getKind()) << ", ";
1345 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1346 os << "\"" << IA->getInputArg().getValue() << "\"";
1347 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1348 os << '"' << BIA->getArchName() << '"' << ", {"
1349 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1350 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1351 bool IsFirst = true;
1352 OA->doOnEachDependence(
1353 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1354 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1355 // sm_35 this will generate:
1356 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1357 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1362 os << A->getOffloadingKindPrefix();
1366 os << TC->getTriple().normalize();
1369 os << ":" << BoundArch;
1372 os << " {" << PrintActions1(C, A, Ids) << "}";
1376 const ActionList *AL = &A->getInputs();
1379 const char *Prefix = "{";
1380 for (Action *PreRequisite : *AL) {
1381 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1389 // Append offload info for all options other than the offloading action
1390 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1391 std::string offload_str;
1392 llvm::raw_string_ostream offload_os(offload_str);
1393 if (!isa<OffloadAction>(A)) {
1394 auto S = A->getOffloadingKindPrefix();
1396 offload_os << ", (" << S;
1397 if (A->getOffloadingArch())
1398 offload_os << ", " << A->getOffloadingArch();
1403 unsigned Id = Ids.size();
1405 llvm::errs() << Id << ": " << os.str() << ", "
1406 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1411 // Print the action graphs in a compilation C.
1412 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1413 void Driver::PrintActions(const Compilation &C) const {
1414 std::map<Action *, unsigned> Ids;
1415 for (Action *A : C.getActions())
1416 PrintActions1(C, A, Ids);
1419 /// \brief Check whether the given input tree contains any compilation or
1420 /// assembly actions.
1421 static bool ContainsCompileOrAssembleAction(const Action *A) {
1422 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1423 isa<AssembleJobAction>(A))
1426 for (const Action *Input : A->inputs())
1427 if (ContainsCompileOrAssembleAction(Input))
1433 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1434 const InputList &BAInputs) const {
1435 DerivedArgList &Args = C.getArgs();
1436 ActionList &Actions = C.getActions();
1437 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1438 // Collect the list of architectures. Duplicates are allowed, but should only
1439 // be handled once (in the order seen).
1440 llvm::StringSet<> ArchNames;
1441 SmallVector<const char *, 4> Archs;
1442 for (Arg *A : Args) {
1443 if (A->getOption().matches(options::OPT_arch)) {
1444 // Validate the option here; we don't save the type here because its
1445 // particular spelling may participate in other driver choices.
1446 llvm::Triple::ArchType Arch =
1447 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1448 if (Arch == llvm::Triple::UnknownArch) {
1449 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1454 if (ArchNames.insert(A->getValue()).second)
1455 Archs.push_back(A->getValue());
1459 // When there is no explicit arch for this platform, make sure we still bind
1460 // the architecture (to the default) so that -Xarch_ is handled correctly.
1462 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1464 ActionList SingleActions;
1465 BuildActions(C, Args, BAInputs, SingleActions);
1467 // Add in arch bindings for every top level action, as well as lipo and
1468 // dsymutil steps if needed.
1469 for (Action* Act : SingleActions) {
1470 // Make sure we can lipo this kind of output. If not (and it is an actual
1471 // output) then we disallow, since we can't create an output file with the
1472 // right name without overwriting it. We could remove this oddity by just
1473 // changing the output names to include the arch, which would also fix
1474 // -save-temps. Compatibility wins for now.
1476 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1477 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1478 << types::getTypeName(Act->getType());
1481 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1482 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1484 // Lipo if necessary, we do it this way because we need to set the arch flag
1485 // so that -Xarch_ gets overwritten.
1486 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1487 Actions.append(Inputs.begin(), Inputs.end());
1489 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1491 // Handle debug info queries.
1492 Arg *A = Args.getLastArg(options::OPT_g_Group);
1493 if (A && !A->getOption().matches(options::OPT_g0) &&
1494 !A->getOption().matches(options::OPT_gstabs) &&
1495 ContainsCompileOrAssembleAction(Actions.back())) {
1497 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1498 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1499 // because the debug info will refer to a temporary object file which
1500 // will be removed at the end of the compilation process.
1501 if (Act->getType() == types::TY_Image) {
1503 Inputs.push_back(Actions.back());
1506 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1509 // Verify the debug info output.
1510 if (Args.hasArg(options::OPT_verify_debug_info)) {
1511 Action* LastAction = Actions.back();
1513 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1514 LastAction, types::TY_Nothing));
1520 /// \brief Check that the file referenced by Value exists. If it doesn't,
1521 /// issue a diagnostic and return false.
1522 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1523 StringRef Value, types::ID Ty) {
1524 if (!D.getCheckInputsExist())
1527 // stdin always exists.
1531 SmallString<64> Path(Value);
1532 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1533 if (!llvm::sys::path::is_absolute(Path)) {
1534 SmallString<64> Directory(WorkDir->getValue());
1535 llvm::sys::path::append(Directory, Value);
1536 Path.assign(Directory);
1540 if (llvm::sys::fs::exists(Twine(Path)))
1544 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1545 llvm::sys::Process::FindInEnvPath("LIB", Value))
1548 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1549 // Arguments to the /link flag might cause the linker to search for object
1550 // and library files in paths we don't know about. Don't error in such
1556 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1560 // Construct a the list of inputs and their types.
1561 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1562 InputList &Inputs) const {
1563 // Track the current user specified (-x) input. We also explicitly track the
1564 // argument used to set the type; we only want to claim the type when we
1565 // actually use it, so we warn about unused -x arguments.
1566 types::ID InputType = types::TY_Nothing;
1567 Arg *InputTypeArg = nullptr;
1569 // The last /TC or /TP option sets the input type to C or C++ globally.
1570 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1571 options::OPT__SLASH_TP)) {
1572 InputTypeArg = TCTP;
1573 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1577 Arg *Previous = nullptr;
1578 bool ShowNote = false;
1579 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1581 Diag(clang::diag::warn_drv_overriding_flag_option)
1582 << Previous->getSpelling() << A->getSpelling();
1588 Diag(clang::diag::note_drv_t_option_is_global);
1590 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1591 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1594 for (Arg *A : Args) {
1595 if (A->getOption().getKind() == Option::InputClass) {
1596 const char *Value = A->getValue();
1597 types::ID Ty = types::TY_INVALID;
1599 // Infer the input type if necessary.
1600 if (InputType == types::TY_Nothing) {
1601 // If there was an explicit arg for this, claim it.
1603 InputTypeArg->claim();
1605 // stdin must be handled specially.
1606 if (memcmp(Value, "-", 2) == 0) {
1607 // If running with -E, treat as a C input (this changes the builtin
1608 // macros, for example). This may be overridden by -ObjC below.
1610 // Otherwise emit an error but still use a valid type to avoid
1611 // spurious errors (e.g., no inputs).
1612 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1613 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1614 : clang::diag::err_drv_unknown_stdin_type);
1617 // Otherwise lookup by extension.
1618 // Fallback is C if invoked as C preprocessor or Object otherwise.
1619 // We use a host hook here because Darwin at least has its own
1620 // idea of what .s is.
1621 if (const char *Ext = strrchr(Value, '.'))
1622 Ty = TC.LookupTypeForExtension(Ext + 1);
1624 if (Ty == types::TY_INVALID) {
1628 Ty = types::TY_Object;
1631 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1632 // should autodetect some input files as C++ for g++ compatibility.
1634 types::ID OldTy = Ty;
1635 Ty = types::lookupCXXTypeForCType(Ty);
1638 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1639 << getTypeName(OldTy) << getTypeName(Ty);
1643 // -ObjC and -ObjC++ override the default language, but only for "source
1644 // files". We just treat everything that isn't a linker input as a
1647 // FIXME: Clean this up if we move the phase sequence into the type.
1648 if (Ty != types::TY_Object) {
1649 if (Args.hasArg(options::OPT_ObjC))
1650 Ty = types::TY_ObjC;
1651 else if (Args.hasArg(options::OPT_ObjCXX))
1652 Ty = types::TY_ObjCXX;
1655 assert(InputTypeArg && "InputType set w/o InputTypeArg");
1656 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1657 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1659 const char *Ext = strrchr(Value, '.');
1660 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1661 Ty = types::TY_Object;
1663 if (Ty == types::TY_INVALID) {
1665 InputTypeArg->claim();
1669 if (DiagnoseInputExistence(*this, Args, Value, Ty))
1670 Inputs.push_back(std::make_pair(Ty, A));
1672 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1673 StringRef Value = A->getValue();
1674 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1675 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1676 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1679 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1680 StringRef Value = A->getValue();
1681 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1682 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1683 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1686 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1687 // Just treat as object type, we could make a special type for this if
1689 Inputs.push_back(std::make_pair(types::TY_Object, A));
1691 } else if (A->getOption().matches(options::OPT_x)) {
1693 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1696 // Follow gcc behavior and treat as linker input for invalid -x
1697 // options. Its not clear why we shouldn't just revert to unknown; but
1698 // this isn't very important, we might as well be bug compatible.
1700 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1701 InputType = types::TY_Object;
1703 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1704 assert(A->getNumValues() == 1 && "The /U option has one value.");
1705 StringRef Val = A->getValue(0);
1706 if (Val.find_first_of("/\\") != StringRef::npos) {
1707 // Warn about e.g. "/Users/me/myfile.c".
1708 Diag(diag::warn_slash_u_filename) << Val;
1709 Diag(diag::note_use_dashdash);
1713 if (CCCIsCPP() && Inputs.empty()) {
1714 // If called as standalone preprocessor, stdin is processed
1715 // if no other input is present.
1716 Arg *A = MakeInputArg(Args, *Opts, "-");
1717 Inputs.push_back(std::make_pair(types::TY_C, A));
1722 /// Provides a convenient interface for different programming models to generate
1723 /// the required device actions.
1724 class OffloadingActionBuilder final {
1725 /// Flag used to trace errors in the builder.
1726 bool IsValid = false;
1728 /// The compilation that is using this builder.
1731 /// Map between an input argument and the offload kinds used to process it.
1732 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1734 /// Builder interface. It doesn't build anything or keep any state.
1735 class DeviceActionBuilder {
1737 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1739 enum ActionBuilderReturnCode {
1740 // The builder acted successfully on the current action.
1742 // The builder didn't have to act on the current action.
1744 // The builder was successful and requested the host action to not be
1750 /// Compilation associated with this builder.
1753 /// Tool chains associated with this builder. The same programming
1754 /// model may have associated one or more tool chains.
1755 SmallVector<const ToolChain *, 2> ToolChains;
1757 /// The derived arguments associated with this builder.
1758 DerivedArgList &Args;
1760 /// The inputs associated with this builder.
1761 const Driver::InputList &Inputs;
1763 /// The associated offload kind.
1764 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1767 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1768 const Driver::InputList &Inputs,
1769 Action::OffloadKind AssociatedOffloadKind)
1770 : C(C), Args(Args), Inputs(Inputs),
1771 AssociatedOffloadKind(AssociatedOffloadKind) {}
1772 virtual ~DeviceActionBuilder() {}
1774 /// Fill up the array \a DA with all the device dependences that should be
1775 /// added to the provided host action \a HostAction. By default it is
1777 virtual ActionBuilderReturnCode
1778 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1779 phases::ID CurPhase, phases::ID FinalPhase,
1781 return ABRT_Inactive;
1784 /// Update the state to include the provided host action \a HostAction as a
1785 /// dependency of the current device action. By default it is inactive.
1786 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1787 return ABRT_Inactive;
1790 /// Append top level actions generated by the builder. Return true if errors
1792 virtual void appendTopLevelActions(ActionList &AL) {}
1794 /// Append linker actions generated by the builder. Return true if errors
1796 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1798 /// Initialize the builder. Return true if any initialization errors are
1800 virtual bool initialize() { return false; }
1802 /// Return true if the builder can use bundling/unbundling.
1803 virtual bool canUseBundlerUnbundler() const { return false; }
1805 /// Return true if this builder is valid. We have a valid builder if we have
1806 /// associated device tool chains.
1807 bool isValid() { return !ToolChains.empty(); }
1809 /// Return the associated offload kind.
1810 Action::OffloadKind getAssociatedOffloadKind() {
1811 return AssociatedOffloadKind;
1815 /// \brief CUDA action builder. It injects device code in the host backend
1817 class CudaActionBuilder final : public DeviceActionBuilder {
1818 /// Flags to signal if the user requested host-only or device-only
1820 bool CompileHostOnly = false;
1821 bool CompileDeviceOnly = false;
1823 /// List of GPU architectures to use in this compilation.
1824 SmallVector<CudaArch, 4> GpuArchList;
1826 /// The CUDA actions for the current input.
1827 ActionList CudaDeviceActions;
1829 /// The CUDA fat binary if it was generated for the current input.
1830 Action *CudaFatBinary = nullptr;
1832 /// Flag that is set to true if this builder acted on the current input.
1833 bool IsActive = false;
1836 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1837 const Driver::InputList &Inputs)
1838 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1840 ActionBuilderReturnCode
1841 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1842 phases::ID CurPhase, phases::ID FinalPhase,
1843 PhasesTy &Phases) override {
1845 return ABRT_Inactive;
1847 // If we don't have more CUDA actions, we don't have any dependences to
1848 // create for the host.
1849 if (CudaDeviceActions.empty())
1850 return ABRT_Success;
1852 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1853 "Expecting one action per GPU architecture.");
1854 assert(!CompileHostOnly &&
1855 "Not expecting CUDA actions in host-only compilation.");
1857 // If we are generating code for the device or we are in a backend phase,
1858 // we attempt to generate the fat binary. We compile each arch to ptx and
1859 // assemble to cubin, then feed the cubin *and* the ptx into a device
1860 // "link" action, which uses fatbinary to combine these cubins into one
1861 // fatbin. The fatbin is then an input to the host action if not in
1862 // device-only mode.
1863 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1864 ActionList DeviceActions;
1865 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1866 // Produce the device action from the current phase up to the assemble
1868 for (auto Ph : Phases) {
1869 // Skip the phases that were already dealt with.
1872 // We have to be consistent with the host final phase.
1873 if (Ph > FinalPhase)
1876 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1877 C, Args, Ph, CudaDeviceActions[I]);
1879 if (Ph == phases::Assemble)
1883 // If we didn't reach the assemble phase, we can't generate the fat
1884 // binary. We don't need to generate the fat binary if we are not in
1885 // device-only mode.
1886 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1890 Action *AssembleAction = CudaDeviceActions[I];
1891 assert(AssembleAction->getType() == types::TY_Object);
1892 assert(AssembleAction->getInputs().size() == 1);
1894 Action *BackendAction = AssembleAction->getInputs()[0];
1895 assert(BackendAction->getType() == types::TY_PP_Asm);
1897 for (auto &A : {AssembleAction, BackendAction}) {
1898 OffloadAction::DeviceDependences DDep;
1899 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1901 DeviceActions.push_back(
1902 C.MakeAction<OffloadAction>(DDep, A->getType()));
1906 // We generate the fat binary if we have device input actions.
1907 if (!DeviceActions.empty()) {
1909 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1911 if (!CompileDeviceOnly) {
1912 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1914 // Clear the fat binary, it is already a dependence to an host
1916 CudaFatBinary = nullptr;
1919 // Remove the CUDA actions as they are already connected to an host
1920 // action or fat binary.
1921 CudaDeviceActions.clear();
1924 // We avoid creating host action in device-only mode.
1925 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
1926 } else if (CurPhase > phases::Backend) {
1927 // If we are past the backend phase and still have a device action, we
1928 // don't have to do anything as this action is already a device
1929 // top-level action.
1930 return ABRT_Success;
1933 assert(CurPhase < phases::Backend && "Generating single CUDA "
1934 "instructions should only occur "
1935 "before the backend phase!");
1937 // By default, we produce an action for each device arch.
1938 for (Action *&A : CudaDeviceActions)
1939 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1941 return ABRT_Success;
1944 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1945 // While generating code for CUDA, we only depend on the host input action
1946 // to trigger the creation of all the CUDA device actions.
1948 // If we are dealing with an input action, replicate it for each GPU
1949 // architecture. If we are in host-only mode we return 'success' so that
1950 // the host uses the CUDA offload kind.
1951 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1952 assert(!GpuArchList.empty() &&
1953 "We should have at least one GPU architecture.");
1955 // If the host input is not CUDA, we don't need to bother about this
1957 if (IA->getType() != types::TY_CUDA) {
1958 // The builder will ignore this input.
1960 return ABRT_Inactive;
1963 // Set the flag to true, so that the builder acts on the current input.
1966 if (CompileHostOnly)
1967 return ABRT_Success;
1969 // Replicate inputs for each GPU architecture.
1970 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1971 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1972 IA->getInputArg(), types::TY_CUDA_DEVICE));
1974 return ABRT_Success;
1977 return IsActive ? ABRT_Success : ABRT_Inactive;
1980 void appendTopLevelActions(ActionList &AL) override {
1981 // Utility to append actions to the top level list.
1982 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1983 OffloadAction::DeviceDependences Dep;
1984 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1986 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1989 // If we have a fat binary, add it to the list.
1990 if (CudaFatBinary) {
1991 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1992 CudaDeviceActions.clear();
1993 CudaFatBinary = nullptr;
1997 if (CudaDeviceActions.empty())
2000 // If we have CUDA actions at this point, that's because we have a have
2001 // partial compilation, so we should have an action for each GPU
2003 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2004 "Expecting one action per GPU architecture.");
2005 assert(ToolChains.size() == 1 &&
2006 "Expecting to have a sing CUDA toolchain.");
2007 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2008 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2010 CudaDeviceActions.clear();
2013 bool initialize() override {
2014 // We don't need to support CUDA.
2015 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
2018 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2019 assert(HostTC && "No toolchain for host compilation.");
2020 if (HostTC->getTriple().isNVPTX()) {
2021 // We do not support targeting NVPTX for host compilation. Throw
2022 // an error and abort pipeline construction early so we don't trip
2023 // asserts that assume device-side compilation.
2024 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
2028 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
2030 Arg *PartialCompilationArg = Args.getLastArg(
2031 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2032 options::OPT_cuda_compile_host_device);
2033 CompileHostOnly = PartialCompilationArg &&
2034 PartialCompilationArg->getOption().matches(
2035 options::OPT_cuda_host_only);
2036 CompileDeviceOnly = PartialCompilationArg &&
2037 PartialCompilationArg->getOption().matches(
2038 options::OPT_cuda_device_only);
2040 // Collect all cuda_gpu_arch parameters, removing duplicates.
2041 std::set<CudaArch> GpuArchs;
2043 for (Arg *A : Args) {
2044 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2045 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2049 const StringRef ArchStr = A->getValue();
2050 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2055 CudaArch Arch = StringToCudaArch(ArchStr);
2056 if (Arch == CudaArch::UNKNOWN) {
2057 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2059 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2060 GpuArchs.insert(Arch);
2061 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2062 GpuArchs.erase(Arch);
2064 llvm_unreachable("Unexpected option.");
2067 // Collect list of GPUs remaining in the set.
2068 for (CudaArch Arch : GpuArchs)
2069 GpuArchList.push_back(Arch);
2071 // Default to sm_20 which is the lowest common denominator for
2072 // supported GPUs. sm_20 code should work correctly, if
2073 // suboptimally, on all newer GPUs.
2074 if (GpuArchList.empty())
2075 GpuArchList.push_back(CudaArch::SM_20);
2081 /// OpenMP action builder. The host bitcode is passed to the device frontend
2082 /// and all the device linked images are passed to the host link phase.
2083 class OpenMPActionBuilder final : public DeviceActionBuilder {
2084 /// The OpenMP actions for the current input.
2085 ActionList OpenMPDeviceActions;
2087 /// The linker inputs obtained for each toolchain.
2088 SmallVector<ActionList, 8> DeviceLinkerInputs;
2091 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2092 const Driver::InputList &Inputs)
2093 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2095 ActionBuilderReturnCode
2096 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2097 phases::ID CurPhase, phases::ID FinalPhase,
2098 PhasesTy &Phases) override {
2100 // We should always have an action for each input.
2101 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2102 "Number of OpenMP actions and toolchains do not match.");
2104 // The host only depends on device action in the linking phase, when all
2105 // the device images have to be embedded in the host image.
2106 if (CurPhase == phases::Link) {
2107 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2108 "Toolchains and linker inputs sizes do not match.");
2109 auto LI = DeviceLinkerInputs.begin();
2110 for (auto *A : OpenMPDeviceActions) {
2115 // We passed the device action as a host dependence, so we don't need to
2116 // do anything else with them.
2117 OpenMPDeviceActions.clear();
2118 return ABRT_Success;
2121 // By default, we produce an action for each device arch.
2122 for (Action *&A : OpenMPDeviceActions)
2123 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2125 return ABRT_Success;
2128 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2130 // If this is an input action replicate it for each OpenMP toolchain.
2131 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2132 OpenMPDeviceActions.clear();
2133 for (unsigned I = 0; I < ToolChains.size(); ++I)
2134 OpenMPDeviceActions.push_back(
2135 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2136 return ABRT_Success;
2139 // If this is an unbundling action use it as is for each OpenMP toolchain.
2140 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2141 OpenMPDeviceActions.clear();
2142 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2143 OpenMPDeviceActions.push_back(UA);
2144 UA->registerDependentActionInfo(
2145 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2147 return ABRT_Success;
2150 // When generating code for OpenMP we use the host compile phase result as
2151 // a dependence to the device compile phase so that it can learn what
2152 // declarations should be emitted. However, this is not the only use for
2153 // the host action, so we prevent it from being collapsed.
2154 if (isa<CompileJobAction>(HostAction)) {
2155 HostAction->setCannotBeCollapsedWithNextDependentAction();
2156 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2157 "Toolchains and device action sizes do not match.");
2158 OffloadAction::HostDependence HDep(
2159 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2160 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2161 auto TC = ToolChains.begin();
2162 for (Action *&A : OpenMPDeviceActions) {
2163 assert(isa<CompileJobAction>(A));
2164 OffloadAction::DeviceDependences DDep;
2165 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2166 A = C.MakeAction<OffloadAction>(HDep, DDep);
2170 return ABRT_Success;
2173 void appendTopLevelActions(ActionList &AL) override {
2174 if (OpenMPDeviceActions.empty())
2177 // We should always have an action for each input.
2178 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2179 "Number of OpenMP actions and toolchains do not match.");
2181 // Append all device actions followed by the proper offload action.
2182 auto TI = ToolChains.begin();
2183 for (auto *A : OpenMPDeviceActions) {
2184 OffloadAction::DeviceDependences Dep;
2185 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2186 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2189 // We no longer need the action stored in this builder.
2190 OpenMPDeviceActions.clear();
2193 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2194 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2195 "Toolchains and linker inputs sizes do not match.");
2197 // Append a new link action for each device.
2198 auto TC = ToolChains.begin();
2199 for (auto &LI : DeviceLinkerInputs) {
2200 auto *DeviceLinkAction =
2201 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2202 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2203 Action::OFK_OpenMP);
2208 bool initialize() override {
2209 // Get the OpenMP toolchains. If we don't get any, the action builder will
2210 // know there is nothing to do related to OpenMP offloading.
2211 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2212 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2214 ToolChains.push_back(TI->second);
2216 DeviceLinkerInputs.resize(ToolChains.size());
2220 bool canUseBundlerUnbundler() const override {
2221 // OpenMP should use bundled files whenever possible.
2227 /// TODO: Add the implementation for other specialized builders here.
2230 /// Specialized builders being used by this offloading action builder.
2231 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2233 /// Flag set to true if all valid builders allow file bundling/unbundling.
2237 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2238 const Driver::InputList &Inputs)
2240 // Create a specialized builder for each device toolchain.
2244 // Create a specialized builder for CUDA.
2245 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2247 // Create a specialized builder for OpenMP.
2248 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2251 // TODO: Build other specialized builders here.
2254 // Initialize all the builders, keeping track of errors. If all valid
2255 // builders agree that we can use bundling, set the flag to true.
2256 unsigned ValidBuilders = 0u;
2257 unsigned ValidBuildersSupportingBundling = 0u;
2258 for (auto *SB : SpecializedBuilders) {
2259 IsValid = IsValid && !SB->initialize();
2261 // Update the counters if the builder is valid.
2262 if (SB->isValid()) {
2264 if (SB->canUseBundlerUnbundler())
2265 ++ValidBuildersSupportingBundling;
2269 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2272 ~OffloadingActionBuilder() {
2273 for (auto *SB : SpecializedBuilders)
2277 /// Generate an action that adds device dependences (if any) to a host action.
2278 /// If no device dependence actions exist, just return the host action \a
2279 /// HostAction. If an error is found or if no builder requires the host action
2280 /// to be generated, return nullptr.
2282 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2283 phases::ID CurPhase, phases::ID FinalPhase,
2284 DeviceActionBuilder::PhasesTy &Phases) {
2288 if (SpecializedBuilders.empty())
2291 assert(HostAction && "Invalid host action!");
2293 OffloadAction::DeviceDependences DDeps;
2294 // Check if all the programming models agree we should not emit the host
2295 // action. Also, keep track of the offloading kinds employed.
2296 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2297 unsigned InactiveBuilders = 0u;
2298 unsigned IgnoringBuilders = 0u;
2299 for (auto *SB : SpecializedBuilders) {
2300 if (!SB->isValid()) {
2306 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2308 // If the builder explicitly says the host action should be ignored,
2309 // we need to increment the variable that tracks the builders that request
2310 // the host object to be ignored.
2311 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2314 // Unless the builder was inactive for this action, we have to record the
2315 // offload kind because the host will have to use it.
2316 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2317 OffloadKind |= SB->getAssociatedOffloadKind();
2320 // If all builders agree that the host object should be ignored, just return
2322 if (IgnoringBuilders &&
2323 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2326 if (DDeps.getActions().empty())
2329 // We have dependences we need to bundle together. We use an offload action
2331 OffloadAction::HostDependence HDep(
2332 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2333 /*BoundArch=*/nullptr, DDeps);
2334 return C.MakeAction<OffloadAction>(HDep, DDeps);
2337 /// Generate an action that adds a host dependence to a device action. The
2338 /// results will be kept in this action builder. Return true if an error was
2340 bool addHostDependenceToDeviceActions(Action *&HostAction,
2341 const Arg *InputArg) {
2345 // If we are supporting bundling/unbundling and the current action is an
2346 // input action of non-source file, we replace the host action by the
2347 // unbundling action. The bundler tool has the logic to detect if an input
2348 // is a bundle or not and if the input is not a bundle it assumes it is a
2349 // host file. Therefore it is safe to create an unbundling action even if
2350 // the input is not a bundle.
2351 if (CanUseBundler && isa<InputAction>(HostAction) &&
2352 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2353 !types::isSrcFile(HostAction->getType())) {
2354 auto UnbundlingHostAction =
2355 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2356 UnbundlingHostAction->registerDependentActionInfo(
2357 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2358 /*BoundArch=*/StringRef(), Action::OFK_Host);
2359 HostAction = UnbundlingHostAction;
2362 assert(HostAction && "Invalid host action!");
2364 // Register the offload kinds that are used.
2365 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2366 for (auto *SB : SpecializedBuilders) {
2370 auto RetCode = SB->addDeviceDepences(HostAction);
2372 // Host dependences for device actions are not compatible with that same
2373 // action being ignored.
2374 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2375 "Host dependence not expected to be ignored.!");
2377 // Unless the builder was inactive for this action, we have to record the
2378 // offload kind because the host will have to use it.
2379 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2380 OffloadKind |= SB->getAssociatedOffloadKind();
2386 /// Add the offloading top level actions to the provided action list. This
2387 /// function can replace the host action by a bundling action if the
2388 /// programming models allow it.
2389 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2390 const Arg *InputArg) {
2391 // Get the device actions to be appended.
2392 ActionList OffloadAL;
2393 for (auto *SB : SpecializedBuilders) {
2396 SB->appendTopLevelActions(OffloadAL);
2399 // If we can use the bundler, replace the host action by the bundling one in
2400 // the resulting list. Otherwise, just append the device actions.
2401 if (CanUseBundler && !OffloadAL.empty()) {
2402 // Add the host action to the list in order to create the bundling action.
2403 OffloadAL.push_back(HostAction);
2405 // We expect that the host action was just appended to the action list
2406 // before this method was called.
2407 assert(HostAction == AL.back() && "Host action not in the list??");
2408 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2409 AL.back() = HostAction;
2411 AL.append(OffloadAL.begin(), OffloadAL.end());
2413 // Propagate to the current host action (if any) the offload information
2414 // associated with the current input.
2416 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2417 /*BoundArch=*/nullptr);
2421 /// Processes the host linker action. This currently consists of replacing it
2422 /// with an offload action if there are device link objects and propagate to
2423 /// the host action all the offload kinds used in the current compilation. The
2424 /// resulting action is returned.
2425 Action *processHostLinkAction(Action *HostAction) {
2426 // Add all the dependences from the device linking actions.
2427 OffloadAction::DeviceDependences DDeps;
2428 for (auto *SB : SpecializedBuilders) {
2432 SB->appendLinkDependences(DDeps);
2435 // Calculate all the offload kinds used in the current compilation.
2436 unsigned ActiveOffloadKinds = 0u;
2437 for (auto &I : InputArgToOffloadKindMap)
2438 ActiveOffloadKinds |= I.second;
2440 // If we don't have device dependencies, we don't have to create an offload
2442 if (DDeps.getActions().empty()) {
2443 // Propagate all the active kinds to host action. Given that it is a link
2444 // action it is assumed to depend on all actions generated so far.
2445 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2446 /*BoundArch=*/nullptr);
2450 // Create the offload action with all dependences. When an offload action
2451 // is created the kinds are propagated to the host action, so we don't have
2452 // to do that explicitly here.
2453 OffloadAction::HostDependence HDep(
2454 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2455 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2456 return C.MakeAction<OffloadAction>(HDep, DDeps);
2459 } // anonymous namespace.
2461 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2462 const InputList &Inputs, ActionList &Actions) const {
2463 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
2465 if (!SuppressMissingInputWarning && Inputs.empty()) {
2466 Diag(clang::diag::err_drv_no_input_files);
2471 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
2473 if (FinalPhase == phases::Link) {
2474 if (Args.hasArg(options::OPT_emit_llvm))
2475 Diag(clang::diag::err_drv_emit_llvm_link);
2476 if (IsCLMode() && LTOMode != LTOK_None &&
2477 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2478 Diag(clang::diag::err_drv_lto_without_lld);
2481 // Reject -Z* at the top level, these options should never have been exposed
2483 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
2484 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
2486 // Diagnose misuse of /Fo.
2487 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
2488 StringRef V = A->getValue();
2489 if (Inputs.size() > 1 && !V.empty() &&
2490 !llvm::sys::path::is_separator(V.back())) {
2491 // Check whether /Fo tries to name an output file for multiple inputs.
2492 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2493 << A->getSpelling() << V;
2494 Args.eraseArg(options::OPT__SLASH_Fo);
2498 // Diagnose misuse of /Fa.
2499 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2500 StringRef V = A->getValue();
2501 if (Inputs.size() > 1 && !V.empty() &&
2502 !llvm::sys::path::is_separator(V.back())) {
2503 // Check whether /Fa tries to name an asm file for multiple inputs.
2504 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2505 << A->getSpelling() << V;
2506 Args.eraseArg(options::OPT__SLASH_Fa);
2510 // Diagnose misuse of /o.
2511 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2512 if (A->getValue()[0] == '\0') {
2513 // It has to have a value.
2514 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2515 Args.eraseArg(options::OPT__SLASH_o);
2519 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2520 // * no filename after it
2521 // * both /Yc and /Yu passed but with different filenames
2522 // * corresponding file not also passed as /FI
2523 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2524 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2525 if (YcArg && YcArg->getValue()[0] == '\0') {
2526 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2527 Args.eraseArg(options::OPT__SLASH_Yc);
2530 if (YuArg && YuArg->getValue()[0] == '\0') {
2531 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2532 Args.eraseArg(options::OPT__SLASH_Yu);
2535 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2536 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2537 Args.eraseArg(options::OPT__SLASH_Yc);
2538 Args.eraseArg(options::OPT__SLASH_Yu);
2539 YcArg = YuArg = nullptr;
2541 if (YcArg || YuArg) {
2542 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2543 bool FoundMatchingInclude = false;
2544 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2545 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2546 if (Inc->getValue() == Val)
2547 FoundMatchingInclude = true;
2549 if (!FoundMatchingInclude) {
2550 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2551 << (YcArg ? YcArg : YuArg)->getSpelling();
2552 Args.eraseArg(options::OPT__SLASH_Yc);
2553 Args.eraseArg(options::OPT__SLASH_Yu);
2554 YcArg = YuArg = nullptr;
2557 if (YcArg && Inputs.size() > 1) {
2558 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2559 Args.eraseArg(options::OPT__SLASH_Yc);
2562 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2563 // /Y- disables all pch handling. Rather than check for it everywhere,
2564 // just remove clang-cl pch-related flags here.
2565 Args.eraseArg(options::OPT__SLASH_Fp);
2566 Args.eraseArg(options::OPT__SLASH_Yc);
2567 Args.eraseArg(options::OPT__SLASH_Yu);
2568 YcArg = YuArg = nullptr;
2571 // Builder to be used to build offloading actions.
2572 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
2574 // Construct the actions to perform.
2575 ActionList LinkerInputs;
2577 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
2578 for (auto &I : Inputs) {
2579 types::ID InputType = I.first;
2580 const Arg *InputArg = I.second;
2583 types::getCompilationPhases(InputType, PL);
2585 // If the first step comes after the final phase we are doing as part of
2586 // this compilation, warn the user about it.
2587 phases::ID InitialPhase = PL[0];
2588 if (InitialPhase > FinalPhase) {
2589 // Claim here to avoid the more general unused warning.
2592 // Suppress all unused style warnings with -Qunused-arguments
2593 if (Args.hasArg(options::OPT_Qunused_arguments))
2596 // Special case when final phase determined by binary name, rather than
2597 // by a command-line argument with a corresponding Arg.
2599 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
2600 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
2601 // Special case '-E' warning on a previously preprocessed file to make
2603 else if (InitialPhase == phases::Compile &&
2604 FinalPhase == phases::Preprocess &&
2605 getPreprocessedType(InputType) == types::TY_INVALID)
2606 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
2607 << InputArg->getAsString(Args) << !!FinalPhaseArg
2608 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2610 Diag(clang::diag::warn_drv_input_file_unused)
2611 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2613 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2618 // Add a separate precompile phase for the compile phase.
2619 if (FinalPhase >= phases::Compile) {
2620 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
2621 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
2622 types::getCompilationPhases(HeaderType, PCHPL);
2623 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
2625 // Build the pipeline for the pch file.
2626 Action *ClangClPch =
2627 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
2628 for (phases::ID Phase : PCHPL)
2629 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2631 Actions.push_back(ClangClPch);
2632 // The driver currently exits after the first failed command. This
2633 // relies on that behavior, to make sure if the pch generation fails,
2634 // the main compilation won't run.
2638 // Build the pipeline for this file.
2639 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
2641 // Use the current host action in any of the offloading actions, if
2643 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2646 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2648 phases::ID Phase = *i;
2650 // We are done if this step is past what the user requested.
2651 if (Phase > FinalPhase)
2654 // Add any offload action the host action depends on.
2655 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2656 Current, InputArg, Phase, FinalPhase, PL);
2660 // Queue linker inputs.
2661 if (Phase == phases::Link) {
2662 assert((i + 1) == e && "linking must be final compilation step.");
2663 LinkerInputs.push_back(Current);
2668 // Otherwise construct the appropriate action.
2669 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2671 // We didn't create a new action, so we will just move to the next phase.
2672 if (NewCurrent == Current)
2675 Current = NewCurrent;
2677 // Use the current host action in any of the offloading actions, if
2679 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2682 if (Current->getType() == types::TY_Nothing)
2686 // If we ended with something, add to the output list.
2688 Actions.push_back(Current);
2690 // Add any top level actions generated for offloading.
2691 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
2694 // Add a link action if necessary.
2695 if (!LinkerInputs.empty()) {
2696 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2697 LA = OffloadBuilder.processHostLinkAction(LA);
2698 Actions.push_back(LA);
2701 // If we are linking, claim any options which are obviously only used for
2703 if (FinalPhase == phases::Link && PL.size() == 1) {
2704 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
2705 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2708 // Claim ignored clang-cl options.
2709 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
2711 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2712 // to non-CUDA compilations and should not trigger warnings there.
2713 Args.ClaimAllArgs(options::OPT_cuda_host_only);
2714 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
2717 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2718 phases::ID Phase, Action *Input) const {
2719 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
2721 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2722 // encode this in the steps because the intermediate type depends on
2723 // arguments. Just special case here.
2724 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2727 // Build the appropriate action.
2730 llvm_unreachable("link action invalid here.");
2731 case phases::Preprocess: {
2733 // -{M, MM} alter the output type.
2734 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
2735 OutputTy = types::TY_Dependencies;
2737 OutputTy = Input->getType();
2738 if (!Args.hasFlag(options::OPT_frewrite_includes,
2739 options::OPT_fno_rewrite_includes, false) &&
2740 !Args.hasFlag(options::OPT_frewrite_imports,
2741 options::OPT_fno_rewrite_imports, false) &&
2743 OutputTy = types::getPreprocessedType(OutputTy);
2744 assert(OutputTy != types::TY_INVALID &&
2745 "Cannot preprocess this input type!");
2747 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
2749 case phases::Precompile: {
2750 types::ID OutputTy = getPrecompiledType(Input->getType());
2751 assert(OutputTy != types::TY_INVALID &&
2752 "Cannot precompile this input type!");
2753 if (Args.hasArg(options::OPT_fsyntax_only)) {
2754 // Syntax checks should not emit a PCH file
2755 OutputTy = types::TY_Nothing;
2757 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
2759 case phases::Compile: {
2760 if (Args.hasArg(options::OPT_fsyntax_only))
2761 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
2762 if (Args.hasArg(options::OPT_rewrite_objc))
2763 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
2764 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
2765 return C.MakeAction<CompileJobAction>(Input,
2766 types::TY_RewrittenLegacyObjC);
2767 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
2768 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
2769 if (Args.hasArg(options::OPT__migrate))
2770 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
2771 if (Args.hasArg(options::OPT_emit_ast))
2772 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
2773 if (Args.hasArg(options::OPT_module_file_info))
2774 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
2775 if (Args.hasArg(options::OPT_verify_pch))
2776 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2777 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
2779 case phases::Backend: {
2782 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
2783 return C.MakeAction<BackendJobAction>(Input, Output);
2785 if (Args.hasArg(options::OPT_emit_llvm)) {
2787 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
2788 return C.MakeAction<BackendJobAction>(Input, Output);
2790 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
2792 case phases::Assemble:
2793 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
2796 llvm_unreachable("invalid phase in ConstructPhaseAction");
2799 void Driver::BuildJobs(Compilation &C) const {
2800 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2802 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2804 // It is an error to provide a -o option if we are making multiple output
2807 unsigned NumOutputs = 0;
2808 for (const Action *A : C.getActions())
2809 if (A->getType() != types::TY_Nothing)
2812 if (NumOutputs > 1) {
2813 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
2814 FinalOutput = nullptr;
2818 // Collect the list of architectures.
2819 llvm::StringSet<> ArchNames;
2820 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2821 for (const Arg *A : C.getArgs())
2822 if (A->getOption().matches(options::OPT_arch))
2823 ArchNames.insert(A->getValue());
2825 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2826 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
2827 for (Action *A : C.getActions()) {
2828 // If we are linking an image for multiple archs then the linker wants
2829 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2830 // doesn't fit in cleanly because we have to pass this information down.
2832 // FIXME: This is a hack; find a cleaner way to integrate this into the
2834 const char *LinkingOutput = nullptr;
2835 if (isa<LipoJobAction>(A)) {
2837 LinkingOutput = FinalOutput->getValue();
2839 LinkingOutput = getDefaultImageName();
2842 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
2843 /*BoundArch*/ StringRef(),
2844 /*AtTopLevel*/ true,
2845 /*MultipleArchs*/ ArchNames.size() > 1,
2846 /*LinkingOutput*/ LinkingOutput, CachedResults,
2847 /*TargetDeviceOffloadKind*/ Action::OFK_None);
2850 // If the user passed -Qunused-arguments or there were errors, don't warn
2851 // about any unused arguments.
2852 if (Diags.hasErrorOccurred() ||
2853 C.getArgs().hasArg(options::OPT_Qunused_arguments))
2857 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
2859 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
2860 (void)C.getArgs().hasArg(options::OPT_driver_mode);
2861 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
2863 for (Arg *A : C.getArgs()) {
2864 // FIXME: It would be nice to be able to send the argument to the
2865 // DiagnosticsEngine, so that extra values, position, and so on could be
2867 if (!A->isClaimed()) {
2868 if (A->getOption().hasFlag(options::NoArgumentUnused))
2871 // Suppress the warning automatically if this is just a flag, and it is an
2872 // instance of an argument we already claimed.
2873 const Option &Opt = A->getOption();
2874 if (Opt.getKind() == Option::FlagClass) {
2875 bool DuplicateClaimed = false;
2877 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2878 if (AA->isClaimed()) {
2879 DuplicateClaimed = true;
2884 if (DuplicateClaimed)
2888 // In clang-cl, don't mention unknown arguments here since they have
2889 // already been warned about.
2890 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2891 Diag(clang::diag::warn_drv_unused_argument)
2892 << A->getAsString(C.getArgs());
2898 /// Utility class to control the collapse of dependent actions and select the
2899 /// tools accordingly.
2900 class ToolSelector final {
2901 /// The tool chain this selector refers to.
2902 const ToolChain &TC;
2904 /// The compilation this selector refers to.
2905 const Compilation &C;
2907 /// The base action this selector refers to.
2908 const JobAction *BaseAction;
2910 /// Set to true if the current toolchain refers to host actions.
2911 bool IsHostSelector;
2913 /// Set to true if save-temps and embed-bitcode functionalities are active.
2917 /// Get previous dependent action or null if that does not exist. If
2918 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2919 /// null will be returned.
2920 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2921 ActionList &SavedOffloadAction,
2922 bool CanBeCollapsed = true) {
2923 // An option can be collapsed only if it has a single input.
2924 if (Inputs.size() != 1)
2927 Action *CurAction = *Inputs.begin();
2928 if (CanBeCollapsed &&
2929 !CurAction->isCollapsingWithNextDependentActionLegal())
2932 // If the input action is an offload action. Look through it and save any
2933 // offload action that can be dropped in the event of a collapse.
2934 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2935 // If the dependent action is a device action, we will attempt to collapse
2936 // only with other device actions. Otherwise, we would do the same but
2937 // with host actions only.
2938 if (!IsHostSelector) {
2939 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2941 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2942 if (CanBeCollapsed &&
2943 !CurAction->isCollapsingWithNextDependentActionLegal())
2945 SavedOffloadAction.push_back(OA);
2946 return dyn_cast<JobAction>(CurAction);
2948 } else if (OA->hasHostDependence()) {
2949 CurAction = OA->getHostDependence();
2950 if (CanBeCollapsed &&
2951 !CurAction->isCollapsingWithNextDependentActionLegal())
2953 SavedOffloadAction.push_back(OA);
2954 return dyn_cast<JobAction>(CurAction);
2959 return dyn_cast<JobAction>(CurAction);
2962 /// Return true if an assemble action can be collapsed.
2963 bool canCollapseAssembleAction() const {
2964 return TC.useIntegratedAs() && !SaveTemps &&
2965 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2966 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2967 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2970 /// Return true if a preprocessor action can be collapsed.
2971 bool canCollapsePreprocessorAction() const {
2972 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2973 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2974 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2977 /// Struct that relates an action with the offload actions that would be
2978 /// collapsed with it.
2979 struct JobActionInfo final {
2980 /// The action this info refers to.
2981 const JobAction *JA = nullptr;
2982 /// The offload actions we need to take care off if this action is
2984 ActionList SavedOffloadAction;
2987 /// Append collapsed offload actions from the give nnumber of elements in the
2988 /// action info array.
2989 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2990 ArrayRef<JobActionInfo> &ActionInfo,
2991 unsigned ElementNum) {
2992 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2993 for (unsigned I = 0; I < ElementNum; ++I)
2994 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2995 ActionInfo[I].SavedOffloadAction.end());
2998 /// Functions that attempt to perform the combining. They detect if that is
2999 /// legal, and if so they update the inputs \a Inputs and the offload action
3000 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3001 /// the combined action is returned. If the combining is not legal or if the
3002 /// tool does not exist, null is returned.
3003 /// Currently three kinds of collapsing are supported:
3004 /// - Assemble + Backend + Compile;
3005 /// - Assemble + Backend ;
3006 /// - Backend + Compile.
3008 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3009 const ActionList *&Inputs,
3010 ActionList &CollapsedOffloadAction) {
3011 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3013 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3014 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3015 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3016 if (!AJ || !BJ || !CJ)
3019 // Get compiler tool.
3020 const Tool *T = TC.SelectTool(*CJ);
3024 // When using -fembed-bitcode, it is required to have the same tool (clang)
3025 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3027 const Tool *BT = TC.SelectTool(*BJ);
3032 if (!T->hasIntegratedAssembler())
3035 Inputs = &CJ->getInputs();
3036 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3040 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3041 const ActionList *&Inputs,
3042 ActionList &CollapsedOffloadAction) {
3043 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3045 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3046 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3050 // Retrieve the compile job, backend action must always be preceded by one.
3051 ActionList CompileJobOffloadActions;
3052 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3053 /*CanBeCollapsed=*/false);
3054 if (!AJ || !BJ || !CJ)
3057 assert(isa<CompileJobAction>(CJ) &&
3058 "Expecting compile job preceding backend job.");
3060 // Get compiler tool.
3061 const Tool *T = TC.SelectTool(*CJ);
3065 if (!T->hasIntegratedAssembler())
3068 Inputs = &BJ->getInputs();
3069 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3073 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3074 const ActionList *&Inputs,
3075 ActionList &CollapsedOffloadAction) {
3076 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3078 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3079 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3083 // Get compiler tool.
3084 const Tool *T = TC.SelectTool(*CJ);
3088 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3091 Inputs = &CJ->getInputs();
3092 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3097 /// Updates the inputs if the obtained tool supports combining with
3098 /// preprocessor action, and the current input is indeed a preprocessor
3099 /// action. If combining results in the collapse of offloading actions, those
3100 /// are appended to \a CollapsedOffloadAction.
3101 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3102 ActionList &CollapsedOffloadAction) {
3103 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3106 // Attempt to get a preprocessor action dependence.
3107 ActionList PreprocessJobOffloadActions;
3108 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3109 if (!PJ || !isa<PreprocessJobAction>(PJ))
3112 // This is legal to combine. Append any offload action we found and set the
3113 // current inputs to preprocessor inputs.
3114 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3115 PreprocessJobOffloadActions.end());
3116 Inputs = &PJ->getInputs();
3120 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3121 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3122 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3123 EmbedBitcode(EmbedBitcode) {
3124 assert(BaseAction && "Invalid base action.");
3125 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3128 /// Check if a chain of actions can be combined and return the tool that can
3129 /// handle the combination of actions. The pointer to the current inputs \a
3130 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3131 /// connected to collapsed actions are updated accordingly. The latter enables
3132 /// the caller of the selector to process them afterwards instead of just
3133 /// dropping them. If no suitable tool is found, null will be returned.
3134 const Tool *getTool(const ActionList *&Inputs,
3135 ActionList &CollapsedOffloadAction) {
3137 // Get the largest chain of actions that we could combine.
3140 SmallVector<JobActionInfo, 5> ActionChain(1);
3141 ActionChain.back().JA = BaseAction;
3142 while (ActionChain.back().JA) {
3143 const Action *CurAction = ActionChain.back().JA;
3145 // Grow the chain by one element.
3146 ActionChain.resize(ActionChain.size() + 1);
3147 JobActionInfo &AI = ActionChain.back();
3149 // Attempt to fill it with the
3151 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3154 // Pop the last action info as it could not be filled.
3155 ActionChain.pop_back();
3158 // Attempt to combine actions. If all combining attempts failed, just return
3159 // the tool of the provided action. At the end we attempt to combine the
3160 // action with any preprocessor action it may depend on.
3163 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3164 CollapsedOffloadAction);
3166 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3168 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3170 Inputs = &BaseAction->getInputs();
3171 T = TC.SelectTool(*BaseAction);
3174 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3180 /// Return a string that uniquely identifies the result of a job. The bound arch
3181 /// is not necessarily represented in the toolchain's triple -- for example,
3182 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
3183 /// Also, we need to add the offloading device kind, as the same tool chain can
3184 /// be used for host and device for some programming models, e.g. OpenMP.
3185 static std::string GetTriplePlusArchString(const ToolChain *TC,
3186 StringRef BoundArch,
3187 Action::OffloadKind OffloadKind) {
3188 std::string TriplePlusArch = TC->getTriple().normalize();
3189 if (!BoundArch.empty()) {
3190 TriplePlusArch += "-";
3191 TriplePlusArch += BoundArch;
3193 TriplePlusArch += "-";
3194 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3195 return TriplePlusArch;
3198 InputInfo Driver::BuildJobsForAction(
3199 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3200 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3201 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3202 Action::OffloadKind TargetDeviceOffloadKind) const {
3203 std::pair<const Action *, std::string> ActionTC = {
3204 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3205 auto CachedResult = CachedResults.find(ActionTC);
3206 if (CachedResult != CachedResults.end()) {
3207 return CachedResult->second;
3209 InputInfo Result = BuildJobsForActionNoCache(
3210 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3211 CachedResults, TargetDeviceOffloadKind);
3212 CachedResults[ActionTC] = Result;
3216 InputInfo Driver::BuildJobsForActionNoCache(
3217 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3218 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3219 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3220 Action::OffloadKind TargetDeviceOffloadKind) const {
3221 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3223 InputInfoList OffloadDependencesInputInfo;
3224 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3225 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3226 // The offload action is expected to be used in four different situations.
3228 // a) Set a toolchain/architecture/kind for a host action:
3229 // Host Action 1 -> OffloadAction -> Host Action 2
3231 // b) Set a toolchain/architecture/kind for a device action;
3232 // Device Action 1 -> OffloadAction -> Device Action 2
3234 // c) Specify a device dependence to a host action;
3235 // Device Action 1 _
3237 // Host Action 1 ---> OffloadAction -> Host Action 2
3239 // d) Specify a host dependence to a device action.
3242 // Device Action 1 ---> OffloadAction -> Device Action 2
3244 // For a) and b), we just return the job generated for the dependence. For
3245 // c) and d) we override the current action with the host/device dependence
3246 // if the current toolchain is host/device and set the offload dependences
3247 // info with the jobs obtained from the device/host dependence(s).
3249 // If there is a single device option, just generate the job for it.
3250 if (OA->hasSingleDeviceDependence()) {
3252 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3253 const char *DepBoundArch) {
3255 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3256 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3257 CachedResults, DepA->getOffloadingDeviceKind());
3262 // If 'Action 2' is host, we generate jobs for the device dependences and
3263 // override the current action with the host dependence. Otherwise, we
3264 // generate the host dependences and override the action with the device
3265 // dependence. The dependences can't therefore be a top-level action.
3266 OA->doOnEachDependence(
3267 /*IsHostDependence=*/BuildingForOffloadDevice,
3268 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3269 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3270 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3271 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3272 DepA->getOffloadingDeviceKind()));
3275 A = BuildingForOffloadDevice
3276 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3277 : OA->getHostDependence();
3280 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3281 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3282 // just using Args was better?
3283 const Arg &Input = IA->getInputArg();
3285 if (Input.getOption().matches(options::OPT_INPUT)) {
3286 const char *Name = Input.getValue();
3287 return InputInfo(A, Name, /* BaseInput = */ Name);
3289 return InputInfo(A, &Input, /* BaseInput = */ "");
3292 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
3293 const ToolChain *TC;
3294 StringRef ArchName = BAA->getArchName();
3296 if (!ArchName.empty())
3297 TC = &getToolChain(C.getArgs(),
3298 computeTargetTriple(*this, DefaultTargetTriple,
3299 C.getArgs(), ArchName));
3301 TC = &C.getDefaultToolChain();
3303 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
3304 MultipleArchs, LinkingOutput, CachedResults,
3305 TargetDeviceOffloadKind);
3309 const ActionList *Inputs = &A->getInputs();
3311 const JobAction *JA = cast<JobAction>(A);
3312 ActionList CollapsedOffloadActions;
3314 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3315 embedBitcodeInObject() && !isUsingLTO());
3316 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3321 // If we've collapsed action list that contained OffloadAction we
3322 // need to build jobs for host/device-side inputs it may have held.
3323 for (const auto *OA : CollapsedOffloadActions)
3324 cast<OffloadAction>(OA)->doOnEachDependence(
3325 /*IsHostDependence=*/BuildingForOffloadDevice,
3326 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3327 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3328 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
3329 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
3330 DepA->getOffloadingDeviceKind()));
3333 // Only use pipes when there is exactly one input.
3334 InputInfoList InputInfos;
3335 for (const Action *Input : *Inputs) {
3336 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3337 // shouldn't get temporary output names.
3338 // FIXME: Clean this up.
3339 bool SubJobAtTopLevel =
3340 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
3341 InputInfos.push_back(BuildJobsForAction(
3342 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
3343 CachedResults, A->getOffloadingDeviceKind()));
3346 // Always use the first input as the base input.
3347 const char *BaseInput = InputInfos[0].getBaseInput();
3349 // ... except dsymutil actions, which use their actual input as the base
3351 if (JA->getType() == types::TY_dSYM)
3352 BaseInput = InputInfos[0].getFilename();
3354 // Append outputs of offload device jobs to the input list
3355 if (!OffloadDependencesInputInfo.empty())
3356 InputInfos.append(OffloadDependencesInputInfo.begin(),
3357 OffloadDependencesInputInfo.end());
3359 // Set the effective triple of the toolchain for the duration of this job.
3360 llvm::Triple EffectiveTriple;
3361 const ToolChain &ToolTC = T->getToolChain();
3362 const ArgList &Args =
3363 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
3364 if (InputInfos.size() != 1) {
3365 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3367 // Pass along the input type if it can be unambiguously determined.
3368 EffectiveTriple = llvm::Triple(
3369 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3371 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3373 // Determine the place to write output to, if any.
3375 InputInfoList UnbundlingResults;
3376 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3377 // If we have an unbundling job, we need to create results for all the
3378 // outputs. We also update the results cache so that other actions using
3379 // this unbundling action can get the right results.
3380 for (auto &UI : UA->getDependentActionsInfo()) {
3381 assert(UI.DependentOffloadKind != Action::OFK_None &&
3382 "Unbundling with no offloading??");
3384 // Unbundling actions are never at the top level. When we generate the
3385 // offloading prefix, we also do that for the host file because the
3386 // unbundling action does not change the type of the output which can
3387 // cause a overwrite.
3388 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3389 UI.DependentOffloadKind,
3390 UI.DependentToolChain->getTriple().normalize(),
3391 /*CreatePrefixForHost=*/true);
3392 auto CurI = InputInfo(
3393 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3394 /*AtTopLevel=*/false, MultipleArchs,
3397 // Save the unbundling result.
3398 UnbundlingResults.push_back(CurI);
3400 // Get the unique string identifier for this dependence and cache the
3402 CachedResults[{A, GetTriplePlusArchString(
3403 UI.DependentToolChain, UI.DependentBoundArch,
3404 UI.DependentOffloadKind)}] = CurI;
3407 // Now that we have all the results generated, select the one that should be
3408 // returned for the current depending action.
3409 std::pair<const Action *, std::string> ActionTC = {
3410 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3411 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3412 "Result does not exist??");
3413 Result = CachedResults[ActionTC];
3414 } else if (JA->getType() == types::TY_Nothing)
3415 Result = InputInfo(A, BaseInput);
3417 // We only have to generate a prefix for the host if this is not a top-level
3419 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3420 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3421 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3423 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
3424 AtTopLevel, MultipleArchs,
3429 if (CCCPrintBindings && !CCGenDiagnostics) {
3430 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3431 << " - \"" << T->getName() << "\", inputs: [";
3432 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3433 llvm::errs() << InputInfos[i].getAsString();
3435 llvm::errs() << ", ";
3437 if (UnbundlingResults.empty())
3438 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3440 llvm::errs() << "], outputs: [";
3441 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3442 llvm::errs() << UnbundlingResults[i].getAsString();
3444 llvm::errs() << ", ";
3446 llvm::errs() << "] \n";
3449 if (UnbundlingResults.empty())
3451 C, *JA, Result, InputInfos,
3452 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3455 T->ConstructJobMultipleOutputs(
3456 C, *JA, UnbundlingResults, InputInfos,
3457 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3463 const char *Driver::getDefaultImageName() const {
3464 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3465 return Target.isOSWindows() ? "a.exe" : "a.out";
3468 /// \brief Create output filename based on ArgValue, which could either be a
3469 /// full filename, filename without extension, or a directory. If ArgValue
3470 /// does not provide a filename, then use BaseName, and use the extension
3471 /// suitable for FileType.
3472 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
3474 types::ID FileType) {
3475 SmallString<128> Filename = ArgValue;
3477 if (ArgValue.empty()) {
3478 // If the argument is empty, output to BaseName in the current dir.
3479 Filename = BaseName;
3480 } else if (llvm::sys::path::is_separator(Filename.back())) {
3481 // If the argument is a directory, output to BaseName in that dir.
3482 llvm::sys::path::append(Filename, BaseName);
3485 if (!llvm::sys::path::has_extension(ArgValue)) {
3486 // If the argument didn't provide an extension, then set it.
3487 const char *Extension = types::getTypeTempSuffix(FileType, true);
3489 if (FileType == types::TY_Image &&
3490 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3491 // The output file is a dll.
3495 llvm::sys::path::replace_extension(Filename, Extension);
3498 return Args.MakeArgString(Filename.c_str());
3501 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
3502 const char *BaseInput,
3503 StringRef BoundArch, bool AtTopLevel,
3505 StringRef OffloadingPrefix) const {
3506 llvm::PrettyStackTraceString CrashInfo("Computing output path");
3507 // Output to a user requested destination?
3508 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
3509 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
3510 return C.addResultFile(FinalOutput->getValue(), &JA);
3513 // For /P, preprocess to file named after BaseInput.
3514 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3515 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3516 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3518 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
3519 NameArg = A->getValue();
3520 return C.addResultFile(
3521 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3525 // Default to writing to stdout?
3526 if (AtTopLevel && !CCGenDiagnostics &&
3527 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
3530 // Is this the assembly listing for /FA?
3531 if (JA.getType() == types::TY_PP_Asm &&
3532 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3533 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3534 // Use /Fa and the input filename to determine the asm file name.
3535 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3536 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
3537 return C.addResultFile(
3538 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3542 // Output to a temporary file?
3543 if ((!AtTopLevel && !isSaveTempsEnabled() &&
3544 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
3546 StringRef Name = llvm::sys::path::filename(BaseInput);
3547 std::pair<StringRef, StringRef> Split = Name.split('.');
3548 std::string TmpName = GetTemporaryPath(
3549 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3550 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3553 SmallString<128> BasePath(BaseInput);
3556 // Dsymutil actions should use the full path.
3557 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
3558 BaseName = BasePath;
3560 BaseName = llvm::sys::path::filename(BasePath);
3562 // Determine what the derived output name should be.
3563 const char *NamedOutput;
3565 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
3566 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3567 // The /Fo or /o flag decides the object filename.
3570 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3573 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
3574 } else if (JA.getType() == types::TY_Image &&
3575 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3576 options::OPT__SLASH_o)) {
3577 // The /Fe or /o flag names the linked file.
3580 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3583 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
3584 } else if (JA.getType() == types::TY_Image) {
3586 // clang-cl uses BaseName for the executable name.
3588 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
3590 SmallString<128> Output(getDefaultImageName());
3591 Output += OffloadingPrefix;
3592 if (MultipleArchs && !BoundArch.empty()) {
3594 Output.append(BoundArch);
3596 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
3598 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
3599 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
3601 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
3602 assert(Suffix && "All types used for output should have a suffix.");
3604 std::string::size_type End = std::string::npos;
3605 if (!types::appendSuffixForType(JA.getType()))
3606 End = BaseName.rfind('.');
3607 SmallString<128> Suffixed(BaseName.substr(0, End));
3608 Suffixed += OffloadingPrefix;
3609 if (MultipleArchs && !BoundArch.empty()) {
3611 Suffixed.append(BoundArch);
3613 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3614 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3615 // optimized bitcode output.
3616 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3617 JA.getType() == types::TY_LLVM_BC)
3621 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3624 // Prepend object file path if -save-temps=obj
3625 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3626 JA.getType() != types::TY_PCH) {
3627 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3628 SmallString<128> TempPath(FinalOutput->getValue());
3629 llvm::sys::path::remove_filename(TempPath);
3630 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3631 llvm::sys::path::append(TempPath, OutputFileName);
3632 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3635 // If we're saving temps and the temp file conflicts with the input file,
3636 // then avoid overwriting input file.
3637 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
3638 bool SameFile = false;
3639 SmallString<256> Result;
3640 llvm::sys::fs::current_path(Result);
3641 llvm::sys::path::append(Result, BaseName);
3642 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3643 // Must share the same path to conflict.
3645 StringRef Name = llvm::sys::path::filename(BaseInput);
3646 std::pair<StringRef, StringRef> Split = Name.split('.');
3647 std::string TmpName = GetTemporaryPath(
3648 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3649 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3653 // As an annoying special case, PCH generation doesn't strip the pathname.
3654 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
3655 llvm::sys::path::remove_filename(BasePath);
3656 if (BasePath.empty())
3657 BasePath = NamedOutput;
3659 llvm::sys::path::append(BasePath, NamedOutput);
3660 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
3662 return C.addResultFile(NamedOutput, &JA);
3666 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
3667 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3668 // attempting to use this prefix when looking for file paths.
3669 for (const std::string &Dir : PrefixDirs) {
3672 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3673 llvm::sys::path::append(P, Name);
3674 if (llvm::sys::fs::exists(Twine(P)))
3678 SmallString<128> P(ResourceDir);
3679 llvm::sys::path::append(P, Name);
3680 if (llvm::sys::fs::exists(Twine(P)))
3683 for (const std::string &Dir : TC.getFilePaths()) {
3686 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3687 llvm::sys::path::append(P, Name);
3688 if (llvm::sys::fs::exists(Twine(P)))
3695 void Driver::generatePrefixedToolNames(
3696 StringRef Tool, const ToolChain &TC,
3697 SmallVectorImpl<std::string> &Names) const {
3698 // FIXME: Needs a better variable than DefaultTargetTriple
3699 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
3700 Names.emplace_back(Tool);
3702 // Allow the discovery of tools prefixed with LLVM's default target triple.
3703 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3704 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
3705 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
3708 static bool ScanDirForExecutable(SmallString<128> &Dir,
3709 ArrayRef<std::string> Names) {
3710 for (const auto &Name : Names) {
3711 llvm::sys::path::append(Dir, Name);
3712 if (llvm::sys::fs::can_execute(Twine(Dir)))
3714 llvm::sys::path::remove_filename(Dir);
3719 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
3720 SmallVector<std::string, 2> TargetSpecificExecutables;
3721 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3723 // Respect a limited subset of the '-Bprefix' functionality in GCC by
3724 // attempting to use this prefix when looking for program paths.
3725 for (const auto &PrefixDir : PrefixDirs) {
3726 if (llvm::sys::fs::is_directory(PrefixDir)) {
3727 SmallString<128> P(PrefixDir);
3728 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3731 SmallString<128> P((PrefixDir + Name).str());
3732 if (llvm::sys::fs::can_execute(Twine(P)))
3737 const ToolChain::path_list &List = TC.getProgramPaths();
3738 for (const auto &Path : List) {
3739 SmallString<128> P(Path);
3740 if (ScanDirForExecutable(P, TargetSpecificExecutables))
3744 // If all else failed, search the path.
3745 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3746 if (llvm::ErrorOr<std::string> P =
3747 llvm::sys::findProgramByName(TargetSpecificExecutable))
3753 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
3754 SmallString<128> Path;
3755 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
3757 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
3764 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3765 SmallString<128> Output;
3766 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3767 // FIXME: If anybody needs it, implement this obscure rule:
3768 // "If you specify a directory without a file name, the default file name
3769 // is VCx0.pch., where x is the major version of Visual C++ in use."
3770 Output = FpArg->getValue();
3772 // "If you do not specify an extension as part of the path name, an
3773 // extension of .pch is assumed. "
3774 if (!llvm::sys::path::has_extension(Output))
3778 llvm::sys::path::replace_extension(Output, ".pch");
3780 return Output.str();
3783 const ToolChain &Driver::getToolChain(const ArgList &Args,
3784 const llvm::Triple &Target) const {
3786 auto &TC = ToolChains[Target.str()];
3788 switch (Target.getOS()) {
3789 case llvm::Triple::Haiku:
3790 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
3792 case llvm::Triple::Ananas:
3793 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
3795 case llvm::Triple::CloudABI:
3796 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
3798 case llvm::Triple::Darwin:
3799 case llvm::Triple::MacOSX:
3800 case llvm::Triple::IOS:
3801 case llvm::Triple::TvOS:
3802 case llvm::Triple::WatchOS:
3803 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
3805 case llvm::Triple::DragonFly:
3806 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
3808 case llvm::Triple::OpenBSD:
3809 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
3811 case llvm::Triple::Bitrig:
3812 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
3814 case llvm::Triple::NetBSD:
3815 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
3817 case llvm::Triple::FreeBSD:
3818 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
3820 case llvm::Triple::Minix:
3821 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
3823 case llvm::Triple::Linux:
3824 case llvm::Triple::ELFIAMCU:
3825 if (Target.getArch() == llvm::Triple::hexagon)
3826 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3828 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3829 !Target.hasEnvironment())
3830 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3833 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
3835 case llvm::Triple::NaCl:
3836 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
3838 case llvm::Triple::Fuchsia:
3839 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
3841 case llvm::Triple::Solaris:
3842 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
3844 case llvm::Triple::AMDHSA:
3845 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
3847 case llvm::Triple::Win32:
3848 switch (Target.getEnvironment()) {
3850 if (Target.isOSBinFormatELF())
3851 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3852 else if (Target.isOSBinFormatMachO())
3853 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3855 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3857 case llvm::Triple::GNU:
3858 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
3860 case llvm::Triple::Itanium:
3861 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3864 case llvm::Triple::MSVC:
3865 case llvm::Triple::UnknownEnvironment:
3866 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
3870 case llvm::Triple::PS4:
3871 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
3873 case llvm::Triple::Contiki:
3874 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
3877 // Of these targets, Hexagon is the only one that might have
3878 // an OS of Linux, in which case it got handled above already.
3879 switch (Target.getArch()) {
3880 case llvm::Triple::tce:
3881 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
3883 case llvm::Triple::tcele:
3884 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
3886 case llvm::Triple::hexagon:
3887 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3890 case llvm::Triple::lanai:
3891 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
3893 case llvm::Triple::xcore:
3894 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
3896 case llvm::Triple::wasm32:
3897 case llvm::Triple::wasm64:
3898 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
3900 case llvm::Triple::avr:
3901 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
3904 if (Target.getVendor() == llvm::Triple::Myriad)
3905 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3907 else if (toolchains::BareMetal::handlesTarget(Target))
3908 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
3909 else if (Target.isOSBinFormatELF())
3910 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3911 else if (Target.isOSBinFormatMachO())
3912 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3914 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3919 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3920 // compiles always need two toolchains, the CUDA toolchain and the host
3921 // toolchain. So the only valid way to create a CUDA toolchain is via
3922 // CreateOffloadingDeviceToolChains.
3927 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
3928 // Say "no" if there is not exactly one input of a type clang understands.
3929 if (JA.size() != 1 ||
3930 !types::isAcceptedByClang((*JA.input_begin())->getType()))
3933 // And say "no" if this is not a kind of action clang understands.
3934 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
3935 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
3941 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3942 /// grouped values as integers. Numbers which are not provided are set to 0.
3944 /// \return True if the entire string was parsed (9.2), or all groups were
3945 /// parsed (10.3.5extrastuff).
3946 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3947 unsigned &Micro, bool &HadExtra) {
3950 Major = Minor = Micro = 0;
3954 if (Str.consumeInteger(10, Major))
3961 Str = Str.drop_front(1);
3963 if (Str.consumeInteger(10, Minor))
3969 Str = Str.drop_front(1);
3971 if (Str.consumeInteger(10, Micro))
3978 /// Parse digits from a string \p Str and fulfill \p Digits with
3979 /// the parsed numbers. This method assumes that the max number of
3980 /// digits to look for is equal to Digits.size().
3982 /// \return True if the entire string was parsed and there are
3983 /// no extra characters remaining at the end.
3984 bool Driver::GetReleaseVersion(StringRef Str,
3985 MutableArrayRef<unsigned> Digits) {
3989 unsigned CurDigit = 0;
3990 while (CurDigit < Digits.size()) {
3992 if (Str.consumeInteger(10, Digit))
3994 Digits[CurDigit] = Digit;
3999 Str = Str.drop_front(1);
4003 // More digits than requested, bail out...
4007 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4008 unsigned IncludedFlagsBitmask = 0;
4009 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
4011 if (Mode == CLMode) {
4012 // Include CL and Core options.
4013 IncludedFlagsBitmask |= options::CLOption;
4014 IncludedFlagsBitmask |= options::CoreOption;
4016 ExcludedFlagsBitmask |= options::CLOption;
4019 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4022 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
4023 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);