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