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