1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Driver/Driver.h"
10 #include "InputInfo.h"
11 #include "ToolChains/AIX.h"
12 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
16 #include "ToolChains/Clang.h"
17 #include "ToolChains/CloudABI.h"
18 #include "ToolChains/Contiki.h"
19 #include "ToolChains/CrossWindows.h"
20 #include "ToolChains/Cuda.h"
21 #include "ToolChains/Darwin.h"
22 #include "ToolChains/DragonFly.h"
23 #include "ToolChains/FreeBSD.h"
24 #include "ToolChains/Fuchsia.h"
25 #include "ToolChains/Gnu.h"
26 #include "ToolChains/HIP.h"
27 #include "ToolChains/Haiku.h"
28 #include "ToolChains/Hexagon.h"
29 #include "ToolChains/Hurd.h"
30 #include "ToolChains/Lanai.h"
31 #include "ToolChains/Linux.h"
32 #include "ToolChains/MSP430.h"
33 #include "ToolChains/MSVC.h"
34 #include "ToolChains/MinGW.h"
35 #include "ToolChains/Minix.h"
36 #include "ToolChains/MipsLinux.h"
37 #include "ToolChains/Myriad.h"
38 #include "ToolChains/NaCl.h"
39 #include "ToolChains/NetBSD.h"
40 #include "ToolChains/OpenBSD.h"
41 #include "ToolChains/PPCLinux.h"
42 #include "ToolChains/PS4CPU.h"
43 #include "ToolChains/RISCVToolchain.h"
44 #include "ToolChains/Solaris.h"
45 #include "ToolChains/TCE.h"
46 #include "ToolChains/WebAssembly.h"
47 #include "ToolChains/XCore.h"
48 #include "clang/Basic/Version.h"
49 #include "clang/Config/config.h"
50 #include "clang/Driver/Action.h"
51 #include "clang/Driver/Compilation.h"
52 #include "clang/Driver/DriverDiagnostic.h"
53 #include "clang/Driver/Job.h"
54 #include "clang/Driver/Options.h"
55 #include "clang/Driver/SanitizerArgs.h"
56 #include "clang/Driver/Tool.h"
57 #include "clang/Driver/ToolChain.h"
58 #include "llvm/ADT/ArrayRef.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include "llvm/ADT/SmallSet.h"
61 #include "llvm/ADT/StringExtras.h"
62 #include "llvm/ADT/StringSet.h"
63 #include "llvm/ADT/StringSwitch.h"
64 #include "llvm/Config/llvm-config.h"
65 #include "llvm/Option/Arg.h"
66 #include "llvm/Option/ArgList.h"
67 #include "llvm/Option/OptSpecifier.h"
68 #include "llvm/Option/OptTable.h"
69 #include "llvm/Option/Option.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/FileSystem.h"
73 #include "llvm/Support/FormatVariadic.h"
74 #include "llvm/Support/Host.h"
75 #include "llvm/Support/Path.h"
76 #include "llvm/Support/PrettyStackTrace.h"
77 #include "llvm/Support/Process.h"
78 #include "llvm/Support/Program.h"
79 #include "llvm/Support/StringSaver.h"
80 #include "llvm/Support/TargetRegistry.h"
81 #include "llvm/Support/VirtualFileSystem.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include <map>
84 #include <memory>
85 #include <utility>
86 #if LLVM_ON_UNIX
87 #include <unistd.h> // getpid
88 #include <sysexits.h> // EX_IOERR
89 #endif
90 
91 using namespace clang::driver;
92 using namespace clang;
93 using namespace llvm::opt;
94 
95 // static
96 std::string Driver::GetResourcesPath(StringRef BinaryPath,
97                                      StringRef CustomResourceDir) {
98   // Since the resource directory is embedded in the module hash, it's important
99   // that all places that need it call this function, so that they get the
100   // exact same string ("a/../b/" and "b/" get different hashes, for example).
101 
102   // Dir is bin/ or lib/, depending on where BinaryPath is.
103   std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
104 
105   SmallString<128> P(Dir);
106   if (CustomResourceDir != "") {
107     llvm::sys::path::append(P, CustomResourceDir);
108   } else {
109     // On Windows, libclang.dll is in bin/.
110     // On non-Windows, libclang.so/.dylib is in lib/.
111     // With a static-library build of libclang, LibClangPath will contain the
112     // path of the embedding binary, which for LLVM binaries will be in bin/.
113     // ../lib gets us to lib/ in both cases.
114     P = llvm::sys::path::parent_path(Dir);
115     llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
116                             CLANG_VERSION_STRING);
117   }
118 
119   return std::string(P.str());
120 }
121 
122 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
123                DiagnosticsEngine &Diags,
124                IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
125     : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
126       SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
127       ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
128       DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
129       CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
130       CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false),
131       CCLogDiagnostics(false), CCGenDiagnostics(false),
132       TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),
133       CheckInputsExist(true), GenReproducer(false),
134       SuppressMissingInputWarning(false) {
135   // Provide a sane fallback if no VFS is specified.
136   if (!this->VFS)
137     this->VFS = llvm::vfs::getRealFileSystem();
138 
139   Name = std::string(llvm::sys::path::filename(ClangExecutable));
140   Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
141   InstalledDir = Dir; // Provide a sensible default installed dir.
142 
143   if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
144     // Prepend InstalledDir if SysRoot is relative
145     SmallString<128> P(InstalledDir);
146     llvm::sys::path::append(P, SysRoot);
147     SysRoot = std::string(P);
148   }
149 
150 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
151   SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
152 #endif
153 #if defined(CLANG_CONFIG_FILE_USER_DIR)
154   UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
155 #endif
156 
157   // Compute the path to the resource directory.
158   ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
159 }
160 
161 void Driver::ParseDriverMode(StringRef ProgramName,
162                              ArrayRef<const char *> Args) {
163   if (ClangNameParts.isEmpty())
164     ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
165   setDriverModeFromOption(ClangNameParts.DriverMode);
166 
167   for (const char *ArgPtr : Args) {
168     // Ignore nullptrs, they are the response file's EOL markers.
169     if (ArgPtr == nullptr)
170       continue;
171     const StringRef Arg = ArgPtr;
172     setDriverModeFromOption(Arg);
173   }
174 }
175 
176 void Driver::setDriverModeFromOption(StringRef Opt) {
177   const std::string OptName =
178       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
179   if (!Opt.startswith(OptName))
180     return;
181   StringRef Value = Opt.drop_front(OptName.size());
182 
183   if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
184                    .Case("gcc", GCCMode)
185                    .Case("g++", GXXMode)
186                    .Case("cpp", CPPMode)
187                    .Case("cl", CLMode)
188                    .Case("flang", FlangMode)
189                    .Default(None))
190     Mode = *M;
191   else
192     Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
193 }
194 
195 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
196                                      bool IsClCompatMode,
197                                      bool &ContainsError) {
198   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
199   ContainsError = false;
200 
201   unsigned IncludedFlagsBitmask;
202   unsigned ExcludedFlagsBitmask;
203   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
204       getIncludeExcludeOptionFlagMasks(IsClCompatMode);
205 
206   unsigned MissingArgIndex, MissingArgCount;
207   InputArgList Args =
208       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
209                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
210 
211   // Check for missing argument error.
212   if (MissingArgCount) {
213     Diag(diag::err_drv_missing_argument)
214         << Args.getArgString(MissingArgIndex) << MissingArgCount;
215     ContainsError |=
216         Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
217                                  SourceLocation()) > DiagnosticsEngine::Warning;
218   }
219 
220   // Check for unsupported options.
221   for (const Arg *A : Args) {
222     if (A->getOption().hasFlag(options::Unsupported)) {
223       unsigned DiagID;
224       auto ArgString = A->getAsString(Args);
225       std::string Nearest;
226       if (getOpts().findNearest(
227             ArgString, Nearest, IncludedFlagsBitmask,
228             ExcludedFlagsBitmask | options::Unsupported) > 1) {
229         DiagID = diag::err_drv_unsupported_opt;
230         Diag(DiagID) << ArgString;
231       } else {
232         DiagID = diag::err_drv_unsupported_opt_with_suggestion;
233         Diag(DiagID) << ArgString << Nearest;
234       }
235       ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
236                        DiagnosticsEngine::Warning;
237       continue;
238     }
239 
240     // Warn about -mcpu= without an argument.
241     if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
242       Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
243       ContainsError |= Diags.getDiagnosticLevel(
244                            diag::warn_drv_empty_joined_argument,
245                            SourceLocation()) > DiagnosticsEngine::Warning;
246     }
247   }
248 
249   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
250     unsigned DiagID;
251     auto ArgString = A->getAsString(Args);
252     std::string Nearest;
253     if (getOpts().findNearest(
254           ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
255       DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
256                           : diag::err_drv_unknown_argument;
257       Diags.Report(DiagID) << ArgString;
258     } else {
259       DiagID = IsCLMode()
260                    ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
261                    : diag::err_drv_unknown_argument_with_suggestion;
262       Diags.Report(DiagID) << ArgString << Nearest;
263     }
264     ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
265                      DiagnosticsEngine::Warning;
266   }
267 
268   return Args;
269 }
270 
271 // Determine which compilation mode we are in. We look for options which
272 // affect the phase, starting with the earliest phases, and record which
273 // option we used to determine the final phase.
274 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
275                                  Arg **FinalPhaseArg) const {
276   Arg *PhaseArg = nullptr;
277   phases::ID FinalPhase;
278 
279   // -{E,EP,P,M,MM} only run the preprocessor.
280   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
281       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
282       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
283       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
284     FinalPhase = phases::Preprocess;
285 
286   // --precompile only runs up to precompilation.
287   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
288     FinalPhase = phases::Precompile;
289 
290   // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
291   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
292              (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
293              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
294              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
295              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
296              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
297              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
298              (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
299              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
300     FinalPhase = phases::Compile;
301 
302   // -S only runs up to the backend.
303   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
304     FinalPhase = phases::Backend;
305 
306   // -c compilation only runs up to the assembler.
307   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
308     FinalPhase = phases::Assemble;
309 
310   // Otherwise do everything.
311   } else
312     FinalPhase = phases::Link;
313 
314   if (FinalPhaseArg)
315     *FinalPhaseArg = PhaseArg;
316 
317   return FinalPhase;
318 }
319 
320 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
321                          StringRef Value, bool Claim = true) {
322   Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
323                    Args.getBaseArgs().MakeIndex(Value), Value.data());
324   Args.AddSynthesizedArg(A);
325   if (Claim)
326     A->claim();
327   return A;
328 }
329 
330 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
331   const llvm::opt::OptTable &Opts = getOpts();
332   DerivedArgList *DAL = new DerivedArgList(Args);
333 
334   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
335   bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
336   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
337   for (Arg *A : Args) {
338     // Unfortunately, we have to parse some forwarding options (-Xassembler,
339     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
340     // (assembler and preprocessor), or bypass a previous driver ('collect2').
341 
342     // Rewrite linker options, to replace --no-demangle with a custom internal
343     // option.
344     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
345          A->getOption().matches(options::OPT_Xlinker)) &&
346         A->containsValue("--no-demangle")) {
347       // Add the rewritten no-demangle argument.
348       DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
349 
350       // Add the remaining values as Xlinker arguments.
351       for (StringRef Val : A->getValues())
352         if (Val != "--no-demangle")
353           DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
354 
355       continue;
356     }
357 
358     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
359     // some build systems. We don't try to be complete here because we don't
360     // care to encourage this usage model.
361     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
362         (A->getValue(0) == StringRef("-MD") ||
363          A->getValue(0) == StringRef("-MMD"))) {
364       // Rewrite to -MD/-MMD along with -MF.
365       if (A->getValue(0) == StringRef("-MD"))
366         DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
367       else
368         DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
369       if (A->getNumValues() == 2)
370         DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
371       continue;
372     }
373 
374     // Rewrite reserved library names.
375     if (A->getOption().matches(options::OPT_l)) {
376       StringRef Value = A->getValue();
377 
378       // Rewrite unless -nostdlib is present.
379       if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
380           Value == "stdc++") {
381         DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
382         continue;
383       }
384 
385       // Rewrite unconditionally.
386       if (Value == "cc_kext") {
387         DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
388         continue;
389       }
390     }
391 
392     // Pick up inputs via the -- option.
393     if (A->getOption().matches(options::OPT__DASH_DASH)) {
394       A->claim();
395       for (StringRef Val : A->getValues())
396         DAL->append(MakeInputArg(*DAL, Opts, Val, false));
397       continue;
398     }
399 
400     DAL->append(A);
401   }
402 
403   // Enforce -static if -miamcu is present.
404   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
405     DAL->AddFlagArg(0, Opts.getOption(options::OPT_static));
406 
407 // Add a default value of -mlinker-version=, if one was given and the user
408 // didn't specify one.
409 #if defined(HOST_LINK_VERSION)
410   if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
411       strlen(HOST_LINK_VERSION) > 0) {
412     DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
413                       HOST_LINK_VERSION);
414     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
415   }
416 #endif
417 
418   return DAL;
419 }
420 
421 /// Compute target triple from args.
422 ///
423 /// This routine provides the logic to compute a target triple from various
424 /// args passed to the driver and the default triple string.
425 static llvm::Triple computeTargetTriple(const Driver &D,
426                                         StringRef TargetTriple,
427                                         const ArgList &Args,
428                                         StringRef DarwinArchName = "") {
429   // FIXME: Already done in Compilation *Driver::BuildCompilation
430   if (const Arg *A = Args.getLastArg(options::OPT_target))
431     TargetTriple = A->getValue();
432 
433   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
434 
435   // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
436   // -gnu* only, and we can not change this, so we have to detect that case as
437   // being the Hurd OS.
438   if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
439       TargetTriple.find("-pc-gnu") != StringRef::npos)
440     Target.setOSName("hurd");
441 
442   // Handle Apple-specific options available here.
443   if (Target.isOSBinFormatMachO()) {
444     // If an explicit Darwin arch name is given, that trumps all.
445     if (!DarwinArchName.empty()) {
446       tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
447       return Target;
448     }
449 
450     // Handle the Darwin '-arch' flag.
451     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
452       StringRef ArchName = A->getValue();
453       tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
454     }
455   }
456 
457   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
458   // '-mbig-endian'/'-EB'.
459   if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
460                                options::OPT_mbig_endian)) {
461     if (A->getOption().matches(options::OPT_mlittle_endian)) {
462       llvm::Triple LE = Target.getLittleEndianArchVariant();
463       if (LE.getArch() != llvm::Triple::UnknownArch)
464         Target = std::move(LE);
465     } else {
466       llvm::Triple BE = Target.getBigEndianArchVariant();
467       if (BE.getArch() != llvm::Triple::UnknownArch)
468         Target = std::move(BE);
469     }
470   }
471 
472   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
473   if (Target.getArch() == llvm::Triple::tce ||
474       Target.getOS() == llvm::Triple::Minix)
475     return Target;
476 
477   // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
478   Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
479                            options::OPT_m32, options::OPT_m16);
480   if (A) {
481     llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
482 
483     if (A->getOption().matches(options::OPT_m64)) {
484       AT = Target.get64BitArchVariant().getArch();
485       if (Target.getEnvironment() == llvm::Triple::GNUX32)
486         Target.setEnvironment(llvm::Triple::GNU);
487     } else if (A->getOption().matches(options::OPT_mx32) &&
488                Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
489       AT = llvm::Triple::x86_64;
490       Target.setEnvironment(llvm::Triple::GNUX32);
491     } else if (A->getOption().matches(options::OPT_m32)) {
492       AT = Target.get32BitArchVariant().getArch();
493       if (Target.getEnvironment() == llvm::Triple::GNUX32)
494         Target.setEnvironment(llvm::Triple::GNU);
495     } else if (A->getOption().matches(options::OPT_m16) &&
496                Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
497       AT = llvm::Triple::x86;
498       Target.setEnvironment(llvm::Triple::CODE16);
499     }
500 
501     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
502       Target.setArch(AT);
503   }
504 
505   // Handle -miamcu flag.
506   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
507     if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
508       D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
509                                                        << Target.str();
510 
511     if (A && !A->getOption().matches(options::OPT_m32))
512       D.Diag(diag::err_drv_argument_not_allowed_with)
513           << "-miamcu" << A->getBaseArg().getAsString(Args);
514 
515     Target.setArch(llvm::Triple::x86);
516     Target.setArchName("i586");
517     Target.setEnvironment(llvm::Triple::UnknownEnvironment);
518     Target.setEnvironmentName("");
519     Target.setOS(llvm::Triple::ELFIAMCU);
520     Target.setVendor(llvm::Triple::UnknownVendor);
521     Target.setVendorName("intel");
522   }
523 
524   // If target is MIPS adjust the target triple
525   // accordingly to provided ABI name.
526   A = Args.getLastArg(options::OPT_mabi_EQ);
527   if (A && Target.isMIPS()) {
528     StringRef ABIName = A->getValue();
529     if (ABIName == "32") {
530       Target = Target.get32BitArchVariant();
531       if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
532           Target.getEnvironment() == llvm::Triple::GNUABIN32)
533         Target.setEnvironment(llvm::Triple::GNU);
534     } else if (ABIName == "n32") {
535       Target = Target.get64BitArchVariant();
536       if (Target.getEnvironment() == llvm::Triple::GNU ||
537           Target.getEnvironment() == llvm::Triple::GNUABI64)
538         Target.setEnvironment(llvm::Triple::GNUABIN32);
539     } else if (ABIName == "64") {
540       Target = Target.get64BitArchVariant();
541       if (Target.getEnvironment() == llvm::Triple::GNU ||
542           Target.getEnvironment() == llvm::Triple::GNUABIN32)
543         Target.setEnvironment(llvm::Triple::GNUABI64);
544     }
545   }
546 
547   // If target is RISC-V adjust the target triple according to
548   // provided architecture name
549   A = Args.getLastArg(options::OPT_march_EQ);
550   if (A && Target.isRISCV()) {
551     StringRef ArchName = A->getValue();
552     if (ArchName.startswith_lower("rv32"))
553       Target.setArch(llvm::Triple::riscv32);
554     else if (ArchName.startswith_lower("rv64"))
555       Target.setArch(llvm::Triple::riscv64);
556   }
557 
558   return Target;
559 }
560 
561 // Parse the LTO options and record the type of LTO compilation
562 // based on which -f(no-)?lto(=.*)? option occurs last.
563 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
564   LTOMode = LTOK_None;
565   if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
566                     options::OPT_fno_lto, false))
567     return;
568 
569   StringRef LTOName("full");
570 
571   const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
572   if (A)
573     LTOName = A->getValue();
574 
575   LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
576                 .Case("full", LTOK_Full)
577                 .Case("thin", LTOK_Thin)
578                 .Default(LTOK_Unknown);
579 
580   if (LTOMode == LTOK_Unknown) {
581     assert(A);
582     Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
583                                                     << A->getValue();
584   }
585 }
586 
587 /// Compute the desired OpenMP runtime from the flags provided.
588 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
589   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
590 
591   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
592   if (A)
593     RuntimeName = A->getValue();
594 
595   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
596                 .Case("libomp", OMPRT_OMP)
597                 .Case("libgomp", OMPRT_GOMP)
598                 .Case("libiomp5", OMPRT_IOMP5)
599                 .Default(OMPRT_Unknown);
600 
601   if (RT == OMPRT_Unknown) {
602     if (A)
603       Diag(diag::err_drv_unsupported_option_argument)
604           << A->getOption().getName() << A->getValue();
605     else
606       // FIXME: We could use a nicer diagnostic here.
607       Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
608   }
609 
610   return RT;
611 }
612 
613 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
614                                               InputList &Inputs) {
615 
616   //
617   // CUDA/HIP
618   //
619   // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
620   // or HIP type. However, mixed CUDA/HIP compilation is not supported.
621   bool IsCuda =
622       llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
623         return types::isCuda(I.first);
624       });
625   bool IsHIP =
626       llvm::any_of(Inputs,
627                    [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
628                      return types::isHIP(I.first);
629                    }) ||
630       C.getInputArgs().hasArg(options::OPT_hip_link);
631   if (IsCuda && IsHIP) {
632     Diag(clang::diag::err_drv_mix_cuda_hip);
633     return;
634   }
635   if (IsCuda) {
636     const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
637     const llvm::Triple &HostTriple = HostTC->getTriple();
638     StringRef DeviceTripleStr;
639     auto OFK = Action::OFK_Cuda;
640     DeviceTripleStr =
641         HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
642     llvm::Triple CudaTriple(DeviceTripleStr);
643     // Use the CUDA and host triples as the key into the ToolChains map,
644     // because the device toolchain we create depends on both.
645     auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
646     if (!CudaTC) {
647       CudaTC = std::make_unique<toolchains::CudaToolChain>(
648           *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
649     }
650     C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
651   } else if (IsHIP) {
652     const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
653     const llvm::Triple &HostTriple = HostTC->getTriple();
654     StringRef DeviceTripleStr;
655     auto OFK = Action::OFK_HIP;
656     DeviceTripleStr = "amdgcn-amd-amdhsa";
657     llvm::Triple HIPTriple(DeviceTripleStr);
658     // Use the HIP and host triples as the key into the ToolChains map,
659     // because the device toolchain we create depends on both.
660     auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
661     if (!HIPTC) {
662       HIPTC = std::make_unique<toolchains::HIPToolChain>(
663           *this, HIPTriple, *HostTC, C.getInputArgs());
664     }
665     C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
666   }
667 
668   //
669   // OpenMP
670   //
671   // We need to generate an OpenMP toolchain if the user specified targets with
672   // the -fopenmp-targets option.
673   if (Arg *OpenMPTargets =
674           C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
675     if (OpenMPTargets->getNumValues()) {
676       // We expect that -fopenmp-targets is always used in conjunction with the
677       // option -fopenmp specifying a valid runtime with offloading support,
678       // i.e. libomp or libiomp.
679       bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
680           options::OPT_fopenmp, options::OPT_fopenmp_EQ,
681           options::OPT_fno_openmp, false);
682       if (HasValidOpenMPRuntime) {
683         OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
684         HasValidOpenMPRuntime =
685             OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
686       }
687 
688       if (HasValidOpenMPRuntime) {
689         llvm::StringMap<const char *> FoundNormalizedTriples;
690         for (const char *Val : OpenMPTargets->getValues()) {
691           llvm::Triple TT(Val);
692           std::string NormalizedName = TT.normalize();
693 
694           // Make sure we don't have a duplicate triple.
695           auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
696           if (Duplicate != FoundNormalizedTriples.end()) {
697             Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
698                 << Val << Duplicate->second;
699             continue;
700           }
701 
702           // Store the current triple so that we can check for duplicates in the
703           // following iterations.
704           FoundNormalizedTriples[NormalizedName] = Val;
705 
706           // If the specified target is invalid, emit a diagnostic.
707           if (TT.getArch() == llvm::Triple::UnknownArch)
708             Diag(clang::diag::err_drv_invalid_omp_target) << Val;
709           else {
710             const ToolChain *TC;
711             // CUDA toolchains have to be selected differently. They pair host
712             // and device in their implementation.
713             if (TT.isNVPTX()) {
714               const ToolChain *HostTC =
715                   C.getSingleOffloadToolChain<Action::OFK_Host>();
716               assert(HostTC && "Host toolchain should be always defined.");
717               auto &CudaTC =
718                   ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
719               if (!CudaTC)
720                 CudaTC = std::make_unique<toolchains::CudaToolChain>(
721                     *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
722               TC = CudaTC.get();
723             } else
724               TC = &getToolChain(C.getInputArgs(), TT);
725             C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
726           }
727         }
728       } else
729         Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
730     } else
731       Diag(clang::diag::warn_drv_empty_joined_argument)
732           << OpenMPTargets->getAsString(C.getInputArgs());
733   }
734 
735   //
736   // TODO: Add support for other offloading programming models here.
737   //
738 }
739 
740 /// Looks the given directories for the specified file.
741 ///
742 /// \param[out] FilePath File path, if the file was found.
743 /// \param[in]  Dirs Directories used for the search.
744 /// \param[in]  FileName Name of the file to search for.
745 /// \return True if file was found.
746 ///
747 /// Looks for file specified by FileName sequentially in directories specified
748 /// by Dirs.
749 ///
750 static bool searchForFile(SmallVectorImpl<char> &FilePath,
751                           ArrayRef<std::string> Dirs,
752                           StringRef FileName) {
753   SmallString<128> WPath;
754   for (const std::string &Dir : Dirs) {
755     if (Dir.empty())
756       continue;
757     WPath.clear();
758     llvm::sys::path::append(WPath, Dir, FileName);
759     llvm::sys::path::native(WPath);
760     if (llvm::sys::fs::is_regular_file(WPath)) {
761       FilePath = std::move(WPath);
762       return true;
763     }
764   }
765   return false;
766 }
767 
768 bool Driver::readConfigFile(StringRef FileName) {
769   // Try reading the given file.
770   SmallVector<const char *, 32> NewCfgArgs;
771   if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
772     Diag(diag::err_drv_cannot_read_config_file) << FileName;
773     return true;
774   }
775 
776   // Read options from config file.
777   llvm::SmallString<128> CfgFileName(FileName);
778   llvm::sys::path::native(CfgFileName);
779   ConfigFile = std::string(CfgFileName.str());
780   bool ContainErrors;
781   CfgOptions = std::make_unique<InputArgList>(
782       ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
783   if (ContainErrors) {
784     CfgOptions.reset();
785     return true;
786   }
787 
788   if (CfgOptions->hasArg(options::OPT_config)) {
789     CfgOptions.reset();
790     Diag(diag::err_drv_nested_config_file);
791     return true;
792   }
793 
794   // Claim all arguments that come from a configuration file so that the driver
795   // does not warn on any that is unused.
796   for (Arg *A : *CfgOptions)
797     A->claim();
798   return false;
799 }
800 
801 bool Driver::loadConfigFile() {
802   std::string CfgFileName;
803   bool FileSpecifiedExplicitly = false;
804 
805   // Process options that change search path for config files.
806   if (CLOptions) {
807     if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
808       SmallString<128> CfgDir;
809       CfgDir.append(
810           CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
811       if (!CfgDir.empty()) {
812         if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
813           SystemConfigDir.clear();
814         else
815           SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
816       }
817     }
818     if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
819       SmallString<128> CfgDir;
820       CfgDir.append(
821           CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
822       if (!CfgDir.empty()) {
823         if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
824           UserConfigDir.clear();
825         else
826           UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
827       }
828     }
829   }
830 
831   // First try to find config file specified in command line.
832   if (CLOptions) {
833     std::vector<std::string> ConfigFiles =
834         CLOptions->getAllArgValues(options::OPT_config);
835     if (ConfigFiles.size() > 1) {
836       if (!std::all_of(
837               ConfigFiles.begin(), ConfigFiles.end(),
838               [ConfigFiles](std::string s) { return s == ConfigFiles[0]; })) {
839         Diag(diag::err_drv_duplicate_config);
840         return true;
841       }
842     }
843 
844     if (!ConfigFiles.empty()) {
845       CfgFileName = ConfigFiles.front();
846       assert(!CfgFileName.empty());
847 
848       // If argument contains directory separator, treat it as a path to
849       // configuration file.
850       if (llvm::sys::path::has_parent_path(CfgFileName)) {
851         SmallString<128> CfgFilePath;
852         if (llvm::sys::path::is_relative(CfgFileName))
853           llvm::sys::fs::current_path(CfgFilePath);
854         llvm::sys::path::append(CfgFilePath, CfgFileName);
855         if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
856           Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
857           return true;
858         }
859         return readConfigFile(CfgFilePath);
860       }
861 
862       FileSpecifiedExplicitly = true;
863     }
864   }
865 
866   // If config file is not specified explicitly, try to deduce configuration
867   // from executable name. For instance, an executable 'armv7l-clang' will
868   // search for config file 'armv7l-clang.cfg'.
869   if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
870     CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
871 
872   if (CfgFileName.empty())
873     return false;
874 
875   // Determine architecture part of the file name, if it is present.
876   StringRef CfgFileArch = CfgFileName;
877   size_t ArchPrefixLen = CfgFileArch.find('-');
878   if (ArchPrefixLen == StringRef::npos)
879     ArchPrefixLen = CfgFileArch.size();
880   llvm::Triple CfgTriple;
881   CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
882   CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
883   if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
884     ArchPrefixLen = 0;
885 
886   if (!StringRef(CfgFileName).endswith(".cfg"))
887     CfgFileName += ".cfg";
888 
889   // If config file starts with architecture name and command line options
890   // redefine architecture (with options like -m32 -LE etc), try finding new
891   // config file with that architecture.
892   SmallString<128> FixedConfigFile;
893   size_t FixedArchPrefixLen = 0;
894   if (ArchPrefixLen) {
895     // Get architecture name from config file name like 'i386.cfg' or
896     // 'armv7l-clang.cfg'.
897     // Check if command line options changes effective triple.
898     llvm::Triple EffectiveTriple = computeTargetTriple(*this,
899                                              CfgTriple.getTriple(), *CLOptions);
900     if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
901       FixedConfigFile = EffectiveTriple.getArchName();
902       FixedArchPrefixLen = FixedConfigFile.size();
903       // Append the rest of original file name so that file name transforms
904       // like: i386-clang.cfg -> x86_64-clang.cfg.
905       if (ArchPrefixLen < CfgFileName.size())
906         FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
907     }
908   }
909 
910   // Prepare list of directories where config file is searched for.
911   SmallVector<std::string, 3> CfgFileSearchDirs;
912   CfgFileSearchDirs.push_back(UserConfigDir);
913   CfgFileSearchDirs.push_back(SystemConfigDir);
914   CfgFileSearchDirs.push_back(Dir);
915 
916   // Try to find config file. First try file with corrected architecture.
917   llvm::SmallString<128> CfgFilePath;
918   if (!FixedConfigFile.empty()) {
919     if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
920       return readConfigFile(CfgFilePath);
921     // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
922     FixedConfigFile.resize(FixedArchPrefixLen);
923     FixedConfigFile.append(".cfg");
924     if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
925       return readConfigFile(CfgFilePath);
926   }
927 
928   // Then try original file name.
929   if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
930     return readConfigFile(CfgFilePath);
931 
932   // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
933   if (!ClangNameParts.ModeSuffix.empty() &&
934       !ClangNameParts.TargetPrefix.empty()) {
935     CfgFileName.assign(ClangNameParts.TargetPrefix);
936     CfgFileName.append(".cfg");
937     if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
938       return readConfigFile(CfgFilePath);
939   }
940 
941   // Report error but only if config file was specified explicitly, by option
942   // --config. If it was deduced from executable name, it is not an error.
943   if (FileSpecifiedExplicitly) {
944     Diag(diag::err_drv_config_file_not_found) << CfgFileName;
945     for (const std::string &SearchDir : CfgFileSearchDirs)
946       if (!SearchDir.empty())
947         Diag(diag::note_drv_config_file_searched_in) << SearchDir;
948     return true;
949   }
950 
951   return false;
952 }
953 
954 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
955   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
956 
957   // FIXME: Handle environment options which affect driver behavior, somewhere
958   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
959 
960   if (Optional<std::string> CompilerPathValue =
961           llvm::sys::Process::GetEnv("COMPILER_PATH")) {
962     StringRef CompilerPath = *CompilerPathValue;
963     while (!CompilerPath.empty()) {
964       std::pair<StringRef, StringRef> Split =
965           CompilerPath.split(llvm::sys::EnvPathSeparator);
966       PrefixDirs.push_back(std::string(Split.first));
967       CompilerPath = Split.second;
968     }
969   }
970 
971   // We look for the driver mode option early, because the mode can affect
972   // how other options are parsed.
973   ParseDriverMode(ClangExecutable, ArgList.slice(1));
974 
975   // FIXME: What are we going to do with -V and -b?
976 
977   // Arguments specified in command line.
978   bool ContainsError;
979   CLOptions = std::make_unique<InputArgList>(
980       ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
981 
982   // Try parsing configuration file.
983   if (!ContainsError)
984     ContainsError = loadConfigFile();
985   bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
986 
987   // All arguments, from both config file and command line.
988   InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
989                                               : std::move(*CLOptions));
990 
991   // The args for config files or /clang: flags belong to different InputArgList
992   // objects than Args. This copies an Arg from one of those other InputArgLists
993   // to the ownership of Args.
994   auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
995       unsigned Index = Args.MakeIndex(Opt->getSpelling());
996       Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
997                                      Index, BaseArg);
998       Copy->getValues() = Opt->getValues();
999       if (Opt->isClaimed())
1000         Copy->claim();
1001       Args.append(Copy);
1002   };
1003 
1004   if (HasConfigFile)
1005     for (auto *Opt : *CLOptions) {
1006       if (Opt->getOption().matches(options::OPT_config))
1007         continue;
1008       const Arg *BaseArg = &Opt->getBaseArg();
1009       if (BaseArg == Opt)
1010         BaseArg = nullptr;
1011       appendOneArg(Opt, BaseArg);
1012     }
1013 
1014   // In CL mode, look for any pass-through arguments
1015   if (IsCLMode() && !ContainsError) {
1016     SmallVector<const char *, 16> CLModePassThroughArgList;
1017     for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1018       A->claim();
1019       CLModePassThroughArgList.push_back(A->getValue());
1020     }
1021 
1022     if (!CLModePassThroughArgList.empty()) {
1023       // Parse any pass through args using default clang processing rather
1024       // than clang-cl processing.
1025       auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1026           ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1027 
1028       if (!ContainsError)
1029         for (auto *Opt : *CLModePassThroughOptions) {
1030           appendOneArg(Opt, nullptr);
1031         }
1032     }
1033   }
1034 
1035   // Check for working directory option before accessing any files
1036   if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1037     if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1038       Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1039 
1040   // FIXME: This stuff needs to go into the Compilation, not the driver.
1041   bool CCCPrintPhases;
1042 
1043   // Silence driver warnings if requested
1044   Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1045 
1046   // -no-canonical-prefixes is used very early in main.
1047   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1048 
1049   // f(no-)integated-cc1 is also used very early in main.
1050   Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1051   Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1052 
1053   // Ignore -pipe.
1054   Args.ClaimAllArgs(options::OPT_pipe);
1055 
1056   // Extract -ccc args.
1057   //
1058   // FIXME: We need to figure out where this behavior should live. Most of it
1059   // should be outside in the client; the parts that aren't should have proper
1060   // options, either by introducing new ones or by overloading gcc ones like -V
1061   // or -b.
1062   CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1063   CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1064   if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1065     CCCGenericGCCName = A->getValue();
1066   GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1067                                options::OPT_fno_crash_diagnostics,
1068                                !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
1069   // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1070   // and getToolChain is const.
1071   if (IsCLMode()) {
1072     // clang-cl targets MSVC-style Win32.
1073     llvm::Triple T(TargetTriple);
1074     T.setOS(llvm::Triple::Win32);
1075     T.setVendor(llvm::Triple::PC);
1076     T.setEnvironment(llvm::Triple::MSVC);
1077     T.setObjectFormat(llvm::Triple::COFF);
1078     TargetTriple = T.str();
1079   }
1080   if (const Arg *A = Args.getLastArg(options::OPT_target))
1081     TargetTriple = A->getValue();
1082   if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1083     Dir = InstalledDir = A->getValue();
1084   for (const Arg *A : Args.filtered(options::OPT_B)) {
1085     A->claim();
1086     PrefixDirs.push_back(A->getValue(0));
1087   }
1088   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1089     SysRoot = A->getValue();
1090   if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1091     DyldPrefix = A->getValue();
1092 
1093   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1094     ResourceDir = A->getValue();
1095 
1096   if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1097     SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1098                     .Case("cwd", SaveTempsCwd)
1099                     .Case("obj", SaveTempsObj)
1100                     .Default(SaveTempsCwd);
1101   }
1102 
1103   setLTOMode(Args);
1104 
1105   // Process -fembed-bitcode= flags.
1106   if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1107     StringRef Name = A->getValue();
1108     unsigned Model = llvm::StringSwitch<unsigned>(Name)
1109         .Case("off", EmbedNone)
1110         .Case("all", EmbedBitcode)
1111         .Case("bitcode", EmbedBitcode)
1112         .Case("marker", EmbedMarker)
1113         .Default(~0U);
1114     if (Model == ~0U) {
1115       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1116                                                 << Name;
1117     } else
1118       BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1119   }
1120 
1121   std::unique_ptr<llvm::opt::InputArgList> UArgs =
1122       std::make_unique<InputArgList>(std::move(Args));
1123 
1124   // Perform the default argument translations.
1125   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1126 
1127   // Owned by the host.
1128   const ToolChain &TC = getToolChain(
1129       *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1130 
1131   // The compilation takes ownership of Args.
1132   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1133                                    ContainsError);
1134 
1135   if (!HandleImmediateArgs(*C))
1136     return C;
1137 
1138   // Construct the list of inputs.
1139   InputList Inputs;
1140   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1141 
1142   // Populate the tool chains for the offloading devices, if any.
1143   CreateOffloadingDeviceToolChains(*C, Inputs);
1144 
1145   // Construct the list of abstract actions to perform for this compilation. On
1146   // MachO targets this uses the driver-driver and universal actions.
1147   if (TC.getTriple().isOSBinFormatMachO())
1148     BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1149   else
1150     BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1151 
1152   if (CCCPrintPhases) {
1153     PrintActions(*C);
1154     return C;
1155   }
1156 
1157   BuildJobs(*C);
1158 
1159   return C;
1160 }
1161 
1162 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1163   llvm::opt::ArgStringList ASL;
1164   for (const auto *A : Args)
1165     A->render(Args, ASL);
1166 
1167   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1168     if (I != ASL.begin())
1169       OS << ' ';
1170     llvm::sys::printArg(OS, *I, true);
1171   }
1172   OS << '\n';
1173 }
1174 
1175 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1176                                     SmallString<128> &CrashDiagDir) {
1177   using namespace llvm::sys;
1178   assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1179          "Only knows about .crash files on Darwin");
1180 
1181   // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1182   // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1183   // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1184   path::home_directory(CrashDiagDir);
1185   if (CrashDiagDir.startswith("/var/root"))
1186     CrashDiagDir = "/";
1187   path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1188   int PID =
1189 #if LLVM_ON_UNIX
1190       getpid();
1191 #else
1192       0;
1193 #endif
1194   std::error_code EC;
1195   fs::file_status FileStatus;
1196   TimePoint<> LastAccessTime;
1197   SmallString<128> CrashFilePath;
1198   // Lookup the .crash files and get the one generated by a subprocess spawned
1199   // by this driver invocation.
1200   for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1201        File != FileEnd && !EC; File.increment(EC)) {
1202     StringRef FileName = path::filename(File->path());
1203     if (!FileName.startswith(Name))
1204       continue;
1205     if (fs::status(File->path(), FileStatus))
1206       continue;
1207     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1208         llvm::MemoryBuffer::getFile(File->path());
1209     if (!CrashFile)
1210       continue;
1211     // The first line should start with "Process:", otherwise this isn't a real
1212     // .crash file.
1213     StringRef Data = CrashFile.get()->getBuffer();
1214     if (!Data.startswith("Process:"))
1215       continue;
1216     // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1217     size_t ParentProcPos = Data.find("Parent Process:");
1218     if (ParentProcPos == StringRef::npos)
1219       continue;
1220     size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1221     if (LineEnd == StringRef::npos)
1222       continue;
1223     StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1224     int OpenBracket = -1, CloseBracket = -1;
1225     for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1226       if (ParentProcess[i] == '[')
1227         OpenBracket = i;
1228       if (ParentProcess[i] == ']')
1229         CloseBracket = i;
1230     }
1231     // Extract the parent process PID from the .crash file and check whether
1232     // it matches this driver invocation pid.
1233     int CrashPID;
1234     if (OpenBracket < 0 || CloseBracket < 0 ||
1235         ParentProcess.slice(OpenBracket + 1, CloseBracket)
1236             .getAsInteger(10, CrashPID) || CrashPID != PID) {
1237       continue;
1238     }
1239 
1240     // Found a .crash file matching the driver pid. To avoid getting an older
1241     // and misleading crash file, continue looking for the most recent.
1242     // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1243     // multiple crashes poiting to the same parent process. Since the driver
1244     // does not collect pid information for the dispatched invocation there's
1245     // currently no way to distinguish among them.
1246     const auto FileAccessTime = FileStatus.getLastModificationTime();
1247     if (FileAccessTime > LastAccessTime) {
1248       CrashFilePath.assign(File->path());
1249       LastAccessTime = FileAccessTime;
1250     }
1251   }
1252 
1253   // If found, copy it over to the location of other reproducer files.
1254   if (!CrashFilePath.empty()) {
1255     EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1256     if (EC)
1257       return false;
1258     return true;
1259   }
1260 
1261   return false;
1262 }
1263 
1264 // When clang crashes, produce diagnostic information including the fully
1265 // preprocessed source file(s).  Request that the developer attach the
1266 // diagnostic information to a bug report.
1267 void Driver::generateCompilationDiagnostics(
1268     Compilation &C, const Command &FailingCommand,
1269     StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1270   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1271     return;
1272 
1273   // Don't try to generate diagnostics for link or dsymutil jobs.
1274   if (FailingCommand.getCreator().isLinkJob() ||
1275       FailingCommand.getCreator().isDsymutilJob())
1276     return;
1277 
1278   // Print the version of the compiler.
1279   PrintVersion(C, llvm::errs());
1280 
1281   // Suppress driver output and emit preprocessor output to temp file.
1282   Mode = CPPMode;
1283   CCGenDiagnostics = true;
1284 
1285   // Save the original job command(s).
1286   Command Cmd = FailingCommand;
1287 
1288   // Keep track of whether we produce any errors while trying to produce
1289   // preprocessed sources.
1290   DiagnosticErrorTrap Trap(Diags);
1291 
1292   // Suppress tool output.
1293   C.initCompilationForDiagnostics();
1294 
1295   // Construct the list of inputs.
1296   InputList Inputs;
1297   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1298 
1299   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1300     bool IgnoreInput = false;
1301 
1302     // Ignore input from stdin or any inputs that cannot be preprocessed.
1303     // Check type first as not all linker inputs have a value.
1304     if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1305       IgnoreInput = true;
1306     } else if (!strcmp(it->second->getValue(), "-")) {
1307       Diag(clang::diag::note_drv_command_failed_diag_msg)
1308           << "Error generating preprocessed source(s) - "
1309              "ignoring input from stdin.";
1310       IgnoreInput = true;
1311     }
1312 
1313     if (IgnoreInput) {
1314       it = Inputs.erase(it);
1315       ie = Inputs.end();
1316     } else {
1317       ++it;
1318     }
1319   }
1320 
1321   if (Inputs.empty()) {
1322     Diag(clang::diag::note_drv_command_failed_diag_msg)
1323         << "Error generating preprocessed source(s) - "
1324            "no preprocessable inputs.";
1325     return;
1326   }
1327 
1328   // Don't attempt to generate preprocessed files if multiple -arch options are
1329   // used, unless they're all duplicates.
1330   llvm::StringSet<> ArchNames;
1331   for (const Arg *A : C.getArgs()) {
1332     if (A->getOption().matches(options::OPT_arch)) {
1333       StringRef ArchName = A->getValue();
1334       ArchNames.insert(ArchName);
1335     }
1336   }
1337   if (ArchNames.size() > 1) {
1338     Diag(clang::diag::note_drv_command_failed_diag_msg)
1339         << "Error generating preprocessed source(s) - cannot generate "
1340            "preprocessed source with multiple -arch options.";
1341     return;
1342   }
1343 
1344   // Construct the list of abstract actions to perform for this compilation. On
1345   // Darwin OSes this uses the driver-driver and builds universal actions.
1346   const ToolChain &TC = C.getDefaultToolChain();
1347   if (TC.getTriple().isOSBinFormatMachO())
1348     BuildUniversalActions(C, TC, Inputs);
1349   else
1350     BuildActions(C, C.getArgs(), Inputs, C.getActions());
1351 
1352   BuildJobs(C);
1353 
1354   // If there were errors building the compilation, quit now.
1355   if (Trap.hasErrorOccurred()) {
1356     Diag(clang::diag::note_drv_command_failed_diag_msg)
1357         << "Error generating preprocessed source(s).";
1358     return;
1359   }
1360 
1361   // Generate preprocessed output.
1362   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1363   C.ExecuteJobs(C.getJobs(), FailingCommands);
1364 
1365   // If any of the preprocessing commands failed, clean up and exit.
1366   if (!FailingCommands.empty()) {
1367     Diag(clang::diag::note_drv_command_failed_diag_msg)
1368         << "Error generating preprocessed source(s).";
1369     return;
1370   }
1371 
1372   const ArgStringList &TempFiles = C.getTempFiles();
1373   if (TempFiles.empty()) {
1374     Diag(clang::diag::note_drv_command_failed_diag_msg)
1375         << "Error generating preprocessed source(s).";
1376     return;
1377   }
1378 
1379   Diag(clang::diag::note_drv_command_failed_diag_msg)
1380       << "\n********************\n\n"
1381          "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1382          "Preprocessed source(s) and associated run script(s) are located at:";
1383 
1384   SmallString<128> VFS;
1385   SmallString<128> ReproCrashFilename;
1386   for (const char *TempFile : TempFiles) {
1387     Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1388     if (Report)
1389       Report->TemporaryFiles.push_back(TempFile);
1390     if (ReproCrashFilename.empty()) {
1391       ReproCrashFilename = TempFile;
1392       llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1393     }
1394     if (StringRef(TempFile).endswith(".cache")) {
1395       // In some cases (modules) we'll dump extra data to help with reproducing
1396       // the crash into a directory next to the output.
1397       VFS = llvm::sys::path::filename(TempFile);
1398       llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1399     }
1400   }
1401 
1402   // Assume associated files are based off of the first temporary file.
1403   CrashReportInfo CrashInfo(TempFiles[0], VFS);
1404 
1405   llvm::SmallString<128> Script(CrashInfo.Filename);
1406   llvm::sys::path::replace_extension(Script, "sh");
1407   std::error_code EC;
1408   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
1409   if (EC) {
1410     Diag(clang::diag::note_drv_command_failed_diag_msg)
1411         << "Error generating run script: " << Script << " " << EC.message();
1412   } else {
1413     ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1414              << "# Driver args: ";
1415     printArgList(ScriptOS, C.getInputArgs());
1416     ScriptOS << "# Original command: ";
1417     Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1418     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1419     if (!AdditionalInformation.empty())
1420       ScriptOS << "\n# Additional information: " << AdditionalInformation
1421                << "\n";
1422     if (Report)
1423       Report->TemporaryFiles.push_back(std::string(Script.str()));
1424     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1425   }
1426 
1427   // On darwin, provide information about the .crash diagnostic report.
1428   if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1429     SmallString<128> CrashDiagDir;
1430     if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1431       Diag(clang::diag::note_drv_command_failed_diag_msg)
1432           << ReproCrashFilename.str();
1433     } else { // Suggest a directory for the user to look for .crash files.
1434       llvm::sys::path::append(CrashDiagDir, Name);
1435       CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1436       Diag(clang::diag::note_drv_command_failed_diag_msg)
1437           << "Crash backtrace is located in";
1438       Diag(clang::diag::note_drv_command_failed_diag_msg)
1439           << CrashDiagDir.str();
1440       Diag(clang::diag::note_drv_command_failed_diag_msg)
1441           << "(choose the .crash file that corresponds to your crash)";
1442     }
1443   }
1444 
1445   for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1446                                             options::OPT_frewrite_map_file_EQ))
1447     Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1448 
1449   Diag(clang::diag::note_drv_command_failed_diag_msg)
1450       << "\n\n********************";
1451 }
1452 
1453 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1454   // Since commandLineFitsWithinSystemLimits() may underestimate system's
1455   // capacity if the tool does not support response files, there is a chance/
1456   // that things will just work without a response file, so we silently just
1457   // skip it.
1458   if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1459       llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1460                                                    Cmd.getArguments()))
1461     return;
1462 
1463   std::string TmpName = GetTemporaryPath("response", "txt");
1464   Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1465 }
1466 
1467 int Driver::ExecuteCompilation(
1468     Compilation &C,
1469     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1470   // Just print if -### was present.
1471   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1472     C.getJobs().Print(llvm::errs(), "\n", true);
1473     return 0;
1474   }
1475 
1476   // If there were errors building the compilation, quit now.
1477   if (Diags.hasErrorOccurred())
1478     return 1;
1479 
1480   // Set up response file names for each command, if necessary
1481   for (auto &Job : C.getJobs())
1482     setUpResponseFiles(C, Job);
1483 
1484   C.ExecuteJobs(C.getJobs(), FailingCommands);
1485 
1486   // If the command succeeded, we are done.
1487   if (FailingCommands.empty())
1488     return 0;
1489 
1490   // Otherwise, remove result files and print extra information about abnormal
1491   // failures.
1492   int Res = 0;
1493   for (const auto &CmdPair : FailingCommands) {
1494     int CommandRes = CmdPair.first;
1495     const Command *FailingCommand = CmdPair.second;
1496 
1497     // Remove result files if we're not saving temps.
1498     if (!isSaveTempsEnabled()) {
1499       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1500       C.CleanupFileMap(C.getResultFiles(), JA, true);
1501 
1502       // Failure result files are valid unless we crashed.
1503       if (CommandRes < 0)
1504         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1505     }
1506 
1507 #if LLVM_ON_UNIX
1508     // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1509     // for SIGPIPE. Do not print diagnostics for this case.
1510     if (CommandRes == EX_IOERR) {
1511       Res = CommandRes;
1512       continue;
1513     }
1514 #endif
1515 
1516     // Print extra information about abnormal failures, if possible.
1517     //
1518     // This is ad-hoc, but we don't want to be excessively noisy. If the result
1519     // status was 1, assume the command failed normally. In particular, if it
1520     // was the compiler then assume it gave a reasonable error code. Failures
1521     // in other tools are less common, and they generally have worse
1522     // diagnostics, so always print the diagnostic there.
1523     const Tool &FailingTool = FailingCommand->getCreator();
1524 
1525     if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1526       // FIXME: See FIXME above regarding result code interpretation.
1527       if (CommandRes < 0)
1528         Diag(clang::diag::err_drv_command_signalled)
1529             << FailingTool.getShortName();
1530       else
1531         Diag(clang::diag::err_drv_command_failed)
1532             << FailingTool.getShortName() << CommandRes;
1533     }
1534   }
1535   return Res;
1536 }
1537 
1538 void Driver::PrintHelp(bool ShowHidden) const {
1539   unsigned IncludedFlagsBitmask;
1540   unsigned ExcludedFlagsBitmask;
1541   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1542       getIncludeExcludeOptionFlagMasks(IsCLMode());
1543 
1544   ExcludedFlagsBitmask |= options::NoDriverOption;
1545   if (!ShowHidden)
1546     ExcludedFlagsBitmask |= HelpHidden;
1547 
1548   std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1549   getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1550                       IncludedFlagsBitmask, ExcludedFlagsBitmask,
1551                       /*ShowAllAliases=*/false);
1552 }
1553 
1554 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1555   // FIXME: The following handlers should use a callback mechanism, we don't
1556   // know what the client would like to do.
1557   OS << getClangFullVersion() << '\n';
1558   const ToolChain &TC = C.getDefaultToolChain();
1559   OS << "Target: " << TC.getTripleString() << '\n';
1560 
1561   // Print the threading model.
1562   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1563     // Don't print if the ToolChain would have barfed on it already
1564     if (TC.isThreadModelSupported(A->getValue()))
1565       OS << "Thread model: " << A->getValue();
1566   } else
1567     OS << "Thread model: " << TC.getThreadModel();
1568   OS << '\n';
1569 
1570   // Print out the install directory.
1571   OS << "InstalledDir: " << InstalledDir << '\n';
1572 
1573   // If configuration file was used, print its path.
1574   if (!ConfigFile.empty())
1575     OS << "Configuration file: " << ConfigFile << '\n';
1576 }
1577 
1578 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1579 /// option.
1580 static void PrintDiagnosticCategories(raw_ostream &OS) {
1581   // Skip the empty category.
1582   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1583        ++i)
1584     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1585 }
1586 
1587 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1588   if (PassedFlags == "")
1589     return;
1590   // Print out all options that start with a given argument. This is used for
1591   // shell autocompletion.
1592   std::vector<std::string> SuggestedCompletions;
1593   std::vector<std::string> Flags;
1594 
1595   unsigned short DisableFlags =
1596       options::NoDriverOption | options::Unsupported | options::Ignored;
1597 
1598   // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1599   // because the latter indicates that the user put space before pushing tab
1600   // which should end up in a file completion.
1601   const bool HasSpace = PassedFlags.endswith(",");
1602 
1603   // Parse PassedFlags by "," as all the command-line flags are passed to this
1604   // function separated by ","
1605   StringRef TargetFlags = PassedFlags;
1606   while (TargetFlags != "") {
1607     StringRef CurFlag;
1608     std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1609     Flags.push_back(std::string(CurFlag));
1610   }
1611 
1612   // We want to show cc1-only options only when clang is invoked with -cc1 or
1613   // -Xclang.
1614   if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1615     DisableFlags &= ~options::NoDriverOption;
1616 
1617   const llvm::opt::OptTable &Opts = getOpts();
1618   StringRef Cur;
1619   Cur = Flags.at(Flags.size() - 1);
1620   StringRef Prev;
1621   if (Flags.size() >= 2) {
1622     Prev = Flags.at(Flags.size() - 2);
1623     SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1624   }
1625 
1626   if (SuggestedCompletions.empty())
1627     SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1628 
1629   // If Flags were empty, it means the user typed `clang [tab]` where we should
1630   // list all possible flags. If there was no value completion and the user
1631   // pressed tab after a space, we should fall back to a file completion.
1632   // We're printing a newline to be consistent with what we print at the end of
1633   // this function.
1634   if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1635     llvm::outs() << '\n';
1636     return;
1637   }
1638 
1639   // When flag ends with '=' and there was no value completion, return empty
1640   // string and fall back to the file autocompletion.
1641   if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1642     // If the flag is in the form of "--autocomplete=-foo",
1643     // we were requested to print out all option names that start with "-foo".
1644     // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1645     SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1646 
1647     // We have to query the -W flags manually as they're not in the OptTable.
1648     // TODO: Find a good way to add them to OptTable instead and them remove
1649     // this code.
1650     for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1651       if (S.startswith(Cur))
1652         SuggestedCompletions.push_back(std::string(S));
1653   }
1654 
1655   // Sort the autocomplete candidates so that shells print them out in a
1656   // deterministic order. We could sort in any way, but we chose
1657   // case-insensitive sorting for consistency with the -help option
1658   // which prints out options in the case-insensitive alphabetical order.
1659   llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1660     if (int X = A.compare_lower(B))
1661       return X < 0;
1662     return A.compare(B) > 0;
1663   });
1664 
1665   llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1666 }
1667 
1668 bool Driver::HandleImmediateArgs(const Compilation &C) {
1669   // The order these options are handled in gcc is all over the place, but we
1670   // don't expect inconsistencies w.r.t. that to matter in practice.
1671 
1672   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1673     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1674     return false;
1675   }
1676 
1677   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1678     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1679     // return an answer which matches our definition of __VERSION__.
1680     llvm::outs() << CLANG_VERSION_STRING << "\n";
1681     return false;
1682   }
1683 
1684   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1685     PrintDiagnosticCategories(llvm::outs());
1686     return false;
1687   }
1688 
1689   if (C.getArgs().hasArg(options::OPT_help) ||
1690       C.getArgs().hasArg(options::OPT__help_hidden)) {
1691     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1692     return false;
1693   }
1694 
1695   if (C.getArgs().hasArg(options::OPT__version)) {
1696     // Follow gcc behavior and use stdout for --version and stderr for -v.
1697     PrintVersion(C, llvm::outs());
1698     return false;
1699   }
1700 
1701   if (C.getArgs().hasArg(options::OPT_v) ||
1702       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
1703       C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
1704     PrintVersion(C, llvm::errs());
1705     SuppressMissingInputWarning = true;
1706   }
1707 
1708   if (C.getArgs().hasArg(options::OPT_v)) {
1709     if (!SystemConfigDir.empty())
1710       llvm::errs() << "System configuration file directory: "
1711                    << SystemConfigDir << "\n";
1712     if (!UserConfigDir.empty())
1713       llvm::errs() << "User configuration file directory: "
1714                    << UserConfigDir << "\n";
1715   }
1716 
1717   const ToolChain &TC = C.getDefaultToolChain();
1718 
1719   if (C.getArgs().hasArg(options::OPT_v))
1720     TC.printVerboseInfo(llvm::errs());
1721 
1722   if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1723     llvm::outs() << ResourceDir << '\n';
1724     return false;
1725   }
1726 
1727   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1728     llvm::outs() << "programs: =";
1729     bool separator = false;
1730     for (const std::string &Path : TC.getProgramPaths()) {
1731       if (separator)
1732         llvm::outs() << llvm::sys::EnvPathSeparator;
1733       llvm::outs() << Path;
1734       separator = true;
1735     }
1736     llvm::outs() << "\n";
1737     llvm::outs() << "libraries: =" << ResourceDir;
1738 
1739     StringRef sysroot = C.getSysRoot();
1740 
1741     for (const std::string &Path : TC.getFilePaths()) {
1742       // Always print a separator. ResourceDir was the first item shown.
1743       llvm::outs() << llvm::sys::EnvPathSeparator;
1744       // Interpretation of leading '=' is needed only for NetBSD.
1745       if (Path[0] == '=')
1746         llvm::outs() << sysroot << Path.substr(1);
1747       else
1748         llvm::outs() << Path;
1749     }
1750     llvm::outs() << "\n";
1751     return false;
1752   }
1753 
1754   // FIXME: The following handlers should use a callback mechanism, we don't
1755   // know what the client would like to do.
1756   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1757     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1758     return false;
1759   }
1760 
1761   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1762     StringRef ProgName = A->getValue();
1763 
1764     // Null program name cannot have a path.
1765     if (! ProgName.empty())
1766       llvm::outs() << GetProgramPath(ProgName, TC);
1767 
1768     llvm::outs() << "\n";
1769     return false;
1770   }
1771 
1772   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1773     StringRef PassedFlags = A->getValue();
1774     HandleAutocompletions(PassedFlags);
1775     return false;
1776   }
1777 
1778   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1779     ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1780     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1781     RegisterEffectiveTriple TripleRAII(TC, Triple);
1782     switch (RLT) {
1783     case ToolChain::RLT_CompilerRT:
1784       llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1785       break;
1786     case ToolChain::RLT_Libgcc:
1787       llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1788       break;
1789     }
1790     return false;
1791   }
1792 
1793   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1794     for (const Multilib &Multilib : TC.getMultilibs())
1795       llvm::outs() << Multilib << "\n";
1796     return false;
1797   }
1798 
1799   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1800     const Multilib &Multilib = TC.getMultilib();
1801     if (Multilib.gccSuffix().empty())
1802       llvm::outs() << ".\n";
1803     else {
1804       StringRef Suffix(Multilib.gccSuffix());
1805       assert(Suffix.front() == '/');
1806       llvm::outs() << Suffix.substr(1) << "\n";
1807     }
1808     return false;
1809   }
1810 
1811   if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1812     llvm::outs() << TC.getTripleString() << "\n";
1813     return false;
1814   }
1815 
1816   if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1817     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1818     llvm::outs() << Triple.getTriple() << "\n";
1819     return false;
1820   }
1821 
1822   if (C.getArgs().hasArg(options::OPT_print_targets)) {
1823     llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
1824     return false;
1825   }
1826 
1827   return true;
1828 }
1829 
1830 enum {
1831   TopLevelAction = 0,
1832   HeadSibAction = 1,
1833   OtherSibAction = 2,
1834 };
1835 
1836 // Display an action graph human-readably.  Action A is the "sink" node
1837 // and latest-occuring action. Traversal is in pre-order, visiting the
1838 // inputs to each action before printing the action itself.
1839 static unsigned PrintActions1(const Compilation &C, Action *A,
1840                               std::map<Action *, unsigned> &Ids,
1841                               Twine Indent = {}, int Kind = TopLevelAction) {
1842   if (Ids.count(A)) // A was already visited.
1843     return Ids[A];
1844 
1845   std::string str;
1846   llvm::raw_string_ostream os(str);
1847 
1848   auto getSibIndent = [](int K) -> Twine {
1849     return (K == HeadSibAction) ? "   " : (K == OtherSibAction) ? "|  " : "";
1850   };
1851 
1852   Twine SibIndent = Indent + getSibIndent(Kind);
1853   int SibKind = HeadSibAction;
1854   os << Action::getClassName(A->getKind()) << ", ";
1855   if (InputAction *IA = dyn_cast<InputAction>(A)) {
1856     os << "\"" << IA->getInputArg().getValue() << "\"";
1857   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1858     os << '"' << BIA->getArchName() << '"' << ", {"
1859        << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
1860   } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1861     bool IsFirst = true;
1862     OA->doOnEachDependence(
1863         [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1864           assert(TC && "Unknown host toolchain");
1865           // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1866           // sm_35 this will generate:
1867           // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1868           // (nvptx64-nvidia-cuda:sm_35) {#ID}
1869           if (!IsFirst)
1870             os << ", ";
1871           os << '"';
1872           os << A->getOffloadingKindPrefix();
1873           os << " (";
1874           os << TC->getTriple().normalize();
1875           if (BoundArch)
1876             os << ":" << BoundArch;
1877           os << ")";
1878           os << '"';
1879           os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
1880           IsFirst = false;
1881           SibKind = OtherSibAction;
1882         });
1883   } else {
1884     const ActionList *AL = &A->getInputs();
1885 
1886     if (AL->size()) {
1887       const char *Prefix = "{";
1888       for (Action *PreRequisite : *AL) {
1889         os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
1890         Prefix = ", ";
1891         SibKind = OtherSibAction;
1892       }
1893       os << "}";
1894     } else
1895       os << "{}";
1896   }
1897 
1898   // Append offload info for all options other than the offloading action
1899   // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1900   std::string offload_str;
1901   llvm::raw_string_ostream offload_os(offload_str);
1902   if (!isa<OffloadAction>(A)) {
1903     auto S = A->getOffloadingKindPrefix();
1904     if (!S.empty()) {
1905       offload_os << ", (" << S;
1906       if (A->getOffloadingArch())
1907         offload_os << ", " << A->getOffloadingArch();
1908       offload_os << ")";
1909     }
1910   }
1911 
1912   auto getSelfIndent = [](int K) -> Twine {
1913     return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
1914   };
1915 
1916   unsigned Id = Ids.size();
1917   Ids[A] = Id;
1918   llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
1919                << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1920 
1921   return Id;
1922 }
1923 
1924 // Print the action graphs in a compilation C.
1925 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1926 void Driver::PrintActions(const Compilation &C) const {
1927   std::map<Action *, unsigned> Ids;
1928   for (Action *A : C.getActions())
1929     PrintActions1(C, A, Ids);
1930 }
1931 
1932 /// Check whether the given input tree contains any compilation or
1933 /// assembly actions.
1934 static bool ContainsCompileOrAssembleAction(const Action *A) {
1935   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1936       isa<AssembleJobAction>(A))
1937     return true;
1938 
1939   for (const Action *Input : A->inputs())
1940     if (ContainsCompileOrAssembleAction(Input))
1941       return true;
1942 
1943   return false;
1944 }
1945 
1946 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1947                                    const InputList &BAInputs) const {
1948   DerivedArgList &Args = C.getArgs();
1949   ActionList &Actions = C.getActions();
1950   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1951   // Collect the list of architectures. Duplicates are allowed, but should only
1952   // be handled once (in the order seen).
1953   llvm::StringSet<> ArchNames;
1954   SmallVector<const char *, 4> Archs;
1955   for (Arg *A : Args) {
1956     if (A->getOption().matches(options::OPT_arch)) {
1957       // Validate the option here; we don't save the type here because its
1958       // particular spelling may participate in other driver choices.
1959       llvm::Triple::ArchType Arch =
1960           tools::darwin::getArchTypeForMachOArchName(A->getValue());
1961       if (Arch == llvm::Triple::UnknownArch) {
1962         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1963         continue;
1964       }
1965 
1966       A->claim();
1967       if (ArchNames.insert(A->getValue()).second)
1968         Archs.push_back(A->getValue());
1969     }
1970   }
1971 
1972   // When there is no explicit arch for this platform, make sure we still bind
1973   // the architecture (to the default) so that -Xarch_ is handled correctly.
1974   if (!Archs.size())
1975     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1976 
1977   ActionList SingleActions;
1978   BuildActions(C, Args, BAInputs, SingleActions);
1979 
1980   // Add in arch bindings for every top level action, as well as lipo and
1981   // dsymutil steps if needed.
1982   for (Action* Act : SingleActions) {
1983     // Make sure we can lipo this kind of output. If not (and it is an actual
1984     // output) then we disallow, since we can't create an output file with the
1985     // right name without overwriting it. We could remove this oddity by just
1986     // changing the output names to include the arch, which would also fix
1987     // -save-temps. Compatibility wins for now.
1988 
1989     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1990       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1991           << types::getTypeName(Act->getType());
1992 
1993     ActionList Inputs;
1994     for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1995       Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1996 
1997     // Lipo if necessary, we do it this way because we need to set the arch flag
1998     // so that -Xarch_ gets overwritten.
1999     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2000       Actions.append(Inputs.begin(), Inputs.end());
2001     else
2002       Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2003 
2004     // Handle debug info queries.
2005     Arg *A = Args.getLastArg(options::OPT_g_Group);
2006     bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2007                             !A->getOption().matches(options::OPT_gstabs);
2008     if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2009         ContainsCompileOrAssembleAction(Actions.back())) {
2010 
2011       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2012       // have a compile input. We need to run 'dsymutil' ourselves in such cases
2013       // because the debug info will refer to a temporary object file which
2014       // will be removed at the end of the compilation process.
2015       if (Act->getType() == types::TY_Image) {
2016         ActionList Inputs;
2017         Inputs.push_back(Actions.back());
2018         Actions.pop_back();
2019         Actions.push_back(
2020             C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2021       }
2022 
2023       // Verify the debug info output.
2024       if (Args.hasArg(options::OPT_verify_debug_info)) {
2025         Action* LastAction = Actions.back();
2026         Actions.pop_back();
2027         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2028             LastAction, types::TY_Nothing));
2029       }
2030     }
2031   }
2032 }
2033 
2034 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2035                                     types::ID Ty, bool TypoCorrect) const {
2036   if (!getCheckInputsExist())
2037     return true;
2038 
2039   // stdin always exists.
2040   if (Value == "-")
2041     return true;
2042 
2043   if (getVFS().exists(Value))
2044     return true;
2045 
2046   if (IsCLMode()) {
2047     if (!llvm::sys::path::is_absolute(Twine(Value)) &&
2048         llvm::sys::Process::FindInEnvPath("LIB", Value))
2049       return true;
2050 
2051     if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2052       // Arguments to the /link flag might cause the linker to search for object
2053       // and library files in paths we don't know about. Don't error in such
2054       // cases.
2055       return true;
2056     }
2057   }
2058 
2059   if (TypoCorrect) {
2060     // Check if the filename is a typo for an option flag. OptTable thinks
2061     // that all args that are not known options and that start with / are
2062     // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2063     // the option `/diagnostics:caret` than a reference to a file in the root
2064     // directory.
2065     unsigned IncludedFlagsBitmask;
2066     unsigned ExcludedFlagsBitmask;
2067     std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2068         getIncludeExcludeOptionFlagMasks(IsCLMode());
2069     std::string Nearest;
2070     if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2071                               ExcludedFlagsBitmask) <= 1) {
2072       Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2073           << Value << Nearest;
2074       return false;
2075     }
2076   }
2077 
2078   Diag(clang::diag::err_drv_no_such_file) << Value;
2079   return false;
2080 }
2081 
2082 // Construct a the list of inputs and their types.
2083 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2084                          InputList &Inputs) const {
2085   const llvm::opt::OptTable &Opts = getOpts();
2086   // Track the current user specified (-x) input. We also explicitly track the
2087   // argument used to set the type; we only want to claim the type when we
2088   // actually use it, so we warn about unused -x arguments.
2089   types::ID InputType = types::TY_Nothing;
2090   Arg *InputTypeArg = nullptr;
2091 
2092   // The last /TC or /TP option sets the input type to C or C++ globally.
2093   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2094                                          options::OPT__SLASH_TP)) {
2095     InputTypeArg = TCTP;
2096     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2097                     ? types::TY_C
2098                     : types::TY_CXX;
2099 
2100     Arg *Previous = nullptr;
2101     bool ShowNote = false;
2102     for (Arg *A :
2103          Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2104       if (Previous) {
2105         Diag(clang::diag::warn_drv_overriding_flag_option)
2106           << Previous->getSpelling() << A->getSpelling();
2107         ShowNote = true;
2108       }
2109       Previous = A;
2110     }
2111     if (ShowNote)
2112       Diag(clang::diag::note_drv_t_option_is_global);
2113 
2114     // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2115     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2116   }
2117 
2118   for (Arg *A : Args) {
2119     if (A->getOption().getKind() == Option::InputClass) {
2120       const char *Value = A->getValue();
2121       types::ID Ty = types::TY_INVALID;
2122 
2123       // Infer the input type if necessary.
2124       if (InputType == types::TY_Nothing) {
2125         // If there was an explicit arg for this, claim it.
2126         if (InputTypeArg)
2127           InputTypeArg->claim();
2128 
2129         // stdin must be handled specially.
2130         if (memcmp(Value, "-", 2) == 0) {
2131           // If running with -E, treat as a C input (this changes the builtin
2132           // macros, for example). This may be overridden by -ObjC below.
2133           //
2134           // Otherwise emit an error but still use a valid type to avoid
2135           // spurious errors (e.g., no inputs).
2136           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2137             Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2138                             : clang::diag::err_drv_unknown_stdin_type);
2139           Ty = types::TY_C;
2140         } else {
2141           // Otherwise lookup by extension.
2142           // Fallback is C if invoked as C preprocessor, C++ if invoked with
2143           // clang-cl /E, or Object otherwise.
2144           // We use a host hook here because Darwin at least has its own
2145           // idea of what .s is.
2146           if (const char *Ext = strrchr(Value, '.'))
2147             Ty = TC.LookupTypeForExtension(Ext + 1);
2148 
2149           if (Ty == types::TY_INVALID) {
2150             if (CCCIsCPP())
2151               Ty = types::TY_C;
2152             else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2153               Ty = types::TY_CXX;
2154             else
2155               Ty = types::TY_Object;
2156           }
2157 
2158           // If the driver is invoked as C++ compiler (like clang++ or c++) it
2159           // should autodetect some input files as C++ for g++ compatibility.
2160           if (CCCIsCXX()) {
2161             types::ID OldTy = Ty;
2162             Ty = types::lookupCXXTypeForCType(Ty);
2163 
2164             if (Ty != OldTy)
2165               Diag(clang::diag::warn_drv_treating_input_as_cxx)
2166                   << getTypeName(OldTy) << getTypeName(Ty);
2167           }
2168 
2169           // If running with -fthinlto-index=, extensions that normally identify
2170           // native object files actually identify LLVM bitcode files.
2171           if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2172               Ty == types::TY_Object)
2173             Ty = types::TY_LLVM_BC;
2174         }
2175 
2176         // -ObjC and -ObjC++ override the default language, but only for "source
2177         // files". We just treat everything that isn't a linker input as a
2178         // source file.
2179         //
2180         // FIXME: Clean this up if we move the phase sequence into the type.
2181         if (Ty != types::TY_Object) {
2182           if (Args.hasArg(options::OPT_ObjC))
2183             Ty = types::TY_ObjC;
2184           else if (Args.hasArg(options::OPT_ObjCXX))
2185             Ty = types::TY_ObjCXX;
2186         }
2187       } else {
2188         assert(InputTypeArg && "InputType set w/o InputTypeArg");
2189         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2190           // If emulating cl.exe, make sure that /TC and /TP don't affect input
2191           // object files.
2192           const char *Ext = strrchr(Value, '.');
2193           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2194             Ty = types::TY_Object;
2195         }
2196         if (Ty == types::TY_INVALID) {
2197           Ty = InputType;
2198           InputTypeArg->claim();
2199         }
2200       }
2201 
2202       if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2203         Inputs.push_back(std::make_pair(Ty, A));
2204 
2205     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2206       StringRef Value = A->getValue();
2207       if (DiagnoseInputExistence(Args, Value, types::TY_C,
2208                                  /*TypoCorrect=*/false)) {
2209         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2210         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2211       }
2212       A->claim();
2213     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2214       StringRef Value = A->getValue();
2215       if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2216                                  /*TypoCorrect=*/false)) {
2217         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2218         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2219       }
2220       A->claim();
2221     } else if (A->getOption().hasFlag(options::LinkerInput)) {
2222       // Just treat as object type, we could make a special type for this if
2223       // necessary.
2224       Inputs.push_back(std::make_pair(types::TY_Object, A));
2225 
2226     } else if (A->getOption().matches(options::OPT_x)) {
2227       InputTypeArg = A;
2228       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2229       A->claim();
2230 
2231       // Follow gcc behavior and treat as linker input for invalid -x
2232       // options. Its not clear why we shouldn't just revert to unknown; but
2233       // this isn't very important, we might as well be bug compatible.
2234       if (!InputType) {
2235         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2236         InputType = types::TY_Object;
2237       }
2238     } else if (A->getOption().getID() == options::OPT_U) {
2239       assert(A->getNumValues() == 1 && "The /U option has one value.");
2240       StringRef Val = A->getValue(0);
2241       if (Val.find_first_of("/\\") != StringRef::npos) {
2242         // Warn about e.g. "/Users/me/myfile.c".
2243         Diag(diag::warn_slash_u_filename) << Val;
2244         Diag(diag::note_use_dashdash);
2245       }
2246     }
2247   }
2248   if (CCCIsCPP() && Inputs.empty()) {
2249     // If called as standalone preprocessor, stdin is processed
2250     // if no other input is present.
2251     Arg *A = MakeInputArg(Args, Opts, "-");
2252     Inputs.push_back(std::make_pair(types::TY_C, A));
2253   }
2254 }
2255 
2256 namespace {
2257 /// Provides a convenient interface for different programming models to generate
2258 /// the required device actions.
2259 class OffloadingActionBuilder final {
2260   /// Flag used to trace errors in the builder.
2261   bool IsValid = false;
2262 
2263   /// The compilation that is using this builder.
2264   Compilation &C;
2265 
2266   /// Map between an input argument and the offload kinds used to process it.
2267   std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2268 
2269   /// Builder interface. It doesn't build anything or keep any state.
2270   class DeviceActionBuilder {
2271   public:
2272     typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2273 
2274     enum ActionBuilderReturnCode {
2275       // The builder acted successfully on the current action.
2276       ABRT_Success,
2277       // The builder didn't have to act on the current action.
2278       ABRT_Inactive,
2279       // The builder was successful and requested the host action to not be
2280       // generated.
2281       ABRT_Ignore_Host,
2282     };
2283 
2284   protected:
2285     /// Compilation associated with this builder.
2286     Compilation &C;
2287 
2288     /// Tool chains associated with this builder. The same programming
2289     /// model may have associated one or more tool chains.
2290     SmallVector<const ToolChain *, 2> ToolChains;
2291 
2292     /// The derived arguments associated with this builder.
2293     DerivedArgList &Args;
2294 
2295     /// The inputs associated with this builder.
2296     const Driver::InputList &Inputs;
2297 
2298     /// The associated offload kind.
2299     Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2300 
2301   public:
2302     DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2303                         const Driver::InputList &Inputs,
2304                         Action::OffloadKind AssociatedOffloadKind)
2305         : C(C), Args(Args), Inputs(Inputs),
2306           AssociatedOffloadKind(AssociatedOffloadKind) {}
2307     virtual ~DeviceActionBuilder() {}
2308 
2309     /// Fill up the array \a DA with all the device dependences that should be
2310     /// added to the provided host action \a HostAction. By default it is
2311     /// inactive.
2312     virtual ActionBuilderReturnCode
2313     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2314                          phases::ID CurPhase, phases::ID FinalPhase,
2315                          PhasesTy &Phases) {
2316       return ABRT_Inactive;
2317     }
2318 
2319     /// Update the state to include the provided host action \a HostAction as a
2320     /// dependency of the current device action. By default it is inactive.
2321     virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2322       return ABRT_Inactive;
2323     }
2324 
2325     /// Append top level actions generated by the builder.
2326     virtual void appendTopLevelActions(ActionList &AL) {}
2327 
2328     /// Append linker device actions generated by the builder.
2329     virtual void appendLinkDeviceActions(ActionList &AL) {}
2330 
2331     /// Append linker host action generated by the builder.
2332     virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2333 
2334     /// Append linker actions generated by the builder.
2335     virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2336 
2337     /// Initialize the builder. Return true if any initialization errors are
2338     /// found.
2339     virtual bool initialize() { return false; }
2340 
2341     /// Return true if the builder can use bundling/unbundling.
2342     virtual bool canUseBundlerUnbundler() const { return false; }
2343 
2344     /// Return true if this builder is valid. We have a valid builder if we have
2345     /// associated device tool chains.
2346     bool isValid() { return !ToolChains.empty(); }
2347 
2348     /// Return the associated offload kind.
2349     Action::OffloadKind getAssociatedOffloadKind() {
2350       return AssociatedOffloadKind;
2351     }
2352   };
2353 
2354   /// Base class for CUDA/HIP action builder. It injects device code in
2355   /// the host backend action.
2356   class CudaActionBuilderBase : public DeviceActionBuilder {
2357   protected:
2358     /// Flags to signal if the user requested host-only or device-only
2359     /// compilation.
2360     bool CompileHostOnly = false;
2361     bool CompileDeviceOnly = false;
2362     bool EmitLLVM = false;
2363     bool EmitAsm = false;
2364 
2365     /// List of GPU architectures to use in this compilation.
2366     SmallVector<CudaArch, 4> GpuArchList;
2367 
2368     /// The CUDA actions for the current input.
2369     ActionList CudaDeviceActions;
2370 
2371     /// The CUDA fat binary if it was generated for the current input.
2372     Action *CudaFatBinary = nullptr;
2373 
2374     /// Flag that is set to true if this builder acted on the current input.
2375     bool IsActive = false;
2376 
2377     /// Flag for -fgpu-rdc.
2378     bool Relocatable = false;
2379 
2380     /// Default GPU architecture if there's no one specified.
2381     CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2382 
2383   public:
2384     CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2385                           const Driver::InputList &Inputs,
2386                           Action::OffloadKind OFKind)
2387         : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2388 
2389     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2390       // While generating code for CUDA, we only depend on the host input action
2391       // to trigger the creation of all the CUDA device actions.
2392 
2393       // If we are dealing with an input action, replicate it for each GPU
2394       // architecture. If we are in host-only mode we return 'success' so that
2395       // the host uses the CUDA offload kind.
2396       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2397         assert(!GpuArchList.empty() &&
2398                "We should have at least one GPU architecture.");
2399 
2400         // If the host input is not CUDA or HIP, we don't need to bother about
2401         // this input.
2402         if (IA->getType() != types::TY_CUDA &&
2403             IA->getType() != types::TY_HIP) {
2404           // The builder will ignore this input.
2405           IsActive = false;
2406           return ABRT_Inactive;
2407         }
2408 
2409         // Set the flag to true, so that the builder acts on the current input.
2410         IsActive = true;
2411 
2412         if (CompileHostOnly)
2413           return ABRT_Success;
2414 
2415         // Replicate inputs for each GPU architecture.
2416         auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2417                                                  : types::TY_CUDA_DEVICE;
2418         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2419           CudaDeviceActions.push_back(
2420               C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2421         }
2422 
2423         return ABRT_Success;
2424       }
2425 
2426       // If this is an unbundling action use it as is for each CUDA toolchain.
2427       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2428 
2429         // If -fgpu-rdc is disabled, should not unbundle since there is no
2430         // device code to link.
2431         if (!Relocatable)
2432           return ABRT_Inactive;
2433 
2434         CudaDeviceActions.clear();
2435         auto *IA = cast<InputAction>(UA->getInputs().back());
2436         std::string FileName = IA->getInputArg().getAsString(Args);
2437         // Check if the type of the file is the same as the action. Do not
2438         // unbundle it if it is not. Do not unbundle .so files, for example,
2439         // which are not object files.
2440         if (IA->getType() == types::TY_Object &&
2441             (!llvm::sys::path::has_extension(FileName) ||
2442              types::lookupTypeForExtension(
2443                  llvm::sys::path::extension(FileName).drop_front()) !=
2444                  types::TY_Object))
2445           return ABRT_Inactive;
2446 
2447         for (auto Arch : GpuArchList) {
2448           CudaDeviceActions.push_back(UA);
2449           UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2450                                           AssociatedOffloadKind);
2451         }
2452         return ABRT_Success;
2453       }
2454 
2455       return IsActive ? ABRT_Success : ABRT_Inactive;
2456     }
2457 
2458     void appendTopLevelActions(ActionList &AL) override {
2459       // Utility to append actions to the top level list.
2460       auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2461         OffloadAction::DeviceDependences Dep;
2462         Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2463                 AssociatedOffloadKind);
2464         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2465       };
2466 
2467       // If we have a fat binary, add it to the list.
2468       if (CudaFatBinary) {
2469         AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2470         CudaDeviceActions.clear();
2471         CudaFatBinary = nullptr;
2472         return;
2473       }
2474 
2475       if (CudaDeviceActions.empty())
2476         return;
2477 
2478       // If we have CUDA actions at this point, that's because we have a have
2479       // partial compilation, so we should have an action for each GPU
2480       // architecture.
2481       assert(CudaDeviceActions.size() == GpuArchList.size() &&
2482              "Expecting one action per GPU architecture.");
2483       assert(ToolChains.size() == 1 &&
2484              "Expecting to have a sing CUDA toolchain.");
2485       for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2486         AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2487 
2488       CudaDeviceActions.clear();
2489     }
2490 
2491     bool initialize() override {
2492       assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2493              AssociatedOffloadKind == Action::OFK_HIP);
2494 
2495       // We don't need to support CUDA.
2496       if (AssociatedOffloadKind == Action::OFK_Cuda &&
2497           !C.hasOffloadToolChain<Action::OFK_Cuda>())
2498         return false;
2499 
2500       // We don't need to support HIP.
2501       if (AssociatedOffloadKind == Action::OFK_HIP &&
2502           !C.hasOffloadToolChain<Action::OFK_HIP>())
2503         return false;
2504 
2505       Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2506           options::OPT_fno_gpu_rdc, /*Default=*/false);
2507 
2508       const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2509       assert(HostTC && "No toolchain for host compilation.");
2510       if (HostTC->getTriple().isNVPTX() ||
2511           HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2512         // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2513         // an error and abort pipeline construction early so we don't trip
2514         // asserts that assume device-side compilation.
2515         C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2516             << HostTC->getTriple().getArchName();
2517         return true;
2518       }
2519 
2520       ToolChains.push_back(
2521           AssociatedOffloadKind == Action::OFK_Cuda
2522               ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2523               : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2524 
2525       Arg *PartialCompilationArg = Args.getLastArg(
2526           options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2527           options::OPT_cuda_compile_host_device);
2528       CompileHostOnly = PartialCompilationArg &&
2529                         PartialCompilationArg->getOption().matches(
2530                             options::OPT_cuda_host_only);
2531       CompileDeviceOnly = PartialCompilationArg &&
2532                           PartialCompilationArg->getOption().matches(
2533                               options::OPT_cuda_device_only);
2534       EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
2535       EmitAsm = Args.getLastArg(options::OPT_S);
2536 
2537       // Collect all cuda_gpu_arch parameters, removing duplicates.
2538       std::set<CudaArch> GpuArchs;
2539       bool Error = false;
2540       for (Arg *A : Args) {
2541         if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
2542               A->getOption().matches(options::OPT_no_offload_arch_EQ)))
2543           continue;
2544         A->claim();
2545 
2546         const StringRef ArchStr = A->getValue();
2547         if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
2548             ArchStr == "all") {
2549           GpuArchs.clear();
2550           continue;
2551         }
2552         CudaArch Arch = StringToCudaArch(ArchStr);
2553         if (Arch == CudaArch::UNKNOWN) {
2554           C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2555           Error = true;
2556         } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
2557           GpuArchs.insert(Arch);
2558         else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
2559           GpuArchs.erase(Arch);
2560         else
2561           llvm_unreachable("Unexpected option.");
2562       }
2563 
2564       // Collect list of GPUs remaining in the set.
2565       for (CudaArch Arch : GpuArchs)
2566         GpuArchList.push_back(Arch);
2567 
2568       // Default to sm_20 which is the lowest common denominator for
2569       // supported GPUs.  sm_20 code should work correctly, if
2570       // suboptimally, on all newer GPUs.
2571       if (GpuArchList.empty())
2572         GpuArchList.push_back(DefaultCudaArch);
2573 
2574       return Error;
2575     }
2576   };
2577 
2578   /// \brief CUDA action builder. It injects device code in the host backend
2579   /// action.
2580   class CudaActionBuilder final : public CudaActionBuilderBase {
2581   public:
2582     CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2583                       const Driver::InputList &Inputs)
2584         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
2585       DefaultCudaArch = CudaArch::SM_20;
2586     }
2587 
2588     ActionBuilderReturnCode
2589     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2590                          phases::ID CurPhase, phases::ID FinalPhase,
2591                          PhasesTy &Phases) override {
2592       if (!IsActive)
2593         return ABRT_Inactive;
2594 
2595       // If we don't have more CUDA actions, we don't have any dependences to
2596       // create for the host.
2597       if (CudaDeviceActions.empty())
2598         return ABRT_Success;
2599 
2600       assert(CudaDeviceActions.size() == GpuArchList.size() &&
2601              "Expecting one action per GPU architecture.");
2602       assert(!CompileHostOnly &&
2603              "Not expecting CUDA actions in host-only compilation.");
2604 
2605       // If we are generating code for the device or we are in a backend phase,
2606       // we attempt to generate the fat binary. We compile each arch to ptx and
2607       // assemble to cubin, then feed the cubin *and* the ptx into a device
2608       // "link" action, which uses fatbinary to combine these cubins into one
2609       // fatbin.  The fatbin is then an input to the host action if not in
2610       // device-only mode.
2611       if (CompileDeviceOnly || CurPhase == phases::Backend) {
2612         ActionList DeviceActions;
2613         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2614           // Produce the device action from the current phase up to the assemble
2615           // phase.
2616           for (auto Ph : Phases) {
2617             // Skip the phases that were already dealt with.
2618             if (Ph < CurPhase)
2619               continue;
2620             // We have to be consistent with the host final phase.
2621             if (Ph > FinalPhase)
2622               break;
2623 
2624             CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2625                 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2626 
2627             if (Ph == phases::Assemble)
2628               break;
2629           }
2630 
2631           // If we didn't reach the assemble phase, we can't generate the fat
2632           // binary. We don't need to generate the fat binary if we are not in
2633           // device-only mode.
2634           if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2635               CompileDeviceOnly)
2636             continue;
2637 
2638           Action *AssembleAction = CudaDeviceActions[I];
2639           assert(AssembleAction->getType() == types::TY_Object);
2640           assert(AssembleAction->getInputs().size() == 1);
2641 
2642           Action *BackendAction = AssembleAction->getInputs()[0];
2643           assert(BackendAction->getType() == types::TY_PP_Asm);
2644 
2645           for (auto &A : {AssembleAction, BackendAction}) {
2646             OffloadAction::DeviceDependences DDep;
2647             DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2648                      Action::OFK_Cuda);
2649             DeviceActions.push_back(
2650                 C.MakeAction<OffloadAction>(DDep, A->getType()));
2651           }
2652         }
2653 
2654         // We generate the fat binary if we have device input actions.
2655         if (!DeviceActions.empty()) {
2656           CudaFatBinary =
2657               C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2658 
2659           if (!CompileDeviceOnly) {
2660             DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2661                    Action::OFK_Cuda);
2662             // Clear the fat binary, it is already a dependence to an host
2663             // action.
2664             CudaFatBinary = nullptr;
2665           }
2666 
2667           // Remove the CUDA actions as they are already connected to an host
2668           // action or fat binary.
2669           CudaDeviceActions.clear();
2670         }
2671 
2672         // We avoid creating host action in device-only mode.
2673         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2674       } else if (CurPhase > phases::Backend) {
2675         // If we are past the backend phase and still have a device action, we
2676         // don't have to do anything as this action is already a device
2677         // top-level action.
2678         return ABRT_Success;
2679       }
2680 
2681       assert(CurPhase < phases::Backend && "Generating single CUDA "
2682                                            "instructions should only occur "
2683                                            "before the backend phase!");
2684 
2685       // By default, we produce an action for each device arch.
2686       for (Action *&A : CudaDeviceActions)
2687         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2688 
2689       return ABRT_Success;
2690     }
2691   };
2692   /// \brief HIP action builder. It injects device code in the host backend
2693   /// action.
2694   class HIPActionBuilder final : public CudaActionBuilderBase {
2695     /// The linker inputs obtained for each device arch.
2696     SmallVector<ActionList, 8> DeviceLinkerInputs;
2697 
2698   public:
2699     HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2700                      const Driver::InputList &Inputs)
2701         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
2702       DefaultCudaArch = CudaArch::GFX803;
2703     }
2704 
2705     bool canUseBundlerUnbundler() const override { return true; }
2706 
2707     ActionBuilderReturnCode
2708     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2709                          phases::ID CurPhase, phases::ID FinalPhase,
2710                          PhasesTy &Phases) override {
2711       // amdgcn does not support linking of object files, therefore we skip
2712       // backend and assemble phases to output LLVM IR. Except for generating
2713       // non-relocatable device coee, where we generate fat binary for device
2714       // code and pass to host in Backend phase.
2715       if (CudaDeviceActions.empty())
2716         return ABRT_Success;
2717 
2718       assert(((CurPhase == phases::Link && Relocatable) ||
2719               CudaDeviceActions.size() == GpuArchList.size()) &&
2720              "Expecting one action per GPU architecture.");
2721       assert(!CompileHostOnly &&
2722              "Not expecting CUDA actions in host-only compilation.");
2723 
2724       if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
2725           !EmitAsm) {
2726         // If we are in backend phase, we attempt to generate the fat binary.
2727         // We compile each arch to IR and use a link action to generate code
2728         // object containing ISA. Then we use a special "link" action to create
2729         // a fat binary containing all the code objects for different GPU's.
2730         // The fat binary is then an input to the host action.
2731         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2732           auto BackendAction = C.getDriver().ConstructPhaseAction(
2733               C, Args, phases::Backend, CudaDeviceActions[I],
2734               AssociatedOffloadKind);
2735           auto AssembleAction = C.getDriver().ConstructPhaseAction(
2736               C, Args, phases::Assemble, BackendAction, AssociatedOffloadKind);
2737           // Create a link action to link device IR with device library
2738           // and generate ISA.
2739           ActionList AL;
2740           AL.push_back(AssembleAction);
2741           CudaDeviceActions[I] =
2742               C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2743 
2744           // OffloadingActionBuilder propagates device arch until an offload
2745           // action. Since the next action for creating fatbin does
2746           // not have device arch, whereas the above link action and its input
2747           // have device arch, an offload action is needed to stop the null
2748           // device arch of the next action being propagated to the above link
2749           // action.
2750           OffloadAction::DeviceDependences DDep;
2751           DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2752                    CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2753           CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2754               DDep, CudaDeviceActions[I]->getType());
2755         }
2756         // Create HIP fat binary with a special "link" action.
2757         CudaFatBinary =
2758             C.MakeAction<LinkJobAction>(CudaDeviceActions,
2759                 types::TY_HIP_FATBIN);
2760 
2761         if (!CompileDeviceOnly) {
2762           DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2763                  AssociatedOffloadKind);
2764           // Clear the fat binary, it is already a dependence to an host
2765           // action.
2766           CudaFatBinary = nullptr;
2767         }
2768 
2769         // Remove the CUDA actions as they are already connected to an host
2770         // action or fat binary.
2771         CudaDeviceActions.clear();
2772 
2773         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2774       } else if (CurPhase == phases::Link) {
2775         // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2776         // This happens to each device action originated from each input file.
2777         // Later on, device actions in DeviceLinkerInputs are used to create
2778         // device link actions in appendLinkDependences and the created device
2779         // link actions are passed to the offload action as device dependence.
2780         DeviceLinkerInputs.resize(CudaDeviceActions.size());
2781         auto LI = DeviceLinkerInputs.begin();
2782         for (auto *A : CudaDeviceActions) {
2783           LI->push_back(A);
2784           ++LI;
2785         }
2786 
2787         // We will pass the device action as a host dependence, so we don't
2788         // need to do anything else with them.
2789         CudaDeviceActions.clear();
2790         return ABRT_Success;
2791       }
2792 
2793       // By default, we produce an action for each device arch.
2794       for (Action *&A : CudaDeviceActions)
2795         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2796                                                AssociatedOffloadKind);
2797 
2798       return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
2799                                                            : ABRT_Success;
2800     }
2801 
2802     void appendLinkDeviceActions(ActionList &AL) override {
2803       if (DeviceLinkerInputs.size() == 0)
2804         return;
2805 
2806       assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
2807              "Linker inputs and GPU arch list sizes do not match.");
2808 
2809       // Append a new link action for each device.
2810       unsigned I = 0;
2811       for (auto &LI : DeviceLinkerInputs) {
2812         // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
2813         auto *DeviceLinkAction =
2814             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2815         // Linking all inputs for the current GPU arch.
2816         // LI contains all the inputs for the linker.
2817         OffloadAction::DeviceDependences DeviceLinkDeps;
2818         DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
2819             CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2820         AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2821             DeviceLinkAction->getType()));
2822         ++I;
2823       }
2824       DeviceLinkerInputs.clear();
2825 
2826       // Create a host object from all the device images by embedding them
2827       // in a fat binary.
2828       OffloadAction::DeviceDependences DDeps;
2829       auto *TopDeviceLinkAction =
2830           C.MakeAction<LinkJobAction>(AL, types::TY_Object);
2831       DDeps.add(*TopDeviceLinkAction, *ToolChains[0],
2832           nullptr, AssociatedOffloadKind);
2833 
2834       // Offload the host object to the host linker.
2835       AL.push_back(C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
2836     }
2837 
2838     Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
2839 
2840     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2841   };
2842 
2843   /// OpenMP action builder. The host bitcode is passed to the device frontend
2844   /// and all the device linked images are passed to the host link phase.
2845   class OpenMPActionBuilder final : public DeviceActionBuilder {
2846     /// The OpenMP actions for the current input.
2847     ActionList OpenMPDeviceActions;
2848 
2849     /// The linker inputs obtained for each toolchain.
2850     SmallVector<ActionList, 8> DeviceLinkerInputs;
2851 
2852   public:
2853     OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2854                         const Driver::InputList &Inputs)
2855         : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2856 
2857     ActionBuilderReturnCode
2858     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2859                          phases::ID CurPhase, phases::ID FinalPhase,
2860                          PhasesTy &Phases) override {
2861       if (OpenMPDeviceActions.empty())
2862         return ABRT_Inactive;
2863 
2864       // We should always have an action for each input.
2865       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2866              "Number of OpenMP actions and toolchains do not match.");
2867 
2868       // The host only depends on device action in the linking phase, when all
2869       // the device images have to be embedded in the host image.
2870       if (CurPhase == phases::Link) {
2871         assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2872                "Toolchains and linker inputs sizes do not match.");
2873         auto LI = DeviceLinkerInputs.begin();
2874         for (auto *A : OpenMPDeviceActions) {
2875           LI->push_back(A);
2876           ++LI;
2877         }
2878 
2879         // We passed the device action as a host dependence, so we don't need to
2880         // do anything else with them.
2881         OpenMPDeviceActions.clear();
2882         return ABRT_Success;
2883       }
2884 
2885       // By default, we produce an action for each device arch.
2886       for (Action *&A : OpenMPDeviceActions)
2887         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2888 
2889       return ABRT_Success;
2890     }
2891 
2892     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2893 
2894       // If this is an input action replicate it for each OpenMP toolchain.
2895       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2896         OpenMPDeviceActions.clear();
2897         for (unsigned I = 0; I < ToolChains.size(); ++I)
2898           OpenMPDeviceActions.push_back(
2899               C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2900         return ABRT_Success;
2901       }
2902 
2903       // If this is an unbundling action use it as is for each OpenMP toolchain.
2904       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2905         OpenMPDeviceActions.clear();
2906         auto *IA = cast<InputAction>(UA->getInputs().back());
2907         std::string FileName = IA->getInputArg().getAsString(Args);
2908         // Check if the type of the file is the same as the action. Do not
2909         // unbundle it if it is not. Do not unbundle .so files, for example,
2910         // which are not object files.
2911         if (IA->getType() == types::TY_Object &&
2912             (!llvm::sys::path::has_extension(FileName) ||
2913              types::lookupTypeForExtension(
2914                  llvm::sys::path::extension(FileName).drop_front()) !=
2915                  types::TY_Object))
2916           return ABRT_Inactive;
2917         for (unsigned I = 0; I < ToolChains.size(); ++I) {
2918           OpenMPDeviceActions.push_back(UA);
2919           UA->registerDependentActionInfo(
2920               ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2921         }
2922         return ABRT_Success;
2923       }
2924 
2925       // When generating code for OpenMP we use the host compile phase result as
2926       // a dependence to the device compile phase so that it can learn what
2927       // declarations should be emitted. However, this is not the only use for
2928       // the host action, so we prevent it from being collapsed.
2929       if (isa<CompileJobAction>(HostAction)) {
2930         HostAction->setCannotBeCollapsedWithNextDependentAction();
2931         assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2932                "Toolchains and device action sizes do not match.");
2933         OffloadAction::HostDependence HDep(
2934             *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2935             /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2936         auto TC = ToolChains.begin();
2937         for (Action *&A : OpenMPDeviceActions) {
2938           assert(isa<CompileJobAction>(A));
2939           OffloadAction::DeviceDependences DDep;
2940           DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2941           A = C.MakeAction<OffloadAction>(HDep, DDep);
2942           ++TC;
2943         }
2944       }
2945       return ABRT_Success;
2946     }
2947 
2948     void appendTopLevelActions(ActionList &AL) override {
2949       if (OpenMPDeviceActions.empty())
2950         return;
2951 
2952       // We should always have an action for each input.
2953       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2954              "Number of OpenMP actions and toolchains do not match.");
2955 
2956       // Append all device actions followed by the proper offload action.
2957       auto TI = ToolChains.begin();
2958       for (auto *A : OpenMPDeviceActions) {
2959         OffloadAction::DeviceDependences Dep;
2960         Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2961         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2962         ++TI;
2963       }
2964       // We no longer need the action stored in this builder.
2965       OpenMPDeviceActions.clear();
2966     }
2967 
2968     void appendLinkDeviceActions(ActionList &AL) override {
2969       assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2970              "Toolchains and linker inputs sizes do not match.");
2971 
2972       // Append a new link action for each device.
2973       auto TC = ToolChains.begin();
2974       for (auto &LI : DeviceLinkerInputs) {
2975         auto *DeviceLinkAction =
2976             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2977         OffloadAction::DeviceDependences DeviceLinkDeps;
2978         DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2979 		        Action::OFK_OpenMP);
2980         AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2981             DeviceLinkAction->getType()));
2982         ++TC;
2983       }
2984       DeviceLinkerInputs.clear();
2985     }
2986 
2987     Action* appendLinkHostActions(ActionList &AL) override {
2988       // Create wrapper bitcode from the result of device link actions and compile
2989       // it to an object which will be added to the host link command.
2990       auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC);
2991       auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
2992       return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
2993     }
2994 
2995     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2996 
2997     bool initialize() override {
2998       // Get the OpenMP toolchains. If we don't get any, the action builder will
2999       // know there is nothing to do related to OpenMP offloading.
3000       auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
3001       for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
3002            ++TI)
3003         ToolChains.push_back(TI->second);
3004 
3005       DeviceLinkerInputs.resize(ToolChains.size());
3006       return false;
3007     }
3008 
3009     bool canUseBundlerUnbundler() const override {
3010       // OpenMP should use bundled files whenever possible.
3011       return true;
3012     }
3013   };
3014 
3015   ///
3016   /// TODO: Add the implementation for other specialized builders here.
3017   ///
3018 
3019   /// Specialized builders being used by this offloading action builder.
3020   SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3021 
3022   /// Flag set to true if all valid builders allow file bundling/unbundling.
3023   bool CanUseBundler;
3024 
3025 public:
3026   OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3027                           const Driver::InputList &Inputs)
3028       : C(C) {
3029     // Create a specialized builder for each device toolchain.
3030 
3031     IsValid = true;
3032 
3033     // Create a specialized builder for CUDA.
3034     SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3035 
3036     // Create a specialized builder for HIP.
3037     SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3038 
3039     // Create a specialized builder for OpenMP.
3040     SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
3041 
3042     //
3043     // TODO: Build other specialized builders here.
3044     //
3045 
3046     // Initialize all the builders, keeping track of errors. If all valid
3047     // builders agree that we can use bundling, set the flag to true.
3048     unsigned ValidBuilders = 0u;
3049     unsigned ValidBuildersSupportingBundling = 0u;
3050     for (auto *SB : SpecializedBuilders) {
3051       IsValid = IsValid && !SB->initialize();
3052 
3053       // Update the counters if the builder is valid.
3054       if (SB->isValid()) {
3055         ++ValidBuilders;
3056         if (SB->canUseBundlerUnbundler())
3057           ++ValidBuildersSupportingBundling;
3058       }
3059     }
3060     CanUseBundler =
3061         ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3062   }
3063 
3064   ~OffloadingActionBuilder() {
3065     for (auto *SB : SpecializedBuilders)
3066       delete SB;
3067   }
3068 
3069   /// Generate an action that adds device dependences (if any) to a host action.
3070   /// If no device dependence actions exist, just return the host action \a
3071   /// HostAction. If an error is found or if no builder requires the host action
3072   /// to be generated, return nullptr.
3073   Action *
3074   addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3075                                    phases::ID CurPhase, phases::ID FinalPhase,
3076                                    DeviceActionBuilder::PhasesTy &Phases) {
3077     if (!IsValid)
3078       return nullptr;
3079 
3080     if (SpecializedBuilders.empty())
3081       return HostAction;
3082 
3083     assert(HostAction && "Invalid host action!");
3084 
3085     OffloadAction::DeviceDependences DDeps;
3086     // Check if all the programming models agree we should not emit the host
3087     // action. Also, keep track of the offloading kinds employed.
3088     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3089     unsigned InactiveBuilders = 0u;
3090     unsigned IgnoringBuilders = 0u;
3091     for (auto *SB : SpecializedBuilders) {
3092       if (!SB->isValid()) {
3093         ++InactiveBuilders;
3094         continue;
3095       }
3096 
3097       auto RetCode =
3098           SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3099 
3100       // If the builder explicitly says the host action should be ignored,
3101       // we need to increment the variable that tracks the builders that request
3102       // the host object to be ignored.
3103       if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3104         ++IgnoringBuilders;
3105 
3106       // Unless the builder was inactive for this action, we have to record the
3107       // offload kind because the host will have to use it.
3108       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3109         OffloadKind |= SB->getAssociatedOffloadKind();
3110     }
3111 
3112     // If all builders agree that the host object should be ignored, just return
3113     // nullptr.
3114     if (IgnoringBuilders &&
3115         SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3116       return nullptr;
3117 
3118     if (DDeps.getActions().empty())
3119       return HostAction;
3120 
3121     // We have dependences we need to bundle together. We use an offload action
3122     // for that.
3123     OffloadAction::HostDependence HDep(
3124         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3125         /*BoundArch=*/nullptr, DDeps);
3126     return C.MakeAction<OffloadAction>(HDep, DDeps);
3127   }
3128 
3129   /// Generate an action that adds a host dependence to a device action. The
3130   /// results will be kept in this action builder. Return true if an error was
3131   /// found.
3132   bool addHostDependenceToDeviceActions(Action *&HostAction,
3133                                         const Arg *InputArg) {
3134     if (!IsValid)
3135       return true;
3136 
3137     // If we are supporting bundling/unbundling and the current action is an
3138     // input action of non-source file, we replace the host action by the
3139     // unbundling action. The bundler tool has the logic to detect if an input
3140     // is a bundle or not and if the input is not a bundle it assumes it is a
3141     // host file. Therefore it is safe to create an unbundling action even if
3142     // the input is not a bundle.
3143     if (CanUseBundler && isa<InputAction>(HostAction) &&
3144         InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3145         !types::isSrcFile(HostAction->getType())) {
3146       auto UnbundlingHostAction =
3147           C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3148       UnbundlingHostAction->registerDependentActionInfo(
3149           C.getSingleOffloadToolChain<Action::OFK_Host>(),
3150           /*BoundArch=*/StringRef(), Action::OFK_Host);
3151       HostAction = UnbundlingHostAction;
3152     }
3153 
3154     assert(HostAction && "Invalid host action!");
3155 
3156     // Register the offload kinds that are used.
3157     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3158     for (auto *SB : SpecializedBuilders) {
3159       if (!SB->isValid())
3160         continue;
3161 
3162       auto RetCode = SB->addDeviceDepences(HostAction);
3163 
3164       // Host dependences for device actions are not compatible with that same
3165       // action being ignored.
3166       assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3167              "Host dependence not expected to be ignored.!");
3168 
3169       // Unless the builder was inactive for this action, we have to record the
3170       // offload kind because the host will have to use it.
3171       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3172         OffloadKind |= SB->getAssociatedOffloadKind();
3173     }
3174 
3175     // Do not use unbundler if the Host does not depend on device action.
3176     if (OffloadKind == Action::OFK_None && CanUseBundler)
3177       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3178         HostAction = UA->getInputs().back();
3179 
3180     return false;
3181   }
3182 
3183   /// Add the offloading top level actions to the provided action list. This
3184   /// function can replace the host action by a bundling action if the
3185   /// programming models allow it.
3186   bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3187                              const Arg *InputArg) {
3188     // Get the device actions to be appended.
3189     ActionList OffloadAL;
3190     for (auto *SB : SpecializedBuilders) {
3191       if (!SB->isValid())
3192         continue;
3193       SB->appendTopLevelActions(OffloadAL);
3194     }
3195 
3196     // If we can use the bundler, replace the host action by the bundling one in
3197     // the resulting list. Otherwise, just append the device actions. For
3198     // device only compilation, HostAction is a null pointer, therefore only do
3199     // this when HostAction is not a null pointer.
3200     if (CanUseBundler && HostAction &&
3201         HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3202       // Add the host action to the list in order to create the bundling action.
3203       OffloadAL.push_back(HostAction);
3204 
3205       // We expect that the host action was just appended to the action list
3206       // before this method was called.
3207       assert(HostAction == AL.back() && "Host action not in the list??");
3208       HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3209       AL.back() = HostAction;
3210     } else
3211       AL.append(OffloadAL.begin(), OffloadAL.end());
3212 
3213     // Propagate to the current host action (if any) the offload information
3214     // associated with the current input.
3215     if (HostAction)
3216       HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3217                                            /*BoundArch=*/nullptr);
3218     return false;
3219   }
3220 
3221   Action* makeHostLinkAction() {
3222     // Build a list of device linking actions.
3223     ActionList DeviceAL;
3224     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3225       if (!SB->isValid())
3226         continue;
3227       SB->appendLinkDeviceActions(DeviceAL);
3228     }
3229 
3230     if (DeviceAL.empty())
3231       return nullptr;
3232 
3233     // Let builders add host linking actions.
3234     Action* HA;
3235     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3236       if (!SB->isValid())
3237         continue;
3238       HA = SB->appendLinkHostActions(DeviceAL);
3239     }
3240     return HA;
3241   }
3242 
3243   /// Processes the host linker action. This currently consists of replacing it
3244   /// with an offload action if there are device link objects and propagate to
3245   /// the host action all the offload kinds used in the current compilation. The
3246   /// resulting action is returned.
3247   Action *processHostLinkAction(Action *HostAction) {
3248     // Add all the dependences from the device linking actions.
3249     OffloadAction::DeviceDependences DDeps;
3250     for (auto *SB : SpecializedBuilders) {
3251       if (!SB->isValid())
3252         continue;
3253 
3254       SB->appendLinkDependences(DDeps);
3255     }
3256 
3257     // Calculate all the offload kinds used in the current compilation.
3258     unsigned ActiveOffloadKinds = 0u;
3259     for (auto &I : InputArgToOffloadKindMap)
3260       ActiveOffloadKinds |= I.second;
3261 
3262     // If we don't have device dependencies, we don't have to create an offload
3263     // action.
3264     if (DDeps.getActions().empty()) {
3265       // Propagate all the active kinds to host action. Given that it is a link
3266       // action it is assumed to depend on all actions generated so far.
3267       HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3268                                            /*BoundArch=*/nullptr);
3269       return HostAction;
3270     }
3271 
3272     // Create the offload action with all dependences. When an offload action
3273     // is created the kinds are propagated to the host action, so we don't have
3274     // to do that explicitly here.
3275     OffloadAction::HostDependence HDep(
3276         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3277         /*BoundArch*/ nullptr, ActiveOffloadKinds);
3278     return C.MakeAction<OffloadAction>(HDep, DDeps);
3279   }
3280 };
3281 } // anonymous namespace.
3282 
3283 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3284                              const InputList &Inputs,
3285                              ActionList &Actions) const {
3286 
3287   // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3288   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3289   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3290   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3291     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3292     Args.eraseArg(options::OPT__SLASH_Yc);
3293     Args.eraseArg(options::OPT__SLASH_Yu);
3294     YcArg = YuArg = nullptr;
3295   }
3296   if (YcArg && Inputs.size() > 1) {
3297     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3298     Args.eraseArg(options::OPT__SLASH_Yc);
3299     YcArg = nullptr;
3300   }
3301 
3302   Arg *FinalPhaseArg;
3303   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3304 
3305   if (FinalPhase == phases::Link) {
3306     if (Args.hasArg(options::OPT_emit_llvm))
3307       Diag(clang::diag::err_drv_emit_llvm_link);
3308     if (IsCLMode() && LTOMode != LTOK_None &&
3309         !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3310       Diag(clang::diag::err_drv_lto_without_lld);
3311   }
3312 
3313   if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3314     // If only preprocessing or /Y- is used, all pch handling is disabled.
3315     // Rather than check for it everywhere, just remove clang-cl pch-related
3316     // flags here.
3317     Args.eraseArg(options::OPT__SLASH_Fp);
3318     Args.eraseArg(options::OPT__SLASH_Yc);
3319     Args.eraseArg(options::OPT__SLASH_Yu);
3320     YcArg = YuArg = nullptr;
3321   }
3322 
3323   unsigned LastPLSize = 0;
3324   for (auto &I : Inputs) {
3325     types::ID InputType = I.first;
3326     const Arg *InputArg = I.second;
3327 
3328     auto PL = types::getCompilationPhases(InputType);
3329     LastPLSize = PL.size();
3330 
3331     // If the first step comes after the final phase we are doing as part of
3332     // this compilation, warn the user about it.
3333     phases::ID InitialPhase = PL[0];
3334     if (InitialPhase > FinalPhase) {
3335       if (InputArg->isClaimed())
3336         continue;
3337 
3338       // Claim here to avoid the more general unused warning.
3339       InputArg->claim();
3340 
3341       // Suppress all unused style warnings with -Qunused-arguments
3342       if (Args.hasArg(options::OPT_Qunused_arguments))
3343         continue;
3344 
3345       // Special case when final phase determined by binary name, rather than
3346       // by a command-line argument with a corresponding Arg.
3347       if (CCCIsCPP())
3348         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3349             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3350       // Special case '-E' warning on a previously preprocessed file to make
3351       // more sense.
3352       else if (InitialPhase == phases::Compile &&
3353                (Args.getLastArg(options::OPT__SLASH_EP,
3354                                 options::OPT__SLASH_P) ||
3355                 Args.getLastArg(options::OPT_E) ||
3356                 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3357                getPreprocessedType(InputType) == types::TY_INVALID)
3358         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3359             << InputArg->getAsString(Args) << !!FinalPhaseArg
3360             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3361       else
3362         Diag(clang::diag::warn_drv_input_file_unused)
3363             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3364             << !!FinalPhaseArg
3365             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3366       continue;
3367     }
3368 
3369     if (YcArg) {
3370       // Add a separate precompile phase for the compile phase.
3371       if (FinalPhase >= phases::Compile) {
3372         const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3373         // Build the pipeline for the pch file.
3374         Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3375         for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3376           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3377         assert(ClangClPch);
3378         Actions.push_back(ClangClPch);
3379         // The driver currently exits after the first failed command.  This
3380         // relies on that behavior, to make sure if the pch generation fails,
3381         // the main compilation won't run.
3382         // FIXME: If the main compilation fails, the PCH generation should
3383         // probably not be considered successful either.
3384       }
3385     }
3386   }
3387 
3388   // If we are linking, claim any options which are obviously only used for
3389   // compilation.
3390   // FIXME: Understand why the last Phase List length is used here.
3391   if (FinalPhase == phases::Link && LastPLSize == 1) {
3392     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3393     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3394   }
3395 }
3396 
3397 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3398                           const InputList &Inputs, ActionList &Actions) const {
3399   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3400 
3401   if (!SuppressMissingInputWarning && Inputs.empty()) {
3402     Diag(clang::diag::err_drv_no_input_files);
3403     return;
3404   }
3405 
3406   // Reject -Z* at the top level, these options should never have been exposed
3407   // by gcc.
3408   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3409     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3410 
3411   // Diagnose misuse of /Fo.
3412   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3413     StringRef V = A->getValue();
3414     if (Inputs.size() > 1 && !V.empty() &&
3415         !llvm::sys::path::is_separator(V.back())) {
3416       // Check whether /Fo tries to name an output file for multiple inputs.
3417       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3418           << A->getSpelling() << V;
3419       Args.eraseArg(options::OPT__SLASH_Fo);
3420     }
3421   }
3422 
3423   // Diagnose misuse of /Fa.
3424   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3425     StringRef V = A->getValue();
3426     if (Inputs.size() > 1 && !V.empty() &&
3427         !llvm::sys::path::is_separator(V.back())) {
3428       // Check whether /Fa tries to name an asm file for multiple inputs.
3429       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3430           << A->getSpelling() << V;
3431       Args.eraseArg(options::OPT__SLASH_Fa);
3432     }
3433   }
3434 
3435   // Diagnose misuse of /o.
3436   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3437     if (A->getValue()[0] == '\0') {
3438       // It has to have a value.
3439       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3440       Args.eraseArg(options::OPT__SLASH_o);
3441     }
3442   }
3443 
3444   handleArguments(C, Args, Inputs, Actions);
3445 
3446   // Builder to be used to build offloading actions.
3447   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3448 
3449   // Construct the actions to perform.
3450   HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3451   ActionList LinkerInputs;
3452   ActionList MergerInputs;
3453 
3454   for (auto &I : Inputs) {
3455     types::ID InputType = I.first;
3456     const Arg *InputArg = I.second;
3457 
3458     auto PL = types::getCompilationPhases(*this, Args, InputType);
3459     if (PL.empty())
3460       continue;
3461 
3462     auto FullPL = types::getCompilationPhases(InputType);
3463 
3464     // Build the pipeline for this file.
3465     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3466 
3467     // Use the current host action in any of the offloading actions, if
3468     // required.
3469     if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3470       break;
3471 
3472     for (phases::ID Phase : PL) {
3473 
3474       // Add any offload action the host action depends on.
3475       Current = OffloadBuilder.addDeviceDependencesToHostAction(
3476           Current, InputArg, Phase, PL.back(), FullPL);
3477       if (!Current)
3478         break;
3479 
3480       // Queue linker inputs.
3481       if (Phase == phases::Link) {
3482         assert(Phase == PL.back() && "linking must be final compilation step.");
3483         LinkerInputs.push_back(Current);
3484         Current = nullptr;
3485         break;
3486       }
3487 
3488       // TODO: Consider removing this because the merged may not end up being
3489       // the final Phase in the pipeline. Perhaps the merged could just merge
3490       // and then pass an artifact of some sort to the Link Phase.
3491       // Queue merger inputs.
3492       if (Phase == phases::IfsMerge) {
3493         assert(Phase == PL.back() && "merging must be final compilation step.");
3494         MergerInputs.push_back(Current);
3495         Current = nullptr;
3496         break;
3497       }
3498 
3499       // Each precompiled header file after a module file action is a module
3500       // header of that same module file, rather than being compiled to a
3501       // separate PCH.
3502       if (Phase == phases::Precompile && HeaderModuleAction &&
3503           getPrecompiledType(InputType) == types::TY_PCH) {
3504         HeaderModuleAction->addModuleHeaderInput(Current);
3505         Current = nullptr;
3506         break;
3507       }
3508 
3509       // FIXME: Should we include any prior module file outputs as inputs of
3510       // later actions in the same command line?
3511 
3512       // Otherwise construct the appropriate action.
3513       Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3514 
3515       // We didn't create a new action, so we will just move to the next phase.
3516       if (NewCurrent == Current)
3517         continue;
3518 
3519       if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3520         HeaderModuleAction = HMA;
3521 
3522       Current = NewCurrent;
3523 
3524       // Use the current host action in any of the offloading actions, if
3525       // required.
3526       if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3527         break;
3528 
3529       if (Current->getType() == types::TY_Nothing)
3530         break;
3531     }
3532 
3533     // If we ended with something, add to the output list.
3534     if (Current)
3535       Actions.push_back(Current);
3536 
3537     // Add any top level actions generated for offloading.
3538     OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3539   }
3540 
3541   // Add a link action if necessary.
3542   if (!LinkerInputs.empty()) {
3543     if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
3544       LinkerInputs.push_back(Wrapper);
3545     Action *LA;
3546     // Check if this Linker Job should emit a static library.
3547     if (ShouldEmitStaticLibrary(Args)) {
3548       LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
3549     } else {
3550       LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3551     }
3552     LA = OffloadBuilder.processHostLinkAction(LA);
3553     Actions.push_back(LA);
3554   }
3555 
3556   // Add an interface stubs merge action if necessary.
3557   if (!MergerInputs.empty())
3558     Actions.push_back(
3559         C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3560 
3561   if (Args.hasArg(options::OPT_emit_interface_stubs)) {
3562     auto PhaseList = types::getCompilationPhases(
3563         types::TY_IFS_CPP,
3564         Args.hasArg(options::OPT_c) ? phases::Compile : phases::LastPhase);
3565 
3566     ActionList MergerInputs;
3567 
3568     for (auto &I : Inputs) {
3569       types::ID InputType = I.first;
3570       const Arg *InputArg = I.second;
3571 
3572       // Currently clang and the llvm assembler do not support generating symbol
3573       // stubs from assembly, so we skip the input on asm files. For ifs files
3574       // we rely on the normal pipeline setup in the pipeline setup code above.
3575       if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
3576           InputType == types::TY_Asm)
3577         continue;
3578 
3579       Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3580 
3581       for (auto Phase : PhaseList) {
3582         switch (Phase) {
3583         default:
3584           llvm_unreachable(
3585               "IFS Pipeline can only consist of Compile followed by IfsMerge.");
3586         case phases::Compile: {
3587           // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
3588           // files where the .o file is located. The compile action can not
3589           // handle this.
3590           if (InputType == types::TY_Object)
3591             break;
3592 
3593           Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
3594           break;
3595         }
3596         case phases::IfsMerge: {
3597           assert(Phase == PhaseList.back() &&
3598                  "merging must be final compilation step.");
3599           MergerInputs.push_back(Current);
3600           Current = nullptr;
3601           break;
3602         }
3603         }
3604       }
3605 
3606       // If we ended with something, add to the output list.
3607       if (Current)
3608         Actions.push_back(Current);
3609     }
3610 
3611     // Add an interface stubs merge action if necessary.
3612     if (!MergerInputs.empty())
3613       Actions.push_back(
3614           C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3615   }
3616 
3617   // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
3618   // Compile phase that prints out supported cpu models and quits.
3619   if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
3620     // Use the -mcpu=? flag as the dummy input to cc1.
3621     Actions.clear();
3622     Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
3623     Actions.push_back(
3624         C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
3625     for (auto &I : Inputs)
3626       I.second->claim();
3627   }
3628 
3629   // Claim ignored clang-cl options.
3630   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3631 
3632   // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3633   // to non-CUDA compilations and should not trigger warnings there.
3634   Args.ClaimAllArgs(options::OPT_cuda_host_only);
3635   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3636 }
3637 
3638 Action *Driver::ConstructPhaseAction(
3639     Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3640     Action::OffloadKind TargetDeviceOffloadKind) const {
3641   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3642 
3643   // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3644   // encode this in the steps because the intermediate type depends on
3645   // arguments. Just special case here.
3646   if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3647     return Input;
3648 
3649   // Build the appropriate action.
3650   switch (Phase) {
3651   case phases::Link:
3652     llvm_unreachable("link action invalid here.");
3653   case phases::IfsMerge:
3654     llvm_unreachable("ifsmerge action invalid here.");
3655   case phases::Preprocess: {
3656     types::ID OutputTy;
3657     // -M and -MM specify the dependency file name by altering the output type,
3658     // -if -MD and -MMD are not specified.
3659     if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
3660         !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
3661       OutputTy = types::TY_Dependencies;
3662     } else {
3663       OutputTy = Input->getType();
3664       if (!Args.hasFlag(options::OPT_frewrite_includes,
3665                         options::OPT_fno_rewrite_includes, false) &&
3666           !Args.hasFlag(options::OPT_frewrite_imports,
3667                         options::OPT_fno_rewrite_imports, false) &&
3668           !CCGenDiagnostics)
3669         OutputTy = types::getPreprocessedType(OutputTy);
3670       assert(OutputTy != types::TY_INVALID &&
3671              "Cannot preprocess this input type!");
3672     }
3673     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3674   }
3675   case phases::Precompile: {
3676     types::ID OutputTy = getPrecompiledType(Input->getType());
3677     assert(OutputTy != types::TY_INVALID &&
3678            "Cannot precompile this input type!");
3679 
3680     // If we're given a module name, precompile header file inputs as a
3681     // module, not as a precompiled header.
3682     const char *ModName = nullptr;
3683     if (OutputTy == types::TY_PCH) {
3684       if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3685         ModName = A->getValue();
3686       if (ModName)
3687         OutputTy = types::TY_ModuleFile;
3688     }
3689 
3690     if (Args.hasArg(options::OPT_fsyntax_only)) {
3691       // Syntax checks should not emit a PCH file
3692       OutputTy = types::TY_Nothing;
3693     }
3694 
3695     if (ModName)
3696       return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3697                                                            ModName);
3698     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3699   }
3700   case phases::Compile: {
3701     if (Args.hasArg(options::OPT_fsyntax_only))
3702       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3703     if (Args.hasArg(options::OPT_rewrite_objc))
3704       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3705     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3706       return C.MakeAction<CompileJobAction>(Input,
3707                                             types::TY_RewrittenLegacyObjC);
3708     if (Args.hasArg(options::OPT__analyze))
3709       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3710     if (Args.hasArg(options::OPT__migrate))
3711       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3712     if (Args.hasArg(options::OPT_emit_ast))
3713       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3714     if (Args.hasArg(options::OPT_module_file_info))
3715       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3716     if (Args.hasArg(options::OPT_verify_pch))
3717       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3718     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3719   }
3720   case phases::Backend: {
3721     if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3722       types::ID Output =
3723           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
3724       return C.MakeAction<BackendJobAction>(Input, Output);
3725     }
3726     if (Args.hasArg(options::OPT_emit_llvm) ||
3727         (TargetDeviceOffloadKind == Action::OFK_HIP &&
3728          Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
3729                       false))) {
3730       types::ID Output =
3731           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
3732       return C.MakeAction<BackendJobAction>(Input, Output);
3733     }
3734     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3735   }
3736   case phases::Assemble:
3737     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3738   }
3739 
3740   llvm_unreachable("invalid phase in ConstructPhaseAction");
3741 }
3742 
3743 void Driver::BuildJobs(Compilation &C) const {
3744   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3745 
3746   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3747 
3748   // It is an error to provide a -o option if we are making multiple output
3749   // files. There are exceptions:
3750   //
3751   // IfsMergeJob: when generating interface stubs enabled we want to be able to
3752   // generate the stub file at the same time that we generate the real
3753   // library/a.out. So when a .o, .so, etc are the output, with clang interface
3754   // stubs there will also be a .ifs and .ifso at the same location.
3755   //
3756   // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
3757   // and -c is passed, we still want to be able to generate a .ifs file while
3758   // we are also generating .o files. So we allow more than one output file in
3759   // this case as well.
3760   //
3761   if (FinalOutput) {
3762     unsigned NumOutputs = 0;
3763     unsigned NumIfsOutputs = 0;
3764     for (const Action *A : C.getActions())
3765       if (A->getType() != types::TY_Nothing &&
3766           !(A->getKind() == Action::IfsMergeJobClass ||
3767             (A->getType() == clang::driver::types::TY_IFS_CPP &&
3768              A->getKind() == clang::driver::Action::CompileJobClass &&
3769              0 == NumIfsOutputs++) ||
3770             (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
3771              A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
3772         ++NumOutputs;
3773 
3774     if (NumOutputs > 1) {
3775       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3776       FinalOutput = nullptr;
3777     }
3778   }
3779 
3780   // Collect the list of architectures.
3781   llvm::StringSet<> ArchNames;
3782   if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3783     for (const Arg *A : C.getArgs())
3784       if (A->getOption().matches(options::OPT_arch))
3785         ArchNames.insert(A->getValue());
3786 
3787   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3788   std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3789   for (Action *A : C.getActions()) {
3790     // If we are linking an image for multiple archs then the linker wants
3791     // -arch_multiple and -final_output <final image name>. Unfortunately, this
3792     // doesn't fit in cleanly because we have to pass this information down.
3793     //
3794     // FIXME: This is a hack; find a cleaner way to integrate this into the
3795     // process.
3796     const char *LinkingOutput = nullptr;
3797     if (isa<LipoJobAction>(A)) {
3798       if (FinalOutput)
3799         LinkingOutput = FinalOutput->getValue();
3800       else
3801         LinkingOutput = getDefaultImageName();
3802     }
3803 
3804     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3805                        /*BoundArch*/ StringRef(),
3806                        /*AtTopLevel*/ true,
3807                        /*MultipleArchs*/ ArchNames.size() > 1,
3808                        /*LinkingOutput*/ LinkingOutput, CachedResults,
3809                        /*TargetDeviceOffloadKind*/ Action::OFK_None);
3810   }
3811 
3812   // If we have more than one job, then disable integrated-cc1 for now.
3813   if (C.getJobs().size() > 1)
3814     for (auto &J : C.getJobs())
3815       J.InProcess = false;
3816 
3817   // If the user passed -Qunused-arguments or there were errors, don't warn
3818   // about any unused arguments.
3819   if (Diags.hasErrorOccurred() ||
3820       C.getArgs().hasArg(options::OPT_Qunused_arguments))
3821     return;
3822 
3823   // Claim -### here.
3824   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
3825 
3826   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
3827   (void)C.getArgs().hasArg(options::OPT_driver_mode);
3828   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
3829 
3830   for (Arg *A : C.getArgs()) {
3831     // FIXME: It would be nice to be able to send the argument to the
3832     // DiagnosticsEngine, so that extra values, position, and so on could be
3833     // printed.
3834     if (!A->isClaimed()) {
3835       if (A->getOption().hasFlag(options::NoArgumentUnused))
3836         continue;
3837 
3838       // Suppress the warning automatically if this is just a flag, and it is an
3839       // instance of an argument we already claimed.
3840       const Option &Opt = A->getOption();
3841       if (Opt.getKind() == Option::FlagClass) {
3842         bool DuplicateClaimed = false;
3843 
3844         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3845           if (AA->isClaimed()) {
3846             DuplicateClaimed = true;
3847             break;
3848           }
3849         }
3850 
3851         if (DuplicateClaimed)
3852           continue;
3853       }
3854 
3855       // In clang-cl, don't mention unknown arguments here since they have
3856       // already been warned about.
3857       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3858         Diag(clang::diag::warn_drv_unused_argument)
3859             << A->getAsString(C.getArgs());
3860     }
3861   }
3862 }
3863 
3864 namespace {
3865 /// Utility class to control the collapse of dependent actions and select the
3866 /// tools accordingly.
3867 class ToolSelector final {
3868   /// The tool chain this selector refers to.
3869   const ToolChain &TC;
3870 
3871   /// The compilation this selector refers to.
3872   const Compilation &C;
3873 
3874   /// The base action this selector refers to.
3875   const JobAction *BaseAction;
3876 
3877   /// Set to true if the current toolchain refers to host actions.
3878   bool IsHostSelector;
3879 
3880   /// Set to true if save-temps and embed-bitcode functionalities are active.
3881   bool SaveTemps;
3882   bool EmbedBitcode;
3883 
3884   /// Get previous dependent action or null if that does not exist. If
3885   /// \a CanBeCollapsed is false, that action must be legal to collapse or
3886   /// null will be returned.
3887   const JobAction *getPrevDependentAction(const ActionList &Inputs,
3888                                           ActionList &SavedOffloadAction,
3889                                           bool CanBeCollapsed = true) {
3890     // An option can be collapsed only if it has a single input.
3891     if (Inputs.size() != 1)
3892       return nullptr;
3893 
3894     Action *CurAction = *Inputs.begin();
3895     if (CanBeCollapsed &&
3896         !CurAction->isCollapsingWithNextDependentActionLegal())
3897       return nullptr;
3898 
3899     // If the input action is an offload action. Look through it and save any
3900     // offload action that can be dropped in the event of a collapse.
3901     if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3902       // If the dependent action is a device action, we will attempt to collapse
3903       // only with other device actions. Otherwise, we would do the same but
3904       // with host actions only.
3905       if (!IsHostSelector) {
3906         if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3907           CurAction =
3908               OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3909           if (CanBeCollapsed &&
3910               !CurAction->isCollapsingWithNextDependentActionLegal())
3911             return nullptr;
3912           SavedOffloadAction.push_back(OA);
3913           return dyn_cast<JobAction>(CurAction);
3914         }
3915       } else if (OA->hasHostDependence()) {
3916         CurAction = OA->getHostDependence();
3917         if (CanBeCollapsed &&
3918             !CurAction->isCollapsingWithNextDependentActionLegal())
3919           return nullptr;
3920         SavedOffloadAction.push_back(OA);
3921         return dyn_cast<JobAction>(CurAction);
3922       }
3923       return nullptr;
3924     }
3925 
3926     return dyn_cast<JobAction>(CurAction);
3927   }
3928 
3929   /// Return true if an assemble action can be collapsed.
3930   bool canCollapseAssembleAction() const {
3931     return TC.useIntegratedAs() && !SaveTemps &&
3932            !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3933            !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3934            !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3935   }
3936 
3937   /// Return true if a preprocessor action can be collapsed.
3938   bool canCollapsePreprocessorAction() const {
3939     return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3940            !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3941            !C.getArgs().hasArg(options::OPT_rewrite_objc);
3942   }
3943 
3944   /// Struct that relates an action with the offload actions that would be
3945   /// collapsed with it.
3946   struct JobActionInfo final {
3947     /// The action this info refers to.
3948     const JobAction *JA = nullptr;
3949     /// The offload actions we need to take care off if this action is
3950     /// collapsed.
3951     ActionList SavedOffloadAction;
3952   };
3953 
3954   /// Append collapsed offload actions from the give nnumber of elements in the
3955   /// action info array.
3956   static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3957                                            ArrayRef<JobActionInfo> &ActionInfo,
3958                                            unsigned ElementNum) {
3959     assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3960     for (unsigned I = 0; I < ElementNum; ++I)
3961       CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3962                                     ActionInfo[I].SavedOffloadAction.end());
3963   }
3964 
3965   /// Functions that attempt to perform the combining. They detect if that is
3966   /// legal, and if so they update the inputs \a Inputs and the offload action
3967   /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3968   /// the combined action is returned. If the combining is not legal or if the
3969   /// tool does not exist, null is returned.
3970   /// Currently three kinds of collapsing are supported:
3971   ///  - Assemble + Backend + Compile;
3972   ///  - Assemble + Backend ;
3973   ///  - Backend + Compile.
3974   const Tool *
3975   combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3976                                 ActionList &Inputs,
3977                                 ActionList &CollapsedOffloadAction) {
3978     if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3979       return nullptr;
3980     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3981     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3982     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3983     if (!AJ || !BJ || !CJ)
3984       return nullptr;
3985 
3986     // Get compiler tool.
3987     const Tool *T = TC.SelectTool(*CJ);
3988     if (!T)
3989       return nullptr;
3990 
3991     // When using -fembed-bitcode, it is required to have the same tool (clang)
3992     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3993     if (EmbedBitcode) {
3994       const Tool *BT = TC.SelectTool(*BJ);
3995       if (BT == T)
3996         return nullptr;
3997     }
3998 
3999     if (!T->hasIntegratedAssembler())
4000       return nullptr;
4001 
4002     Inputs = CJ->getInputs();
4003     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4004                                  /*NumElements=*/3);
4005     return T;
4006   }
4007   const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4008                                      ActionList &Inputs,
4009                                      ActionList &CollapsedOffloadAction) {
4010     if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4011       return nullptr;
4012     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4013     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4014     if (!AJ || !BJ)
4015       return nullptr;
4016 
4017     // Get backend tool.
4018     const Tool *T = TC.SelectTool(*BJ);
4019     if (!T)
4020       return nullptr;
4021 
4022     if (!T->hasIntegratedAssembler())
4023       return nullptr;
4024 
4025     Inputs = BJ->getInputs();
4026     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4027                                  /*NumElements=*/2);
4028     return T;
4029   }
4030   const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4031                                     ActionList &Inputs,
4032                                     ActionList &CollapsedOffloadAction) {
4033     if (ActionInfo.size() < 2)
4034       return nullptr;
4035     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4036     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4037     if (!BJ || !CJ)
4038       return nullptr;
4039 
4040     // Check if the initial input (to the compile job or its predessor if one
4041     // exists) is LLVM bitcode. In that case, no preprocessor step is required
4042     // and we can still collapse the compile and backend jobs when we have
4043     // -save-temps. I.e. there is no need for a separate compile job just to
4044     // emit unoptimized bitcode.
4045     bool InputIsBitcode = true;
4046     for (size_t i = 1; i < ActionInfo.size(); i++)
4047       if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4048           ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4049         InputIsBitcode = false;
4050         break;
4051       }
4052     if (!InputIsBitcode && !canCollapsePreprocessorAction())
4053       return nullptr;
4054 
4055     // Get compiler tool.
4056     const Tool *T = TC.SelectTool(*CJ);
4057     if (!T)
4058       return nullptr;
4059 
4060     if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4061       return nullptr;
4062 
4063     Inputs = CJ->getInputs();
4064     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4065                                  /*NumElements=*/2);
4066     return T;
4067   }
4068 
4069   /// Updates the inputs if the obtained tool supports combining with
4070   /// preprocessor action, and the current input is indeed a preprocessor
4071   /// action. If combining results in the collapse of offloading actions, those
4072   /// are appended to \a CollapsedOffloadAction.
4073   void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4074                                ActionList &CollapsedOffloadAction) {
4075     if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4076       return;
4077 
4078     // Attempt to get a preprocessor action dependence.
4079     ActionList PreprocessJobOffloadActions;
4080     ActionList NewInputs;
4081     for (Action *A : Inputs) {
4082       auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4083       if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4084         NewInputs.push_back(A);
4085         continue;
4086       }
4087 
4088       // This is legal to combine. Append any offload action we found and add the
4089       // current input to preprocessor inputs.
4090       CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
4091                                     PreprocessJobOffloadActions.end());
4092       NewInputs.append(PJ->input_begin(), PJ->input_end());
4093     }
4094     Inputs = NewInputs;
4095   }
4096 
4097 public:
4098   ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
4099                const Compilation &C, bool SaveTemps, bool EmbedBitcode)
4100       : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
4101         EmbedBitcode(EmbedBitcode) {
4102     assert(BaseAction && "Invalid base action.");
4103     IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
4104   }
4105 
4106   /// Check if a chain of actions can be combined and return the tool that can
4107   /// handle the combination of actions. The pointer to the current inputs \a
4108   /// Inputs and the list of offload actions \a CollapsedOffloadActions
4109   /// connected to collapsed actions are updated accordingly. The latter enables
4110   /// the caller of the selector to process them afterwards instead of just
4111   /// dropping them. If no suitable tool is found, null will be returned.
4112   const Tool *getTool(ActionList &Inputs,
4113                       ActionList &CollapsedOffloadAction) {
4114     //
4115     // Get the largest chain of actions that we could combine.
4116     //
4117 
4118     SmallVector<JobActionInfo, 5> ActionChain(1);
4119     ActionChain.back().JA = BaseAction;
4120     while (ActionChain.back().JA) {
4121       const Action *CurAction = ActionChain.back().JA;
4122 
4123       // Grow the chain by one element.
4124       ActionChain.resize(ActionChain.size() + 1);
4125       JobActionInfo &AI = ActionChain.back();
4126 
4127       // Attempt to fill it with the
4128       AI.JA =
4129           getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
4130     }
4131 
4132     // Pop the last action info as it could not be filled.
4133     ActionChain.pop_back();
4134 
4135     //
4136     // Attempt to combine actions. If all combining attempts failed, just return
4137     // the tool of the provided action. At the end we attempt to combine the
4138     // action with any preprocessor action it may depend on.
4139     //
4140 
4141     const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
4142                                                   CollapsedOffloadAction);
4143     if (!T)
4144       T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
4145     if (!T)
4146       T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
4147     if (!T) {
4148       Inputs = BaseAction->getInputs();
4149       T = TC.SelectTool(*BaseAction);
4150     }
4151 
4152     combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
4153     return T;
4154   }
4155 };
4156 }
4157 
4158 /// Return a string that uniquely identifies the result of a job. The bound arch
4159 /// is not necessarily represented in the toolchain's triple -- for example,
4160 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
4161 /// Also, we need to add the offloading device kind, as the same tool chain can
4162 /// be used for host and device for some programming models, e.g. OpenMP.
4163 static std::string GetTriplePlusArchString(const ToolChain *TC,
4164                                            StringRef BoundArch,
4165                                            Action::OffloadKind OffloadKind) {
4166   std::string TriplePlusArch = TC->getTriple().normalize();
4167   if (!BoundArch.empty()) {
4168     TriplePlusArch += "-";
4169     TriplePlusArch += BoundArch;
4170   }
4171   TriplePlusArch += "-";
4172   TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
4173   return TriplePlusArch;
4174 }
4175 
4176 InputInfo Driver::BuildJobsForAction(
4177     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4178     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4179     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4180     Action::OffloadKind TargetDeviceOffloadKind) const {
4181   std::pair<const Action *, std::string> ActionTC = {
4182       A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4183   auto CachedResult = CachedResults.find(ActionTC);
4184   if (CachedResult != CachedResults.end()) {
4185     return CachedResult->second;
4186   }
4187   InputInfo Result = BuildJobsForActionNoCache(
4188       C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
4189       CachedResults, TargetDeviceOffloadKind);
4190   CachedResults[ActionTC] = Result;
4191   return Result;
4192 }
4193 
4194 InputInfo Driver::BuildJobsForActionNoCache(
4195     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4196     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4197     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4198     Action::OffloadKind TargetDeviceOffloadKind) const {
4199   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4200 
4201   InputInfoList OffloadDependencesInputInfo;
4202   bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
4203   if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
4204     // The 'Darwin' toolchain is initialized only when its arguments are
4205     // computed. Get the default arguments for OFK_None to ensure that
4206     // initialization is performed before processing the offload action.
4207     // FIXME: Remove when darwin's toolchain is initialized during construction.
4208     C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
4209 
4210     // The offload action is expected to be used in four different situations.
4211     //
4212     // a) Set a toolchain/architecture/kind for a host action:
4213     //    Host Action 1 -> OffloadAction -> Host Action 2
4214     //
4215     // b) Set a toolchain/architecture/kind for a device action;
4216     //    Device Action 1 -> OffloadAction -> Device Action 2
4217     //
4218     // c) Specify a device dependence to a host action;
4219     //    Device Action 1  _
4220     //                      \
4221     //      Host Action 1  ---> OffloadAction -> Host Action 2
4222     //
4223     // d) Specify a host dependence to a device action.
4224     //      Host Action 1  _
4225     //                      \
4226     //    Device Action 1  ---> OffloadAction -> Device Action 2
4227     //
4228     // For a) and b), we just return the job generated for the dependence. For
4229     // c) and d) we override the current action with the host/device dependence
4230     // if the current toolchain is host/device and set the offload dependences
4231     // info with the jobs obtained from the device/host dependence(s).
4232 
4233     // If there is a single device option, just generate the job for it.
4234     if (OA->hasSingleDeviceDependence()) {
4235       InputInfo DevA;
4236       OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
4237                                        const char *DepBoundArch) {
4238         DevA =
4239             BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
4240                                /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
4241                                CachedResults, DepA->getOffloadingDeviceKind());
4242       });
4243       return DevA;
4244     }
4245 
4246     // If 'Action 2' is host, we generate jobs for the device dependences and
4247     // override the current action with the host dependence. Otherwise, we
4248     // generate the host dependences and override the action with the device
4249     // dependence. The dependences can't therefore be a top-level action.
4250     OA->doOnEachDependence(
4251         /*IsHostDependence=*/BuildingForOffloadDevice,
4252         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4253           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4254               C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
4255               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
4256               DepA->getOffloadingDeviceKind()));
4257         });
4258 
4259     A = BuildingForOffloadDevice
4260             ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
4261             : OA->getHostDependence();
4262   }
4263 
4264   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
4265     // FIXME: It would be nice to not claim this here; maybe the old scheme of
4266     // just using Args was better?
4267     const Arg &Input = IA->getInputArg();
4268     Input.claim();
4269     if (Input.getOption().matches(options::OPT_INPUT)) {
4270       const char *Name = Input.getValue();
4271       return InputInfo(A, Name, /* _BaseInput = */ Name);
4272     }
4273     return InputInfo(A, &Input, /* _BaseInput = */ "");
4274   }
4275 
4276   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
4277     const ToolChain *TC;
4278     StringRef ArchName = BAA->getArchName();
4279 
4280     if (!ArchName.empty())
4281       TC = &getToolChain(C.getArgs(),
4282                          computeTargetTriple(*this, TargetTriple,
4283                                              C.getArgs(), ArchName));
4284     else
4285       TC = &C.getDefaultToolChain();
4286 
4287     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
4288                               MultipleArchs, LinkingOutput, CachedResults,
4289                               TargetDeviceOffloadKind);
4290   }
4291 
4292 
4293   ActionList Inputs = A->getInputs();
4294 
4295   const JobAction *JA = cast<JobAction>(A);
4296   ActionList CollapsedOffloadActions;
4297 
4298   ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4299                   embedBitcodeInObject() && !isUsingLTO());
4300   const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4301 
4302   if (!T)
4303     return InputInfo();
4304 
4305   // If we've collapsed action list that contained OffloadAction we
4306   // need to build jobs for host/device-side inputs it may have held.
4307   for (const auto *OA : CollapsedOffloadActions)
4308     cast<OffloadAction>(OA)->doOnEachDependence(
4309         /*IsHostDependence=*/BuildingForOffloadDevice,
4310         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4311           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4312               C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4313               /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4314               DepA->getOffloadingDeviceKind()));
4315         });
4316 
4317   // Only use pipes when there is exactly one input.
4318   InputInfoList InputInfos;
4319   for (const Action *Input : Inputs) {
4320     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4321     // shouldn't get temporary output names.
4322     // FIXME: Clean this up.
4323     bool SubJobAtTopLevel =
4324         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
4325     InputInfos.push_back(BuildJobsForAction(
4326         C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4327         CachedResults, A->getOffloadingDeviceKind()));
4328   }
4329 
4330   // Always use the first input as the base input.
4331   const char *BaseInput = InputInfos[0].getBaseInput();
4332 
4333   // ... except dsymutil actions, which use their actual input as the base
4334   // input.
4335   if (JA->getType() == types::TY_dSYM)
4336     BaseInput = InputInfos[0].getFilename();
4337 
4338   // ... and in header module compilations, which use the module name.
4339   if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4340     BaseInput = ModuleJA->getModuleName();
4341 
4342   // Append outputs of offload device jobs to the input list
4343   if (!OffloadDependencesInputInfo.empty())
4344     InputInfos.append(OffloadDependencesInputInfo.begin(),
4345                       OffloadDependencesInputInfo.end());
4346 
4347   // Set the effective triple of the toolchain for the duration of this job.
4348   llvm::Triple EffectiveTriple;
4349   const ToolChain &ToolTC = T->getToolChain();
4350   const ArgList &Args =
4351       C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4352   if (InputInfos.size() != 1) {
4353     EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4354   } else {
4355     // Pass along the input type if it can be unambiguously determined.
4356     EffectiveTriple = llvm::Triple(
4357         ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4358   }
4359   RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4360 
4361   // Determine the place to write output to, if any.
4362   InputInfo Result;
4363   InputInfoList UnbundlingResults;
4364   if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4365     // If we have an unbundling job, we need to create results for all the
4366     // outputs. We also update the results cache so that other actions using
4367     // this unbundling action can get the right results.
4368     for (auto &UI : UA->getDependentActionsInfo()) {
4369       assert(UI.DependentOffloadKind != Action::OFK_None &&
4370              "Unbundling with no offloading??");
4371 
4372       // Unbundling actions are never at the top level. When we generate the
4373       // offloading prefix, we also do that for the host file because the
4374       // unbundling action does not change the type of the output which can
4375       // cause a overwrite.
4376       std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4377           UI.DependentOffloadKind,
4378           UI.DependentToolChain->getTriple().normalize(),
4379           /*CreatePrefixForHost=*/true);
4380       auto CurI = InputInfo(
4381           UA,
4382           GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4383                              /*AtTopLevel=*/false,
4384                              MultipleArchs ||
4385                                  UI.DependentOffloadKind == Action::OFK_HIP,
4386                              OffloadingPrefix),
4387           BaseInput);
4388       // Save the unbundling result.
4389       UnbundlingResults.push_back(CurI);
4390 
4391       // Get the unique string identifier for this dependence and cache the
4392       // result.
4393       StringRef Arch;
4394       if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4395         if (UI.DependentOffloadKind == Action::OFK_Host)
4396           Arch = StringRef();
4397         else
4398           Arch = UI.DependentBoundArch;
4399       } else
4400         Arch = BoundArch;
4401 
4402       CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4403                                                 UI.DependentOffloadKind)}] =
4404           CurI;
4405     }
4406 
4407     // Now that we have all the results generated, select the one that should be
4408     // returned for the current depending action.
4409     std::pair<const Action *, std::string> ActionTC = {
4410         A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4411     assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4412            "Result does not exist??");
4413     Result = CachedResults[ActionTC];
4414   } else if (JA->getType() == types::TY_Nothing)
4415     Result = InputInfo(A, BaseInput);
4416   else {
4417     // We only have to generate a prefix for the host if this is not a top-level
4418     // action.
4419     std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4420         A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4421         /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4422             !AtTopLevel);
4423     if (isa<OffloadWrapperJobAction>(JA)) {
4424       OffloadingPrefix += "-wrapper";
4425       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4426         BaseInput = FinalOutput->getValue();
4427       else
4428         BaseInput = getDefaultImageName();
4429     }
4430     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4431                                              AtTopLevel, MultipleArchs,
4432                                              OffloadingPrefix),
4433                        BaseInput);
4434   }
4435 
4436   if (CCCPrintBindings && !CCGenDiagnostics) {
4437     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4438                  << " - \"" << T->getName() << "\", inputs: [";
4439     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4440       llvm::errs() << InputInfos[i].getAsString();
4441       if (i + 1 != e)
4442         llvm::errs() << ", ";
4443     }
4444     if (UnbundlingResults.empty())
4445       llvm::errs() << "], output: " << Result.getAsString() << "\n";
4446     else {
4447       llvm::errs() << "], outputs: [";
4448       for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4449         llvm::errs() << UnbundlingResults[i].getAsString();
4450         if (i + 1 != e)
4451           llvm::errs() << ", ";
4452       }
4453       llvm::errs() << "] \n";
4454     }
4455   } else {
4456     if (UnbundlingResults.empty())
4457       T->ConstructJob(
4458           C, *JA, Result, InputInfos,
4459           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4460           LinkingOutput);
4461     else
4462       T->ConstructJobMultipleOutputs(
4463           C, *JA, UnbundlingResults, InputInfos,
4464           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4465           LinkingOutput);
4466   }
4467   return Result;
4468 }
4469 
4470 const char *Driver::getDefaultImageName() const {
4471   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4472   return Target.isOSWindows() ? "a.exe" : "a.out";
4473 }
4474 
4475 /// Create output filename based on ArgValue, which could either be a
4476 /// full filename, filename without extension, or a directory. If ArgValue
4477 /// does not provide a filename, then use BaseName, and use the extension
4478 /// suitable for FileType.
4479 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4480                                         StringRef BaseName,
4481                                         types::ID FileType) {
4482   SmallString<128> Filename = ArgValue;
4483 
4484   if (ArgValue.empty()) {
4485     // If the argument is empty, output to BaseName in the current dir.
4486     Filename = BaseName;
4487   } else if (llvm::sys::path::is_separator(Filename.back())) {
4488     // If the argument is a directory, output to BaseName in that dir.
4489     llvm::sys::path::append(Filename, BaseName);
4490   }
4491 
4492   if (!llvm::sys::path::has_extension(ArgValue)) {
4493     // If the argument didn't provide an extension, then set it.
4494     const char *Extension = types::getTypeTempSuffix(FileType, true);
4495 
4496     if (FileType == types::TY_Image &&
4497         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4498       // The output file is a dll.
4499       Extension = "dll";
4500     }
4501 
4502     llvm::sys::path::replace_extension(Filename, Extension);
4503   }
4504 
4505   return Args.MakeArgString(Filename.c_str());
4506 }
4507 
4508 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4509                                        const char *BaseInput,
4510                                        StringRef BoundArch, bool AtTopLevel,
4511                                        bool MultipleArchs,
4512                                        StringRef OffloadingPrefix) const {
4513   llvm::PrettyStackTraceString CrashInfo("Computing output path");
4514   // Output to a user requested destination?
4515   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
4516     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4517       return C.addResultFile(FinalOutput->getValue(), &JA);
4518   }
4519 
4520   // For /P, preprocess to file named after BaseInput.
4521   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4522     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4523     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4524     StringRef NameArg;
4525     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4526       NameArg = A->getValue();
4527     return C.addResultFile(
4528         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4529         &JA);
4530   }
4531 
4532   // Default to writing to stdout?
4533   if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
4534     return "-";
4535 
4536   // Is this the assembly listing for /FA?
4537   if (JA.getType() == types::TY_PP_Asm &&
4538       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4539        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4540     // Use /Fa and the input filename to determine the asm file name.
4541     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4542     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4543     return C.addResultFile(
4544         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4545         &JA);
4546   }
4547 
4548   // Output to a temporary file?
4549   if ((!AtTopLevel && !isSaveTempsEnabled() &&
4550        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4551       CCGenDiagnostics) {
4552     StringRef Name = llvm::sys::path::filename(BaseInput);
4553     std::pair<StringRef, StringRef> Split = Name.split('.');
4554     SmallString<128> TmpName;
4555     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4556     Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4557     if (CCGenDiagnostics && A) {
4558       SmallString<128> CrashDirectory(A->getValue());
4559       if (!getVFS().exists(CrashDirectory))
4560         llvm::sys::fs::create_directories(CrashDirectory);
4561       llvm::sys::path::append(CrashDirectory, Split.first);
4562       const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4563       std::error_code EC = llvm::sys::fs::createUniqueFile(
4564           CrashDirectory + Middle + Suffix, TmpName);
4565       if (EC) {
4566         Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4567         return "";
4568       }
4569     } else {
4570       TmpName = GetTemporaryPath(Split.first, Suffix);
4571     }
4572     return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4573   }
4574 
4575   SmallString<128> BasePath(BaseInput);
4576   StringRef BaseName;
4577 
4578   // Dsymutil actions should use the full path.
4579   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4580     BaseName = BasePath;
4581   else
4582     BaseName = llvm::sys::path::filename(BasePath);
4583 
4584   // Determine what the derived output name should be.
4585   const char *NamedOutput;
4586 
4587   if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4588       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4589     // The /Fo or /o flag decides the object filename.
4590     StringRef Val =
4591         C.getArgs()
4592             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4593             ->getValue();
4594     NamedOutput =
4595         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4596   } else if (JA.getType() == types::TY_Image &&
4597              C.getArgs().hasArg(options::OPT__SLASH_Fe,
4598                                 options::OPT__SLASH_o)) {
4599     // The /Fe or /o flag names the linked file.
4600     StringRef Val =
4601         C.getArgs()
4602             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4603             ->getValue();
4604     NamedOutput =
4605         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4606   } else if (JA.getType() == types::TY_Image) {
4607     if (IsCLMode()) {
4608       // clang-cl uses BaseName for the executable name.
4609       NamedOutput =
4610           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4611     } else {
4612       SmallString<128> Output(getDefaultImageName());
4613       // HIP image for device compilation with -fno-gpu-rdc is per compilation
4614       // unit.
4615       bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4616                         !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
4617                                              options::OPT_fno_gpu_rdc, false);
4618       if (IsHIPNoRDC) {
4619         Output = BaseName;
4620         llvm::sys::path::replace_extension(Output, "");
4621       }
4622       Output += OffloadingPrefix;
4623       if (MultipleArchs && !BoundArch.empty()) {
4624         Output += "-";
4625         Output.append(BoundArch);
4626       }
4627       if (IsHIPNoRDC)
4628         Output += ".out";
4629       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4630     }
4631   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
4632     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4633   } else {
4634     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4635     assert(Suffix && "All types used for output should have a suffix.");
4636 
4637     std::string::size_type End = std::string::npos;
4638     if (!types::appendSuffixForType(JA.getType()))
4639       End = BaseName.rfind('.');
4640     SmallString<128> Suffixed(BaseName.substr(0, End));
4641     Suffixed += OffloadingPrefix;
4642     if (MultipleArchs && !BoundArch.empty()) {
4643       Suffixed += "-";
4644       Suffixed.append(BoundArch);
4645     }
4646     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4647     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4648     // optimized bitcode output.
4649     auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
4650                                      const llvm::opt::DerivedArgList &Args) {
4651       // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
4652       // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
4653       // phase.)
4654       return isa<CompileJobAction>(JA) &&
4655              JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4656              Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4657                           false);
4658     };
4659     if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
4660         (C.getArgs().hasArg(options::OPT_emit_llvm) ||
4661          IsHIPRDCInCompilePhase(JA, C.getArgs())))
4662       Suffixed += ".tmp";
4663     Suffixed += '.';
4664     Suffixed += Suffix;
4665     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4666   }
4667 
4668   // Prepend object file path if -save-temps=obj
4669   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4670       JA.getType() != types::TY_PCH) {
4671     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4672     SmallString<128> TempPath(FinalOutput->getValue());
4673     llvm::sys::path::remove_filename(TempPath);
4674     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4675     llvm::sys::path::append(TempPath, OutputFileName);
4676     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4677   }
4678 
4679   // If we're saving temps and the temp file conflicts with the input file,
4680   // then avoid overwriting input file.
4681   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
4682     bool SameFile = false;
4683     SmallString<256> Result;
4684     llvm::sys::fs::current_path(Result);
4685     llvm::sys::path::append(Result, BaseName);
4686     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4687     // Must share the same path to conflict.
4688     if (SameFile) {
4689       StringRef Name = llvm::sys::path::filename(BaseInput);
4690       std::pair<StringRef, StringRef> Split = Name.split('.');
4691       std::string TmpName = GetTemporaryPath(
4692           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4693       return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4694     }
4695   }
4696 
4697   // As an annoying special case, PCH generation doesn't strip the pathname.
4698   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
4699     llvm::sys::path::remove_filename(BasePath);
4700     if (BasePath.empty())
4701       BasePath = NamedOutput;
4702     else
4703       llvm::sys::path::append(BasePath, NamedOutput);
4704     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4705   } else {
4706     return C.addResultFile(NamedOutput, &JA);
4707   }
4708 }
4709 
4710 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4711   // Search for Name in a list of paths.
4712   auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4713       -> llvm::Optional<std::string> {
4714     // Respect a limited subset of the '-Bprefix' functionality in GCC by
4715     // attempting to use this prefix when looking for file paths.
4716     for (const auto &Dir : P) {
4717       if (Dir.empty())
4718         continue;
4719       SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4720       llvm::sys::path::append(P, Name);
4721       if (llvm::sys::fs::exists(Twine(P)))
4722         return std::string(P);
4723     }
4724     return None;
4725   };
4726 
4727   if (auto P = SearchPaths(PrefixDirs))
4728     return *P;
4729 
4730   SmallString<128> R(ResourceDir);
4731   llvm::sys::path::append(R, Name);
4732   if (llvm::sys::fs::exists(Twine(R)))
4733     return std::string(R.str());
4734 
4735   SmallString<128> P(TC.getCompilerRTPath());
4736   llvm::sys::path::append(P, Name);
4737   if (llvm::sys::fs::exists(Twine(P)))
4738     return std::string(P.str());
4739 
4740   SmallString<128> D(Dir);
4741   llvm::sys::path::append(D, "..", Name);
4742   if (llvm::sys::fs::exists(Twine(D)))
4743     return std::string(D.str());
4744 
4745   if (auto P = SearchPaths(TC.getLibraryPaths()))
4746     return *P;
4747 
4748   if (auto P = SearchPaths(TC.getFilePaths()))
4749     return *P;
4750 
4751   return std::string(Name);
4752 }
4753 
4754 void Driver::generatePrefixedToolNames(
4755     StringRef Tool, const ToolChain &TC,
4756     SmallVectorImpl<std::string> &Names) const {
4757   // FIXME: Needs a better variable than TargetTriple
4758   Names.emplace_back((TargetTriple + "-" + Tool).str());
4759   Names.emplace_back(Tool);
4760 
4761   // Allow the discovery of tools prefixed with LLVM's default target triple.
4762   std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4763   if (DefaultTargetTriple != TargetTriple)
4764     Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4765 }
4766 
4767 static bool ScanDirForExecutable(SmallString<128> &Dir,
4768                                  ArrayRef<std::string> Names) {
4769   for (const auto &Name : Names) {
4770     llvm::sys::path::append(Dir, Name);
4771     if (llvm::sys::fs::can_execute(Twine(Dir)))
4772       return true;
4773     llvm::sys::path::remove_filename(Dir);
4774   }
4775   return false;
4776 }
4777 
4778 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4779   SmallVector<std::string, 2> TargetSpecificExecutables;
4780   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4781 
4782   // Respect a limited subset of the '-Bprefix' functionality in GCC by
4783   // attempting to use this prefix when looking for program paths.
4784   for (const auto &PrefixDir : PrefixDirs) {
4785     if (llvm::sys::fs::is_directory(PrefixDir)) {
4786       SmallString<128> P(PrefixDir);
4787       if (ScanDirForExecutable(P, TargetSpecificExecutables))
4788         return std::string(P.str());
4789     } else {
4790       SmallString<128> P((PrefixDir + Name).str());
4791       if (llvm::sys::fs::can_execute(Twine(P)))
4792         return std::string(P.str());
4793     }
4794   }
4795 
4796   const ToolChain::path_list &List = TC.getProgramPaths();
4797   for (const auto &Path : List) {
4798     SmallString<128> P(Path);
4799     if (ScanDirForExecutable(P, TargetSpecificExecutables))
4800       return std::string(P.str());
4801   }
4802 
4803   // If all else failed, search the path.
4804   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4805     if (llvm::ErrorOr<std::string> P =
4806             llvm::sys::findProgramByName(TargetSpecificExecutable))
4807       return *P;
4808 
4809   return std::string(Name);
4810 }
4811 
4812 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
4813   SmallString<128> Path;
4814   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
4815   if (EC) {
4816     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4817     return "";
4818   }
4819 
4820   return std::string(Path.str());
4821 }
4822 
4823 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4824   SmallString<128> Path;
4825   std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4826   if (EC) {
4827     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4828     return "";
4829   }
4830 
4831   return std::string(Path.str());
4832 }
4833 
4834 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4835   SmallString<128> Output;
4836   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4837     // FIXME: If anybody needs it, implement this obscure rule:
4838     // "If you specify a directory without a file name, the default file name
4839     // is VCx0.pch., where x is the major version of Visual C++ in use."
4840     Output = FpArg->getValue();
4841 
4842     // "If you do not specify an extension as part of the path name, an
4843     // extension of .pch is assumed. "
4844     if (!llvm::sys::path::has_extension(Output))
4845       Output += ".pch";
4846   } else {
4847     if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4848       Output = YcArg->getValue();
4849     if (Output.empty())
4850       Output = BaseName;
4851     llvm::sys::path::replace_extension(Output, ".pch");
4852   }
4853   return std::string(Output.str());
4854 }
4855 
4856 const ToolChain &Driver::getToolChain(const ArgList &Args,
4857                                       const llvm::Triple &Target) const {
4858 
4859   auto &TC = ToolChains[Target.str()];
4860   if (!TC) {
4861     switch (Target.getOS()) {
4862     case llvm::Triple::AIX:
4863       TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
4864       break;
4865     case llvm::Triple::Haiku:
4866       TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
4867       break;
4868     case llvm::Triple::Ananas:
4869       TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
4870       break;
4871     case llvm::Triple::CloudABI:
4872       TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
4873       break;
4874     case llvm::Triple::Darwin:
4875     case llvm::Triple::MacOSX:
4876     case llvm::Triple::IOS:
4877     case llvm::Triple::TvOS:
4878     case llvm::Triple::WatchOS:
4879       TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
4880       break;
4881     case llvm::Triple::DragonFly:
4882       TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
4883       break;
4884     case llvm::Triple::OpenBSD:
4885       TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
4886       break;
4887     case llvm::Triple::NetBSD:
4888       TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
4889       break;
4890     case llvm::Triple::FreeBSD:
4891       TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
4892       break;
4893     case llvm::Triple::Minix:
4894       TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
4895       break;
4896     case llvm::Triple::Linux:
4897     case llvm::Triple::ELFIAMCU:
4898       if (Target.getArch() == llvm::Triple::hexagon)
4899         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
4900                                                              Args);
4901       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4902                !Target.hasEnvironment())
4903         TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4904                                                               Args);
4905       else if (Target.getArch() == llvm::Triple::ppc ||
4906                Target.getArch() == llvm::Triple::ppc64 ||
4907                Target.getArch() == llvm::Triple::ppc64le)
4908         TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
4909                                                               Args);
4910       else
4911         TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
4912       break;
4913     case llvm::Triple::NaCl:
4914       TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
4915       break;
4916     case llvm::Triple::Fuchsia:
4917       TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
4918       break;
4919     case llvm::Triple::Solaris:
4920       TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
4921       break;
4922     case llvm::Triple::AMDHSA:
4923       TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
4924       break;
4925     case llvm::Triple::AMDPAL:
4926     case llvm::Triple::Mesa3D:
4927       TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
4928       break;
4929     case llvm::Triple::Win32:
4930       switch (Target.getEnvironment()) {
4931       default:
4932         if (Target.isOSBinFormatELF())
4933           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4934         else if (Target.isOSBinFormatMachO())
4935           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
4936         else
4937           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4938         break;
4939       case llvm::Triple::GNU:
4940         TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
4941         break;
4942       case llvm::Triple::Itanium:
4943         TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4944                                                                   Args);
4945         break;
4946       case llvm::Triple::MSVC:
4947       case llvm::Triple::UnknownEnvironment:
4948         if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4949                 .startswith_lower("bfd"))
4950           TC = std::make_unique<toolchains::CrossWindowsToolChain>(
4951               *this, Target, Args);
4952         else
4953           TC =
4954               std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
4955         break;
4956       }
4957       break;
4958     case llvm::Triple::PS4:
4959       TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
4960       break;
4961     case llvm::Triple::Contiki:
4962       TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
4963       break;
4964     case llvm::Triple::Hurd:
4965       TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
4966       break;
4967     default:
4968       // Of these targets, Hexagon is the only one that might have
4969       // an OS of Linux, in which case it got handled above already.
4970       switch (Target.getArch()) {
4971       case llvm::Triple::tce:
4972         TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
4973         break;
4974       case llvm::Triple::tcele:
4975         TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
4976         break;
4977       case llvm::Triple::hexagon:
4978         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
4979                                                              Args);
4980         break;
4981       case llvm::Triple::lanai:
4982         TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
4983         break;
4984       case llvm::Triple::xcore:
4985         TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
4986         break;
4987       case llvm::Triple::wasm32:
4988       case llvm::Triple::wasm64:
4989         TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
4990         break;
4991       case llvm::Triple::avr:
4992         TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
4993         break;
4994       case llvm::Triple::msp430:
4995         TC =
4996             std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
4997         break;
4998       case llvm::Triple::riscv32:
4999       case llvm::Triple::riscv64:
5000         TC = std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
5001         break;
5002       default:
5003         if (Target.getVendor() == llvm::Triple::Myriad)
5004           TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
5005                                                               Args);
5006         else if (toolchains::BareMetal::handlesTarget(Target))
5007           TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
5008         else if (Target.isOSBinFormatELF())
5009           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5010         else if (Target.isOSBinFormatMachO())
5011           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5012         else
5013           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5014       }
5015     }
5016   }
5017 
5018   // Intentionally omitted from the switch above: llvm::Triple::CUDA.  CUDA
5019   // compiles always need two toolchains, the CUDA toolchain and the host
5020   // toolchain.  So the only valid way to create a CUDA toolchain is via
5021   // CreateOffloadingDeviceToolChains.
5022 
5023   return *TC;
5024 }
5025 
5026 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
5027   // Say "no" if there is not exactly one input of a type clang understands.
5028   if (JA.size() != 1 ||
5029       !types::isAcceptedByClang((*JA.input_begin())->getType()))
5030     return false;
5031 
5032   // And say "no" if this is not a kind of action clang understands.
5033   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
5034       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5035     return false;
5036 
5037   return true;
5038 }
5039 
5040 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
5041   // Say "no" if there is not exactly one input of a type flang understands.
5042   if (JA.size() != 1 ||
5043       !types::isFortran((*JA.input_begin())->getType()))
5044     return false;
5045 
5046   // And say "no" if this is not a kind of action flang understands.
5047   if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5048     return false;
5049 
5050   return true;
5051 }
5052 
5053 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
5054   // Only emit static library if the flag is set explicitly.
5055   if (Args.hasArg(options::OPT_emit_static_lib))
5056     return true;
5057   return false;
5058 }
5059 
5060 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
5061 /// grouped values as integers. Numbers which are not provided are set to 0.
5062 ///
5063 /// \return True if the entire string was parsed (9.2), or all groups were
5064 /// parsed (10.3.5extrastuff).
5065 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
5066                                unsigned &Micro, bool &HadExtra) {
5067   HadExtra = false;
5068 
5069   Major = Minor = Micro = 0;
5070   if (Str.empty())
5071     return false;
5072 
5073   if (Str.consumeInteger(10, Major))
5074     return false;
5075   if (Str.empty())
5076     return true;
5077   if (Str[0] != '.')
5078     return false;
5079 
5080   Str = Str.drop_front(1);
5081 
5082   if (Str.consumeInteger(10, Minor))
5083     return false;
5084   if (Str.empty())
5085     return true;
5086   if (Str[0] != '.')
5087     return false;
5088   Str = Str.drop_front(1);
5089 
5090   if (Str.consumeInteger(10, Micro))
5091     return false;
5092   if (!Str.empty())
5093     HadExtra = true;
5094   return true;
5095 }
5096 
5097 /// Parse digits from a string \p Str and fulfill \p Digits with
5098 /// the parsed numbers. This method assumes that the max number of
5099 /// digits to look for is equal to Digits.size().
5100 ///
5101 /// \return True if the entire string was parsed and there are
5102 /// no extra characters remaining at the end.
5103 bool Driver::GetReleaseVersion(StringRef Str,
5104                                MutableArrayRef<unsigned> Digits) {
5105   if (Str.empty())
5106     return false;
5107 
5108   unsigned CurDigit = 0;
5109   while (CurDigit < Digits.size()) {
5110     unsigned Digit;
5111     if (Str.consumeInteger(10, Digit))
5112       return false;
5113     Digits[CurDigit] = Digit;
5114     if (Str.empty())
5115       return true;
5116     if (Str[0] != '.')
5117       return false;
5118     Str = Str.drop_front(1);
5119     CurDigit++;
5120   }
5121 
5122   // More digits than requested, bail out...
5123   return false;
5124 }
5125 
5126 std::pair<unsigned, unsigned>
5127 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
5128   unsigned IncludedFlagsBitmask = 0;
5129   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
5130 
5131   if (IsClCompatMode) {
5132     // Include CL and Core options.
5133     IncludedFlagsBitmask |= options::CLOption;
5134     IncludedFlagsBitmask |= options::CoreOption;
5135   } else {
5136     ExcludedFlagsBitmask |= options::CLOption;
5137   }
5138 
5139   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
5140 }
5141 
5142 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
5143   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
5144 }
5145 
5146 bool clang::driver::willEmitRemarks(const ArgList &Args) {
5147   // -fsave-optimization-record enables it.
5148   if (Args.hasFlag(options::OPT_fsave_optimization_record,
5149                    options::OPT_fno_save_optimization_record, false))
5150     return true;
5151 
5152   // -fsave-optimization-record=<format> enables it as well.
5153   if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5154                    options::OPT_fno_save_optimization_record, false))
5155     return true;
5156 
5157   // -foptimization-record-file alone enables it too.
5158   if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
5159                    options::OPT_fno_save_optimization_record, false))
5160     return true;
5161 
5162   // -foptimization-record-passes alone enables it too.
5163   if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5164                    options::OPT_fno_save_optimization_record, false))
5165     return true;
5166   return false;
5167 }
5168