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