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