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