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