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