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