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