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