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.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Basic/VirtualFileSystem.h"
15 #include "clang/Config/config.h"
16 #include "clang/Driver/Action.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Job.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "clang/Driver/Tool.h"
23 #include "clang/Driver/ToolChain.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSet.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/Option/Arg.h"
31 #include "llvm/Option/ArgList.h"
32 #include "llvm/Option/OptSpecifier.h"
33 #include "llvm/Option/OptTable.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/Program.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <map>
43 #include <memory>
44 #include <utility>
45 
46 using namespace clang::driver;
47 using namespace clang;
48 using namespace llvm::opt;
49 
50 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
51                DiagnosticsEngine &Diags,
52                IntrusiveRefCntPtr<vfs::FileSystem> VFS)
53     : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
54       Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
55       LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
56       SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
57       DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
58       CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
59       CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
60       CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
61       CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
62       SuppressMissingInputWarning(false) {
63 
64   // Provide a sane fallback if no VFS is specified.
65   if (!this->VFS)
66     this->VFS = vfs::getRealFileSystem();
67 
68   Name = llvm::sys::path::filename(ClangExecutable);
69   Dir = llvm::sys::path::parent_path(ClangExecutable);
70   InstalledDir = Dir; // Provide a sensible default installed dir.
71 
72   // Compute the path to the resource directory.
73   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
74   SmallString<128> P(Dir);
75   if (ClangResourceDir != "") {
76     llvm::sys::path::append(P, ClangResourceDir);
77   } else {
78     StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
79     llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
80                             CLANG_VERSION_STRING);
81   }
82   ResourceDir = P.str();
83 }
84 
85 Driver::~Driver() {
86   delete Opts;
87 
88   llvm::DeleteContainerSeconds(ToolChains);
89 }
90 
91 void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
92   const std::string OptName =
93       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
94 
95   for (const char *ArgPtr : Args) {
96     // Ingore nullptrs, they are response file's EOL markers
97     if (ArgPtr == nullptr)
98       continue;
99     const StringRef Arg = ArgPtr;
100     if (!Arg.startswith(OptName))
101       continue;
102 
103     const StringRef Value = Arg.drop_front(OptName.size());
104     const unsigned M = llvm::StringSwitch<unsigned>(Value)
105                            .Case("gcc", GCCMode)
106                            .Case("g++", GXXMode)
107                            .Case("cpp", CPPMode)
108                            .Case("cl", CLMode)
109                            .Default(~0U);
110 
111     if (M != ~0U)
112       Mode = static_cast<DriverMode>(M);
113     else
114       Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
115   }
116 }
117 
118 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
119   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
120 
121   unsigned IncludedFlagsBitmask;
122   unsigned ExcludedFlagsBitmask;
123   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
124       getIncludeExcludeOptionFlagMasks();
125 
126   unsigned MissingArgIndex, MissingArgCount;
127   InputArgList Args =
128       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
129                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
130 
131   // Check for missing argument error.
132   if (MissingArgCount)
133     Diag(clang::diag::err_drv_missing_argument)
134         << Args.getArgString(MissingArgIndex) << MissingArgCount;
135 
136   // Check for unsupported options.
137   for (const Arg *A : Args) {
138     if (A->getOption().hasFlag(options::Unsupported)) {
139       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
140       continue;
141     }
142 
143     // Warn about -mcpu= without an argument.
144     if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
145       Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
146     }
147   }
148 
149   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
150     Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
151                               diag::err_drv_unknown_argument)
152       << A->getAsString(Args);
153 
154   return Args;
155 }
156 
157 // Determine which compilation mode we are in. We look for options which
158 // affect the phase, starting with the earliest phases, and record which
159 // option we used to determine the final phase.
160 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
161                                  Arg **FinalPhaseArg) const {
162   Arg *PhaseArg = nullptr;
163   phases::ID FinalPhase;
164 
165   // -{E,EP,P,M,MM} only run the preprocessor.
166   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
167       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
168       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
169       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
170     FinalPhase = phases::Preprocess;
171 
172     // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
173   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
174              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
175              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
176              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
177              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
178              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
179              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
180                                         options::OPT__analyze_auto)) ||
181              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
182     FinalPhase = phases::Compile;
183 
184     // -S only runs up to the backend.
185   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
186     FinalPhase = phases::Backend;
187 
188     // -c compilation only runs up to the assembler.
189   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
190     FinalPhase = phases::Assemble;
191 
192     // Otherwise do everything.
193   } else
194     FinalPhase = phases::Link;
195 
196   if (FinalPhaseArg)
197     *FinalPhaseArg = PhaseArg;
198 
199   return FinalPhase;
200 }
201 
202 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
203                          StringRef Value) {
204   Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
205                    Args.getBaseArgs().MakeIndex(Value), Value.data());
206   Args.AddSynthesizedArg(A);
207   A->claim();
208   return A;
209 }
210 
211 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
212   DerivedArgList *DAL = new DerivedArgList(Args);
213 
214   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
215   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
216   for (Arg *A : Args) {
217     // Unfortunately, we have to parse some forwarding options (-Xassembler,
218     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
219     // (assembler and preprocessor), or bypass a previous driver ('collect2').
220 
221     // Rewrite linker options, to replace --no-demangle with a custom internal
222     // option.
223     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
224          A->getOption().matches(options::OPT_Xlinker)) &&
225         A->containsValue("--no-demangle")) {
226       // Add the rewritten no-demangle argument.
227       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
228 
229       // Add the remaining values as Xlinker arguments.
230       for (StringRef Val : A->getValues())
231         if (Val != "--no-demangle")
232           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
233 
234       continue;
235     }
236 
237     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
238     // some build systems. We don't try to be complete here because we don't
239     // care to encourage this usage model.
240     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
241         (A->getValue(0) == StringRef("-MD") ||
242          A->getValue(0) == StringRef("-MMD"))) {
243       // Rewrite to -MD/-MMD along with -MF.
244       if (A->getValue(0) == StringRef("-MD"))
245         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
246       else
247         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
248       if (A->getNumValues() == 2)
249         DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
250                             A->getValue(1));
251       continue;
252     }
253 
254     // Rewrite reserved library names.
255     if (A->getOption().matches(options::OPT_l)) {
256       StringRef Value = A->getValue();
257 
258       // Rewrite unless -nostdlib is present.
259       if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
260         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
261         continue;
262       }
263 
264       // Rewrite unconditionally.
265       if (Value == "cc_kext") {
266         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
267         continue;
268       }
269     }
270 
271     // Pick up inputs via the -- option.
272     if (A->getOption().matches(options::OPT__DASH_DASH)) {
273       A->claim();
274       for (StringRef Val : A->getValues())
275         DAL->append(MakeInputArg(*DAL, Opts, Val));
276       continue;
277     }
278 
279     DAL->append(A);
280   }
281 
282   // Enforce -static if -miamcu is present.
283   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
284     DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
285 
286 // Add a default value of -mlinker-version=, if one was given and the user
287 // didn't specify one.
288 #if defined(HOST_LINK_VERSION)
289   if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
290       strlen(HOST_LINK_VERSION) > 0) {
291     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
292                       HOST_LINK_VERSION);
293     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
294   }
295 #endif
296 
297   return DAL;
298 }
299 
300 /// \brief Compute target triple from args.
301 ///
302 /// This routine provides the logic to compute a target triple from various
303 /// args passed to the driver and the default triple string.
304 static llvm::Triple computeTargetTriple(const Driver &D,
305                                         StringRef DefaultTargetTriple,
306                                         const ArgList &Args,
307                                         StringRef DarwinArchName = "") {
308   // FIXME: Already done in Compilation *Driver::BuildCompilation
309   if (const Arg *A = Args.getLastArg(options::OPT_target))
310     DefaultTargetTriple = A->getValue();
311 
312   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
313 
314   // Handle Apple-specific options available here.
315   if (Target.isOSBinFormatMachO()) {
316     // If an explict Darwin arch name is given, that trumps all.
317     if (!DarwinArchName.empty()) {
318       tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
319       return Target;
320     }
321 
322     // Handle the Darwin '-arch' flag.
323     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
324       StringRef ArchName = A->getValue();
325       tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
326     }
327   }
328 
329   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
330   // '-mbig-endian'/'-EB'.
331   if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
332                                options::OPT_mbig_endian)) {
333     if (A->getOption().matches(options::OPT_mlittle_endian)) {
334       llvm::Triple LE = Target.getLittleEndianArchVariant();
335       if (LE.getArch() != llvm::Triple::UnknownArch)
336         Target = std::move(LE);
337     } else {
338       llvm::Triple BE = Target.getBigEndianArchVariant();
339       if (BE.getArch() != llvm::Triple::UnknownArch)
340         Target = std::move(BE);
341     }
342   }
343 
344   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
345   if (Target.getArch() == llvm::Triple::tce ||
346       Target.getOS() == llvm::Triple::Minix)
347     return Target;
348 
349   // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
350   Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
351                            options::OPT_m32, options::OPT_m16);
352   if (A) {
353     llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
354 
355     if (A->getOption().matches(options::OPT_m64)) {
356       AT = Target.get64BitArchVariant().getArch();
357       if (Target.getEnvironment() == llvm::Triple::GNUX32)
358         Target.setEnvironment(llvm::Triple::GNU);
359     } else if (A->getOption().matches(options::OPT_mx32) &&
360                Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
361       AT = llvm::Triple::x86_64;
362       Target.setEnvironment(llvm::Triple::GNUX32);
363     } else if (A->getOption().matches(options::OPT_m32)) {
364       AT = Target.get32BitArchVariant().getArch();
365       if (Target.getEnvironment() == llvm::Triple::GNUX32)
366         Target.setEnvironment(llvm::Triple::GNU);
367     } else if (A->getOption().matches(options::OPT_m16) &&
368                Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
369       AT = llvm::Triple::x86;
370       Target.setEnvironment(llvm::Triple::CODE16);
371     }
372 
373     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
374       Target.setArch(AT);
375   }
376 
377   // Handle -miamcu flag.
378   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
379     if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
380       D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
381                                                        << Target.str();
382 
383     if (A && !A->getOption().matches(options::OPT_m32))
384       D.Diag(diag::err_drv_argument_not_allowed_with)
385           << "-miamcu" << A->getBaseArg().getAsString(Args);
386 
387     Target.setArch(llvm::Triple::x86);
388     Target.setArchName("i586");
389     Target.setEnvironment(llvm::Triple::UnknownEnvironment);
390     Target.setEnvironmentName("");
391     Target.setOS(llvm::Triple::ELFIAMCU);
392     Target.setVendor(llvm::Triple::UnknownVendor);
393     Target.setVendorName("intel");
394   }
395 
396   return Target;
397 }
398 
399 // \brief Parse the LTO options and record the type of LTO compilation
400 // based on which -f(no-)?lto(=.*)? option occurs last.
401 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
402   LTOMode = LTOK_None;
403   if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
404                     options::OPT_fno_lto, false))
405     return;
406 
407   StringRef LTOName("full");
408 
409   const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
410   if (A)
411     LTOName = A->getValue();
412 
413   LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
414                 .Case("full", LTOK_Full)
415                 .Case("thin", LTOK_Thin)
416                 .Default(LTOK_Unknown);
417 
418   if (LTOMode == LTOK_Unknown) {
419     assert(A);
420     Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
421                                                     << A->getValue();
422   }
423 }
424 
425 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
426                                               InputList &Inputs) {
427 
428   //
429   // CUDA
430   //
431   // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
432   if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
433         return types::isCuda(I.first);
434       })) {
435     const ToolChain &TC = getToolChain(
436         C.getInputArgs(),
437         llvm::Triple(C.getSingleOffloadToolChain<Action::OFK_Host>()
438                              ->getTriple()
439                              .isArch64Bit()
440                          ? "nvptx64-nvidia-cuda"
441                          : "nvptx-nvidia-cuda"));
442     C.addOffloadDeviceToolChain(&TC, Action::OFK_Cuda);
443   }
444 
445   //
446   // TODO: Add support for other offloading programming models here.
447   //
448 
449   return;
450 }
451 
452 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
453   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
454 
455   // FIXME: Handle environment options which affect driver behavior, somewhere
456   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
457 
458   if (Optional<std::string> CompilerPathValue =
459           llvm::sys::Process::GetEnv("COMPILER_PATH")) {
460     StringRef CompilerPath = *CompilerPathValue;
461     while (!CompilerPath.empty()) {
462       std::pair<StringRef, StringRef> Split =
463           CompilerPath.split(llvm::sys::EnvPathSeparator);
464       PrefixDirs.push_back(Split.first);
465       CompilerPath = Split.second;
466     }
467   }
468 
469   // We look for the driver mode option early, because the mode can affect
470   // how other options are parsed.
471   ParseDriverMode(ArgList.slice(1));
472 
473   // FIXME: What are we going to do with -V and -b?
474 
475   // FIXME: This stuff needs to go into the Compilation, not the driver.
476   bool CCCPrintPhases;
477 
478   InputArgList Args = ParseArgStrings(ArgList.slice(1));
479 
480   // Silence driver warnings if requested
481   Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
482 
483   // -no-canonical-prefixes is used very early in main.
484   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
485 
486   // Ignore -pipe.
487   Args.ClaimAllArgs(options::OPT_pipe);
488 
489   // Extract -ccc args.
490   //
491   // FIXME: We need to figure out where this behavior should live. Most of it
492   // should be outside in the client; the parts that aren't should have proper
493   // options, either by introducing new ones or by overloading gcc ones like -V
494   // or -b.
495   CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
496   CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
497   if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
498     CCCGenericGCCName = A->getValue();
499   CCCUsePCH =
500       Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
501   // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
502   // and getToolChain is const.
503   if (IsCLMode()) {
504     // clang-cl targets MSVC-style Win32.
505     llvm::Triple T(DefaultTargetTriple);
506     T.setOS(llvm::Triple::Win32);
507     T.setVendor(llvm::Triple::PC);
508     T.setEnvironment(llvm::Triple::MSVC);
509     DefaultTargetTriple = T.str();
510   }
511   if (const Arg *A = Args.getLastArg(options::OPT_target))
512     DefaultTargetTriple = A->getValue();
513   if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
514     Dir = InstalledDir = A->getValue();
515   for (const Arg *A : Args.filtered(options::OPT_B)) {
516     A->claim();
517     PrefixDirs.push_back(A->getValue(0));
518   }
519   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
520     SysRoot = A->getValue();
521   if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
522     DyldPrefix = A->getValue();
523   if (Args.hasArg(options::OPT_nostdlib))
524     UseStdLib = false;
525 
526   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
527     ResourceDir = A->getValue();
528 
529   if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
530     SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
531                     .Case("cwd", SaveTempsCwd)
532                     .Case("obj", SaveTempsObj)
533                     .Default(SaveTempsCwd);
534   }
535 
536   setLTOMode(Args);
537 
538   // Ignore -fembed-bitcode options with LTO
539   // since the output will be bitcode anyway.
540   if (getLTOMode() == LTOK_None) {
541     if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
542       StringRef Name = A->getValue();
543       unsigned Model = llvm::StringSwitch<unsigned>(Name)
544           .Case("off", EmbedNone)
545           .Case("all", EmbedBitcode)
546           .Case("bitcode", EmbedBitcode)
547           .Case("marker", EmbedMarker)
548           .Default(~0U);
549       if (Model == ~0U) {
550         Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
551                                                   << Name;
552       } else
553         BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
554     }
555   } else {
556     // claim the bitcode option under LTO so no warning is issued.
557     Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ);
558   }
559 
560   std::unique_ptr<llvm::opt::InputArgList> UArgs =
561       llvm::make_unique<InputArgList>(std::move(Args));
562 
563   // Perform the default argument translations.
564   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
565 
566   // Owned by the host.
567   const ToolChain &TC = getToolChain(
568       *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
569 
570   // The compilation takes ownership of Args.
571   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
572 
573   if (!HandleImmediateArgs(*C))
574     return C;
575 
576   // Construct the list of inputs.
577   InputList Inputs;
578   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
579 
580   // Populate the tool chains for the offloading devices, if any.
581   CreateOffloadingDeviceToolChains(*C, Inputs);
582 
583   // Construct the list of abstract actions to perform for this compilation. On
584   // MachO targets this uses the driver-driver and universal actions.
585   if (TC.getTriple().isOSBinFormatMachO())
586     BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
587   else
588     BuildActions(*C, C->getArgs(), Inputs, C->getActions());
589 
590   if (CCCPrintPhases) {
591     PrintActions(*C);
592     return C;
593   }
594 
595   BuildJobs(*C);
596 
597   return C;
598 }
599 
600 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
601   llvm::opt::ArgStringList ASL;
602   for (const auto *A : Args)
603     A->render(Args, ASL);
604 
605   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
606     if (I != ASL.begin())
607       OS << ' ';
608     Command::printArg(OS, *I, true);
609   }
610   OS << '\n';
611 }
612 
613 // When clang crashes, produce diagnostic information including the fully
614 // preprocessed source file(s).  Request that the developer attach the
615 // diagnostic information to a bug report.
616 void Driver::generateCompilationDiagnostics(Compilation &C,
617                                             const Command &FailingCommand) {
618   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
619     return;
620 
621   // Don't try to generate diagnostics for link or dsymutil jobs.
622   if (FailingCommand.getCreator().isLinkJob() ||
623       FailingCommand.getCreator().isDsymutilJob())
624     return;
625 
626   // Print the version of the compiler.
627   PrintVersion(C, llvm::errs());
628 
629   Diag(clang::diag::note_drv_command_failed_diag_msg)
630       << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
631          "crash backtrace, preprocessed source, and associated run script.";
632 
633   // Suppress driver output and emit preprocessor output to temp file.
634   Mode = CPPMode;
635   CCGenDiagnostics = true;
636 
637   // Save the original job command(s).
638   Command Cmd = FailingCommand;
639 
640   // Keep track of whether we produce any errors while trying to produce
641   // preprocessed sources.
642   DiagnosticErrorTrap Trap(Diags);
643 
644   // Suppress tool output.
645   C.initCompilationForDiagnostics();
646 
647   // Construct the list of inputs.
648   InputList Inputs;
649   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
650 
651   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
652     bool IgnoreInput = false;
653 
654     // Ignore input from stdin or any inputs that cannot be preprocessed.
655     // Check type first as not all linker inputs have a value.
656     if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
657       IgnoreInput = true;
658     } else if (!strcmp(it->second->getValue(), "-")) {
659       Diag(clang::diag::note_drv_command_failed_diag_msg)
660           << "Error generating preprocessed source(s) - "
661              "ignoring input from stdin.";
662       IgnoreInput = true;
663     }
664 
665     if (IgnoreInput) {
666       it = Inputs.erase(it);
667       ie = Inputs.end();
668     } else {
669       ++it;
670     }
671   }
672 
673   if (Inputs.empty()) {
674     Diag(clang::diag::note_drv_command_failed_diag_msg)
675         << "Error generating preprocessed source(s) - "
676            "no preprocessable inputs.";
677     return;
678   }
679 
680   // Don't attempt to generate preprocessed files if multiple -arch options are
681   // used, unless they're all duplicates.
682   llvm::StringSet<> ArchNames;
683   for (const Arg *A : C.getArgs()) {
684     if (A->getOption().matches(options::OPT_arch)) {
685       StringRef ArchName = A->getValue();
686       ArchNames.insert(ArchName);
687     }
688   }
689   if (ArchNames.size() > 1) {
690     Diag(clang::diag::note_drv_command_failed_diag_msg)
691         << "Error generating preprocessed source(s) - cannot generate "
692            "preprocessed source with multiple -arch options.";
693     return;
694   }
695 
696   // Construct the list of abstract actions to perform for this compilation. On
697   // Darwin OSes this uses the driver-driver and builds universal actions.
698   const ToolChain &TC = C.getDefaultToolChain();
699   if (TC.getTriple().isOSBinFormatMachO())
700     BuildUniversalActions(C, TC, Inputs);
701   else
702     BuildActions(C, C.getArgs(), Inputs, C.getActions());
703 
704   BuildJobs(C);
705 
706   // If there were errors building the compilation, quit now.
707   if (Trap.hasErrorOccurred()) {
708     Diag(clang::diag::note_drv_command_failed_diag_msg)
709         << "Error generating preprocessed source(s).";
710     return;
711   }
712 
713   // Generate preprocessed output.
714   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
715   C.ExecuteJobs(C.getJobs(), FailingCommands);
716 
717   // If any of the preprocessing commands failed, clean up and exit.
718   if (!FailingCommands.empty()) {
719     if (!isSaveTempsEnabled())
720       C.CleanupFileList(C.getTempFiles(), true);
721 
722     Diag(clang::diag::note_drv_command_failed_diag_msg)
723         << "Error generating preprocessed source(s).";
724     return;
725   }
726 
727   const ArgStringList &TempFiles = C.getTempFiles();
728   if (TempFiles.empty()) {
729     Diag(clang::diag::note_drv_command_failed_diag_msg)
730         << "Error generating preprocessed source(s).";
731     return;
732   }
733 
734   Diag(clang::diag::note_drv_command_failed_diag_msg)
735       << "\n********************\n\n"
736          "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
737          "Preprocessed source(s) and associated run script(s) are located at:";
738 
739   SmallString<128> VFS;
740   for (const char *TempFile : TempFiles) {
741     Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
742     if (StringRef(TempFile).endswith(".cache")) {
743       // In some cases (modules) we'll dump extra data to help with reproducing
744       // the crash into a directory next to the output.
745       VFS = llvm::sys::path::filename(TempFile);
746       llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
747     }
748   }
749 
750   // Assume associated files are based off of the first temporary file.
751   CrashReportInfo CrashInfo(TempFiles[0], VFS);
752 
753   std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
754   std::error_code EC;
755   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
756   if (EC) {
757     Diag(clang::diag::note_drv_command_failed_diag_msg)
758         << "Error generating run script: " + Script + " " + EC.message();
759   } else {
760     ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
761              << "# Driver args: ";
762     printArgList(ScriptOS, C.getInputArgs());
763     ScriptOS << "# Original command: ";
764     Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
765     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
766     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
767   }
768 
769   for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
770                                             options::OPT_frewrite_map_file_EQ))
771     Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
772 
773   Diag(clang::diag::note_drv_command_failed_diag_msg)
774       << "\n\n********************";
775 }
776 
777 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
778   // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
779   // if the tool does not support response files, there is a chance/ that things
780   // will just work without a response file, so we silently just skip it.
781   if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
782       llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
783     return;
784 
785   std::string TmpName = GetTemporaryPath("response", "txt");
786   Cmd.setResponseFile(
787       C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
788 }
789 
790 int Driver::ExecuteCompilation(
791     Compilation &C,
792     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
793   // Just print if -### was present.
794   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
795     C.getJobs().Print(llvm::errs(), "\n", true);
796     return 0;
797   }
798 
799   // If there were errors building the compilation, quit now.
800   if (Diags.hasErrorOccurred())
801     return 1;
802 
803   // Set up response file names for each command, if necessary
804   for (auto &Job : C.getJobs())
805     setUpResponseFiles(C, Job);
806 
807   C.ExecuteJobs(C.getJobs(), FailingCommands);
808 
809   // Remove temp files.
810   C.CleanupFileList(C.getTempFiles());
811 
812   // If the command succeeded, we are done.
813   if (FailingCommands.empty())
814     return 0;
815 
816   // Otherwise, remove result files and print extra information about abnormal
817   // failures.
818   for (const auto &CmdPair : FailingCommands) {
819     int Res = CmdPair.first;
820     const Command *FailingCommand = CmdPair.second;
821 
822     // Remove result files if we're not saving temps.
823     if (!isSaveTempsEnabled()) {
824       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
825       C.CleanupFileMap(C.getResultFiles(), JA, true);
826 
827       // Failure result files are valid unless we crashed.
828       if (Res < 0)
829         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
830     }
831 
832     // Print extra information about abnormal failures, if possible.
833     //
834     // This is ad-hoc, but we don't want to be excessively noisy. If the result
835     // status was 1, assume the command failed normally. In particular, if it
836     // was the compiler then assume it gave a reasonable error code. Failures
837     // in other tools are less common, and they generally have worse
838     // diagnostics, so always print the diagnostic there.
839     const Tool &FailingTool = FailingCommand->getCreator();
840 
841     if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
842       // FIXME: See FIXME above regarding result code interpretation.
843       if (Res < 0)
844         Diag(clang::diag::err_drv_command_signalled)
845             << FailingTool.getShortName();
846       else
847         Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
848                                                   << Res;
849     }
850   }
851   return 0;
852 }
853 
854 void Driver::PrintHelp(bool ShowHidden) const {
855   unsigned IncludedFlagsBitmask;
856   unsigned ExcludedFlagsBitmask;
857   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
858       getIncludeExcludeOptionFlagMasks();
859 
860   ExcludedFlagsBitmask |= options::NoDriverOption;
861   if (!ShowHidden)
862     ExcludedFlagsBitmask |= HelpHidden;
863 
864   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
865                       IncludedFlagsBitmask, ExcludedFlagsBitmask);
866 }
867 
868 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
869   // FIXME: The following handlers should use a callback mechanism, we don't
870   // know what the client would like to do.
871   OS << getClangFullVersion() << '\n';
872   const ToolChain &TC = C.getDefaultToolChain();
873   OS << "Target: " << TC.getTripleString() << '\n';
874 
875   // Print the threading model.
876   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
877     // Don't print if the ToolChain would have barfed on it already
878     if (TC.isThreadModelSupported(A->getValue()))
879       OS << "Thread model: " << A->getValue();
880   } else
881     OS << "Thread model: " << TC.getThreadModel();
882   OS << '\n';
883 
884   // Print out the install directory.
885   OS << "InstalledDir: " << InstalledDir << '\n';
886 }
887 
888 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
889 /// option.
890 static void PrintDiagnosticCategories(raw_ostream &OS) {
891   // Skip the empty category.
892   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
893        ++i)
894     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
895 }
896 
897 bool Driver::HandleImmediateArgs(const Compilation &C) {
898   // The order these options are handled in gcc is all over the place, but we
899   // don't expect inconsistencies w.r.t. that to matter in practice.
900 
901   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
902     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
903     return false;
904   }
905 
906   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
907     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
908     // return an answer which matches our definition of __VERSION__.
909     //
910     // If we want to return a more correct answer some day, then we should
911     // introduce a non-pedantically GCC compatible mode to Clang in which we
912     // provide sensible definitions for -dumpversion, __VERSION__, etc.
913     llvm::outs() << "4.2.1\n";
914     return false;
915   }
916 
917   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
918     PrintDiagnosticCategories(llvm::outs());
919     return false;
920   }
921 
922   if (C.getArgs().hasArg(options::OPT_help) ||
923       C.getArgs().hasArg(options::OPT__help_hidden)) {
924     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
925     return false;
926   }
927 
928   if (C.getArgs().hasArg(options::OPT__version)) {
929     // Follow gcc behavior and use stdout for --version and stderr for -v.
930     PrintVersion(C, llvm::outs());
931     return false;
932   }
933 
934   if (C.getArgs().hasArg(options::OPT_v) ||
935       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
936     PrintVersion(C, llvm::errs());
937     SuppressMissingInputWarning = true;
938   }
939 
940   const ToolChain &TC = C.getDefaultToolChain();
941 
942   if (C.getArgs().hasArg(options::OPT_v))
943     TC.printVerboseInfo(llvm::errs());
944 
945   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
946     llvm::outs() << "programs: =";
947     bool separator = false;
948     for (const std::string &Path : TC.getProgramPaths()) {
949       if (separator)
950         llvm::outs() << ':';
951       llvm::outs() << Path;
952       separator = true;
953     }
954     llvm::outs() << "\n";
955     llvm::outs() << "libraries: =" << ResourceDir;
956 
957     StringRef sysroot = C.getSysRoot();
958 
959     for (const std::string &Path : TC.getFilePaths()) {
960       // Always print a separator. ResourceDir was the first item shown.
961       llvm::outs() << ':';
962       // Interpretation of leading '=' is needed only for NetBSD.
963       if (Path[0] == '=')
964         llvm::outs() << sysroot << Path.substr(1);
965       else
966         llvm::outs() << Path;
967     }
968     llvm::outs() << "\n";
969     return false;
970   }
971 
972   // FIXME: The following handlers should use a callback mechanism, we don't
973   // know what the client would like to do.
974   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
975     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
976     return false;
977   }
978 
979   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
980     llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
981     return false;
982   }
983 
984   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
985     llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
986     return false;
987   }
988 
989   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
990     for (const Multilib &Multilib : TC.getMultilibs())
991       llvm::outs() << Multilib << "\n";
992     return false;
993   }
994 
995   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
996     for (const Multilib &Multilib : TC.getMultilibs()) {
997       if (Multilib.gccSuffix().empty())
998         llvm::outs() << ".\n";
999       else {
1000         StringRef Suffix(Multilib.gccSuffix());
1001         assert(Suffix.front() == '/');
1002         llvm::outs() << Suffix.substr(1) << "\n";
1003       }
1004     }
1005     return false;
1006   }
1007   return true;
1008 }
1009 
1010 // Display an action graph human-readably.  Action A is the "sink" node
1011 // and latest-occuring action. Traversal is in pre-order, visiting the
1012 // inputs to each action before printing the action itself.
1013 static unsigned PrintActions1(const Compilation &C, Action *A,
1014                               std::map<Action *, unsigned> &Ids) {
1015   if (Ids.count(A)) // A was already visited.
1016     return Ids[A];
1017 
1018   std::string str;
1019   llvm::raw_string_ostream os(str);
1020 
1021   os << Action::getClassName(A->getKind()) << ", ";
1022   if (InputAction *IA = dyn_cast<InputAction>(A)) {
1023     os << "\"" << IA->getInputArg().getValue() << "\"";
1024   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1025     os << '"' << BIA->getArchName() << '"' << ", {"
1026        << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1027   } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1028     bool IsFirst = true;
1029     OA->doOnEachDependence(
1030         [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1031           // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1032           // sm_35 this will generate:
1033           // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1034           // (nvptx64-nvidia-cuda:sm_35) {#ID}
1035           if (!IsFirst)
1036             os << ", ";
1037           os << '"';
1038           if (TC)
1039             os << A->getOffloadingKindPrefix();
1040           else
1041             os << "host";
1042           os << " (";
1043           os << TC->getTriple().normalize();
1044 
1045           if (BoundArch)
1046             os << ":" << BoundArch;
1047           os << ")";
1048           os << '"';
1049           os << " {" << PrintActions1(C, A, Ids) << "}";
1050           IsFirst = false;
1051         });
1052   } else {
1053     const ActionList *AL = &A->getInputs();
1054 
1055     if (AL->size()) {
1056       const char *Prefix = "{";
1057       for (Action *PreRequisite : *AL) {
1058         os << Prefix << PrintActions1(C, PreRequisite, Ids);
1059         Prefix = ", ";
1060       }
1061       os << "}";
1062     } else
1063       os << "{}";
1064   }
1065 
1066   // Append offload info for all options other than the offloading action
1067   // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1068   std::string offload_str;
1069   llvm::raw_string_ostream offload_os(offload_str);
1070   if (!isa<OffloadAction>(A)) {
1071     auto S = A->getOffloadingKindPrefix();
1072     if (!S.empty()) {
1073       offload_os << ", (" << S;
1074       if (A->getOffloadingArch())
1075         offload_os << ", " << A->getOffloadingArch();
1076       offload_os << ")";
1077     }
1078   }
1079 
1080   unsigned Id = Ids.size();
1081   Ids[A] = Id;
1082   llvm::errs() << Id << ": " << os.str() << ", "
1083                << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1084 
1085   return Id;
1086 }
1087 
1088 // Print the action graphs in a compilation C.
1089 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1090 void Driver::PrintActions(const Compilation &C) const {
1091   std::map<Action *, unsigned> Ids;
1092   for (Action *A : C.getActions())
1093     PrintActions1(C, A, Ids);
1094 }
1095 
1096 /// \brief Check whether the given input tree contains any compilation or
1097 /// assembly actions.
1098 static bool ContainsCompileOrAssembleAction(const Action *A) {
1099   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1100       isa<AssembleJobAction>(A))
1101     return true;
1102 
1103   for (const Action *Input : A->inputs())
1104     if (ContainsCompileOrAssembleAction(Input))
1105       return true;
1106 
1107   return false;
1108 }
1109 
1110 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1111                                    const InputList &BAInputs) const {
1112   DerivedArgList &Args = C.getArgs();
1113   ActionList &Actions = C.getActions();
1114   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1115   // Collect the list of architectures. Duplicates are allowed, but should only
1116   // be handled once (in the order seen).
1117   llvm::StringSet<> ArchNames;
1118   SmallVector<const char *, 4> Archs;
1119   for (Arg *A : Args) {
1120     if (A->getOption().matches(options::OPT_arch)) {
1121       // Validate the option here; we don't save the type here because its
1122       // particular spelling may participate in other driver choices.
1123       llvm::Triple::ArchType Arch =
1124           tools::darwin::getArchTypeForMachOArchName(A->getValue());
1125       if (Arch == llvm::Triple::UnknownArch) {
1126         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1127         continue;
1128       }
1129 
1130       A->claim();
1131       if (ArchNames.insert(A->getValue()).second)
1132         Archs.push_back(A->getValue());
1133     }
1134   }
1135 
1136   // When there is no explicit arch for this platform, make sure we still bind
1137   // the architecture (to the default) so that -Xarch_ is handled correctly.
1138   if (!Archs.size())
1139     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1140 
1141   ActionList SingleActions;
1142   BuildActions(C, Args, BAInputs, SingleActions);
1143 
1144   // Add in arch bindings for every top level action, as well as lipo and
1145   // dsymutil steps if needed.
1146   for (Action* Act : SingleActions) {
1147     // Make sure we can lipo this kind of output. If not (and it is an actual
1148     // output) then we disallow, since we can't create an output file with the
1149     // right name without overwriting it. We could remove this oddity by just
1150     // changing the output names to include the arch, which would also fix
1151     // -save-temps. Compatibility wins for now.
1152 
1153     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1154       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1155           << types::getTypeName(Act->getType());
1156 
1157     ActionList Inputs;
1158     for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1159       Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1160 
1161     // Lipo if necessary, we do it this way because we need to set the arch flag
1162     // so that -Xarch_ gets overwritten.
1163     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1164       Actions.append(Inputs.begin(), Inputs.end());
1165     else
1166       Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1167 
1168     // Handle debug info queries.
1169     Arg *A = Args.getLastArg(options::OPT_g_Group);
1170     if (A && !A->getOption().matches(options::OPT_g0) &&
1171         !A->getOption().matches(options::OPT_gstabs) &&
1172         ContainsCompileOrAssembleAction(Actions.back())) {
1173 
1174       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1175       // have a compile input. We need to run 'dsymutil' ourselves in such cases
1176       // because the debug info will refer to a temporary object file which
1177       // will be removed at the end of the compilation process.
1178       if (Act->getType() == types::TY_Image) {
1179         ActionList Inputs;
1180         Inputs.push_back(Actions.back());
1181         Actions.pop_back();
1182         Actions.push_back(
1183             C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1184       }
1185 
1186       // Verify the debug info output.
1187       if (Args.hasArg(options::OPT_verify_debug_info)) {
1188         Action* LastAction = Actions.back();
1189         Actions.pop_back();
1190         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1191             LastAction, types::TY_Nothing));
1192       }
1193     }
1194   }
1195 }
1196 
1197 /// \brief Check that the file referenced by Value exists. If it doesn't,
1198 /// issue a diagnostic and return false.
1199 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1200                                    StringRef Value, types::ID Ty) {
1201   if (!D.getCheckInputsExist())
1202     return true;
1203 
1204   // stdin always exists.
1205   if (Value == "-")
1206     return true;
1207 
1208   SmallString<64> Path(Value);
1209   if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1210     if (!llvm::sys::path::is_absolute(Path)) {
1211       SmallString<64> Directory(WorkDir->getValue());
1212       llvm::sys::path::append(Directory, Value);
1213       Path.assign(Directory);
1214     }
1215   }
1216 
1217   if (llvm::sys::fs::exists(Twine(Path)))
1218     return true;
1219 
1220   if (D.IsCLMode()) {
1221     if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1222         llvm::sys::Process::FindInEnvPath("LIB", Value))
1223       return true;
1224 
1225     if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1226       // Arguments to the /link flag might cause the linker to search for object
1227       // and library files in paths we don't know about. Don't error in such
1228       // cases.
1229       return true;
1230     }
1231   }
1232 
1233   D.Diag(clang::diag::err_drv_no_such_file) << Path;
1234   return false;
1235 }
1236 
1237 // Construct a the list of inputs and their types.
1238 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1239                          InputList &Inputs) const {
1240   // Track the current user specified (-x) input. We also explicitly track the
1241   // argument used to set the type; we only want to claim the type when we
1242   // actually use it, so we warn about unused -x arguments.
1243   types::ID InputType = types::TY_Nothing;
1244   Arg *InputTypeArg = nullptr;
1245 
1246   // The last /TC or /TP option sets the input type to C or C++ globally.
1247   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1248                                          options::OPT__SLASH_TP)) {
1249     InputTypeArg = TCTP;
1250     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1251                     ? types::TY_C
1252                     : types::TY_CXX;
1253 
1254     arg_iterator it =
1255         Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
1256     const arg_iterator ie = Args.filtered_end();
1257     Arg *Previous = *it++;
1258     bool ShowNote = false;
1259     while (it != ie) {
1260       Diag(clang::diag::warn_drv_overriding_flag_option)
1261           << Previous->getSpelling() << (*it)->getSpelling();
1262       Previous = *it++;
1263       ShowNote = true;
1264     }
1265     if (ShowNote)
1266       Diag(clang::diag::note_drv_t_option_is_global);
1267 
1268     // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1269     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1270   }
1271 
1272   for (Arg *A : Args) {
1273     if (A->getOption().getKind() == Option::InputClass) {
1274       const char *Value = A->getValue();
1275       types::ID Ty = types::TY_INVALID;
1276 
1277       // Infer the input type if necessary.
1278       if (InputType == types::TY_Nothing) {
1279         // If there was an explicit arg for this, claim it.
1280         if (InputTypeArg)
1281           InputTypeArg->claim();
1282 
1283         // stdin must be handled specially.
1284         if (memcmp(Value, "-", 2) == 0) {
1285           // If running with -E, treat as a C input (this changes the builtin
1286           // macros, for example). This may be overridden by -ObjC below.
1287           //
1288           // Otherwise emit an error but still use a valid type to avoid
1289           // spurious errors (e.g., no inputs).
1290           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1291             Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1292                             : clang::diag::err_drv_unknown_stdin_type);
1293           Ty = types::TY_C;
1294         } else {
1295           // Otherwise lookup by extension.
1296           // Fallback is C if invoked as C preprocessor or Object otherwise.
1297           // We use a host hook here because Darwin at least has its own
1298           // idea of what .s is.
1299           if (const char *Ext = strrchr(Value, '.'))
1300             Ty = TC.LookupTypeForExtension(Ext + 1);
1301 
1302           if (Ty == types::TY_INVALID) {
1303             if (CCCIsCPP())
1304               Ty = types::TY_C;
1305             else
1306               Ty = types::TY_Object;
1307           }
1308 
1309           // If the driver is invoked as C++ compiler (like clang++ or c++) it
1310           // should autodetect some input files as C++ for g++ compatibility.
1311           if (CCCIsCXX()) {
1312             types::ID OldTy = Ty;
1313             Ty = types::lookupCXXTypeForCType(Ty);
1314 
1315             if (Ty != OldTy)
1316               Diag(clang::diag::warn_drv_treating_input_as_cxx)
1317                   << getTypeName(OldTy) << getTypeName(Ty);
1318           }
1319         }
1320 
1321         // -ObjC and -ObjC++ override the default language, but only for "source
1322         // files". We just treat everything that isn't a linker input as a
1323         // source file.
1324         //
1325         // FIXME: Clean this up if we move the phase sequence into the type.
1326         if (Ty != types::TY_Object) {
1327           if (Args.hasArg(options::OPT_ObjC))
1328             Ty = types::TY_ObjC;
1329           else if (Args.hasArg(options::OPT_ObjCXX))
1330             Ty = types::TY_ObjCXX;
1331         }
1332       } else {
1333         assert(InputTypeArg && "InputType set w/o InputTypeArg");
1334         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1335           // If emulating cl.exe, make sure that /TC and /TP don't affect input
1336           // object files.
1337           const char *Ext = strrchr(Value, '.');
1338           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1339             Ty = types::TY_Object;
1340         }
1341         if (Ty == types::TY_INVALID) {
1342           Ty = InputType;
1343           InputTypeArg->claim();
1344         }
1345       }
1346 
1347       if (DiagnoseInputExistence(*this, Args, Value, Ty))
1348         Inputs.push_back(std::make_pair(Ty, A));
1349 
1350     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1351       StringRef Value = A->getValue();
1352       if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1353         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1354         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1355       }
1356       A->claim();
1357     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1358       StringRef Value = A->getValue();
1359       if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1360         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1361         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1362       }
1363       A->claim();
1364     } else if (A->getOption().hasFlag(options::LinkerInput)) {
1365       // Just treat as object type, we could make a special type for this if
1366       // necessary.
1367       Inputs.push_back(std::make_pair(types::TY_Object, A));
1368 
1369     } else if (A->getOption().matches(options::OPT_x)) {
1370       InputTypeArg = A;
1371       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1372       A->claim();
1373 
1374       // Follow gcc behavior and treat as linker input for invalid -x
1375       // options. Its not clear why we shouldn't just revert to unknown; but
1376       // this isn't very important, we might as well be bug compatible.
1377       if (!InputType) {
1378         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1379         InputType = types::TY_Object;
1380       }
1381     }
1382   }
1383   if (CCCIsCPP() && Inputs.empty()) {
1384     // If called as standalone preprocessor, stdin is processed
1385     // if no other input is present.
1386     Arg *A = MakeInputArg(Args, Opts, "-");
1387     Inputs.push_back(std::make_pair(types::TY_C, A));
1388   }
1389 }
1390 
1391 // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE
1392 // input action and then wraps each in CudaDeviceAction paired with
1393 // appropriate GPU arch name. In case of partial (i.e preprocessing
1394 // only) or device-only compilation, each device action is added to /p
1395 // Actions and /p Current is released. Otherwise the function creates
1396 // and returns a new CudaHostAction which wraps /p Current and device
1397 // side actions.
1398 static Action *buildCudaActions(Compilation &C, DerivedArgList &Args,
1399                                 const Arg *InputArg, Action *HostAction,
1400                                 ActionList &Actions) {
1401   Arg *PartialCompilationArg = Args.getLastArg(
1402       options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1403       options::OPT_cuda_compile_host_device);
1404   bool CompileHostOnly =
1405       PartialCompilationArg &&
1406       PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only);
1407   bool CompileDeviceOnly =
1408       PartialCompilationArg &&
1409       PartialCompilationArg->getOption().matches(options::OPT_cuda_device_only);
1410   const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1411   assert(HostTC && "No toolchain for host compilation.");
1412   if (HostTC->getTriple().isNVPTX()) {
1413     // We do not support targeting NVPTX for host compilation. Throw
1414     // an error and abort pipeline construction early so we don't trip
1415     // asserts that assume device-side compilation.
1416     C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1417     return nullptr;
1418   }
1419 
1420   if (CompileHostOnly) {
1421     OffloadAction::HostDependence HDep(*HostAction, *HostTC,
1422                                        /*BoundArch=*/nullptr, Action::OFK_Cuda);
1423     return C.MakeAction<OffloadAction>(HDep);
1424   }
1425 
1426   // Collect all cuda_gpu_arch parameters, removing duplicates.
1427   SmallVector<CudaArch, 4> GpuArchList;
1428   llvm::SmallSet<CudaArch, 4> GpuArchs;
1429   for (Arg *A : Args) {
1430     if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1431       continue;
1432     A->claim();
1433 
1434     const auto &ArchStr = A->getValue();
1435     CudaArch Arch = StringToCudaArch(ArchStr);
1436     if (Arch == CudaArch::UNKNOWN)
1437       C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1438     else if (GpuArchs.insert(Arch).second)
1439       GpuArchList.push_back(Arch);
1440   }
1441 
1442   // Default to sm_20 which is the lowest common denominator for supported GPUs.
1443   // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
1444   if (GpuArchList.empty())
1445     GpuArchList.push_back(CudaArch::SM_20);
1446 
1447   // Replicate inputs for each GPU architecture.
1448   Driver::InputList CudaDeviceInputs;
1449   for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1450     CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
1451 
1452   // Build actions for all device inputs.
1453   ActionList CudaDeviceActions;
1454   C.getDriver().BuildActions(C, Args, CudaDeviceInputs, CudaDeviceActions);
1455   assert(GpuArchList.size() == CudaDeviceActions.size() &&
1456          "Failed to create actions for all devices");
1457 
1458   // Check whether any of device actions stopped before they could generate PTX.
1459   bool PartialCompilation =
1460       llvm::any_of(CudaDeviceActions, [](const Action *a) {
1461         return a->getKind() != Action::AssembleJobClass;
1462       });
1463 
1464   const ToolChain *CudaTC = C.getSingleOffloadToolChain<Action::OFK_Cuda>();
1465 
1466   // Figure out what to do with device actions -- pass them as inputs to the
1467   // host action or run each of them independently.
1468   if (PartialCompilation || CompileDeviceOnly) {
1469     // In case of partial or device-only compilation results of device actions
1470     // are not consumed by the host action device actions have to be added to
1471     // top-level actions list with AtTopLevel=true and run independently.
1472 
1473     // -o is ambiguous if we have more than one top-level action.
1474     if (Args.hasArg(options::OPT_o) &&
1475         (!CompileDeviceOnly || GpuArchList.size() > 1)) {
1476       C.getDriver().Diag(
1477           clang::diag::err_drv_output_argument_with_multiple_files);
1478       return nullptr;
1479     }
1480 
1481     for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1482       OffloadAction::DeviceDependences DDep;
1483       DDep.add(*CudaDeviceActions[I], *CudaTC, CudaArchToString(GpuArchList[I]),
1484                Action::OFK_Cuda);
1485       Actions.push_back(
1486           C.MakeAction<OffloadAction>(DDep, CudaDeviceActions[I]->getType()));
1487     }
1488     // Kill host action in case of device-only compilation.
1489     if (CompileDeviceOnly)
1490       return nullptr;
1491     return HostAction;
1492   }
1493 
1494   // If we're not a partial or device-only compilation, we compile each arch to
1495   // ptx and assemble to cubin, then feed the cubin *and* the ptx into a device
1496   // "link" action, which uses fatbinary to combine these cubins into one
1497   // fatbin.  The fatbin is then an input to the host compilation.
1498   ActionList DeviceActions;
1499   for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1500     Action* AssembleAction = CudaDeviceActions[I];
1501     assert(AssembleAction->getType() == types::TY_Object);
1502     assert(AssembleAction->getInputs().size() == 1);
1503 
1504     Action* BackendAction = AssembleAction->getInputs()[0];
1505     assert(BackendAction->getType() == types::TY_PP_Asm);
1506 
1507     for (auto &A : {AssembleAction, BackendAction}) {
1508       OffloadAction::DeviceDependences DDep;
1509       DDep.add(*A, *CudaTC, CudaArchToString(GpuArchList[I]), Action::OFK_Cuda);
1510       DeviceActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType()));
1511     }
1512   }
1513   auto FatbinAction =
1514       C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1515 
1516   // Return a new host action that incorporates original host action and all
1517   // device actions.
1518   OffloadAction::HostDependence HDep(*HostAction, *HostTC,
1519                                      /*BoundArch=*/nullptr, Action::OFK_Cuda);
1520   OffloadAction::DeviceDependences DDep;
1521   DDep.add(*FatbinAction, *CudaTC, /*BoundArch=*/nullptr, Action::OFK_Cuda);
1522   return C.MakeAction<OffloadAction>(HDep, DDep);
1523 }
1524 
1525 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
1526                           const InputList &Inputs, ActionList &Actions) const {
1527   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1528 
1529   if (!SuppressMissingInputWarning && Inputs.empty()) {
1530     Diag(clang::diag::err_drv_no_input_files);
1531     return;
1532   }
1533 
1534   Arg *FinalPhaseArg;
1535   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1536 
1537   if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1538     Diag(clang::diag::err_drv_emit_llvm_link);
1539   }
1540 
1541   // Reject -Z* at the top level, these options should never have been exposed
1542   // by gcc.
1543   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1544     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1545 
1546   // Diagnose misuse of /Fo.
1547   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
1548     StringRef V = A->getValue();
1549     if (Inputs.size() > 1 && !V.empty() &&
1550         !llvm::sys::path::is_separator(V.back())) {
1551       // Check whether /Fo tries to name an output file for multiple inputs.
1552       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1553           << A->getSpelling() << V;
1554       Args.eraseArg(options::OPT__SLASH_Fo);
1555     }
1556   }
1557 
1558   // Diagnose misuse of /Fa.
1559   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1560     StringRef V = A->getValue();
1561     if (Inputs.size() > 1 && !V.empty() &&
1562         !llvm::sys::path::is_separator(V.back())) {
1563       // Check whether /Fa tries to name an asm file for multiple inputs.
1564       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1565           << A->getSpelling() << V;
1566       Args.eraseArg(options::OPT__SLASH_Fa);
1567     }
1568   }
1569 
1570   // Diagnose misuse of /o.
1571   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
1572     if (A->getValue()[0] == '\0') {
1573       // It has to have a value.
1574       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
1575       Args.eraseArg(options::OPT__SLASH_o);
1576     }
1577   }
1578 
1579   // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
1580   // * no filename after it
1581   // * both /Yc and /Yu passed but with different filenames
1582   // * corresponding file not also passed as /FI
1583   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1584   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1585   if (YcArg && YcArg->getValue()[0] == '\0') {
1586     Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
1587     Args.eraseArg(options::OPT__SLASH_Yc);
1588     YcArg = nullptr;
1589   }
1590   if (YuArg && YuArg->getValue()[0] == '\0') {
1591     Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
1592     Args.eraseArg(options::OPT__SLASH_Yu);
1593     YuArg = nullptr;
1594   }
1595   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
1596     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
1597     Args.eraseArg(options::OPT__SLASH_Yc);
1598     Args.eraseArg(options::OPT__SLASH_Yu);
1599     YcArg = YuArg = nullptr;
1600   }
1601   if (YcArg || YuArg) {
1602     StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
1603     bool FoundMatchingInclude = false;
1604     for (const Arg *Inc : Args.filtered(options::OPT_include)) {
1605       // FIXME: Do case-insensitive matching and consider / and \ as equal.
1606       if (Inc->getValue() == Val)
1607         FoundMatchingInclude = true;
1608     }
1609     if (!FoundMatchingInclude) {
1610       Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
1611           << (YcArg ? YcArg : YuArg)->getSpelling();
1612       Args.eraseArg(options::OPT__SLASH_Yc);
1613       Args.eraseArg(options::OPT__SLASH_Yu);
1614       YcArg = YuArg = nullptr;
1615     }
1616   }
1617   if (YcArg && Inputs.size() > 1) {
1618     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
1619     Args.eraseArg(options::OPT__SLASH_Yc);
1620     YcArg = nullptr;
1621   }
1622   if (Args.hasArg(options::OPT__SLASH_Y_)) {
1623     // /Y- disables all pch handling.  Rather than check for it everywhere,
1624     // just remove clang-cl pch-related flags here.
1625     Args.eraseArg(options::OPT__SLASH_Fp);
1626     Args.eraseArg(options::OPT__SLASH_Yc);
1627     Args.eraseArg(options::OPT__SLASH_Yu);
1628     YcArg = YuArg = nullptr;
1629   }
1630 
1631   // Track the host offload kinds used on this compilation.
1632   unsigned CompilationActiveOffloadHostKinds = 0u;
1633 
1634   // Construct the actions to perform.
1635   ActionList LinkerInputs;
1636 
1637   llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
1638   for (auto &I : Inputs) {
1639     types::ID InputType = I.first;
1640     const Arg *InputArg = I.second;
1641 
1642     PL.clear();
1643     types::getCompilationPhases(InputType, PL);
1644 
1645     // If the first step comes after the final phase we are doing as part of
1646     // this compilation, warn the user about it.
1647     phases::ID InitialPhase = PL[0];
1648     if (InitialPhase > FinalPhase) {
1649       // Claim here to avoid the more general unused warning.
1650       InputArg->claim();
1651 
1652       // Suppress all unused style warnings with -Qunused-arguments
1653       if (Args.hasArg(options::OPT_Qunused_arguments))
1654         continue;
1655 
1656       // Special case when final phase determined by binary name, rather than
1657       // by a command-line argument with a corresponding Arg.
1658       if (CCCIsCPP())
1659         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1660             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
1661       // Special case '-E' warning on a previously preprocessed file to make
1662       // more sense.
1663       else if (InitialPhase == phases::Compile &&
1664                FinalPhase == phases::Preprocess &&
1665                getPreprocessedType(InputType) == types::TY_INVALID)
1666         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1667             << InputArg->getAsString(Args) << !!FinalPhaseArg
1668             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1669       else
1670         Diag(clang::diag::warn_drv_input_file_unused)
1671             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
1672             << !!FinalPhaseArg
1673             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1674       continue;
1675     }
1676 
1677     if (YcArg) {
1678       // Add a separate precompile phase for the compile phase.
1679       if (FinalPhase >= phases::Compile) {
1680         llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
1681         types::getCompilationPhases(types::TY_CXXHeader, PCHPL);
1682         Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue());
1683 
1684         // Build the pipeline for the pch file.
1685         Action *ClangClPch = C.MakeAction<InputAction>(*PchInputArg, InputType);
1686         for (phases::ID Phase : PCHPL)
1687           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
1688         assert(ClangClPch);
1689         Actions.push_back(ClangClPch);
1690         // The driver currently exits after the first failed command.  This
1691         // relies on that behavior, to make sure if the pch generation fails,
1692         // the main compilation won't run.
1693       }
1694     }
1695 
1696     phases::ID CudaInjectionPhase =
1697         (phases::Compile < FinalPhase &&
1698          llvm::find(PL, phases::Compile) != PL.end())
1699             ? phases::Compile
1700             : FinalPhase;
1701 
1702     // Track the host offload kinds used on this input.
1703     unsigned InputActiveOffloadHostKinds = 0u;
1704 
1705     // Build the pipeline for this file.
1706     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
1707     for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
1708          i != e; ++i) {
1709       phases::ID Phase = *i;
1710 
1711       // We are done if this step is past what the user requested.
1712       if (Phase > FinalPhase)
1713         break;
1714 
1715       // Queue linker inputs.
1716       if (Phase == phases::Link) {
1717         assert((i + 1) == e && "linking must be final compilation step.");
1718         LinkerInputs.push_back(Current);
1719         Current = nullptr;
1720         break;
1721       }
1722 
1723       // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1724       // encode this in the steps because the intermediate type depends on
1725       // arguments. Just special case here.
1726       if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1727         continue;
1728 
1729       // Otherwise construct the appropriate action.
1730       Current = ConstructPhaseAction(C, Args, Phase, Current);
1731 
1732       if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) {
1733         Current = buildCudaActions(C, Args, InputArg, Current, Actions);
1734         if (!Current)
1735           break;
1736 
1737         // We produced a CUDA action for this input, so the host has to support
1738         // CUDA.
1739         InputActiveOffloadHostKinds |= Action::OFK_Cuda;
1740         CompilationActiveOffloadHostKinds |= Action::OFK_Cuda;
1741       }
1742 
1743       if (Current->getType() == types::TY_Nothing)
1744         break;
1745     }
1746 
1747     // If we ended with something, add to the output list. Also, propagate the
1748     // offload information to the top-level host action related with the current
1749     // input.
1750     if (Current) {
1751       if (InputActiveOffloadHostKinds)
1752         Current->propagateHostOffloadInfo(InputActiveOffloadHostKinds,
1753                                           /*BoundArch=*/nullptr);
1754       Actions.push_back(Current);
1755     }
1756   }
1757 
1758   // Add a link action if necessary and propagate the offload information for
1759   // the current compilation.
1760   if (!LinkerInputs.empty()) {
1761     Actions.push_back(
1762         C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image));
1763     Actions.back()->propagateHostOffloadInfo(CompilationActiveOffloadHostKinds,
1764                                              /*BoundArch=*/nullptr);
1765   }
1766 
1767   // If we are linking, claim any options which are obviously only used for
1768   // compilation.
1769   if (FinalPhase == phases::Link && PL.size() == 1) {
1770     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1771     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1772   }
1773 
1774   // Claim ignored clang-cl options.
1775   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
1776 
1777   // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
1778   // to non-CUDA compilations and should not trigger warnings there.
1779   Args.ClaimAllArgs(options::OPT_cuda_host_only);
1780   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
1781 }
1782 
1783 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
1784                                      phases::ID Phase, Action *Input) const {
1785   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1786   // Build the appropriate action.
1787   switch (Phase) {
1788   case phases::Link:
1789     llvm_unreachable("link action invalid here.");
1790   case phases::Preprocess: {
1791     types::ID OutputTy;
1792     // -{M, MM} alter the output type.
1793     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1794       OutputTy = types::TY_Dependencies;
1795     } else {
1796       OutputTy = Input->getType();
1797       if (!Args.hasFlag(options::OPT_frewrite_includes,
1798                         options::OPT_fno_rewrite_includes, false) &&
1799           !CCGenDiagnostics)
1800         OutputTy = types::getPreprocessedType(OutputTy);
1801       assert(OutputTy != types::TY_INVALID &&
1802              "Cannot preprocess this input type!");
1803     }
1804     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
1805   }
1806   case phases::Precompile: {
1807     types::ID OutputTy = types::TY_PCH;
1808     if (Args.hasArg(options::OPT_fsyntax_only)) {
1809       // Syntax checks should not emit a PCH file
1810       OutputTy = types::TY_Nothing;
1811     }
1812     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
1813   }
1814   case phases::Compile: {
1815     if (Args.hasArg(options::OPT_fsyntax_only))
1816       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
1817     if (Args.hasArg(options::OPT_rewrite_objc))
1818       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
1819     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
1820       return C.MakeAction<CompileJobAction>(Input,
1821                                             types::TY_RewrittenLegacyObjC);
1822     if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
1823       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
1824     if (Args.hasArg(options::OPT__migrate))
1825       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
1826     if (Args.hasArg(options::OPT_emit_ast))
1827       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
1828     if (Args.hasArg(options::OPT_module_file_info))
1829       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
1830     if (Args.hasArg(options::OPT_verify_pch))
1831       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
1832     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
1833   }
1834   case phases::Backend: {
1835     if (isUsingLTO()) {
1836       types::ID Output =
1837           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1838       return C.MakeAction<BackendJobAction>(Input, Output);
1839     }
1840     if (Args.hasArg(options::OPT_emit_llvm)) {
1841       types::ID Output =
1842           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
1843       return C.MakeAction<BackendJobAction>(Input, Output);
1844     }
1845     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
1846   }
1847   case phases::Assemble:
1848     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
1849   }
1850 
1851   llvm_unreachable("invalid phase in ConstructPhaseAction");
1852 }
1853 
1854 void Driver::BuildJobs(Compilation &C) const {
1855   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1856 
1857   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1858 
1859   // It is an error to provide a -o option if we are making multiple output
1860   // files.
1861   if (FinalOutput) {
1862     unsigned NumOutputs = 0;
1863     for (const Action *A : C.getActions())
1864       if (A->getType() != types::TY_Nothing)
1865         ++NumOutputs;
1866 
1867     if (NumOutputs > 1) {
1868       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1869       FinalOutput = nullptr;
1870     }
1871   }
1872 
1873   // Collect the list of architectures.
1874   llvm::StringSet<> ArchNames;
1875   if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
1876     for (const Arg *A : C.getArgs())
1877       if (A->getOption().matches(options::OPT_arch))
1878         ArchNames.insert(A->getValue());
1879 
1880   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
1881   std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
1882   for (Action *A : C.getActions()) {
1883     // If we are linking an image for multiple archs then the linker wants
1884     // -arch_multiple and -final_output <final image name>. Unfortunately, this
1885     // doesn't fit in cleanly because we have to pass this information down.
1886     //
1887     // FIXME: This is a hack; find a cleaner way to integrate this into the
1888     // process.
1889     const char *LinkingOutput = nullptr;
1890     if (isa<LipoJobAction>(A)) {
1891       if (FinalOutput)
1892         LinkingOutput = FinalOutput->getValue();
1893       else
1894         LinkingOutput = getDefaultImageName();
1895     }
1896 
1897     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1898                        /*BoundArch*/ nullptr,
1899                        /*AtTopLevel*/ true,
1900                        /*MultipleArchs*/ ArchNames.size() > 1,
1901                        /*LinkingOutput*/ LinkingOutput, CachedResults,
1902                        /*BuildForOffloadDevice*/ false);
1903   }
1904 
1905   // If the user passed -Qunused-arguments or there were errors, don't warn
1906   // about any unused arguments.
1907   if (Diags.hasErrorOccurred() ||
1908       C.getArgs().hasArg(options::OPT_Qunused_arguments))
1909     return;
1910 
1911   // Claim -### here.
1912   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1913 
1914   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
1915   (void)C.getArgs().hasArg(options::OPT_driver_mode);
1916   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
1917 
1918   for (Arg *A : C.getArgs()) {
1919     // FIXME: It would be nice to be able to send the argument to the
1920     // DiagnosticsEngine, so that extra values, position, and so on could be
1921     // printed.
1922     if (!A->isClaimed()) {
1923       if (A->getOption().hasFlag(options::NoArgumentUnused))
1924         continue;
1925 
1926       // Suppress the warning automatically if this is just a flag, and it is an
1927       // instance of an argument we already claimed.
1928       const Option &Opt = A->getOption();
1929       if (Opt.getKind() == Option::FlagClass) {
1930         bool DuplicateClaimed = false;
1931 
1932         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
1933           if (AA->isClaimed()) {
1934             DuplicateClaimed = true;
1935             break;
1936           }
1937         }
1938 
1939         if (DuplicateClaimed)
1940           continue;
1941       }
1942 
1943       // In clang-cl, don't mention unknown arguments here since they have
1944       // already been warned about.
1945       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
1946         Diag(clang::diag::warn_drv_unused_argument)
1947             << A->getAsString(C.getArgs());
1948     }
1949   }
1950 }
1951 /// Collapse an offloading action looking for a job of the given type. The input
1952 /// action is changed to the input of the collapsed sequence. If we effectively
1953 /// had a collapse return the corresponding offloading action, otherwise return
1954 /// null.
1955 template <typename T>
1956 static OffloadAction *collapseOffloadingAction(Action *&CurAction) {
1957   if (!CurAction)
1958     return nullptr;
1959   if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
1960     if (OA->hasHostDependence())
1961       if (auto *HDep = dyn_cast<T>(OA->getHostDependence())) {
1962         CurAction = HDep;
1963         return OA;
1964       }
1965     if (OA->hasSingleDeviceDependence())
1966       if (auto *DDep = dyn_cast<T>(OA->getSingleDeviceDependence())) {
1967         CurAction = DDep;
1968         return OA;
1969       }
1970   }
1971   return nullptr;
1972 }
1973 // Returns a Tool for a given JobAction.  In case the action and its
1974 // predecessors can be combined, updates Inputs with the inputs of the
1975 // first combined action. If one of the collapsed actions is a
1976 // CudaHostAction, updates CollapsedCHA with the pointer to it so the
1977 // caller can deal with extra handling such action requires.
1978 static const Tool *selectToolForJob(Compilation &C, bool SaveTemps,
1979                                     bool EmbedBitcode, const ToolChain *TC,
1980                                     const JobAction *JA,
1981                                     const ActionList *&Inputs,
1982                                     ActionList &CollapsedOffloadAction) {
1983   const Tool *ToolForJob = nullptr;
1984   CollapsedOffloadAction.clear();
1985 
1986   // See if we should look for a compiler with an integrated assembler. We match
1987   // bottom up, so what we are actually looking for is an assembler job with a
1988   // compiler input.
1989 
1990   // Look through offload actions between assembler and backend actions.
1991   Action *BackendJA = (isa<AssembleJobAction>(JA) && Inputs->size() == 1)
1992                           ? *Inputs->begin()
1993                           : nullptr;
1994   auto *BackendOA = collapseOffloadingAction<BackendJobAction>(BackendJA);
1995 
1996   if (TC->useIntegratedAs() && !SaveTemps &&
1997       !C.getArgs().hasArg(options::OPT_via_file_asm) &&
1998       !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
1999       !C.getArgs().hasArg(options::OPT__SLASH_Fa) && BackendJA &&
2000       isa<BackendJobAction>(BackendJA)) {
2001     // A BackendJob is always preceded by a CompileJob, and without -save-temps
2002     // or -fembed-bitcode, they will always get combined together, so instead of
2003     // checking the backend tool, check if the tool for the CompileJob has an
2004     // integrated assembler. For -fembed-bitcode, CompileJob is still used to
2005     // look up tools for BackendJob, but they need to match before we can split
2006     // them.
2007 
2008     // Look through offload actions between backend and compile actions.
2009     Action *CompileJA = *BackendJA->getInputs().begin();
2010     auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA);
2011 
2012     assert(CompileJA && isa<CompileJobAction>(CompileJA) &&
2013            "Backend job is not preceeded by compile job.");
2014     const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA));
2015     if (!Compiler)
2016       return nullptr;
2017     // When using -fembed-bitcode, it is required to have the same tool (clang)
2018     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2019     if (EmbedBitcode) {
2020       JobAction *InputJA = cast<JobAction>(*Inputs->begin());
2021       const Tool *BackendTool = TC->SelectTool(*InputJA);
2022       if (BackendTool == Compiler)
2023         CompileJA = InputJA;
2024     }
2025     if (Compiler->hasIntegratedAssembler()) {
2026       Inputs = &CompileJA->getInputs();
2027       ToolForJob = Compiler;
2028       // Save the collapsed offload actions because they may still contain
2029       // device actions.
2030       if (CompileOA)
2031         CollapsedOffloadAction.push_back(CompileOA);
2032       if (BackendOA)
2033         CollapsedOffloadAction.push_back(BackendOA);
2034     }
2035   }
2036 
2037   // A backend job should always be combined with the preceding compile job
2038   // unless OPT_save_temps or OPT_fembed_bitcode is enabled and the compiler is
2039   // capable of emitting LLVM IR as an intermediate output.
2040   if (isa<BackendJobAction>(JA)) {
2041     // Check if the compiler supports emitting LLVM IR.
2042     assert(Inputs->size() == 1);
2043 
2044     // Look through offload actions between backend and compile actions.
2045     Action *CompileJA = *JA->getInputs().begin();
2046     auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA);
2047 
2048     assert(CompileJA && isa<CompileJobAction>(CompileJA) &&
2049            "Backend job is not preceeded by compile job.");
2050     const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA));
2051     if (!Compiler)
2052       return nullptr;
2053     if (!Compiler->canEmitIR() ||
2054         (!SaveTemps && !EmbedBitcode)) {
2055       Inputs = &CompileJA->getInputs();
2056       ToolForJob = Compiler;
2057 
2058       if (CompileOA)
2059         CollapsedOffloadAction.push_back(CompileOA);
2060     }
2061   }
2062 
2063   // Otherwise use the tool for the current job.
2064   if (!ToolForJob)
2065     ToolForJob = TC->SelectTool(*JA);
2066 
2067   // See if we should use an integrated preprocessor. We do so when we have
2068   // exactly one input, since this is the only use case we care about
2069   // (irrelevant since we don't support combine yet).
2070 
2071   // Look through offload actions after preprocessing.
2072   Action *PreprocessJA = (Inputs->size() == 1) ? *Inputs->begin() : nullptr;
2073   auto *PreprocessOA =
2074       collapseOffloadingAction<PreprocessJobAction>(PreprocessJA);
2075 
2076   if (PreprocessJA && isa<PreprocessJobAction>(PreprocessJA) &&
2077       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2078       !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2079       !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
2080       ToolForJob->hasIntegratedCPP()) {
2081     Inputs = &PreprocessJA->getInputs();
2082     if (PreprocessOA)
2083       CollapsedOffloadAction.push_back(PreprocessOA);
2084   }
2085 
2086   return ToolForJob;
2087 }
2088 
2089 InputInfo Driver::BuildJobsForAction(
2090     Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
2091     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
2092     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
2093     bool BuildForOffloadDevice) const {
2094   // The bound arch is not necessarily represented in the toolchain's triple --
2095   // for example, armv7 and armv7s both map to the same triple -- so we need
2096   // both in our map.
2097   std::string TriplePlusArch = TC->getTriple().normalize();
2098   if (BoundArch) {
2099     TriplePlusArch += "-";
2100     TriplePlusArch += BoundArch;
2101   }
2102   std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch};
2103   auto CachedResult = CachedResults.find(ActionTC);
2104   if (CachedResult != CachedResults.end()) {
2105     return CachedResult->second;
2106   }
2107   InputInfo Result = BuildJobsForActionNoCache(
2108       C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
2109       CachedResults, BuildForOffloadDevice);
2110   CachedResults[ActionTC] = Result;
2111   return Result;
2112 }
2113 
2114 InputInfo Driver::BuildJobsForActionNoCache(
2115     Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
2116     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
2117     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
2118     bool BuildForOffloadDevice) const {
2119   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2120 
2121   InputInfoList OffloadDependencesInputInfo;
2122   if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2123     // The offload action is expected to be used in four different situations.
2124     //
2125     // a) Set a toolchain/architecture/kind for a host action:
2126     //    Host Action 1 -> OffloadAction -> Host Action 2
2127     //
2128     // b) Set a toolchain/architecture/kind for a device action;
2129     //    Device Action 1 -> OffloadAction -> Device Action 2
2130     //
2131     // c) Specify a device dependences to a host action;
2132     //    Device Action 1  _
2133     //                      \
2134     //      Host Action 1  ---> OffloadAction -> Host Action 2
2135     //
2136     // d) Specify a host dependence to a device action.
2137     //      Host Action 1  _
2138     //                      \
2139     //    Device Action 1  ---> OffloadAction -> Device Action 2
2140     //
2141     // For a) and b), we just return the job generated for the dependence. For
2142     // c) and d) we override the current action with the host/device dependence
2143     // if the current toolchain is host/device and set the offload dependences
2144     // info with the jobs obtained from the device/host dependence(s).
2145 
2146     // If there is a single device option, just generate the job for it.
2147     if (OA->hasSingleDeviceDependence()) {
2148       InputInfo DevA;
2149       OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
2150                                        const char *DepBoundArch) {
2151         DevA =
2152             BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
2153                                /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
2154                                CachedResults, /*BuildForOffloadDevice=*/true);
2155       });
2156       return DevA;
2157     }
2158 
2159     // If 'Action 2' is host, we generate jobs for the device dependences and
2160     // override the current action with the host dependence. Otherwise, we
2161     // generate the host dependences and override the action with the device
2162     // dependence. The dependences can't therefore be a top-level action.
2163     OA->doOnEachDependence(
2164         /*IsHostDependence=*/BuildForOffloadDevice,
2165         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
2166           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
2167               C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
2168               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
2169               /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() !=
2170                   Action::OFK_None));
2171         });
2172 
2173     A = BuildForOffloadDevice
2174             ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
2175             : OA->getHostDependence();
2176   }
2177 
2178   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
2179     // FIXME: It would be nice to not claim this here; maybe the old scheme of
2180     // just using Args was better?
2181     const Arg &Input = IA->getInputArg();
2182     Input.claim();
2183     if (Input.getOption().matches(options::OPT_INPUT)) {
2184       const char *Name = Input.getValue();
2185       return InputInfo(A, Name, /* BaseInput = */ Name);
2186     }
2187     return InputInfo(A, &Input, /* BaseInput = */ "");
2188   }
2189 
2190   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
2191     const ToolChain *TC;
2192     const char *ArchName = BAA->getArchName();
2193 
2194     if (ArchName)
2195       TC = &getToolChain(C.getArgs(),
2196                          computeTargetTriple(*this, DefaultTargetTriple,
2197                                              C.getArgs(), ArchName));
2198     else
2199       TC = &C.getDefaultToolChain();
2200 
2201     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
2202                               MultipleArchs, LinkingOutput, CachedResults,
2203                               BuildForOffloadDevice);
2204   }
2205 
2206 
2207   const ActionList *Inputs = &A->getInputs();
2208 
2209   const JobAction *JA = cast<JobAction>(A);
2210   ActionList CollapsedOffloadActions;
2211 
2212   const Tool *T =
2213       selectToolForJob(C, isSaveTempsEnabled(), embedBitcodeEnabled(), TC, JA,
2214                        Inputs, CollapsedOffloadActions);
2215   if (!T)
2216     return InputInfo();
2217 
2218   // If we've collapsed action list that contained OffloadAction we
2219   // need to build jobs for host/device-side inputs it may have held.
2220   for (const auto *OA : CollapsedOffloadActions)
2221     cast<OffloadAction>(OA)->doOnEachDependence(
2222         /*IsHostDependence=*/BuildForOffloadDevice,
2223         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
2224           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
2225               C, DepA, DepTC, DepBoundArch, AtTopLevel,
2226               /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
2227               /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() !=
2228                   Action::OFK_None));
2229         });
2230 
2231   // Only use pipes when there is exactly one input.
2232   InputInfoList InputInfos;
2233   for (const Action *Input : *Inputs) {
2234     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
2235     // shouldn't get temporary output names.
2236     // FIXME: Clean this up.
2237     bool SubJobAtTopLevel =
2238         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
2239     InputInfos.push_back(BuildJobsForAction(
2240         C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
2241         CachedResults, BuildForOffloadDevice));
2242   }
2243 
2244   // Always use the first input as the base input.
2245   const char *BaseInput = InputInfos[0].getBaseInput();
2246 
2247   // ... except dsymutil actions, which use their actual input as the base
2248   // input.
2249   if (JA->getType() == types::TY_dSYM)
2250     BaseInput = InputInfos[0].getFilename();
2251 
2252   // Append outputs of offload device jobs to the input list
2253   if (!OffloadDependencesInputInfo.empty())
2254     InputInfos.append(OffloadDependencesInputInfo.begin(),
2255                       OffloadDependencesInputInfo.end());
2256 
2257   // Set the effective triple of the toolchain for the duration of this job.
2258   llvm::Triple EffectiveTriple;
2259   const ToolChain &ToolTC = T->getToolChain();
2260   const ArgList &Args = C.getArgsForToolChain(TC, BoundArch);
2261   if (InputInfos.size() != 1) {
2262     EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
2263   } else {
2264     // Pass along the input type if it can be unambiguously determined.
2265     EffectiveTriple = llvm::Triple(
2266         ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
2267   }
2268   RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
2269 
2270   // Determine the place to write output to, if any.
2271   InputInfo Result;
2272   if (JA->getType() == types::TY_Nothing)
2273     Result = InputInfo(A, BaseInput);
2274   else
2275     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
2276                                              AtTopLevel, MultipleArchs,
2277                                              TC->getTriple().normalize()),
2278                        BaseInput);
2279 
2280   if (CCCPrintBindings && !CCGenDiagnostics) {
2281     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
2282                  << " - \"" << T->getName() << "\", inputs: [";
2283     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
2284       llvm::errs() << InputInfos[i].getAsString();
2285       if (i + 1 != e)
2286         llvm::errs() << ", ";
2287     }
2288     llvm::errs() << "], output: " << Result.getAsString() << "\n";
2289   } else {
2290     T->ConstructJob(C, *JA, Result, InputInfos,
2291                     C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
2292   }
2293   return Result;
2294 }
2295 
2296 const char *Driver::getDefaultImageName() const {
2297   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
2298   return Target.isOSWindows() ? "a.exe" : "a.out";
2299 }
2300 
2301 /// \brief Create output filename based on ArgValue, which could either be a
2302 /// full filename, filename without extension, or a directory. If ArgValue
2303 /// does not provide a filename, then use BaseName, and use the extension
2304 /// suitable for FileType.
2305 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
2306                                         StringRef BaseName,
2307                                         types::ID FileType) {
2308   SmallString<128> Filename = ArgValue;
2309 
2310   if (ArgValue.empty()) {
2311     // If the argument is empty, output to BaseName in the current dir.
2312     Filename = BaseName;
2313   } else if (llvm::sys::path::is_separator(Filename.back())) {
2314     // If the argument is a directory, output to BaseName in that dir.
2315     llvm::sys::path::append(Filename, BaseName);
2316   }
2317 
2318   if (!llvm::sys::path::has_extension(ArgValue)) {
2319     // If the argument didn't provide an extension, then set it.
2320     const char *Extension = types::getTypeTempSuffix(FileType, true);
2321 
2322     if (FileType == types::TY_Image &&
2323         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
2324       // The output file is a dll.
2325       Extension = "dll";
2326     }
2327 
2328     llvm::sys::path::replace_extension(Filename, Extension);
2329   }
2330 
2331   return Args.MakeArgString(Filename.c_str());
2332 }
2333 
2334 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
2335                                        const char *BaseInput,
2336                                        const char *BoundArch, bool AtTopLevel,
2337                                        bool MultipleArchs,
2338                                        StringRef NormalizedTriple) const {
2339   llvm::PrettyStackTraceString CrashInfo("Computing output path");
2340   // Output to a user requested destination?
2341   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
2342     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
2343       return C.addResultFile(FinalOutput->getValue(), &JA);
2344   }
2345 
2346   // For /P, preprocess to file named after BaseInput.
2347   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
2348     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
2349     StringRef BaseName = llvm::sys::path::filename(BaseInput);
2350     StringRef NameArg;
2351     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
2352       NameArg = A->getValue();
2353     return C.addResultFile(
2354         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
2355         &JA);
2356   }
2357 
2358   // Default to writing to stdout?
2359   if (AtTopLevel && !CCGenDiagnostics &&
2360       (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
2361     return "-";
2362 
2363   // Is this the assembly listing for /FA?
2364   if (JA.getType() == types::TY_PP_Asm &&
2365       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
2366        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
2367     // Use /Fa and the input filename to determine the asm file name.
2368     StringRef BaseName = llvm::sys::path::filename(BaseInput);
2369     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
2370     return C.addResultFile(
2371         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
2372         &JA);
2373   }
2374 
2375   // Output to a temporary file?
2376   if ((!AtTopLevel && !isSaveTempsEnabled() &&
2377        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
2378       CCGenDiagnostics) {
2379     StringRef Name = llvm::sys::path::filename(BaseInput);
2380     std::pair<StringRef, StringRef> Split = Name.split('.');
2381     std::string TmpName = GetTemporaryPath(
2382         Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2383     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2384   }
2385 
2386   SmallString<128> BasePath(BaseInput);
2387   StringRef BaseName;
2388 
2389   // Dsymutil actions should use the full path.
2390   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
2391     BaseName = BasePath;
2392   else
2393     BaseName = llvm::sys::path::filename(BasePath);
2394 
2395   // Determine what the derived output name should be.
2396   const char *NamedOutput;
2397 
2398   if (JA.getType() == types::TY_Object &&
2399       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
2400     // The /Fo or /o flag decides the object filename.
2401     StringRef Val =
2402         C.getArgs()
2403             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
2404             ->getValue();
2405     NamedOutput =
2406         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
2407   } else if (JA.getType() == types::TY_Image &&
2408              C.getArgs().hasArg(options::OPT__SLASH_Fe,
2409                                 options::OPT__SLASH_o)) {
2410     // The /Fe or /o flag names the linked file.
2411     StringRef Val =
2412         C.getArgs()
2413             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
2414             ->getValue();
2415     NamedOutput =
2416         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
2417   } else if (JA.getType() == types::TY_Image) {
2418     if (IsCLMode()) {
2419       // clang-cl uses BaseName for the executable name.
2420       NamedOutput =
2421           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
2422     } else if (MultipleArchs && BoundArch) {
2423       SmallString<128> Output(getDefaultImageName());
2424       Output += JA.getOffloadingFileNamePrefix(NormalizedTriple);
2425       Output += "-";
2426       Output.append(BoundArch);
2427       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
2428     } else {
2429       NamedOutput = getDefaultImageName();
2430     }
2431   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
2432     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str());
2433   } else {
2434     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
2435     assert(Suffix && "All types used for output should have a suffix.");
2436 
2437     std::string::size_type End = std::string::npos;
2438     if (!types::appendSuffixForType(JA.getType()))
2439       End = BaseName.rfind('.');
2440     SmallString<128> Suffixed(BaseName.substr(0, End));
2441     Suffixed += JA.getOffloadingFileNamePrefix(NormalizedTriple);
2442     if (MultipleArchs && BoundArch) {
2443       Suffixed += "-";
2444       Suffixed.append(BoundArch);
2445     }
2446     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
2447     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
2448     // optimized bitcode output.
2449     if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
2450         JA.getType() == types::TY_LLVM_BC)
2451       Suffixed += ".tmp";
2452     Suffixed += '.';
2453     Suffixed += Suffix;
2454     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
2455   }
2456 
2457   // Prepend object file path if -save-temps=obj
2458   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
2459       JA.getType() != types::TY_PCH) {
2460     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2461     SmallString<128> TempPath(FinalOutput->getValue());
2462     llvm::sys::path::remove_filename(TempPath);
2463     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
2464     llvm::sys::path::append(TempPath, OutputFileName);
2465     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
2466   }
2467 
2468   // If we're saving temps and the temp file conflicts with the input file,
2469   // then avoid overwriting input file.
2470   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
2471     bool SameFile = false;
2472     SmallString<256> Result;
2473     llvm::sys::fs::current_path(Result);
2474     llvm::sys::path::append(Result, BaseName);
2475     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
2476     // Must share the same path to conflict.
2477     if (SameFile) {
2478       StringRef Name = llvm::sys::path::filename(BaseInput);
2479       std::pair<StringRef, StringRef> Split = Name.split('.');
2480       std::string TmpName = GetTemporaryPath(
2481           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2482       return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2483     }
2484   }
2485 
2486   // As an annoying special case, PCH generation doesn't strip the pathname.
2487   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
2488     llvm::sys::path::remove_filename(BasePath);
2489     if (BasePath.empty())
2490       BasePath = NamedOutput;
2491     else
2492       llvm::sys::path::append(BasePath, NamedOutput);
2493     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
2494   } else {
2495     return C.addResultFile(NamedOutput, &JA);
2496   }
2497 }
2498 
2499 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
2500   // Respect a limited subset of the '-Bprefix' functionality in GCC by
2501   // attempting to use this prefix when looking for file paths.
2502   for (const std::string &Dir : PrefixDirs) {
2503     if (Dir.empty())
2504       continue;
2505     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2506     llvm::sys::path::append(P, Name);
2507     if (llvm::sys::fs::exists(Twine(P)))
2508       return P.str();
2509   }
2510 
2511   SmallString<128> P(ResourceDir);
2512   llvm::sys::path::append(P, Name);
2513   if (llvm::sys::fs::exists(Twine(P)))
2514     return P.str();
2515 
2516   for (const std::string &Dir : TC.getFilePaths()) {
2517     if (Dir.empty())
2518       continue;
2519     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2520     llvm::sys::path::append(P, Name);
2521     if (llvm::sys::fs::exists(Twine(P)))
2522       return P.str();
2523   }
2524 
2525   return Name;
2526 }
2527 
2528 void Driver::generatePrefixedToolNames(
2529     const char *Tool, const ToolChain &TC,
2530     SmallVectorImpl<std::string> &Names) const {
2531   // FIXME: Needs a better variable than DefaultTargetTriple
2532   Names.emplace_back(DefaultTargetTriple + "-" + Tool);
2533   Names.emplace_back(Tool);
2534 
2535   // Allow the discovery of tools prefixed with LLVM's default target triple.
2536   std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
2537   if (LLVMDefaultTargetTriple != DefaultTargetTriple)
2538     Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool);
2539 }
2540 
2541 static bool ScanDirForExecutable(SmallString<128> &Dir,
2542                                  ArrayRef<std::string> Names) {
2543   for (const auto &Name : Names) {
2544     llvm::sys::path::append(Dir, Name);
2545     if (llvm::sys::fs::can_execute(Twine(Dir)))
2546       return true;
2547     llvm::sys::path::remove_filename(Dir);
2548   }
2549   return false;
2550 }
2551 
2552 std::string Driver::GetProgramPath(const char *Name,
2553                                    const ToolChain &TC) const {
2554   SmallVector<std::string, 2> TargetSpecificExecutables;
2555   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2556 
2557   // Respect a limited subset of the '-Bprefix' functionality in GCC by
2558   // attempting to use this prefix when looking for program paths.
2559   for (const auto &PrefixDir : PrefixDirs) {
2560     if (llvm::sys::fs::is_directory(PrefixDir)) {
2561       SmallString<128> P(PrefixDir);
2562       if (ScanDirForExecutable(P, TargetSpecificExecutables))
2563         return P.str();
2564     } else {
2565       SmallString<128> P(PrefixDir + Name);
2566       if (llvm::sys::fs::can_execute(Twine(P)))
2567         return P.str();
2568     }
2569   }
2570 
2571   const ToolChain::path_list &List = TC.getProgramPaths();
2572   for (const auto &Path : List) {
2573     SmallString<128> P(Path);
2574     if (ScanDirForExecutable(P, TargetSpecificExecutables))
2575       return P.str();
2576   }
2577 
2578   // If all else failed, search the path.
2579   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
2580     if (llvm::ErrorOr<std::string> P =
2581             llvm::sys::findProgramByName(TargetSpecificExecutable))
2582       return *P;
2583 
2584   return Name;
2585 }
2586 
2587 std::string Driver::GetTemporaryPath(StringRef Prefix,
2588                                      const char *Suffix) const {
2589   SmallString<128> Path;
2590   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
2591   if (EC) {
2592     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
2593     return "";
2594   }
2595 
2596   return Path.str();
2597 }
2598 
2599 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
2600   SmallString<128> Output;
2601   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
2602     // FIXME: If anybody needs it, implement this obscure rule:
2603     // "If you specify a directory without a file name, the default file name
2604     // is VCx0.pch., where x is the major version of Visual C++ in use."
2605     Output = FpArg->getValue();
2606 
2607     // "If you do not specify an extension as part of the path name, an
2608     // extension of .pch is assumed. "
2609     if (!llvm::sys::path::has_extension(Output))
2610       Output += ".pch";
2611   } else {
2612     Output = BaseName;
2613     llvm::sys::path::replace_extension(Output, ".pch");
2614   }
2615   return Output.str();
2616 }
2617 
2618 const ToolChain &Driver::getToolChain(const ArgList &Args,
2619                                       const llvm::Triple &Target) const {
2620 
2621   ToolChain *&TC = ToolChains[Target.str()];
2622   if (!TC) {
2623     switch (Target.getOS()) {
2624     case llvm::Triple::Haiku:
2625       TC = new toolchains::Haiku(*this, Target, Args);
2626       break;
2627     case llvm::Triple::CloudABI:
2628       TC = new toolchains::CloudABI(*this, Target, Args);
2629       break;
2630     case llvm::Triple::Darwin:
2631     case llvm::Triple::MacOSX:
2632     case llvm::Triple::IOS:
2633     case llvm::Triple::TvOS:
2634     case llvm::Triple::WatchOS:
2635       TC = new toolchains::DarwinClang(*this, Target, Args);
2636       break;
2637     case llvm::Triple::DragonFly:
2638       TC = new toolchains::DragonFly(*this, Target, Args);
2639       break;
2640     case llvm::Triple::OpenBSD:
2641       TC = new toolchains::OpenBSD(*this, Target, Args);
2642       break;
2643     case llvm::Triple::Bitrig:
2644       TC = new toolchains::Bitrig(*this, Target, Args);
2645       break;
2646     case llvm::Triple::NetBSD:
2647       TC = new toolchains::NetBSD(*this, Target, Args);
2648       break;
2649     case llvm::Triple::FreeBSD:
2650       TC = new toolchains::FreeBSD(*this, Target, Args);
2651       break;
2652     case llvm::Triple::Minix:
2653       TC = new toolchains::Minix(*this, Target, Args);
2654       break;
2655     case llvm::Triple::Linux:
2656     case llvm::Triple::ELFIAMCU:
2657       if (Target.getArch() == llvm::Triple::hexagon)
2658         TC = new toolchains::HexagonToolChain(*this, Target, Args);
2659       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
2660                !Target.hasEnvironment())
2661         TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
2662       else
2663         TC = new toolchains::Linux(*this, Target, Args);
2664       break;
2665     case llvm::Triple::NaCl:
2666       TC = new toolchains::NaClToolChain(*this, Target, Args);
2667       break;
2668     case llvm::Triple::Solaris:
2669       TC = new toolchains::Solaris(*this, Target, Args);
2670       break;
2671     case llvm::Triple::AMDHSA:
2672       TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
2673       break;
2674     case llvm::Triple::Win32:
2675       switch (Target.getEnvironment()) {
2676       default:
2677         if (Target.isOSBinFormatELF())
2678           TC = new toolchains::Generic_ELF(*this, Target, Args);
2679         else if (Target.isOSBinFormatMachO())
2680           TC = new toolchains::MachO(*this, Target, Args);
2681         else
2682           TC = new toolchains::Generic_GCC(*this, Target, Args);
2683         break;
2684       case llvm::Triple::GNU:
2685         TC = new toolchains::MinGW(*this, Target, Args);
2686         break;
2687       case llvm::Triple::Itanium:
2688         TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
2689         break;
2690       case llvm::Triple::MSVC:
2691       case llvm::Triple::UnknownEnvironment:
2692         TC = new toolchains::MSVCToolChain(*this, Target, Args);
2693         break;
2694       }
2695       break;
2696     case llvm::Triple::CUDA:
2697       TC = new toolchains::CudaToolChain(*this, Target, Args);
2698       break;
2699     case llvm::Triple::PS4:
2700       TC = new toolchains::PS4CPU(*this, Target, Args);
2701       break;
2702     default:
2703       // Of these targets, Hexagon is the only one that might have
2704       // an OS of Linux, in which case it got handled above already.
2705       switch (Target.getArch()) {
2706       case llvm::Triple::tce:
2707         TC = new toolchains::TCEToolChain(*this, Target, Args);
2708         break;
2709       case llvm::Triple::hexagon:
2710         TC = new toolchains::HexagonToolChain(*this, Target, Args);
2711         break;
2712       case llvm::Triple::lanai:
2713         TC = new toolchains::LanaiToolChain(*this, Target, Args);
2714         break;
2715       case llvm::Triple::xcore:
2716         TC = new toolchains::XCoreToolChain(*this, Target, Args);
2717         break;
2718       case llvm::Triple::wasm32:
2719       case llvm::Triple::wasm64:
2720         TC = new toolchains::WebAssembly(*this, Target, Args);
2721         break;
2722       default:
2723         if (Target.getVendor() == llvm::Triple::Myriad)
2724           TC = new toolchains::MyriadToolChain(*this, Target, Args);
2725         else if (Target.isOSBinFormatELF())
2726           TC = new toolchains::Generic_ELF(*this, Target, Args);
2727         else if (Target.isOSBinFormatMachO())
2728           TC = new toolchains::MachO(*this, Target, Args);
2729         else
2730           TC = new toolchains::Generic_GCC(*this, Target, Args);
2731       }
2732     }
2733   }
2734   return *TC;
2735 }
2736 
2737 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
2738   // Say "no" if there is not exactly one input of a type clang understands.
2739   if (JA.size() != 1 ||
2740       !types::isAcceptedByClang((*JA.input_begin())->getType()))
2741     return false;
2742 
2743   // And say "no" if this is not a kind of action clang understands.
2744   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
2745       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
2746     return false;
2747 
2748   return true;
2749 }
2750 
2751 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
2752 /// grouped values as integers. Numbers which are not provided are set to 0.
2753 ///
2754 /// \return True if the entire string was parsed (9.2), or all groups were
2755 /// parsed (10.3.5extrastuff).
2756 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
2757                                unsigned &Minor, unsigned &Micro,
2758                                bool &HadExtra) {
2759   HadExtra = false;
2760 
2761   Major = Minor = Micro = 0;
2762   if (*Str == '\0')
2763     return false;
2764 
2765   char *End;
2766   Major = (unsigned)strtol(Str, &End, 10);
2767   if (*Str != '\0' && *End == '\0')
2768     return true;
2769   if (*End != '.')
2770     return false;
2771 
2772   Str = End + 1;
2773   Minor = (unsigned)strtol(Str, &End, 10);
2774   if (*Str != '\0' && *End == '\0')
2775     return true;
2776   if (*End != '.')
2777     return false;
2778 
2779   Str = End + 1;
2780   Micro = (unsigned)strtol(Str, &End, 10);
2781   if (*Str != '\0' && *End == '\0')
2782     return true;
2783   if (Str == End)
2784     return false;
2785   HadExtra = true;
2786   return true;
2787 }
2788 
2789 /// Parse digits from a string \p Str and fulfill \p Digits with
2790 /// the parsed numbers. This method assumes that the max number of
2791 /// digits to look for is equal to Digits.size().
2792 ///
2793 /// \return True if the entire string was parsed and there are
2794 /// no extra characters remaining at the end.
2795 bool Driver::GetReleaseVersion(const char *Str,
2796                                MutableArrayRef<unsigned> Digits) {
2797   if (*Str == '\0')
2798     return false;
2799 
2800   char *End;
2801   unsigned CurDigit = 0;
2802   while (CurDigit < Digits.size()) {
2803     unsigned Digit = (unsigned)strtol(Str, &End, 10);
2804     Digits[CurDigit] = Digit;
2805     if (*Str != '\0' && *End == '\0')
2806       return true;
2807     if (*End != '.' || Str == End)
2808       return false;
2809     Str = End + 1;
2810     CurDigit++;
2811   }
2812 
2813   // More digits than requested, bail out...
2814   return false;
2815 }
2816 
2817 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
2818   unsigned IncludedFlagsBitmask = 0;
2819   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
2820 
2821   if (Mode == CLMode) {
2822     // Include CL and Core options.
2823     IncludedFlagsBitmask |= options::CLOption;
2824     IncludedFlagsBitmask |= options::CoreOption;
2825   } else {
2826     ExcludedFlagsBitmask |= options::CLOption;
2827   }
2828 
2829   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2830 }
2831 
2832 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
2833   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
2834 }
2835