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