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