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