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