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