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