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