1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Driver/Driver.h"
11 #include "InputInfo.h"
12 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Bitrig.h"
15 #include "ToolChains/Clang.h"
16 #include "ToolChains/CloudABI.h"
17 #include "ToolChains/Contiki.h"
18 #include "ToolChains/CrossWindows.h"
19 #include "ToolChains/Cuda.h"
20 #include "ToolChains/Darwin.h"
21 #include "ToolChains/DragonFly.h"
22 #include "ToolChains/FreeBSD.h"
23 #include "ToolChains/Fuchsia.h"
24 #include "ToolChains/Gnu.h"
25 #include "ToolChains/Haiku.h"
26 #include "ToolChains/Hexagon.h"
27 #include "ToolChains/Lanai.h"
28 #include "ToolChains/Linux.h"
29 #include "ToolChains/MinGW.h"
30 #include "ToolChains/Minix.h"
31 #include "ToolChains/MipsLinux.h"
32 #include "ToolChains/MSVC.h"
33 #include "ToolChains/Myriad.h"
34 #include "ToolChains/NaCl.h"
35 #include "ToolChains/NetBSD.h"
36 #include "ToolChains/OpenBSD.h"
37 #include "ToolChains/PS4CPU.h"
38 #include "ToolChains/Solaris.h"
39 #include "ToolChains/TCE.h"
40 #include "ToolChains/WebAssembly.h"
41 #include "ToolChains/XCore.h"
42 #include "clang/Basic/Version.h"
43 #include "clang/Basic/VirtualFileSystem.h"
44 #include "clang/Config/config.h"
45 #include "clang/Driver/Action.h"
46 #include "clang/Driver/Compilation.h"
47 #include "clang/Driver/DriverDiagnostic.h"
48 #include "clang/Driver/Job.h"
49 #include "clang/Driver/Options.h"
50 #include "clang/Driver/SanitizerArgs.h"
51 #include "clang/Driver/Tool.h"
52 #include "clang/Driver/ToolChain.h"
53 #include "llvm/ADT/ArrayRef.h"
54 #include "llvm/ADT/STLExtras.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/ADT/StringSet.h"
58 #include "llvm/ADT/StringSwitch.h"
59 #include "llvm/Option/Arg.h"
60 #include "llvm/Option/ArgList.h"
61 #include "llvm/Option/OptSpecifier.h"
62 #include "llvm/Option/OptTable.h"
63 #include "llvm/Option/Option.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/FileSystem.h"
66 #include "llvm/Support/Path.h"
67 #include "llvm/Support/PrettyStackTrace.h"
68 #include "llvm/Support/Process.h"
69 #include "llvm/Support/Program.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include <map>
72 #include <memory>
73 #include <utility>
74 #if LLVM_ON_UNIX
75 #include <unistd.h> // getpid
76 #endif
77 
78 using namespace clang::driver;
79 using namespace clang;
80 using namespace llvm::opt;
81 
82 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
83                DiagnosticsEngine &Diags,
84                IntrusiveRefCntPtr<vfs::FileSystem> VFS)
85     : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
86       Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
87       LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
88       SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
89       DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
90       CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
91       CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
92       CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
93       CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
94       GenReproducer(false), SuppressMissingInputWarning(false) {
95 
96   // Provide a sane fallback if no VFS is specified.
97   if (!this->VFS)
98     this->VFS = vfs::getRealFileSystem();
99 
100   Name = llvm::sys::path::filename(ClangExecutable);
101   Dir = llvm::sys::path::parent_path(ClangExecutable);
102   InstalledDir = Dir; // Provide a sensible default installed dir.
103 
104   // Compute the path to the resource directory.
105   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
106   SmallString<128> P(Dir);
107   if (ClangResourceDir != "") {
108     llvm::sys::path::append(P, ClangResourceDir);
109   } else {
110     StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
111     P = llvm::sys::path::parent_path(Dir);
112     llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
113                             CLANG_VERSION_STRING);
114   }
115   ResourceDir = P.str();
116 }
117 
118 void Driver::ParseDriverMode(StringRef ProgramName,
119                              ArrayRef<const char *> Args) {
120   auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
121   StringRef DefaultMode(Default.second);
122   setDriverModeFromOption(DefaultMode);
123 
124   for (const char *ArgPtr : Args) {
125     // Ingore nullptrs, they are response file's EOL markers
126     if (ArgPtr == nullptr)
127       continue;
128     const StringRef Arg = ArgPtr;
129     setDriverModeFromOption(Arg);
130   }
131 }
132 
133 void Driver::setDriverModeFromOption(StringRef Opt) {
134   const std::string OptName =
135       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
136   if (!Opt.startswith(OptName))
137     return;
138   StringRef Value = Opt.drop_front(OptName.size());
139 
140   const unsigned M = llvm::StringSwitch<unsigned>(Value)
141                          .Case("gcc", GCCMode)
142                          .Case("g++", GXXMode)
143                          .Case("cpp", CPPMode)
144                          .Case("cl", CLMode)
145                          .Default(~0U);
146 
147   if (M != ~0U)
148     Mode = static_cast<DriverMode>(M);
149   else
150     Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
151 }
152 
153 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
154   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
155 
156   unsigned IncludedFlagsBitmask;
157   unsigned ExcludedFlagsBitmask;
158   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
159       getIncludeExcludeOptionFlagMasks();
160 
161   unsigned MissingArgIndex, MissingArgCount;
162   InputArgList Args =
163       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
164                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
165 
166   // Check for missing argument error.
167   if (MissingArgCount)
168     Diag(clang::diag::err_drv_missing_argument)
169         << Args.getArgString(MissingArgIndex) << MissingArgCount;
170 
171   // Check for unsupported options.
172   for (const Arg *A : Args) {
173     if (A->getOption().hasFlag(options::Unsupported)) {
174       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
175       continue;
176     }
177 
178     // Warn about -mcpu= without an argument.
179     if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
180       Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
181     }
182   }
183 
184   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
185     Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
186                               diag::err_drv_unknown_argument)
187       << A->getAsString(Args);
188 
189   return Args;
190 }
191 
192 // Determine which compilation mode we are in. We look for options which
193 // affect the phase, starting with the earliest phases, and record which
194 // option we used to determine the final phase.
195 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
196                                  Arg **FinalPhaseArg) const {
197   Arg *PhaseArg = nullptr;
198   phases::ID FinalPhase;
199 
200   // -{E,EP,P,M,MM} only run the preprocessor.
201   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
202       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
203       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
204       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
205     FinalPhase = phases::Preprocess;
206 
207     // --precompile only runs up to precompilation.
208   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
209     FinalPhase = phases::Precompile;
210 
211     // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
212   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
213              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
214              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
215              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
216              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
217              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
218              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
219                                         options::OPT__analyze_auto)) ||
220              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
221     FinalPhase = phases::Compile;
222 
223     // -S only runs up to the backend.
224   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
225     FinalPhase = phases::Backend;
226 
227     // -c compilation only runs up to the assembler.
228   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
229     FinalPhase = phases::Assemble;
230 
231     // Otherwise do everything.
232   } else
233     FinalPhase = phases::Link;
234 
235   if (FinalPhaseArg)
236     *FinalPhaseArg = PhaseArg;
237 
238   return FinalPhase;
239 }
240 
241 static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
242                          StringRef Value) {
243   Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
244                    Args.getBaseArgs().MakeIndex(Value), Value.data());
245   Args.AddSynthesizedArg(A);
246   A->claim();
247   return A;
248 }
249 
250 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
251   DerivedArgList *DAL = new DerivedArgList(Args);
252 
253   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
254   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
255   for (Arg *A : Args) {
256     // Unfortunately, we have to parse some forwarding options (-Xassembler,
257     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
258     // (assembler and preprocessor), or bypass a previous driver ('collect2').
259 
260     // Rewrite linker options, to replace --no-demangle with a custom internal
261     // option.
262     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
263          A->getOption().matches(options::OPT_Xlinker)) &&
264         A->containsValue("--no-demangle")) {
265       // Add the rewritten no-demangle argument.
266       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
267 
268       // Add the remaining values as Xlinker arguments.
269       for (StringRef Val : A->getValues())
270         if (Val != "--no-demangle")
271           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
272 
273       continue;
274     }
275 
276     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
277     // some build systems. We don't try to be complete here because we don't
278     // care to encourage this usage model.
279     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
280         (A->getValue(0) == StringRef("-MD") ||
281          A->getValue(0) == StringRef("-MMD"))) {
282       // Rewrite to -MD/-MMD along with -MF.
283       if (A->getValue(0) == StringRef("-MD"))
284         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
285       else
286         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
287       if (A->getNumValues() == 2)
288         DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
289                             A->getValue(1));
290       continue;
291     }
292 
293     // Rewrite reserved library names.
294     if (A->getOption().matches(options::OPT_l)) {
295       StringRef Value = A->getValue();
296 
297       // Rewrite unless -nostdlib is present.
298       if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
299         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
300         continue;
301       }
302 
303       // Rewrite unconditionally.
304       if (Value == "cc_kext") {
305         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
306         continue;
307       }
308     }
309 
310     // Pick up inputs via the -- option.
311     if (A->getOption().matches(options::OPT__DASH_DASH)) {
312       A->claim();
313       for (StringRef Val : A->getValues())
314         DAL->append(MakeInputArg(*DAL, *Opts, Val));
315       continue;
316     }
317 
318     DAL->append(A);
319   }
320 
321   // Enforce -static if -miamcu is present.
322   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
323     DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
324 
325 // Add a default value of -mlinker-version=, if one was given and the user
326 // didn't specify one.
327 #if defined(HOST_LINK_VERSION)
328   if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
329       strlen(HOST_LINK_VERSION) > 0) {
330     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
331                       HOST_LINK_VERSION);
332     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
333   }
334 #endif
335 
336   return DAL;
337 }
338 
339 /// \brief Compute target triple from args.
340 ///
341 /// This routine provides the logic to compute a target triple from various
342 /// args passed to the driver and the default triple string.
343 static llvm::Triple computeTargetTriple(const Driver &D,
344                                         StringRef DefaultTargetTriple,
345                                         const ArgList &Args,
346                                         StringRef DarwinArchName = "") {
347   // FIXME: Already done in Compilation *Driver::BuildCompilation
348   if (const Arg *A = Args.getLastArg(options::OPT_target))
349     DefaultTargetTriple = A->getValue();
350 
351   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
352 
353   // Handle Apple-specific options available here.
354   if (Target.isOSBinFormatMachO()) {
355     // If an explict Darwin arch name is given, that trumps all.
356     if (!DarwinArchName.empty()) {
357       tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
358       return Target;
359     }
360 
361     // Handle the Darwin '-arch' flag.
362     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
363       StringRef ArchName = A->getValue();
364       tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
365     }
366   }
367 
368   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
369   // '-mbig-endian'/'-EB'.
370   if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
371                                options::OPT_mbig_endian)) {
372     if (A->getOption().matches(options::OPT_mlittle_endian)) {
373       llvm::Triple LE = Target.getLittleEndianArchVariant();
374       if (LE.getArch() != llvm::Triple::UnknownArch)
375         Target = std::move(LE);
376     } else {
377       llvm::Triple BE = Target.getBigEndianArchVariant();
378       if (BE.getArch() != llvm::Triple::UnknownArch)
379         Target = std::move(BE);
380     }
381   }
382 
383   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
384   if (Target.getArch() == llvm::Triple::tce ||
385       Target.getOS() == llvm::Triple::Minix)
386     return Target;
387 
388   // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
389   Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
390                            options::OPT_m32, options::OPT_m16);
391   if (A) {
392     llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
393 
394     if (A->getOption().matches(options::OPT_m64)) {
395       AT = Target.get64BitArchVariant().getArch();
396       if (Target.getEnvironment() == llvm::Triple::GNUX32)
397         Target.setEnvironment(llvm::Triple::GNU);
398     } else if (A->getOption().matches(options::OPT_mx32) &&
399                Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
400       AT = llvm::Triple::x86_64;
401       Target.setEnvironment(llvm::Triple::GNUX32);
402     } else if (A->getOption().matches(options::OPT_m32)) {
403       AT = Target.get32BitArchVariant().getArch();
404       if (Target.getEnvironment() == llvm::Triple::GNUX32)
405         Target.setEnvironment(llvm::Triple::GNU);
406     } else if (A->getOption().matches(options::OPT_m16) &&
407                Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
408       AT = llvm::Triple::x86;
409       Target.setEnvironment(llvm::Triple::CODE16);
410     }
411 
412     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
413       Target.setArch(AT);
414   }
415 
416   // Handle -miamcu flag.
417   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
418     if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
419       D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
420                                                        << Target.str();
421 
422     if (A && !A->getOption().matches(options::OPT_m32))
423       D.Diag(diag::err_drv_argument_not_allowed_with)
424           << "-miamcu" << A->getBaseArg().getAsString(Args);
425 
426     Target.setArch(llvm::Triple::x86);
427     Target.setArchName("i586");
428     Target.setEnvironment(llvm::Triple::UnknownEnvironment);
429     Target.setEnvironmentName("");
430     Target.setOS(llvm::Triple::ELFIAMCU);
431     Target.setVendor(llvm::Triple::UnknownVendor);
432     Target.setVendorName("intel");
433   }
434 
435   return Target;
436 }
437 
438 // \brief Parse the LTO options and record the type of LTO compilation
439 // based on which -f(no-)?lto(=.*)? option occurs last.
440 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
441   LTOMode = LTOK_None;
442   if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
443                     options::OPT_fno_lto, false))
444     return;
445 
446   StringRef LTOName("full");
447 
448   const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
449   if (A)
450     LTOName = A->getValue();
451 
452   LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
453                 .Case("full", LTOK_Full)
454                 .Case("thin", LTOK_Thin)
455                 .Default(LTOK_Unknown);
456 
457   if (LTOMode == LTOK_Unknown) {
458     assert(A);
459     Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
460                                                     << A->getValue();
461   }
462 }
463 
464 /// Compute the desired OpenMP runtime from the flags provided.
465 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
466   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
467 
468   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
469   if (A)
470     RuntimeName = A->getValue();
471 
472   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
473                 .Case("libomp", OMPRT_OMP)
474                 .Case("libgomp", OMPRT_GOMP)
475                 .Case("libiomp5", OMPRT_IOMP5)
476                 .Default(OMPRT_Unknown);
477 
478   if (RT == OMPRT_Unknown) {
479     if (A)
480       Diag(diag::err_drv_unsupported_option_argument)
481           << A->getOption().getName() << A->getValue();
482     else
483       // FIXME: We could use a nicer diagnostic here.
484       Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
485   }
486 
487   return RT;
488 }
489 
490 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
491                                               InputList &Inputs) {
492 
493   //
494   // CUDA
495   //
496   // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
497   if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
498         return types::isCuda(I.first);
499       })) {
500     const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
501     const llvm::Triple &HostTriple = HostTC->getTriple();
502     llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
503                                                      : "nvptx-nvidia-cuda");
504     // Use the CUDA and host triples as the key into the ToolChains map, because
505     // the device toolchain we create depends on both.
506     auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
507     if (!CudaTC) {
508       CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
509           *this, CudaTriple, *HostTC, C.getInputArgs());
510     }
511     C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
512   }
513 
514   //
515   // OpenMP
516   //
517   // We need to generate an OpenMP toolchain if the user specified targets with
518   // the -fopenmp-targets option.
519   if (Arg *OpenMPTargets =
520           C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
521     if (OpenMPTargets->getNumValues()) {
522       // We expect that -fopenmp-targets is always used in conjunction with the
523       // option -fopenmp specifying a valid runtime with offloading support,
524       // i.e. libomp or libiomp.
525       bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
526           options::OPT_fopenmp, options::OPT_fopenmp_EQ,
527           options::OPT_fno_openmp, false);
528       if (HasValidOpenMPRuntime) {
529         OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
530         HasValidOpenMPRuntime =
531             OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
532       }
533 
534       if (HasValidOpenMPRuntime) {
535         llvm::StringMap<const char *> FoundNormalizedTriples;
536         for (const char *Val : OpenMPTargets->getValues()) {
537           llvm::Triple TT(Val);
538           std::string NormalizedName = TT.normalize();
539 
540           // Make sure we don't have a duplicate triple.
541           auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
542           if (Duplicate != FoundNormalizedTriples.end()) {
543             Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
544                 << Val << Duplicate->second;
545             continue;
546           }
547 
548           // Store the current triple so that we can check for duplicates in the
549           // following iterations.
550           FoundNormalizedTriples[NormalizedName] = Val;
551 
552           // If the specified target is invalid, emit a diagnostic.
553           if (TT.getArch() == llvm::Triple::UnknownArch)
554             Diag(clang::diag::err_drv_invalid_omp_target) << Val;
555           else {
556             const ToolChain &TC = getToolChain(C.getInputArgs(), TT);
557             C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP);
558           }
559         }
560       } else
561         Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
562     } else
563       Diag(clang::diag::warn_drv_empty_joined_argument)
564           << OpenMPTargets->getAsString(C.getInputArgs());
565   }
566 
567   //
568   // TODO: Add support for other offloading programming models here.
569   //
570 
571   return;
572 }
573 
574 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
575   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
576 
577   // FIXME: Handle environment options which affect driver behavior, somewhere
578   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
579 
580   if (Optional<std::string> CompilerPathValue =
581           llvm::sys::Process::GetEnv("COMPILER_PATH")) {
582     StringRef CompilerPath = *CompilerPathValue;
583     while (!CompilerPath.empty()) {
584       std::pair<StringRef, StringRef> Split =
585           CompilerPath.split(llvm::sys::EnvPathSeparator);
586       PrefixDirs.push_back(Split.first);
587       CompilerPath = Split.second;
588     }
589   }
590 
591   // We look for the driver mode option early, because the mode can affect
592   // how other options are parsed.
593   ParseDriverMode(ClangExecutable, ArgList.slice(1));
594 
595   // FIXME: What are we going to do with -V and -b?
596 
597   // FIXME: This stuff needs to go into the Compilation, not the driver.
598   bool CCCPrintPhases;
599 
600   InputArgList Args = ParseArgStrings(ArgList.slice(1));
601 
602   // Silence driver warnings if requested
603   Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
604 
605   // -no-canonical-prefixes is used very early in main.
606   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
607 
608   // Ignore -pipe.
609   Args.ClaimAllArgs(options::OPT_pipe);
610 
611   // Extract -ccc args.
612   //
613   // FIXME: We need to figure out where this behavior should live. Most of it
614   // should be outside in the client; the parts that aren't should have proper
615   // options, either by introducing new ones or by overloading gcc ones like -V
616   // or -b.
617   CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
618   CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
619   if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
620     CCCGenericGCCName = A->getValue();
621   CCCUsePCH =
622       Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
623   GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
624                                options::OPT_fno_crash_diagnostics,
625                                !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
626   // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
627   // and getToolChain is const.
628   if (IsCLMode()) {
629     // clang-cl targets MSVC-style Win32.
630     llvm::Triple T(DefaultTargetTriple);
631     T.setOS(llvm::Triple::Win32);
632     T.setVendor(llvm::Triple::PC);
633     T.setEnvironment(llvm::Triple::MSVC);
634     DefaultTargetTriple = T.str();
635   }
636   if (const Arg *A = Args.getLastArg(options::OPT_target))
637     DefaultTargetTriple = A->getValue();
638   if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
639     Dir = InstalledDir = A->getValue();
640   for (const Arg *A : Args.filtered(options::OPT_B)) {
641     A->claim();
642     PrefixDirs.push_back(A->getValue(0));
643   }
644   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
645     SysRoot = A->getValue();
646   if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
647     DyldPrefix = A->getValue();
648   if (Args.hasArg(options::OPT_nostdlib))
649     UseStdLib = false;
650 
651   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
652     ResourceDir = A->getValue();
653 
654   if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
655     SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
656                     .Case("cwd", SaveTempsCwd)
657                     .Case("obj", SaveTempsObj)
658                     .Default(SaveTempsCwd);
659   }
660 
661   setLTOMode(Args);
662 
663   // Process -fembed-bitcode= flags.
664   if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
665     StringRef Name = A->getValue();
666     unsigned Model = llvm::StringSwitch<unsigned>(Name)
667         .Case("off", EmbedNone)
668         .Case("all", EmbedBitcode)
669         .Case("bitcode", EmbedBitcode)
670         .Case("marker", EmbedMarker)
671         .Default(~0U);
672     if (Model == ~0U) {
673       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
674                                                 << Name;
675     } else
676       BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
677   }
678 
679   std::unique_ptr<llvm::opt::InputArgList> UArgs =
680       llvm::make_unique<InputArgList>(std::move(Args));
681 
682   // Perform the default argument translations.
683   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
684 
685   // Owned by the host.
686   const ToolChain &TC = getToolChain(
687       *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
688 
689   // The compilation takes ownership of Args.
690   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
691 
692   if (!HandleImmediateArgs(*C))
693     return C;
694 
695   // Construct the list of inputs.
696   InputList Inputs;
697   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
698 
699   // Populate the tool chains for the offloading devices, if any.
700   CreateOffloadingDeviceToolChains(*C, Inputs);
701 
702   // Construct the list of abstract actions to perform for this compilation. On
703   // MachO targets this uses the driver-driver and universal actions.
704   if (TC.getTriple().isOSBinFormatMachO())
705     BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
706   else
707     BuildActions(*C, C->getArgs(), Inputs, C->getActions());
708 
709   if (CCCPrintPhases) {
710     PrintActions(*C);
711     return C;
712   }
713 
714   BuildJobs(*C);
715 
716   return C;
717 }
718 
719 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
720   llvm::opt::ArgStringList ASL;
721   for (const auto *A : Args)
722     A->render(Args, ASL);
723 
724   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
725     if (I != ASL.begin())
726       OS << ' ';
727     Command::printArg(OS, *I, true);
728   }
729   OS << '\n';
730 }
731 
732 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
733                                     SmallString<128> &CrashDiagDir) {
734   using namespace llvm::sys;
735   assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
736          "Only knows about .crash files on Darwin");
737 
738   // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
739   // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
740   // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
741   path::home_directory(CrashDiagDir);
742   if (CrashDiagDir.startswith("/var/root"))
743     CrashDiagDir = "/";
744   path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
745   int PID =
746 #if LLVM_ON_UNIX
747       getpid();
748 #else
749       0;
750 #endif
751   std::error_code EC;
752   fs::file_status FileStatus;
753   TimePoint<> LastAccessTime;
754   SmallString<128> CrashFilePath;
755   // Lookup the .crash files and get the one generated by a subprocess spawned
756   // by this driver invocation.
757   for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
758        File != FileEnd && !EC; File.increment(EC)) {
759     StringRef FileName = path::filename(File->path());
760     if (!FileName.startswith(Name))
761       continue;
762     if (fs::status(File->path(), FileStatus))
763       continue;
764     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
765         llvm::MemoryBuffer::getFile(File->path());
766     if (!CrashFile)
767       continue;
768     // The first line should start with "Process:", otherwise this isn't a real
769     // .crash file.
770     StringRef Data = CrashFile.get()->getBuffer();
771     if (!Data.startswith("Process:"))
772       continue;
773     // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
774     size_t ParentProcPos = Data.find("Parent Process:");
775     if (ParentProcPos == StringRef::npos)
776       continue;
777     size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
778     if (LineEnd == StringRef::npos)
779       continue;
780     StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
781     int OpenBracket = -1, CloseBracket = -1;
782     for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
783       if (ParentProcess[i] == '[')
784         OpenBracket = i;
785       if (ParentProcess[i] == ']')
786         CloseBracket = i;
787     }
788     // Extract the parent process PID from the .crash file and check whether
789     // it matches this driver invocation pid.
790     int CrashPID;
791     if (OpenBracket < 0 || CloseBracket < 0 ||
792         ParentProcess.slice(OpenBracket + 1, CloseBracket)
793             .getAsInteger(10, CrashPID) || CrashPID != PID) {
794       continue;
795     }
796 
797     // Found a .crash file matching the driver pid. To avoid getting an older
798     // and misleading crash file, continue looking for the most recent.
799     // FIXME: the driver can dispatch multiple cc1 invocations, leading to
800     // multiple crashes poiting to the same parent process. Since the driver
801     // does not collect pid information for the dispatched invocation there's
802     // currently no way to distinguish among them.
803     const auto FileAccessTime = FileStatus.getLastModificationTime();
804     if (FileAccessTime > LastAccessTime) {
805       CrashFilePath.assign(File->path());
806       LastAccessTime = FileAccessTime;
807     }
808   }
809 
810   // If found, copy it over to the location of other reproducer files.
811   if (!CrashFilePath.empty()) {
812     EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
813     if (EC)
814       return false;
815     return true;
816   }
817 
818   return false;
819 }
820 
821 // When clang crashes, produce diagnostic information including the fully
822 // preprocessed source file(s).  Request that the developer attach the
823 // diagnostic information to a bug report.
824 void Driver::generateCompilationDiagnostics(Compilation &C,
825                                             const Command &FailingCommand) {
826   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
827     return;
828 
829   // Don't try to generate diagnostics for link or dsymutil jobs.
830   if (FailingCommand.getCreator().isLinkJob() ||
831       FailingCommand.getCreator().isDsymutilJob())
832     return;
833 
834   // Print the version of the compiler.
835   PrintVersion(C, llvm::errs());
836 
837   Diag(clang::diag::note_drv_command_failed_diag_msg)
838       << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
839          "crash backtrace, preprocessed source, and associated run script.";
840 
841   // Suppress driver output and emit preprocessor output to temp file.
842   Mode = CPPMode;
843   CCGenDiagnostics = true;
844 
845   // Save the original job command(s).
846   Command Cmd = FailingCommand;
847 
848   // Keep track of whether we produce any errors while trying to produce
849   // preprocessed sources.
850   DiagnosticErrorTrap Trap(Diags);
851 
852   // Suppress tool output.
853   C.initCompilationForDiagnostics();
854 
855   // Construct the list of inputs.
856   InputList Inputs;
857   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
858 
859   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
860     bool IgnoreInput = false;
861 
862     // Ignore input from stdin or any inputs that cannot be preprocessed.
863     // Check type first as not all linker inputs have a value.
864     if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
865       IgnoreInput = true;
866     } else if (!strcmp(it->second->getValue(), "-")) {
867       Diag(clang::diag::note_drv_command_failed_diag_msg)
868           << "Error generating preprocessed source(s) - "
869              "ignoring input from stdin.";
870       IgnoreInput = true;
871     }
872 
873     if (IgnoreInput) {
874       it = Inputs.erase(it);
875       ie = Inputs.end();
876     } else {
877       ++it;
878     }
879   }
880 
881   if (Inputs.empty()) {
882     Diag(clang::diag::note_drv_command_failed_diag_msg)
883         << "Error generating preprocessed source(s) - "
884            "no preprocessable inputs.";
885     return;
886   }
887 
888   // Don't attempt to generate preprocessed files if multiple -arch options are
889   // used, unless they're all duplicates.
890   llvm::StringSet<> ArchNames;
891   for (const Arg *A : C.getArgs()) {
892     if (A->getOption().matches(options::OPT_arch)) {
893       StringRef ArchName = A->getValue();
894       ArchNames.insert(ArchName);
895     }
896   }
897   if (ArchNames.size() > 1) {
898     Diag(clang::diag::note_drv_command_failed_diag_msg)
899         << "Error generating preprocessed source(s) - cannot generate "
900            "preprocessed source with multiple -arch options.";
901     return;
902   }
903 
904   // Construct the list of abstract actions to perform for this compilation. On
905   // Darwin OSes this uses the driver-driver and builds universal actions.
906   const ToolChain &TC = C.getDefaultToolChain();
907   if (TC.getTriple().isOSBinFormatMachO())
908     BuildUniversalActions(C, TC, Inputs);
909   else
910     BuildActions(C, C.getArgs(), Inputs, C.getActions());
911 
912   BuildJobs(C);
913 
914   // If there were errors building the compilation, quit now.
915   if (Trap.hasErrorOccurred()) {
916     Diag(clang::diag::note_drv_command_failed_diag_msg)
917         << "Error generating preprocessed source(s).";
918     return;
919   }
920 
921   // Generate preprocessed output.
922   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
923   C.ExecuteJobs(C.getJobs(), FailingCommands);
924 
925   // If any of the preprocessing commands failed, clean up and exit.
926   if (!FailingCommands.empty()) {
927     if (!isSaveTempsEnabled())
928       C.CleanupFileList(C.getTempFiles(), true);
929 
930     Diag(clang::diag::note_drv_command_failed_diag_msg)
931         << "Error generating preprocessed source(s).";
932     return;
933   }
934 
935   const ArgStringList &TempFiles = C.getTempFiles();
936   if (TempFiles.empty()) {
937     Diag(clang::diag::note_drv_command_failed_diag_msg)
938         << "Error generating preprocessed source(s).";
939     return;
940   }
941 
942   Diag(clang::diag::note_drv_command_failed_diag_msg)
943       << "\n********************\n\n"
944          "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
945          "Preprocessed source(s) and associated run script(s) are located at:";
946 
947   SmallString<128> VFS;
948   SmallString<128> ReproCrashFilename;
949   for (const char *TempFile : TempFiles) {
950     Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
951     if (ReproCrashFilename.empty()) {
952       ReproCrashFilename = TempFile;
953       llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
954     }
955     if (StringRef(TempFile).endswith(".cache")) {
956       // In some cases (modules) we'll dump extra data to help with reproducing
957       // the crash into a directory next to the output.
958       VFS = llvm::sys::path::filename(TempFile);
959       llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
960     }
961   }
962 
963   // Assume associated files are based off of the first temporary file.
964   CrashReportInfo CrashInfo(TempFiles[0], VFS);
965 
966   std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
967   std::error_code EC;
968   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
969   if (EC) {
970     Diag(clang::diag::note_drv_command_failed_diag_msg)
971         << "Error generating run script: " + Script + " " + EC.message();
972   } else {
973     ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
974              << "# Driver args: ";
975     printArgList(ScriptOS, C.getInputArgs());
976     ScriptOS << "# Original command: ";
977     Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
978     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
979     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
980   }
981 
982   // On darwin, provide information about the .crash diagnostic report.
983   if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
984     SmallString<128> CrashDiagDir;
985     if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
986       Diag(clang::diag::note_drv_command_failed_diag_msg)
987           << ReproCrashFilename.str();
988     } else { // Suggest a directory for the user to look for .crash files.
989       llvm::sys::path::append(CrashDiagDir, Name);
990       CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
991       Diag(clang::diag::note_drv_command_failed_diag_msg)
992           << "Crash backtrace is located in";
993       Diag(clang::diag::note_drv_command_failed_diag_msg)
994           << CrashDiagDir.str();
995       Diag(clang::diag::note_drv_command_failed_diag_msg)
996           << "(choose the .crash file that corresponds to your crash)";
997     }
998   }
999 
1000   for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1001                                             options::OPT_frewrite_map_file_EQ))
1002     Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1003 
1004   Diag(clang::diag::note_drv_command_failed_diag_msg)
1005       << "\n\n********************";
1006 }
1007 
1008 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1009   // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
1010   // if the tool does not support response files, there is a chance/ that things
1011   // will just work without a response file, so we silently just skip it.
1012   if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1013       llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
1014     return;
1015 
1016   std::string TmpName = GetTemporaryPath("response", "txt");
1017   Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1018 }
1019 
1020 int Driver::ExecuteCompilation(
1021     Compilation &C,
1022     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1023   // Just print if -### was present.
1024   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1025     C.getJobs().Print(llvm::errs(), "\n", true);
1026     return 0;
1027   }
1028 
1029   // If there were errors building the compilation, quit now.
1030   if (Diags.hasErrorOccurred())
1031     return 1;
1032 
1033   // Set up response file names for each command, if necessary
1034   for (auto &Job : C.getJobs())
1035     setUpResponseFiles(C, Job);
1036 
1037   C.ExecuteJobs(C.getJobs(), FailingCommands);
1038 
1039   // Remove temp files.
1040   C.CleanupFileList(C.getTempFiles());
1041 
1042   // If the command succeeded, we are done.
1043   if (FailingCommands.empty())
1044     return 0;
1045 
1046   // Otherwise, remove result files and print extra information about abnormal
1047   // failures.
1048   for (const auto &CmdPair : FailingCommands) {
1049     int Res = CmdPair.first;
1050     const Command *FailingCommand = CmdPair.second;
1051 
1052     // Remove result files if we're not saving temps.
1053     if (!isSaveTempsEnabled()) {
1054       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1055       C.CleanupFileMap(C.getResultFiles(), JA, true);
1056 
1057       // Failure result files are valid unless we crashed.
1058       if (Res < 0)
1059         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1060     }
1061 
1062     // Print extra information about abnormal failures, if possible.
1063     //
1064     // This is ad-hoc, but we don't want to be excessively noisy. If the result
1065     // status was 1, assume the command failed normally. In particular, if it
1066     // was the compiler then assume it gave a reasonable error code. Failures
1067     // in other tools are less common, and they generally have worse
1068     // diagnostics, so always print the diagnostic there.
1069     const Tool &FailingTool = FailingCommand->getCreator();
1070 
1071     if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1072       // FIXME: See FIXME above regarding result code interpretation.
1073       if (Res < 0)
1074         Diag(clang::diag::err_drv_command_signalled)
1075             << FailingTool.getShortName();
1076       else
1077         Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1078                                                   << Res;
1079     }
1080   }
1081   return 0;
1082 }
1083 
1084 void Driver::PrintHelp(bool ShowHidden) const {
1085   unsigned IncludedFlagsBitmask;
1086   unsigned ExcludedFlagsBitmask;
1087   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1088       getIncludeExcludeOptionFlagMasks();
1089 
1090   ExcludedFlagsBitmask |= options::NoDriverOption;
1091   if (!ShowHidden)
1092     ExcludedFlagsBitmask |= HelpHidden;
1093 
1094   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1095                       IncludedFlagsBitmask, ExcludedFlagsBitmask);
1096 }
1097 
1098 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1099   // FIXME: The following handlers should use a callback mechanism, we don't
1100   // know what the client would like to do.
1101   OS << getClangFullVersion() << '\n';
1102   const ToolChain &TC = C.getDefaultToolChain();
1103   OS << "Target: " << TC.getTripleString() << '\n';
1104 
1105   // Print the threading model.
1106   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1107     // Don't print if the ToolChain would have barfed on it already
1108     if (TC.isThreadModelSupported(A->getValue()))
1109       OS << "Thread model: " << A->getValue();
1110   } else
1111     OS << "Thread model: " << TC.getThreadModel();
1112   OS << '\n';
1113 
1114   // Print out the install directory.
1115   OS << "InstalledDir: " << InstalledDir << '\n';
1116 }
1117 
1118 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1119 /// option.
1120 static void PrintDiagnosticCategories(raw_ostream &OS) {
1121   // Skip the empty category.
1122   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1123        ++i)
1124     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1125 }
1126 
1127 bool Driver::HandleImmediateArgs(const Compilation &C) {
1128   // The order these options are handled in gcc is all over the place, but we
1129   // don't expect inconsistencies w.r.t. that to matter in practice.
1130 
1131   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1132     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1133     return false;
1134   }
1135 
1136   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1137     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1138     // return an answer which matches our definition of __VERSION__.
1139     //
1140     // If we want to return a more correct answer some day, then we should
1141     // introduce a non-pedantically GCC compatible mode to Clang in which we
1142     // provide sensible definitions for -dumpversion, __VERSION__, etc.
1143     llvm::outs() << "4.2.1\n";
1144     return false;
1145   }
1146 
1147   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1148     PrintDiagnosticCategories(llvm::outs());
1149     return false;
1150   }
1151 
1152   if (C.getArgs().hasArg(options::OPT_help) ||
1153       C.getArgs().hasArg(options::OPT__help_hidden)) {
1154     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1155     return false;
1156   }
1157 
1158   if (C.getArgs().hasArg(options::OPT__version)) {
1159     // Follow gcc behavior and use stdout for --version and stderr for -v.
1160     PrintVersion(C, llvm::outs());
1161     return false;
1162   }
1163 
1164   if (C.getArgs().hasArg(options::OPT_v) ||
1165       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1166     PrintVersion(C, llvm::errs());
1167     SuppressMissingInputWarning = true;
1168   }
1169 
1170   const ToolChain &TC = C.getDefaultToolChain();
1171 
1172   if (C.getArgs().hasArg(options::OPT_v))
1173     TC.printVerboseInfo(llvm::errs());
1174 
1175   if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1176     llvm::outs() << ResourceDir << '\n';
1177     return false;
1178   }
1179 
1180   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1181     llvm::outs() << "programs: =";
1182     bool separator = false;
1183     for (const std::string &Path : TC.getProgramPaths()) {
1184       if (separator)
1185         llvm::outs() << ':';
1186       llvm::outs() << Path;
1187       separator = true;
1188     }
1189     llvm::outs() << "\n";
1190     llvm::outs() << "libraries: =" << ResourceDir;
1191 
1192     StringRef sysroot = C.getSysRoot();
1193 
1194     for (const std::string &Path : TC.getFilePaths()) {
1195       // Always print a separator. ResourceDir was the first item shown.
1196       llvm::outs() << ':';
1197       // Interpretation of leading '=' is needed only for NetBSD.
1198       if (Path[0] == '=')
1199         llvm::outs() << sysroot << Path.substr(1);
1200       else
1201         llvm::outs() << Path;
1202     }
1203     llvm::outs() << "\n";
1204     return false;
1205   }
1206 
1207   // FIXME: The following handlers should use a callback mechanism, we don't
1208   // know what the client would like to do.
1209   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1210     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1211     return false;
1212   }
1213 
1214   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1215     llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
1216     return false;
1217   }
1218 
1219   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1220     // Print out all options that start with a given argument. This is used for
1221     // shell autocompletion.
1222     llvm::outs() << llvm::join(Opts->findByPrefix(A->getValue()), " ") << '\n';
1223     return false;
1224   }
1225 
1226   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1227     ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1228     switch (RLT) {
1229     case ToolChain::RLT_CompilerRT:
1230       llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1231       break;
1232     case ToolChain::RLT_Libgcc:
1233       llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1234       break;
1235     }
1236     return false;
1237   }
1238 
1239   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1240     for (const Multilib &Multilib : TC.getMultilibs())
1241       llvm::outs() << Multilib << "\n";
1242     return false;
1243   }
1244 
1245   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1246     for (const Multilib &Multilib : TC.getMultilibs()) {
1247       if (Multilib.gccSuffix().empty())
1248         llvm::outs() << ".\n";
1249       else {
1250         StringRef Suffix(Multilib.gccSuffix());
1251         assert(Suffix.front() == '/');
1252         llvm::outs() << Suffix.substr(1) << "\n";
1253       }
1254     }
1255     return false;
1256   }
1257   return true;
1258 }
1259 
1260 // Display an action graph human-readably.  Action A is the "sink" node
1261 // and latest-occuring action. Traversal is in pre-order, visiting the
1262 // inputs to each action before printing the action itself.
1263 static unsigned PrintActions1(const Compilation &C, Action *A,
1264                               std::map<Action *, unsigned> &Ids) {
1265   if (Ids.count(A)) // A was already visited.
1266     return Ids[A];
1267 
1268   std::string str;
1269   llvm::raw_string_ostream os(str);
1270 
1271   os << Action::getClassName(A->getKind()) << ", ";
1272   if (InputAction *IA = dyn_cast<InputAction>(A)) {
1273     os << "\"" << IA->getInputArg().getValue() << "\"";
1274   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1275     os << '"' << BIA->getArchName() << '"' << ", {"
1276        << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1277   } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1278     bool IsFirst = true;
1279     OA->doOnEachDependence(
1280         [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1281           // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1282           // sm_35 this will generate:
1283           // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1284           // (nvptx64-nvidia-cuda:sm_35) {#ID}
1285           if (!IsFirst)
1286             os << ", ";
1287           os << '"';
1288           if (TC)
1289             os << A->getOffloadingKindPrefix();
1290           else
1291             os << "host";
1292           os << " (";
1293           os << TC->getTriple().normalize();
1294 
1295           if (BoundArch)
1296             os << ":" << BoundArch;
1297           os << ")";
1298           os << '"';
1299           os << " {" << PrintActions1(C, A, Ids) << "}";
1300           IsFirst = false;
1301         });
1302   } else {
1303     const ActionList *AL = &A->getInputs();
1304 
1305     if (AL->size()) {
1306       const char *Prefix = "{";
1307       for (Action *PreRequisite : *AL) {
1308         os << Prefix << PrintActions1(C, PreRequisite, Ids);
1309         Prefix = ", ";
1310       }
1311       os << "}";
1312     } else
1313       os << "{}";
1314   }
1315 
1316   // Append offload info for all options other than the offloading action
1317   // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1318   std::string offload_str;
1319   llvm::raw_string_ostream offload_os(offload_str);
1320   if (!isa<OffloadAction>(A)) {
1321     auto S = A->getOffloadingKindPrefix();
1322     if (!S.empty()) {
1323       offload_os << ", (" << S;
1324       if (A->getOffloadingArch())
1325         offload_os << ", " << A->getOffloadingArch();
1326       offload_os << ")";
1327     }
1328   }
1329 
1330   unsigned Id = Ids.size();
1331   Ids[A] = Id;
1332   llvm::errs() << Id << ": " << os.str() << ", "
1333                << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1334 
1335   return Id;
1336 }
1337 
1338 // Print the action graphs in a compilation C.
1339 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1340 void Driver::PrintActions(const Compilation &C) const {
1341   std::map<Action *, unsigned> Ids;
1342   for (Action *A : C.getActions())
1343     PrintActions1(C, A, Ids);
1344 }
1345 
1346 /// \brief Check whether the given input tree contains any compilation or
1347 /// assembly actions.
1348 static bool ContainsCompileOrAssembleAction(const Action *A) {
1349   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1350       isa<AssembleJobAction>(A))
1351     return true;
1352 
1353   for (const Action *Input : A->inputs())
1354     if (ContainsCompileOrAssembleAction(Input))
1355       return true;
1356 
1357   return false;
1358 }
1359 
1360 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1361                                    const InputList &BAInputs) const {
1362   DerivedArgList &Args = C.getArgs();
1363   ActionList &Actions = C.getActions();
1364   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1365   // Collect the list of architectures. Duplicates are allowed, but should only
1366   // be handled once (in the order seen).
1367   llvm::StringSet<> ArchNames;
1368   SmallVector<const char *, 4> Archs;
1369   for (Arg *A : Args) {
1370     if (A->getOption().matches(options::OPT_arch)) {
1371       // Validate the option here; we don't save the type here because its
1372       // particular spelling may participate in other driver choices.
1373       llvm::Triple::ArchType Arch =
1374           tools::darwin::getArchTypeForMachOArchName(A->getValue());
1375       if (Arch == llvm::Triple::UnknownArch) {
1376         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1377         continue;
1378       }
1379 
1380       A->claim();
1381       if (ArchNames.insert(A->getValue()).second)
1382         Archs.push_back(A->getValue());
1383     }
1384   }
1385 
1386   // When there is no explicit arch for this platform, make sure we still bind
1387   // the architecture (to the default) so that -Xarch_ is handled correctly.
1388   if (!Archs.size())
1389     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1390 
1391   ActionList SingleActions;
1392   BuildActions(C, Args, BAInputs, SingleActions);
1393 
1394   // Add in arch bindings for every top level action, as well as lipo and
1395   // dsymutil steps if needed.
1396   for (Action* Act : SingleActions) {
1397     // Make sure we can lipo this kind of output. If not (and it is an actual
1398     // output) then we disallow, since we can't create an output file with the
1399     // right name without overwriting it. We could remove this oddity by just
1400     // changing the output names to include the arch, which would also fix
1401     // -save-temps. Compatibility wins for now.
1402 
1403     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1404       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1405           << types::getTypeName(Act->getType());
1406 
1407     ActionList Inputs;
1408     for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1409       Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1410 
1411     // Lipo if necessary, we do it this way because we need to set the arch flag
1412     // so that -Xarch_ gets overwritten.
1413     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1414       Actions.append(Inputs.begin(), Inputs.end());
1415     else
1416       Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1417 
1418     // Handle debug info queries.
1419     Arg *A = Args.getLastArg(options::OPT_g_Group);
1420     if (A && !A->getOption().matches(options::OPT_g0) &&
1421         !A->getOption().matches(options::OPT_gstabs) &&
1422         ContainsCompileOrAssembleAction(Actions.back())) {
1423 
1424       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1425       // have a compile input. We need to run 'dsymutil' ourselves in such cases
1426       // because the debug info will refer to a temporary object file which
1427       // will be removed at the end of the compilation process.
1428       if (Act->getType() == types::TY_Image) {
1429         ActionList Inputs;
1430         Inputs.push_back(Actions.back());
1431         Actions.pop_back();
1432         Actions.push_back(
1433             C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1434       }
1435 
1436       // Verify the debug info output.
1437       if (Args.hasArg(options::OPT_verify_debug_info)) {
1438         Action* LastAction = Actions.back();
1439         Actions.pop_back();
1440         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1441             LastAction, types::TY_Nothing));
1442       }
1443     }
1444   }
1445 }
1446 
1447 /// \brief Check that the file referenced by Value exists. If it doesn't,
1448 /// issue a diagnostic and return false.
1449 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1450                                    StringRef Value, types::ID Ty) {
1451   if (!D.getCheckInputsExist())
1452     return true;
1453 
1454   // stdin always exists.
1455   if (Value == "-")
1456     return true;
1457 
1458   SmallString<64> Path(Value);
1459   if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1460     if (!llvm::sys::path::is_absolute(Path)) {
1461       SmallString<64> Directory(WorkDir->getValue());
1462       llvm::sys::path::append(Directory, Value);
1463       Path.assign(Directory);
1464     }
1465   }
1466 
1467   if (llvm::sys::fs::exists(Twine(Path)))
1468     return true;
1469 
1470   if (D.IsCLMode()) {
1471     if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1472         llvm::sys::Process::FindInEnvPath("LIB", Value))
1473       return true;
1474 
1475     if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1476       // Arguments to the /link flag might cause the linker to search for object
1477       // and library files in paths we don't know about. Don't error in such
1478       // cases.
1479       return true;
1480     }
1481   }
1482 
1483   D.Diag(clang::diag::err_drv_no_such_file) << Path;
1484   return false;
1485 }
1486 
1487 // Construct a the list of inputs and their types.
1488 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1489                          InputList &Inputs) const {
1490   // Track the current user specified (-x) input. We also explicitly track the
1491   // argument used to set the type; we only want to claim the type when we
1492   // actually use it, so we warn about unused -x arguments.
1493   types::ID InputType = types::TY_Nothing;
1494   Arg *InputTypeArg = nullptr;
1495 
1496   // The last /TC or /TP option sets the input type to C or C++ globally.
1497   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1498                                          options::OPT__SLASH_TP)) {
1499     InputTypeArg = TCTP;
1500     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1501                     ? types::TY_C
1502                     : types::TY_CXX;
1503 
1504     Arg *Previous = nullptr;
1505     bool ShowNote = false;
1506     for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1507       if (Previous) {
1508         Diag(clang::diag::warn_drv_overriding_flag_option)
1509           << Previous->getSpelling() << A->getSpelling();
1510         ShowNote = true;
1511       }
1512       Previous = A;
1513     }
1514     if (ShowNote)
1515       Diag(clang::diag::note_drv_t_option_is_global);
1516 
1517     // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1518     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1519   }
1520 
1521   for (Arg *A : Args) {
1522     if (A->getOption().getKind() == Option::InputClass) {
1523       const char *Value = A->getValue();
1524       types::ID Ty = types::TY_INVALID;
1525 
1526       // Infer the input type if necessary.
1527       if (InputType == types::TY_Nothing) {
1528         // If there was an explicit arg for this, claim it.
1529         if (InputTypeArg)
1530           InputTypeArg->claim();
1531 
1532         // stdin must be handled specially.
1533         if (memcmp(Value, "-", 2) == 0) {
1534           // If running with -E, treat as a C input (this changes the builtin
1535           // macros, for example). This may be overridden by -ObjC below.
1536           //
1537           // Otherwise emit an error but still use a valid type to avoid
1538           // spurious errors (e.g., no inputs).
1539           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1540             Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1541                             : clang::diag::err_drv_unknown_stdin_type);
1542           Ty = types::TY_C;
1543         } else {
1544           // Otherwise lookup by extension.
1545           // Fallback is C if invoked as C preprocessor or Object otherwise.
1546           // We use a host hook here because Darwin at least has its own
1547           // idea of what .s is.
1548           if (const char *Ext = strrchr(Value, '.'))
1549             Ty = TC.LookupTypeForExtension(Ext + 1);
1550 
1551           if (Ty == types::TY_INVALID) {
1552             if (CCCIsCPP())
1553               Ty = types::TY_C;
1554             else
1555               Ty = types::TY_Object;
1556           }
1557 
1558           // If the driver is invoked as C++ compiler (like clang++ or c++) it
1559           // should autodetect some input files as C++ for g++ compatibility.
1560           if (CCCIsCXX()) {
1561             types::ID OldTy = Ty;
1562             Ty = types::lookupCXXTypeForCType(Ty);
1563 
1564             if (Ty != OldTy)
1565               Diag(clang::diag::warn_drv_treating_input_as_cxx)
1566                   << getTypeName(OldTy) << getTypeName(Ty);
1567           }
1568         }
1569 
1570         // -ObjC and -ObjC++ override the default language, but only for "source
1571         // files". We just treat everything that isn't a linker input as a
1572         // source file.
1573         //
1574         // FIXME: Clean this up if we move the phase sequence into the type.
1575         if (Ty != types::TY_Object) {
1576           if (Args.hasArg(options::OPT_ObjC))
1577             Ty = types::TY_ObjC;
1578           else if (Args.hasArg(options::OPT_ObjCXX))
1579             Ty = types::TY_ObjCXX;
1580         }
1581       } else {
1582         assert(InputTypeArg && "InputType set w/o InputTypeArg");
1583         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1584           // If emulating cl.exe, make sure that /TC and /TP don't affect input
1585           // object files.
1586           const char *Ext = strrchr(Value, '.');
1587           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1588             Ty = types::TY_Object;
1589         }
1590         if (Ty == types::TY_INVALID) {
1591           Ty = InputType;
1592           InputTypeArg->claim();
1593         }
1594       }
1595 
1596       if (DiagnoseInputExistence(*this, Args, Value, Ty))
1597         Inputs.push_back(std::make_pair(Ty, A));
1598 
1599     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1600       StringRef Value = A->getValue();
1601       if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1602         Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1603         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1604       }
1605       A->claim();
1606     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1607       StringRef Value = A->getValue();
1608       if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1609         Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
1610         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1611       }
1612       A->claim();
1613     } else if (A->getOption().hasFlag(options::LinkerInput)) {
1614       // Just treat as object type, we could make a special type for this if
1615       // necessary.
1616       Inputs.push_back(std::make_pair(types::TY_Object, A));
1617 
1618     } else if (A->getOption().matches(options::OPT_x)) {
1619       InputTypeArg = A;
1620       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1621       A->claim();
1622 
1623       // Follow gcc behavior and treat as linker input for invalid -x
1624       // options. Its not clear why we shouldn't just revert to unknown; but
1625       // this isn't very important, we might as well be bug compatible.
1626       if (!InputType) {
1627         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1628         InputType = types::TY_Object;
1629       }
1630     } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1631       assert(A->getNumValues() == 1 && "The /U option has one value.");
1632       StringRef Val = A->getValue(0);
1633       if (Val.find_first_of("/\\") != StringRef::npos) {
1634         // Warn about e.g. "/Users/me/myfile.c".
1635         Diag(diag::warn_slash_u_filename) << Val;
1636         Diag(diag::note_use_dashdash);
1637       }
1638     }
1639   }
1640   if (CCCIsCPP() && Inputs.empty()) {
1641     // If called as standalone preprocessor, stdin is processed
1642     // if no other input is present.
1643     Arg *A = MakeInputArg(Args, *Opts, "-");
1644     Inputs.push_back(std::make_pair(types::TY_C, A));
1645   }
1646 }
1647 
1648 namespace {
1649 /// Provides a convenient interface for different programming models to generate
1650 /// the required device actions.
1651 class OffloadingActionBuilder final {
1652   /// Flag used to trace errors in the builder.
1653   bool IsValid = false;
1654 
1655   /// The compilation that is using this builder.
1656   Compilation &C;
1657 
1658   /// Map between an input argument and the offload kinds used to process it.
1659   std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1660 
1661   /// Builder interface. It doesn't build anything or keep any state.
1662   class DeviceActionBuilder {
1663   public:
1664     typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1665 
1666     enum ActionBuilderReturnCode {
1667       // The builder acted successfully on the current action.
1668       ABRT_Success,
1669       // The builder didn't have to act on the current action.
1670       ABRT_Inactive,
1671       // The builder was successful and requested the host action to not be
1672       // generated.
1673       ABRT_Ignore_Host,
1674     };
1675 
1676   protected:
1677     /// Compilation associated with this builder.
1678     Compilation &C;
1679 
1680     /// Tool chains associated with this builder. The same programming
1681     /// model may have associated one or more tool chains.
1682     SmallVector<const ToolChain *, 2> ToolChains;
1683 
1684     /// The derived arguments associated with this builder.
1685     DerivedArgList &Args;
1686 
1687     /// The inputs associated with this builder.
1688     const Driver::InputList &Inputs;
1689 
1690     /// The associated offload kind.
1691     Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1692 
1693   public:
1694     DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1695                         const Driver::InputList &Inputs,
1696                         Action::OffloadKind AssociatedOffloadKind)
1697         : C(C), Args(Args), Inputs(Inputs),
1698           AssociatedOffloadKind(AssociatedOffloadKind) {}
1699     virtual ~DeviceActionBuilder() {}
1700 
1701     /// Fill up the array \a DA with all the device dependences that should be
1702     /// added to the provided host action \a HostAction. By default it is
1703     /// inactive.
1704     virtual ActionBuilderReturnCode
1705     getDeviceDependences(OffloadAction::DeviceDependences &DA,
1706                          phases::ID CurPhase, phases::ID FinalPhase,
1707                          PhasesTy &Phases) {
1708       return ABRT_Inactive;
1709     }
1710 
1711     /// Update the state to include the provided host action \a HostAction as a
1712     /// dependency of the current device action. By default it is inactive.
1713     virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1714       return ABRT_Inactive;
1715     }
1716 
1717     /// Append top level actions generated by the builder. Return true if errors
1718     /// were found.
1719     virtual void appendTopLevelActions(ActionList &AL) {}
1720 
1721     /// Append linker actions generated by the builder. Return true if errors
1722     /// were found.
1723     virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1724 
1725     /// Initialize the builder. Return true if any initialization errors are
1726     /// found.
1727     virtual bool initialize() { return false; }
1728 
1729     /// Return true if the builder can use bundling/unbundling.
1730     virtual bool canUseBundlerUnbundler() const { return false; }
1731 
1732     /// Return true if this builder is valid. We have a valid builder if we have
1733     /// associated device tool chains.
1734     bool isValid() { return !ToolChains.empty(); }
1735 
1736     /// Return the associated offload kind.
1737     Action::OffloadKind getAssociatedOffloadKind() {
1738       return AssociatedOffloadKind;
1739     }
1740   };
1741 
1742   /// \brief CUDA action builder. It injects device code in the host backend
1743   /// action.
1744   class CudaActionBuilder final : public DeviceActionBuilder {
1745     /// Flags to signal if the user requested host-only or device-only
1746     /// compilation.
1747     bool CompileHostOnly = false;
1748     bool CompileDeviceOnly = false;
1749 
1750     /// List of GPU architectures to use in this compilation.
1751     SmallVector<CudaArch, 4> GpuArchList;
1752 
1753     /// The CUDA actions for the current input.
1754     ActionList CudaDeviceActions;
1755 
1756     /// The CUDA fat binary if it was generated for the current input.
1757     Action *CudaFatBinary = nullptr;
1758 
1759     /// Flag that is set to true if this builder acted on the current input.
1760     bool IsActive = false;
1761 
1762   public:
1763     CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1764                       const Driver::InputList &Inputs)
1765         : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1766 
1767     ActionBuilderReturnCode
1768     getDeviceDependences(OffloadAction::DeviceDependences &DA,
1769                          phases::ID CurPhase, phases::ID FinalPhase,
1770                          PhasesTy &Phases) override {
1771       if (!IsActive)
1772         return ABRT_Inactive;
1773 
1774       // If we don't have more CUDA actions, we don't have any dependences to
1775       // create for the host.
1776       if (CudaDeviceActions.empty())
1777         return ABRT_Success;
1778 
1779       assert(CudaDeviceActions.size() == GpuArchList.size() &&
1780              "Expecting one action per GPU architecture.");
1781       assert(!CompileHostOnly &&
1782              "Not expecting CUDA actions in host-only compilation.");
1783 
1784       // If we are generating code for the device or we are in a backend phase,
1785       // we attempt to generate the fat binary. We compile each arch to ptx and
1786       // assemble to cubin, then feed the cubin *and* the ptx into a device
1787       // "link" action, which uses fatbinary to combine these cubins into one
1788       // fatbin.  The fatbin is then an input to the host action if not in
1789       // device-only mode.
1790       if (CompileDeviceOnly || CurPhase == phases::Backend) {
1791         ActionList DeviceActions;
1792         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1793           // Produce the device action from the current phase up to the assemble
1794           // phase.
1795           for (auto Ph : Phases) {
1796             // Skip the phases that were already dealt with.
1797             if (Ph < CurPhase)
1798               continue;
1799             // We have to be consistent with the host final phase.
1800             if (Ph > FinalPhase)
1801               break;
1802 
1803             CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1804                 C, Args, Ph, CudaDeviceActions[I]);
1805 
1806             if (Ph == phases::Assemble)
1807               break;
1808           }
1809 
1810           // If we didn't reach the assemble phase, we can't generate the fat
1811           // binary. We don't need to generate the fat binary if we are not in
1812           // device-only mode.
1813           if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1814               CompileDeviceOnly)
1815             continue;
1816 
1817           Action *AssembleAction = CudaDeviceActions[I];
1818           assert(AssembleAction->getType() == types::TY_Object);
1819           assert(AssembleAction->getInputs().size() == 1);
1820 
1821           Action *BackendAction = AssembleAction->getInputs()[0];
1822           assert(BackendAction->getType() == types::TY_PP_Asm);
1823 
1824           for (auto &A : {AssembleAction, BackendAction}) {
1825             OffloadAction::DeviceDependences DDep;
1826             DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1827                      Action::OFK_Cuda);
1828             DeviceActions.push_back(
1829                 C.MakeAction<OffloadAction>(DDep, A->getType()));
1830           }
1831         }
1832 
1833         // We generate the fat binary if we have device input actions.
1834         if (!DeviceActions.empty()) {
1835           CudaFatBinary =
1836               C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1837 
1838           if (!CompileDeviceOnly) {
1839             DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1840                    Action::OFK_Cuda);
1841             // Clear the fat binary, it is already a dependence to an host
1842             // action.
1843             CudaFatBinary = nullptr;
1844           }
1845 
1846           // Remove the CUDA actions as they are already connected to an host
1847           // action or fat binary.
1848           CudaDeviceActions.clear();
1849         }
1850 
1851         // We avoid creating host action in device-only mode.
1852         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
1853       } else if (CurPhase > phases::Backend) {
1854         // If we are past the backend phase and still have a device action, we
1855         // don't have to do anything as this action is already a device
1856         // top-level action.
1857         return ABRT_Success;
1858       }
1859 
1860       assert(CurPhase < phases::Backend && "Generating single CUDA "
1861                                            "instructions should only occur "
1862                                            "before the backend phase!");
1863 
1864       // By default, we produce an action for each device arch.
1865       for (Action *&A : CudaDeviceActions)
1866         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1867 
1868       return ABRT_Success;
1869     }
1870 
1871     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1872       // While generating code for CUDA, we only depend on the host input action
1873       // to trigger the creation of all the CUDA device actions.
1874 
1875       // If we are dealing with an input action, replicate it for each GPU
1876       // architecture. If we are in host-only mode we return 'success' so that
1877       // the host uses the CUDA offload kind.
1878       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1879         assert(!GpuArchList.empty() &&
1880                "We should have at least one GPU architecture.");
1881 
1882         // If the host input is not CUDA, we don't need to bother about this
1883         // input.
1884         if (IA->getType() != types::TY_CUDA) {
1885           // The builder will ignore this input.
1886           IsActive = false;
1887           return ABRT_Inactive;
1888         }
1889 
1890         // Set the flag to true, so that the builder acts on the current input.
1891         IsActive = true;
1892 
1893         if (CompileHostOnly)
1894           return ABRT_Success;
1895 
1896         // Replicate inputs for each GPU architecture.
1897         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1898           CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1899               IA->getInputArg(), types::TY_CUDA_DEVICE));
1900 
1901         return ABRT_Success;
1902       }
1903 
1904       return IsActive ? ABRT_Success : ABRT_Inactive;
1905     }
1906 
1907     void appendTopLevelActions(ActionList &AL) override {
1908       // Utility to append actions to the top level list.
1909       auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1910         OffloadAction::DeviceDependences Dep;
1911         Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1912                 Action::OFK_Cuda);
1913         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1914       };
1915 
1916       // If we have a fat binary, add it to the list.
1917       if (CudaFatBinary) {
1918         AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1919         CudaDeviceActions.clear();
1920         CudaFatBinary = nullptr;
1921         return;
1922       }
1923 
1924       if (CudaDeviceActions.empty())
1925         return;
1926 
1927       // If we have CUDA actions at this point, that's because we have a have
1928       // partial compilation, so we should have an action for each GPU
1929       // architecture.
1930       assert(CudaDeviceActions.size() == GpuArchList.size() &&
1931              "Expecting one action per GPU architecture.");
1932       assert(ToolChains.size() == 1 &&
1933              "Expecting to have a sing CUDA toolchain.");
1934       for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1935         AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1936 
1937       CudaDeviceActions.clear();
1938     }
1939 
1940     bool initialize() override {
1941       // We don't need to support CUDA.
1942       if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1943         return false;
1944 
1945       const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1946       assert(HostTC && "No toolchain for host compilation.");
1947       if (HostTC->getTriple().isNVPTX()) {
1948         // We do not support targeting NVPTX for host compilation. Throw
1949         // an error and abort pipeline construction early so we don't trip
1950         // asserts that assume device-side compilation.
1951         C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1952         return true;
1953       }
1954 
1955       ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1956 
1957       Arg *PartialCompilationArg = Args.getLastArg(
1958           options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1959           options::OPT_cuda_compile_host_device);
1960       CompileHostOnly = PartialCompilationArg &&
1961                         PartialCompilationArg->getOption().matches(
1962                             options::OPT_cuda_host_only);
1963       CompileDeviceOnly = PartialCompilationArg &&
1964                           PartialCompilationArg->getOption().matches(
1965                               options::OPT_cuda_device_only);
1966 
1967       // Collect all cuda_gpu_arch parameters, removing duplicates.
1968       std::set<CudaArch> GpuArchs;
1969       bool Error = false;
1970       for (Arg *A : Args) {
1971         if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
1972               A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
1973           continue;
1974         A->claim();
1975 
1976         const StringRef ArchStr = A->getValue();
1977         if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
1978             ArchStr == "all") {
1979           GpuArchs.clear();
1980           continue;
1981         }
1982         CudaArch Arch = StringToCudaArch(ArchStr);
1983         if (Arch == CudaArch::UNKNOWN) {
1984           C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1985           Error = true;
1986         } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1987           GpuArchs.insert(Arch);
1988         else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
1989           GpuArchs.erase(Arch);
1990         else
1991           llvm_unreachable("Unexpected option.");
1992       }
1993 
1994       // Collect list of GPUs remaining in the set.
1995       for (CudaArch Arch : GpuArchs)
1996         GpuArchList.push_back(Arch);
1997 
1998       // Default to sm_20 which is the lowest common denominator for
1999       // supported GPUs.  sm_20 code should work correctly, if
2000       // suboptimally, on all newer GPUs.
2001       if (GpuArchList.empty())
2002         GpuArchList.push_back(CudaArch::SM_20);
2003 
2004       return Error;
2005     }
2006   };
2007 
2008   /// OpenMP action builder. The host bitcode is passed to the device frontend
2009   /// and all the device linked images are passed to the host link phase.
2010   class OpenMPActionBuilder final : public DeviceActionBuilder {
2011     /// The OpenMP actions for the current input.
2012     ActionList OpenMPDeviceActions;
2013 
2014     /// The linker inputs obtained for each toolchain.
2015     SmallVector<ActionList, 8> DeviceLinkerInputs;
2016 
2017   public:
2018     OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2019                         const Driver::InputList &Inputs)
2020         : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2021 
2022     ActionBuilderReturnCode
2023     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2024                          phases::ID CurPhase, phases::ID FinalPhase,
2025                          PhasesTy &Phases) override {
2026 
2027       // We should always have an action for each input.
2028       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2029              "Number of OpenMP actions and toolchains do not match.");
2030 
2031       // The host only depends on device action in the linking phase, when all
2032       // the device images have to be embedded in the host image.
2033       if (CurPhase == phases::Link) {
2034         assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2035                "Toolchains and linker inputs sizes do not match.");
2036         auto LI = DeviceLinkerInputs.begin();
2037         for (auto *A : OpenMPDeviceActions) {
2038           LI->push_back(A);
2039           ++LI;
2040         }
2041 
2042         // We passed the device action as a host dependence, so we don't need to
2043         // do anything else with them.
2044         OpenMPDeviceActions.clear();
2045         return ABRT_Success;
2046       }
2047 
2048       // By default, we produce an action for each device arch.
2049       for (Action *&A : OpenMPDeviceActions)
2050         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2051 
2052       return ABRT_Success;
2053     }
2054 
2055     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2056 
2057       // If this is an input action replicate it for each OpenMP toolchain.
2058       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2059         OpenMPDeviceActions.clear();
2060         for (unsigned I = 0; I < ToolChains.size(); ++I)
2061           OpenMPDeviceActions.push_back(
2062               C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2063         return ABRT_Success;
2064       }
2065 
2066       // If this is an unbundling action use it as is for each OpenMP toolchain.
2067       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2068         OpenMPDeviceActions.clear();
2069         for (unsigned I = 0; I < ToolChains.size(); ++I) {
2070           OpenMPDeviceActions.push_back(UA);
2071           UA->registerDependentActionInfo(
2072               ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2073         }
2074         return ABRT_Success;
2075       }
2076 
2077       // When generating code for OpenMP we use the host compile phase result as
2078       // a dependence to the device compile phase so that it can learn what
2079       // declarations should be emitted. However, this is not the only use for
2080       // the host action, so we prevent it from being collapsed.
2081       if (isa<CompileJobAction>(HostAction)) {
2082         HostAction->setCannotBeCollapsedWithNextDependentAction();
2083         assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2084                "Toolchains and device action sizes do not match.");
2085         OffloadAction::HostDependence HDep(
2086             *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2087             /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2088         auto TC = ToolChains.begin();
2089         for (Action *&A : OpenMPDeviceActions) {
2090           assert(isa<CompileJobAction>(A));
2091           OffloadAction::DeviceDependences DDep;
2092           DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2093           A = C.MakeAction<OffloadAction>(HDep, DDep);
2094           ++TC;
2095         }
2096       }
2097       return ABRT_Success;
2098     }
2099 
2100     void appendTopLevelActions(ActionList &AL) override {
2101       if (OpenMPDeviceActions.empty())
2102         return;
2103 
2104       // We should always have an action for each input.
2105       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2106              "Number of OpenMP actions and toolchains do not match.");
2107 
2108       // Append all device actions followed by the proper offload action.
2109       auto TI = ToolChains.begin();
2110       for (auto *A : OpenMPDeviceActions) {
2111         OffloadAction::DeviceDependences Dep;
2112         Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2113         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2114         ++TI;
2115       }
2116       // We no longer need the action stored in this builder.
2117       OpenMPDeviceActions.clear();
2118     }
2119 
2120     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2121       assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2122              "Toolchains and linker inputs sizes do not match.");
2123 
2124       // Append a new link action for each device.
2125       auto TC = ToolChains.begin();
2126       for (auto &LI : DeviceLinkerInputs) {
2127         auto *DeviceLinkAction =
2128             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2129         DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2130                Action::OFK_OpenMP);
2131         ++TC;
2132       }
2133     }
2134 
2135     bool initialize() override {
2136       // Get the OpenMP toolchains. If we don't get any, the action builder will
2137       // know there is nothing to do related to OpenMP offloading.
2138       auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2139       for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2140            ++TI)
2141         ToolChains.push_back(TI->second);
2142 
2143       DeviceLinkerInputs.resize(ToolChains.size());
2144       return false;
2145     }
2146 
2147     bool canUseBundlerUnbundler() const override {
2148       // OpenMP should use bundled files whenever possible.
2149       return true;
2150     }
2151   };
2152 
2153   ///
2154   /// TODO: Add the implementation for other specialized builders here.
2155   ///
2156 
2157   /// Specialized builders being used by this offloading action builder.
2158   SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2159 
2160   /// Flag set to true if all valid builders allow file bundling/unbundling.
2161   bool CanUseBundler;
2162 
2163 public:
2164   OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2165                           const Driver::InputList &Inputs)
2166       : C(C) {
2167     // Create a specialized builder for each device toolchain.
2168 
2169     IsValid = true;
2170 
2171     // Create a specialized builder for CUDA.
2172     SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2173 
2174     // Create a specialized builder for OpenMP.
2175     SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2176 
2177     //
2178     // TODO: Build other specialized builders here.
2179     //
2180 
2181     // Initialize all the builders, keeping track of errors. If all valid
2182     // builders agree that we can use bundling, set the flag to true.
2183     unsigned ValidBuilders = 0u;
2184     unsigned ValidBuildersSupportingBundling = 0u;
2185     for (auto *SB : SpecializedBuilders) {
2186       IsValid = IsValid && !SB->initialize();
2187 
2188       // Update the counters if the builder is valid.
2189       if (SB->isValid()) {
2190         ++ValidBuilders;
2191         if (SB->canUseBundlerUnbundler())
2192           ++ValidBuildersSupportingBundling;
2193       }
2194     }
2195     CanUseBundler =
2196         ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
2197   }
2198 
2199   ~OffloadingActionBuilder() {
2200     for (auto *SB : SpecializedBuilders)
2201       delete SB;
2202   }
2203 
2204   /// Generate an action that adds device dependences (if any) to a host action.
2205   /// If no device dependence actions exist, just return the host action \a
2206   /// HostAction. If an error is found or if no builder requires the host action
2207   /// to be generated, return nullptr.
2208   Action *
2209   addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2210                                    phases::ID CurPhase, phases::ID FinalPhase,
2211                                    DeviceActionBuilder::PhasesTy &Phases) {
2212     if (!IsValid)
2213       return nullptr;
2214 
2215     if (SpecializedBuilders.empty())
2216       return HostAction;
2217 
2218     assert(HostAction && "Invalid host action!");
2219 
2220     OffloadAction::DeviceDependences DDeps;
2221     // Check if all the programming models agree we should not emit the host
2222     // action. Also, keep track of the offloading kinds employed.
2223     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2224     unsigned InactiveBuilders = 0u;
2225     unsigned IgnoringBuilders = 0u;
2226     for (auto *SB : SpecializedBuilders) {
2227       if (!SB->isValid()) {
2228         ++InactiveBuilders;
2229         continue;
2230       }
2231 
2232       auto RetCode =
2233           SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
2234 
2235       // If the builder explicitly says the host action should be ignored,
2236       // we need to increment the variable that tracks the builders that request
2237       // the host object to be ignored.
2238       if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2239         ++IgnoringBuilders;
2240 
2241       // Unless the builder was inactive for this action, we have to record the
2242       // offload kind because the host will have to use it.
2243       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2244         OffloadKind |= SB->getAssociatedOffloadKind();
2245     }
2246 
2247     // If all builders agree that the host object should be ignored, just return
2248     // nullptr.
2249     if (IgnoringBuilders &&
2250         SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2251       return nullptr;
2252 
2253     if (DDeps.getActions().empty())
2254       return HostAction;
2255 
2256     // We have dependences we need to bundle together. We use an offload action
2257     // for that.
2258     OffloadAction::HostDependence HDep(
2259         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2260         /*BoundArch=*/nullptr, DDeps);
2261     return C.MakeAction<OffloadAction>(HDep, DDeps);
2262   }
2263 
2264   /// Generate an action that adds a host dependence to a device action. The
2265   /// results will be kept in this action builder. Return true if an error was
2266   /// found.
2267   bool addHostDependenceToDeviceActions(Action *&HostAction,
2268                                         const Arg *InputArg) {
2269     if (!IsValid)
2270       return true;
2271 
2272     // If we are supporting bundling/unbundling and the current action is an
2273     // input action of non-source file, we replace the host action by the
2274     // unbundling action. The bundler tool has the logic to detect if an input
2275     // is a bundle or not and if the input is not a bundle it assumes it is a
2276     // host file. Therefore it is safe to create an unbundling action even if
2277     // the input is not a bundle.
2278     if (CanUseBundler && isa<InputAction>(HostAction) &&
2279         InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2280         !types::isSrcFile(HostAction->getType())) {
2281       auto UnbundlingHostAction =
2282           C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2283       UnbundlingHostAction->registerDependentActionInfo(
2284           C.getSingleOffloadToolChain<Action::OFK_Host>(),
2285           /*BoundArch=*/StringRef(), Action::OFK_Host);
2286       HostAction = UnbundlingHostAction;
2287     }
2288 
2289     assert(HostAction && "Invalid host action!");
2290 
2291     // Register the offload kinds that are used.
2292     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2293     for (auto *SB : SpecializedBuilders) {
2294       if (!SB->isValid())
2295         continue;
2296 
2297       auto RetCode = SB->addDeviceDepences(HostAction);
2298 
2299       // Host dependences for device actions are not compatible with that same
2300       // action being ignored.
2301       assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2302              "Host dependence not expected to be ignored.!");
2303 
2304       // Unless the builder was inactive for this action, we have to record the
2305       // offload kind because the host will have to use it.
2306       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2307         OffloadKind |= SB->getAssociatedOffloadKind();
2308     }
2309 
2310     return false;
2311   }
2312 
2313   /// Add the offloading top level actions to the provided action list. This
2314   /// function can replace the host action by a bundling action if the
2315   /// programming models allow it.
2316   bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2317                              const Arg *InputArg) {
2318     // Get the device actions to be appended.
2319     ActionList OffloadAL;
2320     for (auto *SB : SpecializedBuilders) {
2321       if (!SB->isValid())
2322         continue;
2323       SB->appendTopLevelActions(OffloadAL);
2324     }
2325 
2326     // If we can use the bundler, replace the host action by the bundling one in
2327     // the resulting list. Otherwise, just append the device actions.
2328     if (CanUseBundler && !OffloadAL.empty()) {
2329       // Add the host action to the list in order to create the bundling action.
2330       OffloadAL.push_back(HostAction);
2331 
2332       // We expect that the host action was just appended to the action list
2333       // before this method was called.
2334       assert(HostAction == AL.back() && "Host action not in the list??");
2335       HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2336       AL.back() = HostAction;
2337     } else
2338       AL.append(OffloadAL.begin(), OffloadAL.end());
2339 
2340     // Propagate to the current host action (if any) the offload information
2341     // associated with the current input.
2342     if (HostAction)
2343       HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2344                                            /*BoundArch=*/nullptr);
2345     return false;
2346   }
2347 
2348   /// Processes the host linker action. This currently consists of replacing it
2349   /// with an offload action if there are device link objects and propagate to
2350   /// the host action all the offload kinds used in the current compilation. The
2351   /// resulting action is returned.
2352   Action *processHostLinkAction(Action *HostAction) {
2353     // Add all the dependences from the device linking actions.
2354     OffloadAction::DeviceDependences DDeps;
2355     for (auto *SB : SpecializedBuilders) {
2356       if (!SB->isValid())
2357         continue;
2358 
2359       SB->appendLinkDependences(DDeps);
2360     }
2361 
2362     // Calculate all the offload kinds used in the current compilation.
2363     unsigned ActiveOffloadKinds = 0u;
2364     for (auto &I : InputArgToOffloadKindMap)
2365       ActiveOffloadKinds |= I.second;
2366 
2367     // If we don't have device dependencies, we don't have to create an offload
2368     // action.
2369     if (DDeps.getActions().empty()) {
2370       // Propagate all the active kinds to host action. Given that it is a link
2371       // action it is assumed to depend on all actions generated so far.
2372       HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2373                                            /*BoundArch=*/nullptr);
2374       return HostAction;
2375     }
2376 
2377     // Create the offload action with all dependences. When an offload action
2378     // is created the kinds are propagated to the host action, so we don't have
2379     // to do that explicitly here.
2380     OffloadAction::HostDependence HDep(
2381         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2382         /*BoundArch*/ nullptr, ActiveOffloadKinds);
2383     return C.MakeAction<OffloadAction>(HDep, DDeps);
2384   }
2385 };
2386 } // anonymous namespace.
2387 
2388 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2389                           const InputList &Inputs, ActionList &Actions) const {
2390   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
2391 
2392   if (!SuppressMissingInputWarning && Inputs.empty()) {
2393     Diag(clang::diag::err_drv_no_input_files);
2394     return;
2395   }
2396 
2397   Arg *FinalPhaseArg;
2398   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
2399 
2400   if (FinalPhase == phases::Link) {
2401     if (Args.hasArg(options::OPT_emit_llvm))
2402       Diag(clang::diag::err_drv_emit_llvm_link);
2403     if (IsCLMode() && LTOMode != LTOK_None &&
2404         !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2405       Diag(clang::diag::err_drv_lto_without_lld);
2406   }
2407 
2408   // Reject -Z* at the top level, these options should never have been exposed
2409   // by gcc.
2410   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
2411     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
2412 
2413   // Diagnose misuse of /Fo.
2414   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
2415     StringRef V = A->getValue();
2416     if (Inputs.size() > 1 && !V.empty() &&
2417         !llvm::sys::path::is_separator(V.back())) {
2418       // Check whether /Fo tries to name an output file for multiple inputs.
2419       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2420           << A->getSpelling() << V;
2421       Args.eraseArg(options::OPT__SLASH_Fo);
2422     }
2423   }
2424 
2425   // Diagnose misuse of /Fa.
2426   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2427     StringRef V = A->getValue();
2428     if (Inputs.size() > 1 && !V.empty() &&
2429         !llvm::sys::path::is_separator(V.back())) {
2430       // Check whether /Fa tries to name an asm file for multiple inputs.
2431       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
2432           << A->getSpelling() << V;
2433       Args.eraseArg(options::OPT__SLASH_Fa);
2434     }
2435   }
2436 
2437   // Diagnose misuse of /o.
2438   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2439     if (A->getValue()[0] == '\0') {
2440       // It has to have a value.
2441       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2442       Args.eraseArg(options::OPT__SLASH_o);
2443     }
2444   }
2445 
2446   // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2447   // * no filename after it
2448   // * both /Yc and /Yu passed but with different filenames
2449   // * corresponding file not also passed as /FI
2450   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2451   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2452   if (YcArg && YcArg->getValue()[0] == '\0') {
2453     Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2454     Args.eraseArg(options::OPT__SLASH_Yc);
2455     YcArg = nullptr;
2456   }
2457   if (YuArg && YuArg->getValue()[0] == '\0') {
2458     Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2459     Args.eraseArg(options::OPT__SLASH_Yu);
2460     YuArg = nullptr;
2461   }
2462   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2463     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2464     Args.eraseArg(options::OPT__SLASH_Yc);
2465     Args.eraseArg(options::OPT__SLASH_Yu);
2466     YcArg = YuArg = nullptr;
2467   }
2468   if (YcArg || YuArg) {
2469     StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2470     bool FoundMatchingInclude = false;
2471     for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2472       // FIXME: Do case-insensitive matching and consider / and \ as equal.
2473       if (Inc->getValue() == Val)
2474         FoundMatchingInclude = true;
2475     }
2476     if (!FoundMatchingInclude) {
2477       Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2478           << (YcArg ? YcArg : YuArg)->getSpelling();
2479       Args.eraseArg(options::OPT__SLASH_Yc);
2480       Args.eraseArg(options::OPT__SLASH_Yu);
2481       YcArg = YuArg = nullptr;
2482     }
2483   }
2484   if (YcArg && Inputs.size() > 1) {
2485     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2486     Args.eraseArg(options::OPT__SLASH_Yc);
2487     YcArg = nullptr;
2488   }
2489   if (Args.hasArg(options::OPT__SLASH_Y_)) {
2490     // /Y- disables all pch handling.  Rather than check for it everywhere,
2491     // just remove clang-cl pch-related flags here.
2492     Args.eraseArg(options::OPT__SLASH_Fp);
2493     Args.eraseArg(options::OPT__SLASH_Yc);
2494     Args.eraseArg(options::OPT__SLASH_Yu);
2495     YcArg = YuArg = nullptr;
2496   }
2497 
2498   // Builder to be used to build offloading actions.
2499   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
2500 
2501   // Construct the actions to perform.
2502   ActionList LinkerInputs;
2503 
2504   llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
2505   for (auto &I : Inputs) {
2506     types::ID InputType = I.first;
2507     const Arg *InputArg = I.second;
2508 
2509     PL.clear();
2510     types::getCompilationPhases(InputType, PL);
2511 
2512     // If the first step comes after the final phase we are doing as part of
2513     // this compilation, warn the user about it.
2514     phases::ID InitialPhase = PL[0];
2515     if (InitialPhase > FinalPhase) {
2516       // Claim here to avoid the more general unused warning.
2517       InputArg->claim();
2518 
2519       // Suppress all unused style warnings with -Qunused-arguments
2520       if (Args.hasArg(options::OPT_Qunused_arguments))
2521         continue;
2522 
2523       // Special case when final phase determined by binary name, rather than
2524       // by a command-line argument with a corresponding Arg.
2525       if (CCCIsCPP())
2526         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
2527             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
2528       // Special case '-E' warning on a previously preprocessed file to make
2529       // more sense.
2530       else if (InitialPhase == phases::Compile &&
2531                FinalPhase == phases::Preprocess &&
2532                getPreprocessedType(InputType) == types::TY_INVALID)
2533         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
2534             << InputArg->getAsString(Args) << !!FinalPhaseArg
2535             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2536       else
2537         Diag(clang::diag::warn_drv_input_file_unused)
2538             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2539             << !!FinalPhaseArg
2540             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2541       continue;
2542     }
2543 
2544     if (YcArg) {
2545       // Add a separate precompile phase for the compile phase.
2546       if (FinalPhase >= phases::Compile) {
2547         const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
2548         llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
2549         types::getCompilationPhases(HeaderType, PCHPL);
2550         Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
2551 
2552         // Build the pipeline for the pch file.
2553         Action *ClangClPch =
2554             C.MakeAction<InputAction>(*PchInputArg, HeaderType);
2555         for (phases::ID Phase : PCHPL)
2556           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2557         assert(ClangClPch);
2558         Actions.push_back(ClangClPch);
2559         // The driver currently exits after the first failed command.  This
2560         // relies on that behavior, to make sure if the pch generation fails,
2561         // the main compilation won't run.
2562       }
2563     }
2564 
2565     // Build the pipeline for this file.
2566     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
2567 
2568     // Use the current host action in any of the offloading actions, if
2569     // required.
2570     if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2571       break;
2572 
2573     for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2574          i != e; ++i) {
2575       phases::ID Phase = *i;
2576 
2577       // We are done if this step is past what the user requested.
2578       if (Phase > FinalPhase)
2579         break;
2580 
2581       // Add any offload action the host action depends on.
2582       Current = OffloadBuilder.addDeviceDependencesToHostAction(
2583           Current, InputArg, Phase, FinalPhase, PL);
2584       if (!Current)
2585         break;
2586 
2587       // Queue linker inputs.
2588       if (Phase == phases::Link) {
2589         assert((i + 1) == e && "linking must be final compilation step.");
2590         LinkerInputs.push_back(Current);
2591         Current = nullptr;
2592         break;
2593       }
2594 
2595       // Otherwise construct the appropriate action.
2596       auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2597 
2598       // We didn't create a new action, so we will just move to the next phase.
2599       if (NewCurrent == Current)
2600         continue;
2601 
2602       Current = NewCurrent;
2603 
2604       // Use the current host action in any of the offloading actions, if
2605       // required.
2606       if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2607         break;
2608 
2609       if (Current->getType() == types::TY_Nothing)
2610         break;
2611     }
2612 
2613     // If we ended with something, add to the output list.
2614     if (Current)
2615       Actions.push_back(Current);
2616 
2617     // Add any top level actions generated for offloading.
2618     OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
2619   }
2620 
2621   // Add a link action if necessary.
2622   if (!LinkerInputs.empty()) {
2623     Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2624     LA = OffloadBuilder.processHostLinkAction(LA);
2625     Actions.push_back(LA);
2626   }
2627 
2628   // If we are linking, claim any options which are obviously only used for
2629   // compilation.
2630   if (FinalPhase == phases::Link && PL.size() == 1) {
2631     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
2632     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2633   }
2634 
2635   // Claim ignored clang-cl options.
2636   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
2637 
2638   // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2639   // to non-CUDA compilations and should not trigger warnings there.
2640   Args.ClaimAllArgs(options::OPT_cuda_host_only);
2641   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
2642 }
2643 
2644 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2645                                      phases::ID Phase, Action *Input) const {
2646   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
2647 
2648   // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2649   // encode this in the steps because the intermediate type depends on
2650   // arguments. Just special case here.
2651   if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2652     return Input;
2653 
2654   // Build the appropriate action.
2655   switch (Phase) {
2656   case phases::Link:
2657     llvm_unreachable("link action invalid here.");
2658   case phases::Preprocess: {
2659     types::ID OutputTy;
2660     // -{M, MM} alter the output type.
2661     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
2662       OutputTy = types::TY_Dependencies;
2663     } else {
2664       OutputTy = Input->getType();
2665       if (!Args.hasFlag(options::OPT_frewrite_includes,
2666                         options::OPT_fno_rewrite_includes, false) &&
2667           !CCGenDiagnostics)
2668         OutputTy = types::getPreprocessedType(OutputTy);
2669       assert(OutputTy != types::TY_INVALID &&
2670              "Cannot preprocess this input type!");
2671     }
2672     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
2673   }
2674   case phases::Precompile: {
2675     types::ID OutputTy = getPrecompiledType(Input->getType());
2676     assert(OutputTy != types::TY_INVALID &&
2677            "Cannot precompile this input type!");
2678     if (Args.hasArg(options::OPT_fsyntax_only)) {
2679       // Syntax checks should not emit a PCH file
2680       OutputTy = types::TY_Nothing;
2681     }
2682     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
2683   }
2684   case phases::Compile: {
2685     if (Args.hasArg(options::OPT_fsyntax_only))
2686       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
2687     if (Args.hasArg(options::OPT_rewrite_objc))
2688       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
2689     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
2690       return C.MakeAction<CompileJobAction>(Input,
2691                                             types::TY_RewrittenLegacyObjC);
2692     if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
2693       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
2694     if (Args.hasArg(options::OPT__migrate))
2695       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
2696     if (Args.hasArg(options::OPT_emit_ast))
2697       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
2698     if (Args.hasArg(options::OPT_module_file_info))
2699       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
2700     if (Args.hasArg(options::OPT_verify_pch))
2701       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2702     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
2703   }
2704   case phases::Backend: {
2705     if (isUsingLTO()) {
2706       types::ID Output =
2707           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
2708       return C.MakeAction<BackendJobAction>(Input, Output);
2709     }
2710     if (Args.hasArg(options::OPT_emit_llvm)) {
2711       types::ID Output =
2712           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
2713       return C.MakeAction<BackendJobAction>(Input, Output);
2714     }
2715     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
2716   }
2717   case phases::Assemble:
2718     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
2719   }
2720 
2721   llvm_unreachable("invalid phase in ConstructPhaseAction");
2722 }
2723 
2724 void Driver::BuildJobs(Compilation &C) const {
2725   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2726 
2727   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2728 
2729   // It is an error to provide a -o option if we are making multiple output
2730   // files.
2731   if (FinalOutput) {
2732     unsigned NumOutputs = 0;
2733     for (const Action *A : C.getActions())
2734       if (A->getType() != types::TY_Nothing)
2735         ++NumOutputs;
2736 
2737     if (NumOutputs > 1) {
2738       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
2739       FinalOutput = nullptr;
2740     }
2741   }
2742 
2743   // Collect the list of architectures.
2744   llvm::StringSet<> ArchNames;
2745   if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2746     for (const Arg *A : C.getArgs())
2747       if (A->getOption().matches(options::OPT_arch))
2748         ArchNames.insert(A->getValue());
2749 
2750   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2751   std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
2752   for (Action *A : C.getActions()) {
2753     // If we are linking an image for multiple archs then the linker wants
2754     // -arch_multiple and -final_output <final image name>. Unfortunately, this
2755     // doesn't fit in cleanly because we have to pass this information down.
2756     //
2757     // FIXME: This is a hack; find a cleaner way to integrate this into the
2758     // process.
2759     const char *LinkingOutput = nullptr;
2760     if (isa<LipoJobAction>(A)) {
2761       if (FinalOutput)
2762         LinkingOutput = FinalOutput->getValue();
2763       else
2764         LinkingOutput = getDefaultImageName();
2765     }
2766 
2767     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
2768                        /*BoundArch*/ StringRef(),
2769                        /*AtTopLevel*/ true,
2770                        /*MultipleArchs*/ ArchNames.size() > 1,
2771                        /*LinkingOutput*/ LinkingOutput, CachedResults,
2772                        /*TargetDeviceOffloadKind*/ Action::OFK_None);
2773   }
2774 
2775   // If the user passed -Qunused-arguments or there were errors, don't warn
2776   // about any unused arguments.
2777   if (Diags.hasErrorOccurred() ||
2778       C.getArgs().hasArg(options::OPT_Qunused_arguments))
2779     return;
2780 
2781   // Claim -### here.
2782   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
2783 
2784   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
2785   (void)C.getArgs().hasArg(options::OPT_driver_mode);
2786   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
2787 
2788   for (Arg *A : C.getArgs()) {
2789     // FIXME: It would be nice to be able to send the argument to the
2790     // DiagnosticsEngine, so that extra values, position, and so on could be
2791     // printed.
2792     if (!A->isClaimed()) {
2793       if (A->getOption().hasFlag(options::NoArgumentUnused))
2794         continue;
2795 
2796       // Suppress the warning automatically if this is just a flag, and it is an
2797       // instance of an argument we already claimed.
2798       const Option &Opt = A->getOption();
2799       if (Opt.getKind() == Option::FlagClass) {
2800         bool DuplicateClaimed = false;
2801 
2802         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2803           if (AA->isClaimed()) {
2804             DuplicateClaimed = true;
2805             break;
2806           }
2807         }
2808 
2809         if (DuplicateClaimed)
2810           continue;
2811       }
2812 
2813       // In clang-cl, don't mention unknown arguments here since they have
2814       // already been warned about.
2815       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2816         Diag(clang::diag::warn_drv_unused_argument)
2817             << A->getAsString(C.getArgs());
2818     }
2819   }
2820 }
2821 
2822 namespace {
2823 /// Utility class to control the collapse of dependent actions and select the
2824 /// tools accordingly.
2825 class ToolSelector final {
2826   /// The tool chain this selector refers to.
2827   const ToolChain &TC;
2828 
2829   /// The compilation this selector refers to.
2830   const Compilation &C;
2831 
2832   /// The base action this selector refers to.
2833   const JobAction *BaseAction;
2834 
2835   /// Set to true if the current toolchain refers to host actions.
2836   bool IsHostSelector;
2837 
2838   /// Set to true if save-temps and embed-bitcode functionalities are active.
2839   bool SaveTemps;
2840   bool EmbedBitcode;
2841 
2842   /// Get previous dependent action or null if that does not exist. If
2843   /// \a CanBeCollapsed is false, that action must be legal to collapse or
2844   /// null will be returned.
2845   const JobAction *getPrevDependentAction(const ActionList &Inputs,
2846                                           ActionList &SavedOffloadAction,
2847                                           bool CanBeCollapsed = true) {
2848     // An option can be collapsed only if it has a single input.
2849     if (Inputs.size() != 1)
2850       return nullptr;
2851 
2852     Action *CurAction = *Inputs.begin();
2853     if (CanBeCollapsed &&
2854         !CurAction->isCollapsingWithNextDependentActionLegal())
2855       return nullptr;
2856 
2857     // If the input action is an offload action. Look through it and save any
2858     // offload action that can be dropped in the event of a collapse.
2859     if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2860       // If the dependent action is a device action, we will attempt to collapse
2861       // only with other device actions. Otherwise, we would do the same but
2862       // with host actions only.
2863       if (!IsHostSelector) {
2864         if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2865           CurAction =
2866               OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2867           if (CanBeCollapsed &&
2868               !CurAction->isCollapsingWithNextDependentActionLegal())
2869             return nullptr;
2870           SavedOffloadAction.push_back(OA);
2871           return dyn_cast<JobAction>(CurAction);
2872         }
2873       } else if (OA->hasHostDependence()) {
2874         CurAction = OA->getHostDependence();
2875         if (CanBeCollapsed &&
2876             !CurAction->isCollapsingWithNextDependentActionLegal())
2877           return nullptr;
2878         SavedOffloadAction.push_back(OA);
2879         return dyn_cast<JobAction>(CurAction);
2880       }
2881       return nullptr;
2882     }
2883 
2884     return dyn_cast<JobAction>(CurAction);
2885   }
2886 
2887   /// Return true if an assemble action can be collapsed.
2888   bool canCollapseAssembleAction() const {
2889     return TC.useIntegratedAs() && !SaveTemps &&
2890            !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2891            !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2892            !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2893   }
2894 
2895   /// Return true if a preprocessor action can be collapsed.
2896   bool canCollapsePreprocessorAction() const {
2897     return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2898            !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2899            !C.getArgs().hasArg(options::OPT_rewrite_objc);
2900   }
2901 
2902   /// Struct that relates an action with the offload actions that would be
2903   /// collapsed with it.
2904   struct JobActionInfo final {
2905     /// The action this info refers to.
2906     const JobAction *JA = nullptr;
2907     /// The offload actions we need to take care off if this action is
2908     /// collapsed.
2909     ActionList SavedOffloadAction;
2910   };
2911 
2912   /// Append collapsed offload actions from the give nnumber of elements in the
2913   /// action info array.
2914   static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2915                                            ArrayRef<JobActionInfo> &ActionInfo,
2916                                            unsigned ElementNum) {
2917     assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2918     for (unsigned I = 0; I < ElementNum; ++I)
2919       CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2920                                     ActionInfo[I].SavedOffloadAction.end());
2921   }
2922 
2923   /// Functions that attempt to perform the combining. They detect if that is
2924   /// legal, and if so they update the inputs \a Inputs and the offload action
2925   /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
2926   /// the combined action is returned. If the combining is not legal or if the
2927   /// tool does not exist, null is returned.
2928   /// Currently three kinds of collapsing are supported:
2929   ///  - Assemble + Backend + Compile;
2930   ///  - Assemble + Backend ;
2931   ///  - Backend + Compile.
2932   const Tool *
2933   combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2934                                 const ActionList *&Inputs,
2935                                 ActionList &CollapsedOffloadAction) {
2936     if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
2937       return nullptr;
2938     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2939     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2940     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
2941     if (!AJ || !BJ || !CJ)
2942       return nullptr;
2943 
2944     // Get compiler tool.
2945     const Tool *T = TC.SelectTool(*CJ);
2946     if (!T)
2947       return nullptr;
2948 
2949     // When using -fembed-bitcode, it is required to have the same tool (clang)
2950     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2951     if (EmbedBitcode) {
2952       const Tool *BT = TC.SelectTool(*BJ);
2953       if (BT == T)
2954         return nullptr;
2955     }
2956 
2957     if (!T->hasIntegratedAssembler())
2958       return nullptr;
2959 
2960     Inputs = &CJ->getInputs();
2961     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2962                                  /*NumElements=*/3);
2963     return T;
2964   }
2965   const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
2966                                      const ActionList *&Inputs,
2967                                      ActionList &CollapsedOffloadAction) {
2968     if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
2969       return nullptr;
2970     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2971     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2972     if (!AJ || !BJ)
2973       return nullptr;
2974 
2975     // Retrieve the compile job, backend action must always be preceded by one.
2976     ActionList CompileJobOffloadActions;
2977     auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
2978                                       /*CanBeCollapsed=*/false);
2979     if (!AJ || !BJ || !CJ)
2980       return nullptr;
2981 
2982     assert(isa<CompileJobAction>(CJ) &&
2983            "Expecting compile job preceding backend job.");
2984 
2985     // Get compiler tool.
2986     const Tool *T = TC.SelectTool(*CJ);
2987     if (!T)
2988       return nullptr;
2989 
2990     if (!T->hasIntegratedAssembler())
2991       return nullptr;
2992 
2993     Inputs = &BJ->getInputs();
2994     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2995                                  /*NumElements=*/2);
2996     return T;
2997   }
2998   const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2999                                     const ActionList *&Inputs,
3000                                     ActionList &CollapsedOffloadAction) {
3001     if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3002       return nullptr;
3003     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3004     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3005     if (!BJ || !CJ)
3006       return nullptr;
3007 
3008     // Get compiler tool.
3009     const Tool *T = TC.SelectTool(*CJ);
3010     if (!T)
3011       return nullptr;
3012 
3013     if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3014       return nullptr;
3015 
3016     Inputs = &CJ->getInputs();
3017     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3018                                  /*NumElements=*/2);
3019     return T;
3020   }
3021 
3022   /// Updates the inputs if the obtained tool supports combining with
3023   /// preprocessor action, and the current input is indeed a preprocessor
3024   /// action. If combining results in the collapse of offloading actions, those
3025   /// are appended to \a CollapsedOffloadAction.
3026   void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3027                                ActionList &CollapsedOffloadAction) {
3028     if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3029       return;
3030 
3031     // Attempt to get a preprocessor action dependence.
3032     ActionList PreprocessJobOffloadActions;
3033     auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3034     if (!PJ || !isa<PreprocessJobAction>(PJ))
3035       return;
3036 
3037     // This is legal to combine. Append any offload action we found and set the
3038     // current inputs to preprocessor inputs.
3039     CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3040                                   PreprocessJobOffloadActions.end());
3041     Inputs = &PJ->getInputs();
3042   }
3043 
3044 public:
3045   ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3046                const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3047       : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3048         EmbedBitcode(EmbedBitcode) {
3049     assert(BaseAction && "Invalid base action.");
3050     IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3051   }
3052 
3053   /// Check if a chain of actions can be combined and return the tool that can
3054   /// handle the combination of actions. The pointer to the current inputs \a
3055   /// Inputs and the list of offload actions \a CollapsedOffloadActions
3056   /// connected to collapsed actions are updated accordingly. The latter enables
3057   /// the caller of the selector to process them afterwards instead of just
3058   /// dropping them. If no suitable tool is found, null will be returned.
3059   const Tool *getTool(const ActionList *&Inputs,
3060                       ActionList &CollapsedOffloadAction) {
3061     //
3062     // Get the largest chain of actions that we could combine.
3063     //
3064 
3065     SmallVector<JobActionInfo, 5> ActionChain(1);
3066     ActionChain.back().JA = BaseAction;
3067     while (ActionChain.back().JA) {
3068       const Action *CurAction = ActionChain.back().JA;
3069 
3070       // Grow the chain by one element.
3071       ActionChain.resize(ActionChain.size() + 1);
3072       JobActionInfo &AI = ActionChain.back();
3073 
3074       // Attempt to fill it with the
3075       AI.JA =
3076           getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
3077     }
3078 
3079     // Pop the last action info as it could not be filled.
3080     ActionChain.pop_back();
3081 
3082     //
3083     // Attempt to combine actions. If all combining attempts failed, just return
3084     // the tool of the provided action. At the end we attempt to combine the
3085     // action with any preprocessor action it may depend on.
3086     //
3087 
3088     const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3089                                                   CollapsedOffloadAction);
3090     if (!T)
3091       T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3092     if (!T)
3093       T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3094     if (!T) {
3095       Inputs = &BaseAction->getInputs();
3096       T = TC.SelectTool(*BaseAction);
3097     }
3098 
3099     combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3100     return T;
3101   }
3102 };
3103 }
3104 
3105 /// Return a string that uniquely identifies the result of a job. The bound arch
3106 /// is not necessarily represented in the toolchain's triple -- for example,
3107 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
3108 /// Also, we need to add the offloading device kind, as the same tool chain can
3109 /// be used for host and device for some programming models, e.g. OpenMP.
3110 static std::string GetTriplePlusArchString(const ToolChain *TC,
3111                                            StringRef BoundArch,
3112                                            Action::OffloadKind OffloadKind) {
3113   std::string TriplePlusArch = TC->getTriple().normalize();
3114   if (!BoundArch.empty()) {
3115     TriplePlusArch += "-";
3116     TriplePlusArch += BoundArch;
3117   }
3118   TriplePlusArch += "-";
3119   TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3120   return TriplePlusArch;
3121 }
3122 
3123 InputInfo Driver::BuildJobsForAction(
3124     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3125     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3126     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3127     Action::OffloadKind TargetDeviceOffloadKind) const {
3128   std::pair<const Action *, std::string> ActionTC = {
3129       A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3130   auto CachedResult = CachedResults.find(ActionTC);
3131   if (CachedResult != CachedResults.end()) {
3132     return CachedResult->second;
3133   }
3134   InputInfo Result = BuildJobsForActionNoCache(
3135       C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
3136       CachedResults, TargetDeviceOffloadKind);
3137   CachedResults[ActionTC] = Result;
3138   return Result;
3139 }
3140 
3141 InputInfo Driver::BuildJobsForActionNoCache(
3142     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3143     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3144     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3145     Action::OffloadKind TargetDeviceOffloadKind) const {
3146   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3147 
3148   InputInfoList OffloadDependencesInputInfo;
3149   bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
3150   if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3151     // The offload action is expected to be used in four different situations.
3152     //
3153     // a) Set a toolchain/architecture/kind for a host action:
3154     //    Host Action 1 -> OffloadAction -> Host Action 2
3155     //
3156     // b) Set a toolchain/architecture/kind for a device action;
3157     //    Device Action 1 -> OffloadAction -> Device Action 2
3158     //
3159     // c) Specify a device dependence to a host action;
3160     //    Device Action 1  _
3161     //                      \
3162     //      Host Action 1  ---> OffloadAction -> Host Action 2
3163     //
3164     // d) Specify a host dependence to a device action.
3165     //      Host Action 1  _
3166     //                      \
3167     //    Device Action 1  ---> OffloadAction -> Device Action 2
3168     //
3169     // For a) and b), we just return the job generated for the dependence. For
3170     // c) and d) we override the current action with the host/device dependence
3171     // if the current toolchain is host/device and set the offload dependences
3172     // info with the jobs obtained from the device/host dependence(s).
3173 
3174     // If there is a single device option, just generate the job for it.
3175     if (OA->hasSingleDeviceDependence()) {
3176       InputInfo DevA;
3177       OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3178                                        const char *DepBoundArch) {
3179         DevA =
3180             BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3181                                /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
3182                                CachedResults, DepA->getOffloadingDeviceKind());
3183       });
3184       return DevA;
3185     }
3186 
3187     // If 'Action 2' is host, we generate jobs for the device dependences and
3188     // override the current action with the host dependence. Otherwise, we
3189     // generate the host dependences and override the action with the device
3190     // dependence. The dependences can't therefore be a top-level action.
3191     OA->doOnEachDependence(
3192         /*IsHostDependence=*/BuildingForOffloadDevice,
3193         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3194           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3195               C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3196               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
3197               DepA->getOffloadingDeviceKind()));
3198         });
3199 
3200     A = BuildingForOffloadDevice
3201             ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3202             : OA->getHostDependence();
3203   }
3204 
3205   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
3206     // FIXME: It would be nice to not claim this here; maybe the old scheme of
3207     // just using Args was better?
3208     const Arg &Input = IA->getInputArg();
3209     Input.claim();
3210     if (Input.getOption().matches(options::OPT_INPUT)) {
3211       const char *Name = Input.getValue();
3212       return InputInfo(A, Name, /* BaseInput = */ Name);
3213     }
3214     return InputInfo(A, &Input, /* BaseInput = */ "");
3215   }
3216 
3217   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
3218     const ToolChain *TC;
3219     StringRef ArchName = BAA->getArchName();
3220 
3221     if (!ArchName.empty())
3222       TC = &getToolChain(C.getArgs(),
3223                          computeTargetTriple(*this, DefaultTargetTriple,
3224                                              C.getArgs(), ArchName));
3225     else
3226       TC = &C.getDefaultToolChain();
3227 
3228     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
3229                               MultipleArchs, LinkingOutput, CachedResults,
3230                               TargetDeviceOffloadKind);
3231   }
3232 
3233 
3234   const ActionList *Inputs = &A->getInputs();
3235 
3236   const JobAction *JA = cast<JobAction>(A);
3237   ActionList CollapsedOffloadActions;
3238 
3239   ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3240                   embedBitcodeInObject() && !isUsingLTO());
3241   const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3242 
3243   if (!T)
3244     return InputInfo();
3245 
3246   // If we've collapsed action list that contained OffloadAction we
3247   // need to build jobs for host/device-side inputs it may have held.
3248   for (const auto *OA : CollapsedOffloadActions)
3249     cast<OffloadAction>(OA)->doOnEachDependence(
3250         /*IsHostDependence=*/BuildingForOffloadDevice,
3251         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3252           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3253               C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
3254               /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
3255               DepA->getOffloadingDeviceKind()));
3256         });
3257 
3258   // Only use pipes when there is exactly one input.
3259   InputInfoList InputInfos;
3260   for (const Action *Input : *Inputs) {
3261     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3262     // shouldn't get temporary output names.
3263     // FIXME: Clean this up.
3264     bool SubJobAtTopLevel =
3265         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
3266     InputInfos.push_back(BuildJobsForAction(
3267         C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
3268         CachedResults, A->getOffloadingDeviceKind()));
3269   }
3270 
3271   // Always use the first input as the base input.
3272   const char *BaseInput = InputInfos[0].getBaseInput();
3273 
3274   // ... except dsymutil actions, which use their actual input as the base
3275   // input.
3276   if (JA->getType() == types::TY_dSYM)
3277     BaseInput = InputInfos[0].getFilename();
3278 
3279   // Append outputs of offload device jobs to the input list
3280   if (!OffloadDependencesInputInfo.empty())
3281     InputInfos.append(OffloadDependencesInputInfo.begin(),
3282                       OffloadDependencesInputInfo.end());
3283 
3284   // Set the effective triple of the toolchain for the duration of this job.
3285   llvm::Triple EffectiveTriple;
3286   const ToolChain &ToolTC = T->getToolChain();
3287   const ArgList &Args =
3288       C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
3289   if (InputInfos.size() != 1) {
3290     EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3291   } else {
3292     // Pass along the input type if it can be unambiguously determined.
3293     EffectiveTriple = llvm::Triple(
3294         ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3295   }
3296   RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3297 
3298   // Determine the place to write output to, if any.
3299   InputInfo Result;
3300   InputInfoList UnbundlingResults;
3301   if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3302     // If we have an unbundling job, we need to create results for all the
3303     // outputs. We also update the results cache so that other actions using
3304     // this unbundling action can get the right results.
3305     for (auto &UI : UA->getDependentActionsInfo()) {
3306       assert(UI.DependentOffloadKind != Action::OFK_None &&
3307              "Unbundling with no offloading??");
3308 
3309       // Unbundling actions are never at the top level. When we generate the
3310       // offloading prefix, we also do that for the host file because the
3311       // unbundling action does not change the type of the output which can
3312       // cause a overwrite.
3313       std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3314           UI.DependentOffloadKind,
3315           UI.DependentToolChain->getTriple().normalize(),
3316           /*CreatePrefixForHost=*/true);
3317       auto CurI = InputInfo(
3318           UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3319                                  /*AtTopLevel=*/false, MultipleArchs,
3320                                  OffloadingPrefix),
3321           BaseInput);
3322       // Save the unbundling result.
3323       UnbundlingResults.push_back(CurI);
3324 
3325       // Get the unique string identifier for this dependence and cache the
3326       // result.
3327       CachedResults[{A, GetTriplePlusArchString(
3328                             UI.DependentToolChain, UI.DependentBoundArch,
3329                             UI.DependentOffloadKind)}] = CurI;
3330     }
3331 
3332     // Now that we have all the results generated, select the one that should be
3333     // returned for the current depending action.
3334     std::pair<const Action *, std::string> ActionTC = {
3335         A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3336     assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3337            "Result does not exist??");
3338     Result = CachedResults[ActionTC];
3339   } else if (JA->getType() == types::TY_Nothing)
3340     Result = InputInfo(A, BaseInput);
3341   else {
3342     // We only have to generate a prefix for the host if this is not a top-level
3343     // action.
3344     std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3345         A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3346         /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3347             !AtTopLevel);
3348     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
3349                                              AtTopLevel, MultipleArchs,
3350                                              OffloadingPrefix),
3351                        BaseInput);
3352   }
3353 
3354   if (CCCPrintBindings && !CCGenDiagnostics) {
3355     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3356                  << " - \"" << T->getName() << "\", inputs: [";
3357     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3358       llvm::errs() << InputInfos[i].getAsString();
3359       if (i + 1 != e)
3360         llvm::errs() << ", ";
3361     }
3362     if (UnbundlingResults.empty())
3363       llvm::errs() << "], output: " << Result.getAsString() << "\n";
3364     else {
3365       llvm::errs() << "], outputs: [";
3366       for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3367         llvm::errs() << UnbundlingResults[i].getAsString();
3368         if (i + 1 != e)
3369           llvm::errs() << ", ";
3370       }
3371       llvm::errs() << "] \n";
3372     }
3373   } else {
3374     if (UnbundlingResults.empty())
3375       T->ConstructJob(
3376           C, *JA, Result, InputInfos,
3377           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3378           LinkingOutput);
3379     else
3380       T->ConstructJobMultipleOutputs(
3381           C, *JA, UnbundlingResults, InputInfos,
3382           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3383           LinkingOutput);
3384   }
3385   return Result;
3386 }
3387 
3388 const char *Driver::getDefaultImageName() const {
3389   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3390   return Target.isOSWindows() ? "a.exe" : "a.out";
3391 }
3392 
3393 /// \brief Create output filename based on ArgValue, which could either be a
3394 /// full filename, filename without extension, or a directory. If ArgValue
3395 /// does not provide a filename, then use BaseName, and use the extension
3396 /// suitable for FileType.
3397 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
3398                                         StringRef BaseName,
3399                                         types::ID FileType) {
3400   SmallString<128> Filename = ArgValue;
3401 
3402   if (ArgValue.empty()) {
3403     // If the argument is empty, output to BaseName in the current dir.
3404     Filename = BaseName;
3405   } else if (llvm::sys::path::is_separator(Filename.back())) {
3406     // If the argument is a directory, output to BaseName in that dir.
3407     llvm::sys::path::append(Filename, BaseName);
3408   }
3409 
3410   if (!llvm::sys::path::has_extension(ArgValue)) {
3411     // If the argument didn't provide an extension, then set it.
3412     const char *Extension = types::getTypeTempSuffix(FileType, true);
3413 
3414     if (FileType == types::TY_Image &&
3415         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3416       // The output file is a dll.
3417       Extension = "dll";
3418     }
3419 
3420     llvm::sys::path::replace_extension(Filename, Extension);
3421   }
3422 
3423   return Args.MakeArgString(Filename.c_str());
3424 }
3425 
3426 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
3427                                        const char *BaseInput,
3428                                        StringRef BoundArch, bool AtTopLevel,
3429                                        bool MultipleArchs,
3430                                        StringRef OffloadingPrefix) const {
3431   llvm::PrettyStackTraceString CrashInfo("Computing output path");
3432   // Output to a user requested destination?
3433   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
3434     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
3435       return C.addResultFile(FinalOutput->getValue(), &JA);
3436   }
3437 
3438   // For /P, preprocess to file named after BaseInput.
3439   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3440     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3441     StringRef BaseName = llvm::sys::path::filename(BaseInput);
3442     StringRef NameArg;
3443     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
3444       NameArg = A->getValue();
3445     return C.addResultFile(
3446         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3447         &JA);
3448   }
3449 
3450   // Default to writing to stdout?
3451   if (AtTopLevel && !CCGenDiagnostics &&
3452       (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
3453     return "-";
3454 
3455   // Is this the assembly listing for /FA?
3456   if (JA.getType() == types::TY_PP_Asm &&
3457       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3458        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3459     // Use /Fa and the input filename to determine the asm file name.
3460     StringRef BaseName = llvm::sys::path::filename(BaseInput);
3461     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
3462     return C.addResultFile(
3463         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3464         &JA);
3465   }
3466 
3467   // Output to a temporary file?
3468   if ((!AtTopLevel && !isSaveTempsEnabled() &&
3469        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
3470       CCGenDiagnostics) {
3471     StringRef Name = llvm::sys::path::filename(BaseInput);
3472     std::pair<StringRef, StringRef> Split = Name.split('.');
3473     std::string TmpName = GetTemporaryPath(
3474         Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3475     return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3476   }
3477 
3478   SmallString<128> BasePath(BaseInput);
3479   StringRef BaseName;
3480 
3481   // Dsymutil actions should use the full path.
3482   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
3483     BaseName = BasePath;
3484   else
3485     BaseName = llvm::sys::path::filename(BasePath);
3486 
3487   // Determine what the derived output name should be.
3488   const char *NamedOutput;
3489 
3490   if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
3491       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3492     // The /Fo or /o flag decides the object filename.
3493     StringRef Val =
3494         C.getArgs()
3495             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3496             ->getValue();
3497     NamedOutput =
3498         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
3499   } else if (JA.getType() == types::TY_Image &&
3500              C.getArgs().hasArg(options::OPT__SLASH_Fe,
3501                                 options::OPT__SLASH_o)) {
3502     // The /Fe or /o flag names the linked file.
3503     StringRef Val =
3504         C.getArgs()
3505             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3506             ->getValue();
3507     NamedOutput =
3508         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
3509   } else if (JA.getType() == types::TY_Image) {
3510     if (IsCLMode()) {
3511       // clang-cl uses BaseName for the executable name.
3512       NamedOutput =
3513           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
3514     } else {
3515       SmallString<128> Output(getDefaultImageName());
3516       Output += OffloadingPrefix;
3517       if (MultipleArchs && !BoundArch.empty()) {
3518         Output += "-";
3519         Output.append(BoundArch);
3520       }
3521       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
3522     }
3523   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
3524     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
3525   } else {
3526     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
3527     assert(Suffix && "All types used for output should have a suffix.");
3528 
3529     std::string::size_type End = std::string::npos;
3530     if (!types::appendSuffixForType(JA.getType()))
3531       End = BaseName.rfind('.');
3532     SmallString<128> Suffixed(BaseName.substr(0, End));
3533     Suffixed += OffloadingPrefix;
3534     if (MultipleArchs && !BoundArch.empty()) {
3535       Suffixed += "-";
3536       Suffixed.append(BoundArch);
3537     }
3538     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3539     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3540     // optimized bitcode output.
3541     if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3542         JA.getType() == types::TY_LLVM_BC)
3543       Suffixed += ".tmp";
3544     Suffixed += '.';
3545     Suffixed += Suffix;
3546     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3547   }
3548 
3549   // Prepend object file path if -save-temps=obj
3550   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3551       JA.getType() != types::TY_PCH) {
3552     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3553     SmallString<128> TempPath(FinalOutput->getValue());
3554     llvm::sys::path::remove_filename(TempPath);
3555     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3556     llvm::sys::path::append(TempPath, OutputFileName);
3557     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3558   }
3559 
3560   // If we're saving temps and the temp file conflicts with the input file,
3561   // then avoid overwriting input file.
3562   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
3563     bool SameFile = false;
3564     SmallString<256> Result;
3565     llvm::sys::fs::current_path(Result);
3566     llvm::sys::path::append(Result, BaseName);
3567     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3568     // Must share the same path to conflict.
3569     if (SameFile) {
3570       StringRef Name = llvm::sys::path::filename(BaseInput);
3571       std::pair<StringRef, StringRef> Split = Name.split('.');
3572       std::string TmpName = GetTemporaryPath(
3573           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
3574       return C.addTempFile(C.getArgs().MakeArgString(TmpName));
3575     }
3576   }
3577 
3578   // As an annoying special case, PCH generation doesn't strip the pathname.
3579   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
3580     llvm::sys::path::remove_filename(BasePath);
3581     if (BasePath.empty())
3582       BasePath = NamedOutput;
3583     else
3584       llvm::sys::path::append(BasePath, NamedOutput);
3585     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
3586   } else {
3587     return C.addResultFile(NamedOutput, &JA);
3588   }
3589 }
3590 
3591 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
3592   // Respect a limited subset of the '-Bprefix' functionality in GCC by
3593   // attempting to use this prefix when looking for file paths.
3594   for (const std::string &Dir : PrefixDirs) {
3595     if (Dir.empty())
3596       continue;
3597     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3598     llvm::sys::path::append(P, Name);
3599     if (llvm::sys::fs::exists(Twine(P)))
3600       return P.str();
3601   }
3602 
3603   SmallString<128> P(ResourceDir);
3604   llvm::sys::path::append(P, Name);
3605   if (llvm::sys::fs::exists(Twine(P)))
3606     return P.str();
3607 
3608   for (const std::string &Dir : TC.getFilePaths()) {
3609     if (Dir.empty())
3610       continue;
3611     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
3612     llvm::sys::path::append(P, Name);
3613     if (llvm::sys::fs::exists(Twine(P)))
3614       return P.str();
3615   }
3616 
3617   return Name;
3618 }
3619 
3620 void Driver::generatePrefixedToolNames(
3621     StringRef Tool, const ToolChain &TC,
3622     SmallVectorImpl<std::string> &Names) const {
3623   // FIXME: Needs a better variable than DefaultTargetTriple
3624   Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
3625   Names.emplace_back(Tool);
3626 
3627   // Allow the discovery of tools prefixed with LLVM's default target triple.
3628   std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3629   if (LLVMDefaultTargetTriple != DefaultTargetTriple)
3630     Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
3631 }
3632 
3633 static bool ScanDirForExecutable(SmallString<128> &Dir,
3634                                  ArrayRef<std::string> Names) {
3635   for (const auto &Name : Names) {
3636     llvm::sys::path::append(Dir, Name);
3637     if (llvm::sys::fs::can_execute(Twine(Dir)))
3638       return true;
3639     llvm::sys::path::remove_filename(Dir);
3640   }
3641   return false;
3642 }
3643 
3644 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
3645   SmallVector<std::string, 2> TargetSpecificExecutables;
3646   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3647 
3648   // Respect a limited subset of the '-Bprefix' functionality in GCC by
3649   // attempting to use this prefix when looking for program paths.
3650   for (const auto &PrefixDir : PrefixDirs) {
3651     if (llvm::sys::fs::is_directory(PrefixDir)) {
3652       SmallString<128> P(PrefixDir);
3653       if (ScanDirForExecutable(P, TargetSpecificExecutables))
3654         return P.str();
3655     } else {
3656       SmallString<128> P((PrefixDir + Name).str());
3657       if (llvm::sys::fs::can_execute(Twine(P)))
3658         return P.str();
3659     }
3660   }
3661 
3662   const ToolChain::path_list &List = TC.getProgramPaths();
3663   for (const auto &Path : List) {
3664     SmallString<128> P(Path);
3665     if (ScanDirForExecutable(P, TargetSpecificExecutables))
3666       return P.str();
3667   }
3668 
3669   // If all else failed, search the path.
3670   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3671     if (llvm::ErrorOr<std::string> P =
3672             llvm::sys::findProgramByName(TargetSpecificExecutable))
3673       return *P;
3674 
3675   return Name;
3676 }
3677 
3678 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
3679   SmallString<128> Path;
3680   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
3681   if (EC) {
3682     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
3683     return "";
3684   }
3685 
3686   return Path.str();
3687 }
3688 
3689 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3690   SmallString<128> Output;
3691   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3692     // FIXME: If anybody needs it, implement this obscure rule:
3693     // "If you specify a directory without a file name, the default file name
3694     // is VCx0.pch., where x is the major version of Visual C++ in use."
3695     Output = FpArg->getValue();
3696 
3697     // "If you do not specify an extension as part of the path name, an
3698     // extension of .pch is assumed. "
3699     if (!llvm::sys::path::has_extension(Output))
3700       Output += ".pch";
3701   } else {
3702     Output = BaseName;
3703     llvm::sys::path::replace_extension(Output, ".pch");
3704   }
3705   return Output.str();
3706 }
3707 
3708 const ToolChain &Driver::getToolChain(const ArgList &Args,
3709                                       const llvm::Triple &Target) const {
3710 
3711   auto &TC = ToolChains[Target.str()];
3712   if (!TC) {
3713     switch (Target.getOS()) {
3714     case llvm::Triple::Haiku:
3715       TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
3716       break;
3717     case llvm::Triple::CloudABI:
3718       TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
3719       break;
3720     case llvm::Triple::Darwin:
3721     case llvm::Triple::MacOSX:
3722     case llvm::Triple::IOS:
3723     case llvm::Triple::TvOS:
3724     case llvm::Triple::WatchOS:
3725       TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
3726       break;
3727     case llvm::Triple::DragonFly:
3728       TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
3729       break;
3730     case llvm::Triple::OpenBSD:
3731       TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
3732       break;
3733     case llvm::Triple::Bitrig:
3734       TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
3735       break;
3736     case llvm::Triple::NetBSD:
3737       TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
3738       break;
3739     case llvm::Triple::FreeBSD:
3740       TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
3741       break;
3742     case llvm::Triple::Minix:
3743       TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
3744       break;
3745     case llvm::Triple::Linux:
3746     case llvm::Triple::ELFIAMCU:
3747       if (Target.getArch() == llvm::Triple::hexagon)
3748         TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3749                                                              Args);
3750       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3751                !Target.hasEnvironment())
3752         TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3753                                                               Args);
3754       else
3755         TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
3756       break;
3757     case llvm::Triple::NaCl:
3758       TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
3759       break;
3760     case llvm::Triple::Fuchsia:
3761       TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
3762       break;
3763     case llvm::Triple::Solaris:
3764       TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
3765       break;
3766     case llvm::Triple::AMDHSA:
3767       TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
3768       break;
3769     case llvm::Triple::Win32:
3770       switch (Target.getEnvironment()) {
3771       default:
3772         if (Target.isOSBinFormatELF())
3773           TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3774         else if (Target.isOSBinFormatMachO())
3775           TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3776         else
3777           TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3778         break;
3779       case llvm::Triple::GNU:
3780         TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
3781         break;
3782       case llvm::Triple::Itanium:
3783         TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3784                                                                   Args);
3785         break;
3786       case llvm::Triple::MSVC:
3787       case llvm::Triple::UnknownEnvironment:
3788         TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
3789         break;
3790       }
3791       break;
3792     case llvm::Triple::PS4:
3793       TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
3794       break;
3795     case llvm::Triple::Contiki:
3796       TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
3797       break;
3798     default:
3799       // Of these targets, Hexagon is the only one that might have
3800       // an OS of Linux, in which case it got handled above already.
3801       switch (Target.getArch()) {
3802       case llvm::Triple::tce:
3803         TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
3804         break;
3805       case llvm::Triple::tcele:
3806         TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
3807         break;
3808       case llvm::Triple::hexagon:
3809         TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3810                                                              Args);
3811         break;
3812       case llvm::Triple::lanai:
3813         TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
3814         break;
3815       case llvm::Triple::xcore:
3816         TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
3817         break;
3818       case llvm::Triple::wasm32:
3819       case llvm::Triple::wasm64:
3820         TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
3821         break;
3822       case llvm::Triple::avr:
3823         TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
3824         break;
3825       default:
3826         if (Target.getVendor() == llvm::Triple::Myriad)
3827           TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3828                                                               Args);
3829         else if (Target.isOSBinFormatELF())
3830           TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
3831         else if (Target.isOSBinFormatMachO())
3832           TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
3833         else
3834           TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
3835       }
3836     }
3837   }
3838 
3839   // Intentionally omitted from the switch above: llvm::Triple::CUDA.  CUDA
3840   // compiles always need two toolchains, the CUDA toolchain and the host
3841   // toolchain.  So the only valid way to create a CUDA toolchain is via
3842   // CreateOffloadingDeviceToolChains.
3843 
3844   return *TC;
3845 }
3846 
3847 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
3848   // Say "no" if there is not exactly one input of a type clang understands.
3849   if (JA.size() != 1 ||
3850       !types::isAcceptedByClang((*JA.input_begin())->getType()))
3851     return false;
3852 
3853   // And say "no" if this is not a kind of action clang understands.
3854   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
3855       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
3856     return false;
3857 
3858   return true;
3859 }
3860 
3861 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3862 /// grouped values as integers. Numbers which are not provided are set to 0.
3863 ///
3864 /// \return True if the entire string was parsed (9.2), or all groups were
3865 /// parsed (10.3.5extrastuff).
3866 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3867                                unsigned &Micro, bool &HadExtra) {
3868   HadExtra = false;
3869 
3870   Major = Minor = Micro = 0;
3871   if (Str.empty())
3872     return false;
3873 
3874   if (Str.consumeInteger(10, Major))
3875     return false;
3876   if (Str.empty())
3877     return true;
3878   if (Str[0] != '.')
3879     return false;
3880 
3881   Str = Str.drop_front(1);
3882 
3883   if (Str.consumeInteger(10, Minor))
3884     return false;
3885   if (Str.empty())
3886     return true;
3887   if (Str[0] != '.')
3888     return false;
3889   Str = Str.drop_front(1);
3890 
3891   if (Str.consumeInteger(10, Micro))
3892     return false;
3893   if (!Str.empty())
3894     HadExtra = true;
3895   return true;
3896 }
3897 
3898 /// Parse digits from a string \p Str and fulfill \p Digits with
3899 /// the parsed numbers. This method assumes that the max number of
3900 /// digits to look for is equal to Digits.size().
3901 ///
3902 /// \return True if the entire string was parsed and there are
3903 /// no extra characters remaining at the end.
3904 bool Driver::GetReleaseVersion(StringRef Str,
3905                                MutableArrayRef<unsigned> Digits) {
3906   if (Str.empty())
3907     return false;
3908 
3909   unsigned CurDigit = 0;
3910   while (CurDigit < Digits.size()) {
3911     unsigned Digit;
3912     if (Str.consumeInteger(10, Digit))
3913       return false;
3914     Digits[CurDigit] = Digit;
3915     if (Str.empty())
3916       return true;
3917     if (Str[0] != '.')
3918       return false;
3919     Str = Str.drop_front(1);
3920     CurDigit++;
3921   }
3922 
3923   // More digits than requested, bail out...
3924   return false;
3925 }
3926 
3927 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3928   unsigned IncludedFlagsBitmask = 0;
3929   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
3930 
3931   if (Mode == CLMode) {
3932     // Include CL and Core options.
3933     IncludedFlagsBitmask |= options::CLOption;
3934     IncludedFlagsBitmask |= options::CoreOption;
3935   } else {
3936     ExcludedFlagsBitmask |= options::CLOption;
3937   }
3938 
3939   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3940 }
3941 
3942 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
3943   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
3944 }
3945