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