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