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_insensitive("rv32"))
595       Target.setArch(llvm::Triple::riscv32);
596     else if (ArchName.startswith_insensitive("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_insensitive(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 || !IsNVIDIAGpuArch(Arch)) {
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 (C.getDriver().isUsingLTO(/*IsOffload=*/true)) {
2977             // When LTO is enabled, skip the backend and assemble phases and
2978             // use lld to link the bitcode.
2979             ActionList AL;
2980             AL.push_back(CudaDeviceActions[I]);
2981             // Create a link action to link device IR with device library
2982             // and generate ISA.
2983             CudaDeviceActions[I] =
2984                 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2985           } else {
2986             // When LTO is not enabled, we follow the conventional
2987             // compiler phases, including backend and assemble phases.
2988             ActionList AL;
2989             auto BackendAction = C.getDriver().ConstructPhaseAction(
2990                 C, Args, phases::Backend, CudaDeviceActions[I],
2991                 AssociatedOffloadKind);
2992             auto AssembleAction = C.getDriver().ConstructPhaseAction(
2993                 C, Args, phases::Assemble, BackendAction,
2994                 AssociatedOffloadKind);
2995             AL.push_back(AssembleAction);
2996             // Create a link action to link device IR with device library
2997             // and generate ISA.
2998             CudaDeviceActions[I] =
2999                 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3000           }
3001 
3002           // OffloadingActionBuilder propagates device arch until an offload
3003           // action. Since the next action for creating fatbin does
3004           // not have device arch, whereas the above link action and its input
3005           // have device arch, an offload action is needed to stop the null
3006           // device arch of the next action being propagated to the above link
3007           // action.
3008           OffloadAction::DeviceDependences DDep;
3009           DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3010                    AssociatedOffloadKind);
3011           CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3012               DDep, CudaDeviceActions[I]->getType());
3013         }
3014 
3015         if (!CompileDeviceOnly || !BundleOutput.hasValue() ||
3016             BundleOutput.getValue()) {
3017           // Create HIP fat binary with a special "link" action.
3018           CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions,
3019                                                       types::TY_HIP_FATBIN);
3020 
3021           if (!CompileDeviceOnly) {
3022             DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3023                    AssociatedOffloadKind);
3024             // Clear the fat binary, it is already a dependence to an host
3025             // action.
3026             CudaFatBinary = nullptr;
3027           }
3028 
3029           // Remove the CUDA actions as they are already connected to an host
3030           // action or fat binary.
3031           CudaDeviceActions.clear();
3032         }
3033 
3034         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3035       } else if (CurPhase == phases::Link) {
3036         // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
3037         // This happens to each device action originated from each input file.
3038         // Later on, device actions in DeviceLinkerInputs are used to create
3039         // device link actions in appendLinkDependences and the created device
3040         // link actions are passed to the offload action as device dependence.
3041         DeviceLinkerInputs.resize(CudaDeviceActions.size());
3042         auto LI = DeviceLinkerInputs.begin();
3043         for (auto *A : CudaDeviceActions) {
3044           LI->push_back(A);
3045           ++LI;
3046         }
3047 
3048         // We will pass the device action as a host dependence, so we don't
3049         // need to do anything else with them.
3050         CudaDeviceActions.clear();
3051         return ABRT_Success;
3052       }
3053 
3054       // By default, we produce an action for each device arch.
3055       for (Action *&A : CudaDeviceActions)
3056         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
3057                                                AssociatedOffloadKind);
3058 
3059       if (CompileDeviceOnly && CurPhase == FinalPhase &&
3060           BundleOutput.hasValue() && BundleOutput.getValue()) {
3061         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3062           OffloadAction::DeviceDependences DDep;
3063           DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3064                    AssociatedOffloadKind);
3065           CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3066               DDep, CudaDeviceActions[I]->getType());
3067         }
3068         CudaFatBinary =
3069             C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions);
3070         CudaDeviceActions.clear();
3071       }
3072 
3073       return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
3074                                                            : ABRT_Success;
3075     }
3076 
3077     void appendLinkDeviceActions(ActionList &AL) override {
3078       if (DeviceLinkerInputs.size() == 0)
3079         return;
3080 
3081       assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
3082              "Linker inputs and GPU arch list sizes do not match.");
3083 
3084       // Append a new link action for each device.
3085       unsigned I = 0;
3086       for (auto &LI : DeviceLinkerInputs) {
3087         // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
3088         auto *DeviceLinkAction =
3089             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
3090         // Linking all inputs for the current GPU arch.
3091         // LI contains all the inputs for the linker.
3092         OffloadAction::DeviceDependences DeviceLinkDeps;
3093         DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
3094             GpuArchList[I], AssociatedOffloadKind);
3095         AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
3096             DeviceLinkAction->getType()));
3097         ++I;
3098       }
3099       DeviceLinkerInputs.clear();
3100 
3101       // Create a host object from all the device images by embedding them
3102       // in a fat binary.
3103       OffloadAction::DeviceDependences DDeps;
3104       auto *TopDeviceLinkAction =
3105           C.MakeAction<LinkJobAction>(AL, types::TY_Object);
3106       DDeps.add(*TopDeviceLinkAction, *ToolChains[0],
3107           nullptr, AssociatedOffloadKind);
3108 
3109       // Offload the host object to the host linker.
3110       AL.push_back(C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
3111     }
3112 
3113     Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
3114 
3115     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3116   };
3117 
3118   /// OpenMP action builder. The host bitcode is passed to the device frontend
3119   /// and all the device linked images are passed to the host link phase.
3120   class OpenMPActionBuilder final : public DeviceActionBuilder {
3121     /// The OpenMP actions for the current input.
3122     ActionList OpenMPDeviceActions;
3123 
3124     /// The linker inputs obtained for each toolchain.
3125     SmallVector<ActionList, 8> DeviceLinkerInputs;
3126 
3127   public:
3128     OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
3129                         const Driver::InputList &Inputs)
3130         : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
3131 
3132     ActionBuilderReturnCode
3133     getDeviceDependences(OffloadAction::DeviceDependences &DA,
3134                          phases::ID CurPhase, phases::ID FinalPhase,
3135                          PhasesTy &Phases) override {
3136       if (OpenMPDeviceActions.empty())
3137         return ABRT_Inactive;
3138 
3139       // We should always have an action for each input.
3140       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
3141              "Number of OpenMP actions and toolchains do not match.");
3142 
3143       // The host only depends on device action in the linking phase, when all
3144       // the device images have to be embedded in the host image.
3145       if (CurPhase == phases::Link) {
3146         assert(ToolChains.size() == DeviceLinkerInputs.size() &&
3147                "Toolchains and linker inputs sizes do not match.");
3148         auto LI = DeviceLinkerInputs.begin();
3149         for (auto *A : OpenMPDeviceActions) {
3150           LI->push_back(A);
3151           ++LI;
3152         }
3153 
3154         // We passed the device action as a host dependence, so we don't need to
3155         // do anything else with them.
3156         OpenMPDeviceActions.clear();
3157         return ABRT_Success;
3158       }
3159 
3160       // By default, we produce an action for each device arch.
3161       for (Action *&A : OpenMPDeviceActions)
3162         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
3163 
3164       return ABRT_Success;
3165     }
3166 
3167     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
3168 
3169       // If this is an input action replicate it for each OpenMP toolchain.
3170       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
3171         OpenMPDeviceActions.clear();
3172         for (unsigned I = 0; I < ToolChains.size(); ++I)
3173           OpenMPDeviceActions.push_back(
3174               C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
3175         return ABRT_Success;
3176       }
3177 
3178       // If this is an unbundling action use it as is for each OpenMP toolchain.
3179       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
3180         OpenMPDeviceActions.clear();
3181         auto *IA = cast<InputAction>(UA->getInputs().back());
3182         std::string FileName = IA->getInputArg().getAsString(Args);
3183         // Check if the type of the file is the same as the action. Do not
3184         // unbundle it if it is not. Do not unbundle .so files, for example,
3185         // which are not object files.
3186         if (IA->getType() == types::TY_Object &&
3187             (!llvm::sys::path::has_extension(FileName) ||
3188              types::lookupTypeForExtension(
3189                  llvm::sys::path::extension(FileName).drop_front()) !=
3190                  types::TY_Object))
3191           return ABRT_Inactive;
3192         for (unsigned I = 0; I < ToolChains.size(); ++I) {
3193           OpenMPDeviceActions.push_back(UA);
3194           UA->registerDependentActionInfo(
3195               ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
3196         }
3197         return ABRT_Success;
3198       }
3199 
3200       // When generating code for OpenMP we use the host compile phase result as
3201       // a dependence to the device compile phase so that it can learn what
3202       // declarations should be emitted. However, this is not the only use for
3203       // the host action, so we prevent it from being collapsed.
3204       if (isa<CompileJobAction>(HostAction)) {
3205         HostAction->setCannotBeCollapsedWithNextDependentAction();
3206         assert(ToolChains.size() == OpenMPDeviceActions.size() &&
3207                "Toolchains and device action sizes do not match.");
3208         OffloadAction::HostDependence HDep(
3209             *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3210             /*BoundArch=*/nullptr, Action::OFK_OpenMP);
3211         auto TC = ToolChains.begin();
3212         for (Action *&A : OpenMPDeviceActions) {
3213           assert(isa<CompileJobAction>(A));
3214           OffloadAction::DeviceDependences DDep;
3215           DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
3216           A = C.MakeAction<OffloadAction>(HDep, DDep);
3217           ++TC;
3218         }
3219       }
3220       return ABRT_Success;
3221     }
3222 
3223     void appendTopLevelActions(ActionList &AL) override {
3224       if (OpenMPDeviceActions.empty())
3225         return;
3226 
3227       // We should always have an action for each input.
3228       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
3229              "Number of OpenMP actions and toolchains do not match.");
3230 
3231       // Append all device actions followed by the proper offload action.
3232       auto TI = ToolChains.begin();
3233       for (auto *A : OpenMPDeviceActions) {
3234         OffloadAction::DeviceDependences Dep;
3235         Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
3236         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
3237         ++TI;
3238       }
3239       // We no longer need the action stored in this builder.
3240       OpenMPDeviceActions.clear();
3241     }
3242 
3243     void appendLinkDeviceActions(ActionList &AL) override {
3244       assert(ToolChains.size() == DeviceLinkerInputs.size() &&
3245              "Toolchains and linker inputs sizes do not match.");
3246 
3247       // Append a new link action for each device.
3248       auto TC = ToolChains.begin();
3249       for (auto &LI : DeviceLinkerInputs) {
3250         auto *DeviceLinkAction =
3251             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
3252         OffloadAction::DeviceDependences DeviceLinkDeps;
3253         DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
3254 		        Action::OFK_OpenMP);
3255         AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
3256             DeviceLinkAction->getType()));
3257         ++TC;
3258       }
3259       DeviceLinkerInputs.clear();
3260     }
3261 
3262     Action* appendLinkHostActions(ActionList &AL) override {
3263       // Create wrapper bitcode from the result of device link actions and compile
3264       // it to an object which will be added to the host link command.
3265       auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC);
3266       auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
3267       return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
3268     }
3269 
3270     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3271 
3272     bool initialize() override {
3273       // Get the OpenMP toolchains. If we don't get any, the action builder will
3274       // know there is nothing to do related to OpenMP offloading.
3275       auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
3276       for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
3277            ++TI)
3278         ToolChains.push_back(TI->second);
3279 
3280       DeviceLinkerInputs.resize(ToolChains.size());
3281       return false;
3282     }
3283 
3284     bool canUseBundlerUnbundler() const override {
3285       // OpenMP should use bundled files whenever possible.
3286       return true;
3287     }
3288   };
3289 
3290   ///
3291   /// TODO: Add the implementation for other specialized builders here.
3292   ///
3293 
3294   /// Specialized builders being used by this offloading action builder.
3295   SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3296 
3297   /// Flag set to true if all valid builders allow file bundling/unbundling.
3298   bool CanUseBundler;
3299 
3300 public:
3301   OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3302                           const Driver::InputList &Inputs)
3303       : C(C) {
3304     // Create a specialized builder for each device toolchain.
3305 
3306     IsValid = true;
3307 
3308     // Create a specialized builder for CUDA.
3309     SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3310 
3311     // Create a specialized builder for HIP.
3312     SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3313 
3314     // Create a specialized builder for OpenMP.
3315     SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
3316 
3317     //
3318     // TODO: Build other specialized builders here.
3319     //
3320 
3321     // Initialize all the builders, keeping track of errors. If all valid
3322     // builders agree that we can use bundling, set the flag to true.
3323     unsigned ValidBuilders = 0u;
3324     unsigned ValidBuildersSupportingBundling = 0u;
3325     for (auto *SB : SpecializedBuilders) {
3326       IsValid = IsValid && !SB->initialize();
3327 
3328       // Update the counters if the builder is valid.
3329       if (SB->isValid()) {
3330         ++ValidBuilders;
3331         if (SB->canUseBundlerUnbundler())
3332           ++ValidBuildersSupportingBundling;
3333       }
3334     }
3335     CanUseBundler =
3336         ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3337   }
3338 
3339   ~OffloadingActionBuilder() {
3340     for (auto *SB : SpecializedBuilders)
3341       delete SB;
3342   }
3343 
3344   /// Generate an action that adds device dependences (if any) to a host action.
3345   /// If no device dependence actions exist, just return the host action \a
3346   /// HostAction. If an error is found or if no builder requires the host action
3347   /// to be generated, return nullptr.
3348   Action *
3349   addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3350                                    phases::ID CurPhase, phases::ID FinalPhase,
3351                                    DeviceActionBuilder::PhasesTy &Phases) {
3352     if (!IsValid)
3353       return nullptr;
3354 
3355     if (SpecializedBuilders.empty())
3356       return HostAction;
3357 
3358     assert(HostAction && "Invalid host action!");
3359 
3360     OffloadAction::DeviceDependences DDeps;
3361     // Check if all the programming models agree we should not emit the host
3362     // action. Also, keep track of the offloading kinds employed.
3363     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3364     unsigned InactiveBuilders = 0u;
3365     unsigned IgnoringBuilders = 0u;
3366     for (auto *SB : SpecializedBuilders) {
3367       if (!SB->isValid()) {
3368         ++InactiveBuilders;
3369         continue;
3370       }
3371 
3372       auto RetCode =
3373           SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3374 
3375       // If the builder explicitly says the host action should be ignored,
3376       // we need to increment the variable that tracks the builders that request
3377       // the host object to be ignored.
3378       if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3379         ++IgnoringBuilders;
3380 
3381       // Unless the builder was inactive for this action, we have to record the
3382       // offload kind because the host will have to use it.
3383       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3384         OffloadKind |= SB->getAssociatedOffloadKind();
3385     }
3386 
3387     // If all builders agree that the host object should be ignored, just return
3388     // nullptr.
3389     if (IgnoringBuilders &&
3390         SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3391       return nullptr;
3392 
3393     if (DDeps.getActions().empty())
3394       return HostAction;
3395 
3396     // We have dependences we need to bundle together. We use an offload action
3397     // for that.
3398     OffloadAction::HostDependence HDep(
3399         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3400         /*BoundArch=*/nullptr, DDeps);
3401     return C.MakeAction<OffloadAction>(HDep, DDeps);
3402   }
3403 
3404   /// Generate an action that adds a host dependence to a device action. The
3405   /// results will be kept in this action builder. Return true if an error was
3406   /// found.
3407   bool addHostDependenceToDeviceActions(Action *&HostAction,
3408                                         const Arg *InputArg) {
3409     if (!IsValid)
3410       return true;
3411 
3412     // If we are supporting bundling/unbundling and the current action is an
3413     // input action of non-source file, we replace the host action by the
3414     // unbundling action. The bundler tool has the logic to detect if an input
3415     // is a bundle or not and if the input is not a bundle it assumes it is a
3416     // host file. Therefore it is safe to create an unbundling action even if
3417     // the input is not a bundle.
3418     if (CanUseBundler && isa<InputAction>(HostAction) &&
3419         InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3420         (!types::isSrcFile(HostAction->getType()) ||
3421          HostAction->getType() == types::TY_PP_HIP)) {
3422       auto UnbundlingHostAction =
3423           C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3424       UnbundlingHostAction->registerDependentActionInfo(
3425           C.getSingleOffloadToolChain<Action::OFK_Host>(),
3426           /*BoundArch=*/StringRef(), Action::OFK_Host);
3427       HostAction = UnbundlingHostAction;
3428     }
3429 
3430     assert(HostAction && "Invalid host action!");
3431 
3432     // Register the offload kinds that are used.
3433     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3434     for (auto *SB : SpecializedBuilders) {
3435       if (!SB->isValid())
3436         continue;
3437 
3438       auto RetCode = SB->addDeviceDepences(HostAction);
3439 
3440       // Host dependences for device actions are not compatible with that same
3441       // action being ignored.
3442       assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3443              "Host dependence not expected to be ignored.!");
3444 
3445       // Unless the builder was inactive for this action, we have to record the
3446       // offload kind because the host will have to use it.
3447       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3448         OffloadKind |= SB->getAssociatedOffloadKind();
3449     }
3450 
3451     // Do not use unbundler if the Host does not depend on device action.
3452     if (OffloadKind == Action::OFK_None && CanUseBundler)
3453       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3454         HostAction = UA->getInputs().back();
3455 
3456     return false;
3457   }
3458 
3459   /// Add the offloading top level actions to the provided action list. This
3460   /// function can replace the host action by a bundling action if the
3461   /// programming models allow it.
3462   bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3463                              const Arg *InputArg) {
3464     // Get the device actions to be appended.
3465     ActionList OffloadAL;
3466     for (auto *SB : SpecializedBuilders) {
3467       if (!SB->isValid())
3468         continue;
3469       SB->appendTopLevelActions(OffloadAL);
3470     }
3471 
3472     // If we can use the bundler, replace the host action by the bundling one in
3473     // the resulting list. Otherwise, just append the device actions. For
3474     // device only compilation, HostAction is a null pointer, therefore only do
3475     // this when HostAction is not a null pointer.
3476     if (CanUseBundler && HostAction &&
3477         HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3478       // Add the host action to the list in order to create the bundling action.
3479       OffloadAL.push_back(HostAction);
3480 
3481       // We expect that the host action was just appended to the action list
3482       // before this method was called.
3483       assert(HostAction == AL.back() && "Host action not in the list??");
3484       HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3485       AL.back() = HostAction;
3486     } else
3487       AL.append(OffloadAL.begin(), OffloadAL.end());
3488 
3489     // Propagate to the current host action (if any) the offload information
3490     // associated with the current input.
3491     if (HostAction)
3492       HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3493                                            /*BoundArch=*/nullptr);
3494     return false;
3495   }
3496 
3497   Action* makeHostLinkAction() {
3498     // Build a list of device linking actions.
3499     ActionList DeviceAL;
3500     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3501       if (!SB->isValid())
3502         continue;
3503       SB->appendLinkDeviceActions(DeviceAL);
3504     }
3505 
3506     if (DeviceAL.empty())
3507       return nullptr;
3508 
3509     // Let builders add host linking actions.
3510     Action* HA = nullptr;
3511     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3512       if (!SB->isValid())
3513         continue;
3514       HA = SB->appendLinkHostActions(DeviceAL);
3515     }
3516     return HA;
3517   }
3518 
3519   /// Processes the host linker action. This currently consists of replacing it
3520   /// with an offload action if there are device link objects and propagate to
3521   /// the host action all the offload kinds used in the current compilation. The
3522   /// resulting action is returned.
3523   Action *processHostLinkAction(Action *HostAction) {
3524     // Add all the dependences from the device linking actions.
3525     OffloadAction::DeviceDependences DDeps;
3526     for (auto *SB : SpecializedBuilders) {
3527       if (!SB->isValid())
3528         continue;
3529 
3530       SB->appendLinkDependences(DDeps);
3531     }
3532 
3533     // Calculate all the offload kinds used in the current compilation.
3534     unsigned ActiveOffloadKinds = 0u;
3535     for (auto &I : InputArgToOffloadKindMap)
3536       ActiveOffloadKinds |= I.second;
3537 
3538     // If we don't have device dependencies, we don't have to create an offload
3539     // action.
3540     if (DDeps.getActions().empty()) {
3541       // Propagate all the active kinds to host action. Given that it is a link
3542       // action it is assumed to depend on all actions generated so far.
3543       HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3544                                            /*BoundArch=*/nullptr);
3545       return HostAction;
3546     }
3547 
3548     // Create the offload action with all dependences. When an offload action
3549     // is created the kinds are propagated to the host action, so we don't have
3550     // to do that explicitly here.
3551     OffloadAction::HostDependence HDep(
3552         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3553         /*BoundArch*/ nullptr, ActiveOffloadKinds);
3554     return C.MakeAction<OffloadAction>(HDep, DDeps);
3555   }
3556 };
3557 } // anonymous namespace.
3558 
3559 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3560                              const InputList &Inputs,
3561                              ActionList &Actions) const {
3562 
3563   // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3564   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3565   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3566   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3567     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3568     Args.eraseArg(options::OPT__SLASH_Yc);
3569     Args.eraseArg(options::OPT__SLASH_Yu);
3570     YcArg = YuArg = nullptr;
3571   }
3572   if (YcArg && Inputs.size() > 1) {
3573     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3574     Args.eraseArg(options::OPT__SLASH_Yc);
3575     YcArg = nullptr;
3576   }
3577 
3578   Arg *FinalPhaseArg;
3579   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3580 
3581   if (FinalPhase == phases::Link) {
3582     if (Args.hasArg(options::OPT_emit_llvm))
3583       Diag(clang::diag::err_drv_emit_llvm_link);
3584     if (IsCLMode() && LTOMode != LTOK_None &&
3585         !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
3586              .equals_insensitive("lld"))
3587       Diag(clang::diag::err_drv_lto_without_lld);
3588   }
3589 
3590   if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3591     // If only preprocessing or /Y- is used, all pch handling is disabled.
3592     // Rather than check for it everywhere, just remove clang-cl pch-related
3593     // flags here.
3594     Args.eraseArg(options::OPT__SLASH_Fp);
3595     Args.eraseArg(options::OPT__SLASH_Yc);
3596     Args.eraseArg(options::OPT__SLASH_Yu);
3597     YcArg = YuArg = nullptr;
3598   }
3599 
3600   unsigned LastPLSize = 0;
3601   for (auto &I : Inputs) {
3602     types::ID InputType = I.first;
3603     const Arg *InputArg = I.second;
3604 
3605     auto PL = types::getCompilationPhases(InputType);
3606     LastPLSize = PL.size();
3607 
3608     // If the first step comes after the final phase we are doing as part of
3609     // this compilation, warn the user about it.
3610     phases::ID InitialPhase = PL[0];
3611     if (InitialPhase > FinalPhase) {
3612       if (InputArg->isClaimed())
3613         continue;
3614 
3615       // Claim here to avoid the more general unused warning.
3616       InputArg->claim();
3617 
3618       // Suppress all unused style warnings with -Qunused-arguments
3619       if (Args.hasArg(options::OPT_Qunused_arguments))
3620         continue;
3621 
3622       // Special case when final phase determined by binary name, rather than
3623       // by a command-line argument with a corresponding Arg.
3624       if (CCCIsCPP())
3625         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3626             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3627       // Special case '-E' warning on a previously preprocessed file to make
3628       // more sense.
3629       else if (InitialPhase == phases::Compile &&
3630                (Args.getLastArg(options::OPT__SLASH_EP,
3631                                 options::OPT__SLASH_P) ||
3632                 Args.getLastArg(options::OPT_E) ||
3633                 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3634                getPreprocessedType(InputType) == types::TY_INVALID)
3635         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3636             << InputArg->getAsString(Args) << !!FinalPhaseArg
3637             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3638       else
3639         Diag(clang::diag::warn_drv_input_file_unused)
3640             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3641             << !!FinalPhaseArg
3642             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3643       continue;
3644     }
3645 
3646     if (YcArg) {
3647       // Add a separate precompile phase for the compile phase.
3648       if (FinalPhase >= phases::Compile) {
3649         const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3650         // Build the pipeline for the pch file.
3651         Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3652         for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3653           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3654         assert(ClangClPch);
3655         Actions.push_back(ClangClPch);
3656         // The driver currently exits after the first failed command.  This
3657         // relies on that behavior, to make sure if the pch generation fails,
3658         // the main compilation won't run.
3659         // FIXME: If the main compilation fails, the PCH generation should
3660         // probably not be considered successful either.
3661       }
3662     }
3663   }
3664 
3665   // If we are linking, claim any options which are obviously only used for
3666   // compilation.
3667   // FIXME: Understand why the last Phase List length is used here.
3668   if (FinalPhase == phases::Link && LastPLSize == 1) {
3669     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3670     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3671   }
3672 }
3673 
3674 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3675                           const InputList &Inputs, ActionList &Actions) const {
3676   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3677 
3678   if (!SuppressMissingInputWarning && Inputs.empty()) {
3679     Diag(clang::diag::err_drv_no_input_files);
3680     return;
3681   }
3682 
3683   // Reject -Z* at the top level, these options should never have been exposed
3684   // by gcc.
3685   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3686     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3687 
3688   // Diagnose misuse of /Fo.
3689   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3690     StringRef V = A->getValue();
3691     if (Inputs.size() > 1 && !V.empty() &&
3692         !llvm::sys::path::is_separator(V.back())) {
3693       // Check whether /Fo tries to name an output file for multiple inputs.
3694       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3695           << A->getSpelling() << V;
3696       Args.eraseArg(options::OPT__SLASH_Fo);
3697     }
3698   }
3699 
3700   // Diagnose misuse of /Fa.
3701   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3702     StringRef V = A->getValue();
3703     if (Inputs.size() > 1 && !V.empty() &&
3704         !llvm::sys::path::is_separator(V.back())) {
3705       // Check whether /Fa tries to name an asm file for multiple inputs.
3706       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3707           << A->getSpelling() << V;
3708       Args.eraseArg(options::OPT__SLASH_Fa);
3709     }
3710   }
3711 
3712   // Diagnose misuse of /o.
3713   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3714     if (A->getValue()[0] == '\0') {
3715       // It has to have a value.
3716       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3717       Args.eraseArg(options::OPT__SLASH_o);
3718     }
3719   }
3720 
3721   handleArguments(C, Args, Inputs, Actions);
3722 
3723   // Builder to be used to build offloading actions.
3724   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3725 
3726   // Construct the actions to perform.
3727   HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3728   ActionList LinkerInputs;
3729   ActionList MergerInputs;
3730 
3731   for (auto &I : Inputs) {
3732     types::ID InputType = I.first;
3733     const Arg *InputArg = I.second;
3734 
3735     auto PL = types::getCompilationPhases(*this, Args, InputType);
3736     if (PL.empty())
3737       continue;
3738 
3739     auto FullPL = types::getCompilationPhases(InputType);
3740 
3741     // Build the pipeline for this file.
3742     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3743 
3744     // Use the current host action in any of the offloading actions, if
3745     // required.
3746     if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3747       break;
3748 
3749     for (phases::ID Phase : PL) {
3750 
3751       // Add any offload action the host action depends on.
3752       Current = OffloadBuilder.addDeviceDependencesToHostAction(
3753           Current, InputArg, Phase, PL.back(), FullPL);
3754       if (!Current)
3755         break;
3756 
3757       // Queue linker inputs.
3758       if (Phase == phases::Link) {
3759         assert(Phase == PL.back() && "linking must be final compilation step.");
3760         LinkerInputs.push_back(Current);
3761         Current = nullptr;
3762         break;
3763       }
3764 
3765       // TODO: Consider removing this because the merged may not end up being
3766       // the final Phase in the pipeline. Perhaps the merged could just merge
3767       // and then pass an artifact of some sort to the Link Phase.
3768       // Queue merger inputs.
3769       if (Phase == phases::IfsMerge) {
3770         assert(Phase == PL.back() && "merging must be final compilation step.");
3771         MergerInputs.push_back(Current);
3772         Current = nullptr;
3773         break;
3774       }
3775 
3776       // Each precompiled header file after a module file action is a module
3777       // header of that same module file, rather than being compiled to a
3778       // separate PCH.
3779       if (Phase == phases::Precompile && HeaderModuleAction &&
3780           getPrecompiledType(InputType) == types::TY_PCH) {
3781         HeaderModuleAction->addModuleHeaderInput(Current);
3782         Current = nullptr;
3783         break;
3784       }
3785 
3786       // FIXME: Should we include any prior module file outputs as inputs of
3787       // later actions in the same command line?
3788 
3789       // Otherwise construct the appropriate action.
3790       Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3791 
3792       // We didn't create a new action, so we will just move to the next phase.
3793       if (NewCurrent == Current)
3794         continue;
3795 
3796       if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3797         HeaderModuleAction = HMA;
3798 
3799       Current = NewCurrent;
3800 
3801       // Use the current host action in any of the offloading actions, if
3802       // required.
3803       if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3804         break;
3805 
3806       if (Current->getType() == types::TY_Nothing)
3807         break;
3808     }
3809 
3810     // If we ended with something, add to the output list.
3811     if (Current)
3812       Actions.push_back(Current);
3813 
3814     // Add any top level actions generated for offloading.
3815     OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3816   }
3817 
3818   // Add a link action if necessary.
3819   if (!LinkerInputs.empty()) {
3820     if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
3821       LinkerInputs.push_back(Wrapper);
3822     Action *LA;
3823     // Check if this Linker Job should emit a static library.
3824     if (ShouldEmitStaticLibrary(Args)) {
3825       LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
3826     } else {
3827       LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3828     }
3829     LA = OffloadBuilder.processHostLinkAction(LA);
3830     Actions.push_back(LA);
3831   }
3832 
3833   // Add an interface stubs merge action if necessary.
3834   if (!MergerInputs.empty())
3835     Actions.push_back(
3836         C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3837 
3838   if (Args.hasArg(options::OPT_emit_interface_stubs)) {
3839     auto PhaseList = types::getCompilationPhases(
3840         types::TY_IFS_CPP,
3841         Args.hasArg(options::OPT_c) ? phases::Compile : phases::LastPhase);
3842 
3843     ActionList MergerInputs;
3844 
3845     for (auto &I : Inputs) {
3846       types::ID InputType = I.first;
3847       const Arg *InputArg = I.second;
3848 
3849       // Currently clang and the llvm assembler do not support generating symbol
3850       // stubs from assembly, so we skip the input on asm files. For ifs files
3851       // we rely on the normal pipeline setup in the pipeline setup code above.
3852       if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
3853           InputType == types::TY_Asm)
3854         continue;
3855 
3856       Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3857 
3858       for (auto Phase : PhaseList) {
3859         switch (Phase) {
3860         default:
3861           llvm_unreachable(
3862               "IFS Pipeline can only consist of Compile followed by IfsMerge.");
3863         case phases::Compile: {
3864           // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
3865           // files where the .o file is located. The compile action can not
3866           // handle this.
3867           if (InputType == types::TY_Object)
3868             break;
3869 
3870           Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
3871           break;
3872         }
3873         case phases::IfsMerge: {
3874           assert(Phase == PhaseList.back() &&
3875                  "merging must be final compilation step.");
3876           MergerInputs.push_back(Current);
3877           Current = nullptr;
3878           break;
3879         }
3880         }
3881       }
3882 
3883       // If we ended with something, add to the output list.
3884       if (Current)
3885         Actions.push_back(Current);
3886     }
3887 
3888     // Add an interface stubs merge action if necessary.
3889     if (!MergerInputs.empty())
3890       Actions.push_back(
3891           C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3892   }
3893 
3894   // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
3895   // Compile phase that prints out supported cpu models and quits.
3896   if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
3897     // Use the -mcpu=? flag as the dummy input to cc1.
3898     Actions.clear();
3899     Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
3900     Actions.push_back(
3901         C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
3902     for (auto &I : Inputs)
3903       I.second->claim();
3904   }
3905 
3906   // Claim ignored clang-cl options.
3907   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3908 
3909   // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3910   // to non-CUDA compilations and should not trigger warnings there.
3911   Args.ClaimAllArgs(options::OPT_cuda_host_only);
3912   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3913 }
3914 
3915 Action *Driver::ConstructPhaseAction(
3916     Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3917     Action::OffloadKind TargetDeviceOffloadKind) const {
3918   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3919 
3920   // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3921   // encode this in the steps because the intermediate type depends on
3922   // arguments. Just special case here.
3923   if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3924     return Input;
3925 
3926   // Build the appropriate action.
3927   switch (Phase) {
3928   case phases::Link:
3929     llvm_unreachable("link action invalid here.");
3930   case phases::IfsMerge:
3931     llvm_unreachable("ifsmerge action invalid here.");
3932   case phases::Preprocess: {
3933     types::ID OutputTy;
3934     // -M and -MM specify the dependency file name by altering the output type,
3935     // -if -MD and -MMD are not specified.
3936     if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
3937         !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
3938       OutputTy = types::TY_Dependencies;
3939     } else {
3940       OutputTy = Input->getType();
3941       if (!Args.hasFlag(options::OPT_frewrite_includes,
3942                         options::OPT_fno_rewrite_includes, false) &&
3943           !Args.hasFlag(options::OPT_frewrite_imports,
3944                         options::OPT_fno_rewrite_imports, false) &&
3945           !CCGenDiagnostics)
3946         OutputTy = types::getPreprocessedType(OutputTy);
3947       assert(OutputTy != types::TY_INVALID &&
3948              "Cannot preprocess this input type!");
3949     }
3950     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3951   }
3952   case phases::Precompile: {
3953     types::ID OutputTy = getPrecompiledType(Input->getType());
3954     assert(OutputTy != types::TY_INVALID &&
3955            "Cannot precompile this input type!");
3956 
3957     // If we're given a module name, precompile header file inputs as a
3958     // module, not as a precompiled header.
3959     const char *ModName = nullptr;
3960     if (OutputTy == types::TY_PCH) {
3961       if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3962         ModName = A->getValue();
3963       if (ModName)
3964         OutputTy = types::TY_ModuleFile;
3965     }
3966 
3967     if (Args.hasArg(options::OPT_fsyntax_only)) {
3968       // Syntax checks should not emit a PCH file
3969       OutputTy = types::TY_Nothing;
3970     }
3971 
3972     if (ModName)
3973       return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3974                                                            ModName);
3975     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3976   }
3977   case phases::Compile: {
3978     if (Args.hasArg(options::OPT_fsyntax_only))
3979       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3980     if (Args.hasArg(options::OPT_rewrite_objc))
3981       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3982     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3983       return C.MakeAction<CompileJobAction>(Input,
3984                                             types::TY_RewrittenLegacyObjC);
3985     if (Args.hasArg(options::OPT__analyze))
3986       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3987     if (Args.hasArg(options::OPT__migrate))
3988       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3989     if (Args.hasArg(options::OPT_emit_ast))
3990       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3991     if (Args.hasArg(options::OPT_module_file_info))
3992       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3993     if (Args.hasArg(options::OPT_verify_pch))
3994       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3995     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3996   }
3997   case phases::Backend: {
3998     if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3999       types::ID Output =
4000           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4001       return C.MakeAction<BackendJobAction>(Input, Output);
4002     }
4003     if (Args.hasArg(options::OPT_emit_llvm) ||
4004         (TargetDeviceOffloadKind == Action::OFK_HIP &&
4005          Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4006                       false))) {
4007       types::ID Output =
4008           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
4009       return C.MakeAction<BackendJobAction>(Input, Output);
4010     }
4011     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
4012   }
4013   case phases::Assemble:
4014     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
4015   }
4016 
4017   llvm_unreachable("invalid phase in ConstructPhaseAction");
4018 }
4019 
4020 void Driver::BuildJobs(Compilation &C) const {
4021   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4022 
4023   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4024 
4025   // It is an error to provide a -o option if we are making multiple output
4026   // files. There are exceptions:
4027   //
4028   // IfsMergeJob: when generating interface stubs enabled we want to be able to
4029   // generate the stub file at the same time that we generate the real
4030   // library/a.out. So when a .o, .so, etc are the output, with clang interface
4031   // stubs there will also be a .ifs and .ifso at the same location.
4032   //
4033   // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
4034   // and -c is passed, we still want to be able to generate a .ifs file while
4035   // we are also generating .o files. So we allow more than one output file in
4036   // this case as well.
4037   //
4038   if (FinalOutput) {
4039     unsigned NumOutputs = 0;
4040     unsigned NumIfsOutputs = 0;
4041     for (const Action *A : C.getActions())
4042       if (A->getType() != types::TY_Nothing &&
4043           !(A->getKind() == Action::IfsMergeJobClass ||
4044             (A->getType() == clang::driver::types::TY_IFS_CPP &&
4045              A->getKind() == clang::driver::Action::CompileJobClass &&
4046              0 == NumIfsOutputs++) ||
4047             (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
4048              A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
4049         ++NumOutputs;
4050 
4051     if (NumOutputs > 1) {
4052       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
4053       FinalOutput = nullptr;
4054     }
4055   }
4056 
4057   const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
4058   if (RawTriple.isOSAIX()) {
4059     if (Arg *A = C.getArgs().getLastArg(options::OPT_G))
4060       Diag(diag::err_drv_unsupported_opt_for_target)
4061           << A->getSpelling() << RawTriple.str();
4062     if (LTOMode == LTOK_Thin)
4063       Diag(diag::err_drv_clang_unsupported) << "thinLTO on AIX";
4064   }
4065 
4066   // Collect the list of architectures.
4067   llvm::StringSet<> ArchNames;
4068   if (RawTriple.isOSBinFormatMachO())
4069     for (const Arg *A : C.getArgs())
4070       if (A->getOption().matches(options::OPT_arch))
4071         ArchNames.insert(A->getValue());
4072 
4073   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
4074   std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
4075   for (Action *A : C.getActions()) {
4076     // If we are linking an image for multiple archs then the linker wants
4077     // -arch_multiple and -final_output <final image name>. Unfortunately, this
4078     // doesn't fit in cleanly because we have to pass this information down.
4079     //
4080     // FIXME: This is a hack; find a cleaner way to integrate this into the
4081     // process.
4082     const char *LinkingOutput = nullptr;
4083     if (isa<LipoJobAction>(A)) {
4084       if (FinalOutput)
4085         LinkingOutput = FinalOutput->getValue();
4086       else
4087         LinkingOutput = getDefaultImageName();
4088     }
4089 
4090     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
4091                        /*BoundArch*/ StringRef(),
4092                        /*AtTopLevel*/ true,
4093                        /*MultipleArchs*/ ArchNames.size() > 1,
4094                        /*LinkingOutput*/ LinkingOutput, CachedResults,
4095                        /*TargetDeviceOffloadKind*/ Action::OFK_None);
4096   }
4097 
4098   // If we have more than one job, then disable integrated-cc1 for now. Do this
4099   // also when we need to report process execution statistics.
4100   if (C.getJobs().size() > 1 || CCPrintProcessStats)
4101     for (auto &J : C.getJobs())
4102       J.InProcess = false;
4103 
4104   if (CCPrintProcessStats) {
4105     C.setPostCallback([=](const Command &Cmd, int Res) {
4106       Optional<llvm::sys::ProcessStatistics> ProcStat =
4107           Cmd.getProcessStatistics();
4108       if (!ProcStat)
4109         return;
4110 
4111       const char *LinkingOutput = nullptr;
4112       if (FinalOutput)
4113         LinkingOutput = FinalOutput->getValue();
4114       else if (!Cmd.getOutputFilenames().empty())
4115         LinkingOutput = Cmd.getOutputFilenames().front().c_str();
4116       else
4117         LinkingOutput = getDefaultImageName();
4118 
4119       if (CCPrintStatReportFilename.empty()) {
4120         using namespace llvm;
4121         // Human readable output.
4122         outs() << sys::path::filename(Cmd.getExecutable()) << ": "
4123                << "output=" << LinkingOutput;
4124         outs() << ", total="
4125                << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
4126                << ", user="
4127                << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
4128                << ", mem=" << ProcStat->PeakMemory << " Kb\n";
4129       } else {
4130         // CSV format.
4131         std::string Buffer;
4132         llvm::raw_string_ostream Out(Buffer);
4133         llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
4134                             /*Quote*/ true);
4135         Out << ',';
4136         llvm::sys::printArg(Out, LinkingOutput, true);
4137         Out << ',' << ProcStat->TotalTime.count() << ','
4138             << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
4139             << '\n';
4140         Out.flush();
4141         std::error_code EC;
4142         llvm::raw_fd_ostream OS(CCPrintStatReportFilename.c_str(), EC,
4143                                 llvm::sys::fs::OF_Append |
4144                                     llvm::sys::fs::OF_Text);
4145         if (EC)
4146           return;
4147         auto L = OS.lock();
4148         if (!L) {
4149           llvm::errs() << "ERROR: Cannot lock file "
4150                        << CCPrintStatReportFilename << ": "
4151                        << toString(L.takeError()) << "\n";
4152           return;
4153         }
4154         OS << Buffer;
4155         OS.flush();
4156       }
4157     });
4158   }
4159 
4160   // If the user passed -Qunused-arguments or there were errors, don't warn
4161   // about any unused arguments.
4162   if (Diags.hasErrorOccurred() ||
4163       C.getArgs().hasArg(options::OPT_Qunused_arguments))
4164     return;
4165 
4166   // Claim -### here.
4167   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4168 
4169   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4170   (void)C.getArgs().hasArg(options::OPT_driver_mode);
4171   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4172 
4173   for (Arg *A : C.getArgs()) {
4174     // FIXME: It would be nice to be able to send the argument to the
4175     // DiagnosticsEngine, so that extra values, position, and so on could be
4176     // printed.
4177     if (!A->isClaimed()) {
4178       if (A->getOption().hasFlag(options::NoArgumentUnused))
4179         continue;
4180 
4181       // Suppress the warning automatically if this is just a flag, and it is an
4182       // instance of an argument we already claimed.
4183       const Option &Opt = A->getOption();
4184       if (Opt.getKind() == Option::FlagClass) {
4185         bool DuplicateClaimed = false;
4186 
4187         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4188           if (AA->isClaimed()) {
4189             DuplicateClaimed = true;
4190             break;
4191           }
4192         }
4193 
4194         if (DuplicateClaimed)
4195           continue;
4196       }
4197 
4198       // In clang-cl, don't mention unknown arguments here since they have
4199       // already been warned about.
4200       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
4201         Diag(clang::diag::warn_drv_unused_argument)
4202             << A->getAsString(C.getArgs());
4203     }
4204   }
4205 }
4206 
4207 namespace {
4208 /// Utility class to control the collapse of dependent actions and select the
4209 /// tools accordingly.
4210 class ToolSelector final {
4211   /// The tool chain this selector refers to.
4212   const ToolChain &TC;
4213 
4214   /// The compilation this selector refers to.
4215   const Compilation &C;
4216 
4217   /// The base action this selector refers to.
4218   const JobAction *BaseAction;
4219 
4220   /// Set to true if the current toolchain refers to host actions.
4221   bool IsHostSelector;
4222 
4223   /// Set to true if save-temps and embed-bitcode functionalities are active.
4224   bool SaveTemps;
4225   bool EmbedBitcode;
4226 
4227   /// Get previous dependent action or null if that does not exist. If
4228   /// \a CanBeCollapsed is false, that action must be legal to collapse or
4229   /// null will be returned.
4230   const JobAction *getPrevDependentAction(const ActionList &Inputs,
4231                                           ActionList &SavedOffloadAction,
4232                                           bool CanBeCollapsed = true) {
4233     // An option can be collapsed only if it has a single input.
4234     if (Inputs.size() != 1)
4235       return nullptr;
4236 
4237     Action *CurAction = *Inputs.begin();
4238     if (CanBeCollapsed &&
4239         !CurAction->isCollapsingWithNextDependentActionLegal())
4240       return nullptr;
4241 
4242     // If the input action is an offload action. Look through it and save any
4243     // offload action that can be dropped in the event of a collapse.
4244     if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
4245       // If the dependent action is a device action, we will attempt to collapse
4246       // only with other device actions. Otherwise, we would do the same but
4247       // with host actions only.
4248       if (!IsHostSelector) {
4249         if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
4250           CurAction =
4251               OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
4252           if (CanBeCollapsed &&
4253               !CurAction->isCollapsingWithNextDependentActionLegal())
4254             return nullptr;
4255           SavedOffloadAction.push_back(OA);
4256           return dyn_cast<JobAction>(CurAction);
4257         }
4258       } else if (OA->hasHostDependence()) {
4259         CurAction = OA->getHostDependence();
4260         if (CanBeCollapsed &&
4261             !CurAction->isCollapsingWithNextDependentActionLegal())
4262           return nullptr;
4263         SavedOffloadAction.push_back(OA);
4264         return dyn_cast<JobAction>(CurAction);
4265       }
4266       return nullptr;
4267     }
4268 
4269     return dyn_cast<JobAction>(CurAction);
4270   }
4271 
4272   /// Return true if an assemble action can be collapsed.
4273   bool canCollapseAssembleAction() const {
4274     return TC.useIntegratedAs() && !SaveTemps &&
4275            !C.getArgs().hasArg(options::OPT_via_file_asm) &&
4276            !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
4277            !C.getArgs().hasArg(options::OPT__SLASH_Fa);
4278   }
4279 
4280   /// Return true if a preprocessor action can be collapsed.
4281   bool canCollapsePreprocessorAction() const {
4282     return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
4283            !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
4284            !C.getArgs().hasArg(options::OPT_rewrite_objc);
4285   }
4286 
4287   /// Struct that relates an action with the offload actions that would be
4288   /// collapsed with it.
4289   struct JobActionInfo final {
4290     /// The action this info refers to.
4291     const JobAction *JA = nullptr;
4292     /// The offload actions we need to take care off if this action is
4293     /// collapsed.
4294     ActionList SavedOffloadAction;
4295   };
4296 
4297   /// Append collapsed offload actions from the give nnumber of elements in the
4298   /// action info array.
4299   static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
4300                                            ArrayRef<JobActionInfo> &ActionInfo,
4301                                            unsigned ElementNum) {
4302     assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
4303     for (unsigned I = 0; I < ElementNum; ++I)
4304       CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
4305                                     ActionInfo[I].SavedOffloadAction.end());
4306   }
4307 
4308   /// Functions that attempt to perform the combining. They detect if that is
4309   /// legal, and if so they update the inputs \a Inputs and the offload action
4310   /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
4311   /// the combined action is returned. If the combining is not legal or if the
4312   /// tool does not exist, null is returned.
4313   /// Currently three kinds of collapsing are supported:
4314   ///  - Assemble + Backend + Compile;
4315   ///  - Assemble + Backend ;
4316   ///  - Backend + Compile.
4317   const Tool *
4318   combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4319                                 ActionList &Inputs,
4320                                 ActionList &CollapsedOffloadAction) {
4321     if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
4322       return nullptr;
4323     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4324     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4325     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
4326     if (!AJ || !BJ || !CJ)
4327       return nullptr;
4328 
4329     // Get compiler tool.
4330     const Tool *T = TC.SelectTool(*CJ);
4331     if (!T)
4332       return nullptr;
4333 
4334     // When using -fembed-bitcode, it is required to have the same tool (clang)
4335     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
4336     if (EmbedBitcode) {
4337       const Tool *BT = TC.SelectTool(*BJ);
4338       if (BT == T)
4339         return nullptr;
4340     }
4341 
4342     if (!T->hasIntegratedAssembler())
4343       return nullptr;
4344 
4345     Inputs = CJ->getInputs();
4346     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4347                                  /*NumElements=*/3);
4348     return T;
4349   }
4350   const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4351                                      ActionList &Inputs,
4352                                      ActionList &CollapsedOffloadAction) {
4353     if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4354       return nullptr;
4355     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4356     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4357     if (!AJ || !BJ)
4358       return nullptr;
4359 
4360     // Get backend tool.
4361     const Tool *T = TC.SelectTool(*BJ);
4362     if (!T)
4363       return nullptr;
4364 
4365     if (!T->hasIntegratedAssembler())
4366       return nullptr;
4367 
4368     Inputs = BJ->getInputs();
4369     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4370                                  /*NumElements=*/2);
4371     return T;
4372   }
4373   const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4374                                     ActionList &Inputs,
4375                                     ActionList &CollapsedOffloadAction) {
4376     if (ActionInfo.size() < 2)
4377       return nullptr;
4378     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4379     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4380     if (!BJ || !CJ)
4381       return nullptr;
4382 
4383     // Check if the initial input (to the compile job or its predessor if one
4384     // exists) is LLVM bitcode. In that case, no preprocessor step is required
4385     // and we can still collapse the compile and backend jobs when we have
4386     // -save-temps. I.e. there is no need for a separate compile job just to
4387     // emit unoptimized bitcode.
4388     bool InputIsBitcode = true;
4389     for (size_t i = 1; i < ActionInfo.size(); i++)
4390       if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4391           ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4392         InputIsBitcode = false;
4393         break;
4394       }
4395     if (!InputIsBitcode && !canCollapsePreprocessorAction())
4396       return nullptr;
4397 
4398     // Get compiler tool.
4399     const Tool *T = TC.SelectTool(*CJ);
4400     if (!T)
4401       return nullptr;
4402 
4403     if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4404       return nullptr;
4405 
4406     Inputs = CJ->getInputs();
4407     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4408                                  /*NumElements=*/2);
4409     return T;
4410   }
4411 
4412   /// Updates the inputs if the obtained tool supports combining with
4413   /// preprocessor action, and the current input is indeed a preprocessor
4414   /// action. If combining results in the collapse of offloading actions, those
4415   /// are appended to \a CollapsedOffloadAction.
4416   void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4417                                ActionList &CollapsedOffloadAction) {
4418     if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4419       return;
4420 
4421     // Attempt to get a preprocessor action dependence.
4422     ActionList PreprocessJobOffloadActions;
4423     ActionList NewInputs;
4424     for (Action *A : Inputs) {
4425       auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4426       if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4427         NewInputs.push_back(A);
4428         continue;
4429       }
4430 
4431       // This is legal to combine. Append any offload action we found and add the
4432       // current input to preprocessor inputs.
4433       CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
4434                                     PreprocessJobOffloadActions.end());
4435       NewInputs.append(PJ->input_begin(), PJ->input_end());
4436     }
4437     Inputs = NewInputs;
4438   }
4439 
4440 public:
4441   ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
4442                const Compilation &C, bool SaveTemps, bool EmbedBitcode)
4443       : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
4444         EmbedBitcode(EmbedBitcode) {
4445     assert(BaseAction && "Invalid base action.");
4446     IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
4447   }
4448 
4449   /// Check if a chain of actions can be combined and return the tool that can
4450   /// handle the combination of actions. The pointer to the current inputs \a
4451   /// Inputs and the list of offload actions \a CollapsedOffloadActions
4452   /// connected to collapsed actions are updated accordingly. The latter enables
4453   /// the caller of the selector to process them afterwards instead of just
4454   /// dropping them. If no suitable tool is found, null will be returned.
4455   const Tool *getTool(ActionList &Inputs,
4456                       ActionList &CollapsedOffloadAction) {
4457     //
4458     // Get the largest chain of actions that we could combine.
4459     //
4460 
4461     SmallVector<JobActionInfo, 5> ActionChain(1);
4462     ActionChain.back().JA = BaseAction;
4463     while (ActionChain.back().JA) {
4464       const Action *CurAction = ActionChain.back().JA;
4465 
4466       // Grow the chain by one element.
4467       ActionChain.resize(ActionChain.size() + 1);
4468       JobActionInfo &AI = ActionChain.back();
4469 
4470       // Attempt to fill it with the
4471       AI.JA =
4472           getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
4473     }
4474 
4475     // Pop the last action info as it could not be filled.
4476     ActionChain.pop_back();
4477 
4478     //
4479     // Attempt to combine actions. If all combining attempts failed, just return
4480     // the tool of the provided action. At the end we attempt to combine the
4481     // action with any preprocessor action it may depend on.
4482     //
4483 
4484     const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
4485                                                   CollapsedOffloadAction);
4486     if (!T)
4487       T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
4488     if (!T)
4489       T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
4490     if (!T) {
4491       Inputs = BaseAction->getInputs();
4492       T = TC.SelectTool(*BaseAction);
4493     }
4494 
4495     combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
4496     return T;
4497   }
4498 };
4499 }
4500 
4501 /// Return a string that uniquely identifies the result of a job. The bound arch
4502 /// is not necessarily represented in the toolchain's triple -- for example,
4503 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
4504 /// Also, we need to add the offloading device kind, as the same tool chain can
4505 /// be used for host and device for some programming models, e.g. OpenMP.
4506 static std::string GetTriplePlusArchString(const ToolChain *TC,
4507                                            StringRef BoundArch,
4508                                            Action::OffloadKind OffloadKind) {
4509   std::string TriplePlusArch = TC->getTriple().normalize();
4510   if (!BoundArch.empty()) {
4511     TriplePlusArch += "-";
4512     TriplePlusArch += BoundArch;
4513   }
4514   TriplePlusArch += "-";
4515   TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
4516   return TriplePlusArch;
4517 }
4518 
4519 InputInfo Driver::BuildJobsForAction(
4520     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4521     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4522     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4523     Action::OffloadKind TargetDeviceOffloadKind) const {
4524   std::pair<const Action *, std::string> ActionTC = {
4525       A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4526   auto CachedResult = CachedResults.find(ActionTC);
4527   if (CachedResult != CachedResults.end()) {
4528     return CachedResult->second;
4529   }
4530   InputInfo Result = BuildJobsForActionNoCache(
4531       C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
4532       CachedResults, TargetDeviceOffloadKind);
4533   CachedResults[ActionTC] = Result;
4534   return Result;
4535 }
4536 
4537 InputInfo Driver::BuildJobsForActionNoCache(
4538     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4539     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4540     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4541     Action::OffloadKind TargetDeviceOffloadKind) const {
4542   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4543 
4544   InputInfoList OffloadDependencesInputInfo;
4545   bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
4546   if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
4547     // The 'Darwin' toolchain is initialized only when its arguments are
4548     // computed. Get the default arguments for OFK_None to ensure that
4549     // initialization is performed before processing the offload action.
4550     // FIXME: Remove when darwin's toolchain is initialized during construction.
4551     C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
4552 
4553     // The offload action is expected to be used in four different situations.
4554     //
4555     // a) Set a toolchain/architecture/kind for a host action:
4556     //    Host Action 1 -> OffloadAction -> Host Action 2
4557     //
4558     // b) Set a toolchain/architecture/kind for a device action;
4559     //    Device Action 1 -> OffloadAction -> Device Action 2
4560     //
4561     // c) Specify a device dependence to a host action;
4562     //    Device Action 1  _
4563     //                      \
4564     //      Host Action 1  ---> OffloadAction -> Host Action 2
4565     //
4566     // d) Specify a host dependence to a device action.
4567     //      Host Action 1  _
4568     //                      \
4569     //    Device Action 1  ---> OffloadAction -> Device Action 2
4570     //
4571     // For a) and b), we just return the job generated for the dependence. For
4572     // c) and d) we override the current action with the host/device dependence
4573     // if the current toolchain is host/device and set the offload dependences
4574     // info with the jobs obtained from the device/host dependence(s).
4575 
4576     // If there is a single device option, just generate the job for it.
4577     if (OA->hasSingleDeviceDependence()) {
4578       InputInfo DevA;
4579       OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
4580                                        const char *DepBoundArch) {
4581         DevA =
4582             BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
4583                                /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
4584                                CachedResults, DepA->getOffloadingDeviceKind());
4585       });
4586       return DevA;
4587     }
4588 
4589     // If 'Action 2' is host, we generate jobs for the device dependences and
4590     // override the current action with the host dependence. Otherwise, we
4591     // generate the host dependences and override the action with the device
4592     // dependence. The dependences can't therefore be a top-level action.
4593     OA->doOnEachDependence(
4594         /*IsHostDependence=*/BuildingForOffloadDevice,
4595         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4596           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4597               C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
4598               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
4599               DepA->getOffloadingDeviceKind()));
4600         });
4601 
4602     A = BuildingForOffloadDevice
4603             ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
4604             : OA->getHostDependence();
4605   }
4606 
4607   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
4608     // FIXME: It would be nice to not claim this here; maybe the old scheme of
4609     // just using Args was better?
4610     const Arg &Input = IA->getInputArg();
4611     Input.claim();
4612     if (Input.getOption().matches(options::OPT_INPUT)) {
4613       const char *Name = Input.getValue();
4614       return InputInfo(A, Name, /* _BaseInput = */ Name);
4615     }
4616     return InputInfo(A, &Input, /* _BaseInput = */ "");
4617   }
4618 
4619   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
4620     const ToolChain *TC;
4621     StringRef ArchName = BAA->getArchName();
4622 
4623     if (!ArchName.empty())
4624       TC = &getToolChain(C.getArgs(),
4625                          computeTargetTriple(*this, TargetTriple,
4626                                              C.getArgs(), ArchName));
4627     else
4628       TC = &C.getDefaultToolChain();
4629 
4630     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
4631                               MultipleArchs, LinkingOutput, CachedResults,
4632                               TargetDeviceOffloadKind);
4633   }
4634 
4635 
4636   ActionList Inputs = A->getInputs();
4637 
4638   const JobAction *JA = cast<JobAction>(A);
4639   ActionList CollapsedOffloadActions;
4640 
4641   ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4642                   embedBitcodeInObject() && !isUsingLTO());
4643   const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4644 
4645   if (!T)
4646     return InputInfo();
4647 
4648   if (BuildingForOffloadDevice &&
4649       A->getOffloadingDeviceKind() == Action::OFK_OpenMP) {
4650     if (TC->getTriple().isAMDGCN()) {
4651       // AMDGCN treats backend and assemble actions as no-op because
4652       // linker does not support object files.
4653       if (const BackendJobAction *BA = dyn_cast<BackendJobAction>(A)) {
4654         return BuildJobsForAction(C, *BA->input_begin(), TC, BoundArch,
4655                                   AtTopLevel, MultipleArchs, LinkingOutput,
4656                                   CachedResults, TargetDeviceOffloadKind);
4657       }
4658 
4659       if (const AssembleJobAction *AA = dyn_cast<AssembleJobAction>(A)) {
4660         return BuildJobsForAction(C, *AA->input_begin(), TC, BoundArch,
4661                                   AtTopLevel, MultipleArchs, LinkingOutput,
4662                                   CachedResults, TargetDeviceOffloadKind);
4663       }
4664     }
4665   }
4666 
4667   // If we've collapsed action list that contained OffloadAction we
4668   // need to build jobs for host/device-side inputs it may have held.
4669   for (const auto *OA : CollapsedOffloadActions)
4670     cast<OffloadAction>(OA)->doOnEachDependence(
4671         /*IsHostDependence=*/BuildingForOffloadDevice,
4672         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4673           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4674               C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4675               /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4676               DepA->getOffloadingDeviceKind()));
4677         });
4678 
4679   // Only use pipes when there is exactly one input.
4680   InputInfoList InputInfos;
4681   for (const Action *Input : Inputs) {
4682     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4683     // shouldn't get temporary output names.
4684     // FIXME: Clean this up.
4685     bool SubJobAtTopLevel =
4686         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
4687     InputInfos.push_back(BuildJobsForAction(
4688         C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4689         CachedResults, A->getOffloadingDeviceKind()));
4690   }
4691 
4692   // Always use the first input as the base input.
4693   const char *BaseInput = InputInfos[0].getBaseInput();
4694 
4695   // ... except dsymutil actions, which use their actual input as the base
4696   // input.
4697   if (JA->getType() == types::TY_dSYM)
4698     BaseInput = InputInfos[0].getFilename();
4699 
4700   // ... and in header module compilations, which use the module name.
4701   if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4702     BaseInput = ModuleJA->getModuleName();
4703 
4704   // Append outputs of offload device jobs to the input list
4705   if (!OffloadDependencesInputInfo.empty())
4706     InputInfos.append(OffloadDependencesInputInfo.begin(),
4707                       OffloadDependencesInputInfo.end());
4708 
4709   // Set the effective triple of the toolchain for the duration of this job.
4710   llvm::Triple EffectiveTriple;
4711   const ToolChain &ToolTC = T->getToolChain();
4712   const ArgList &Args =
4713       C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4714   if (InputInfos.size() != 1) {
4715     EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4716   } else {
4717     // Pass along the input type if it can be unambiguously determined.
4718     EffectiveTriple = llvm::Triple(
4719         ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4720   }
4721   RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4722 
4723   // Determine the place to write output to, if any.
4724   InputInfo Result;
4725   InputInfoList UnbundlingResults;
4726   if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4727     // If we have an unbundling job, we need to create results for all the
4728     // outputs. We also update the results cache so that other actions using
4729     // this unbundling action can get the right results.
4730     for (auto &UI : UA->getDependentActionsInfo()) {
4731       assert(UI.DependentOffloadKind != Action::OFK_None &&
4732              "Unbundling with no offloading??");
4733 
4734       // Unbundling actions are never at the top level. When we generate the
4735       // offloading prefix, we also do that for the host file because the
4736       // unbundling action does not change the type of the output which can
4737       // cause a overwrite.
4738       std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4739           UI.DependentOffloadKind,
4740           UI.DependentToolChain->getTriple().normalize(),
4741           /*CreatePrefixForHost=*/true);
4742       auto CurI = InputInfo(
4743           UA,
4744           GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4745                              /*AtTopLevel=*/false,
4746                              MultipleArchs ||
4747                                  UI.DependentOffloadKind == Action::OFK_HIP,
4748                              OffloadingPrefix),
4749           BaseInput);
4750       // Save the unbundling result.
4751       UnbundlingResults.push_back(CurI);
4752 
4753       // Get the unique string identifier for this dependence and cache the
4754       // result.
4755       StringRef Arch;
4756       if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4757         if (UI.DependentOffloadKind == Action::OFK_Host)
4758           Arch = StringRef();
4759         else
4760           Arch = UI.DependentBoundArch;
4761       } else
4762         Arch = BoundArch;
4763 
4764       CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4765                                                 UI.DependentOffloadKind)}] =
4766           CurI;
4767     }
4768 
4769     // Now that we have all the results generated, select the one that should be
4770     // returned for the current depending action.
4771     std::pair<const Action *, std::string> ActionTC = {
4772         A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4773     assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4774            "Result does not exist??");
4775     Result = CachedResults[ActionTC];
4776   } else if (JA->getType() == types::TY_Nothing)
4777     Result = InputInfo(A, BaseInput);
4778   else {
4779     // We only have to generate a prefix for the host if this is not a top-level
4780     // action.
4781     std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4782         A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4783         /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4784             !AtTopLevel);
4785     if (isa<OffloadWrapperJobAction>(JA)) {
4786       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4787         BaseInput = FinalOutput->getValue();
4788       else
4789         BaseInput = getDefaultImageName();
4790       BaseInput =
4791           C.getArgs().MakeArgString(std::string(BaseInput) + "-wrapper");
4792     }
4793     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4794                                              AtTopLevel, MultipleArchs,
4795                                              OffloadingPrefix),
4796                        BaseInput);
4797   }
4798 
4799   if (CCCPrintBindings && !CCGenDiagnostics) {
4800     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4801                  << " - \"" << T->getName() << "\", inputs: [";
4802     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4803       llvm::errs() << InputInfos[i].getAsString();
4804       if (i + 1 != e)
4805         llvm::errs() << ", ";
4806     }
4807     if (UnbundlingResults.empty())
4808       llvm::errs() << "], output: " << Result.getAsString() << "\n";
4809     else {
4810       llvm::errs() << "], outputs: [";
4811       for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4812         llvm::errs() << UnbundlingResults[i].getAsString();
4813         if (i + 1 != e)
4814           llvm::errs() << ", ";
4815       }
4816       llvm::errs() << "] \n";
4817     }
4818   } else {
4819     if (UnbundlingResults.empty())
4820       T->ConstructJob(
4821           C, *JA, Result, InputInfos,
4822           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4823           LinkingOutput);
4824     else
4825       T->ConstructJobMultipleOutputs(
4826           C, *JA, UnbundlingResults, InputInfos,
4827           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4828           LinkingOutput);
4829   }
4830   return Result;
4831 }
4832 
4833 const char *Driver::getDefaultImageName() const {
4834   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4835   return Target.isOSWindows() ? "a.exe" : "a.out";
4836 }
4837 
4838 /// Create output filename based on ArgValue, which could either be a
4839 /// full filename, filename without extension, or a directory. If ArgValue
4840 /// does not provide a filename, then use BaseName, and use the extension
4841 /// suitable for FileType.
4842 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4843                                         StringRef BaseName,
4844                                         types::ID FileType) {
4845   SmallString<128> Filename = ArgValue;
4846 
4847   if (ArgValue.empty()) {
4848     // If the argument is empty, output to BaseName in the current dir.
4849     Filename = BaseName;
4850   } else if (llvm::sys::path::is_separator(Filename.back())) {
4851     // If the argument is a directory, output to BaseName in that dir.
4852     llvm::sys::path::append(Filename, BaseName);
4853   }
4854 
4855   if (!llvm::sys::path::has_extension(ArgValue)) {
4856     // If the argument didn't provide an extension, then set it.
4857     const char *Extension = types::getTypeTempSuffix(FileType, true);
4858 
4859     if (FileType == types::TY_Image &&
4860         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4861       // The output file is a dll.
4862       Extension = "dll";
4863     }
4864 
4865     llvm::sys::path::replace_extension(Filename, Extension);
4866   }
4867 
4868   return Args.MakeArgString(Filename.c_str());
4869 }
4870 
4871 static bool HasPreprocessOutput(const Action &JA) {
4872   if (isa<PreprocessJobAction>(JA))
4873     return true;
4874   if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0]))
4875     return true;
4876   if (isa<OffloadBundlingJobAction>(JA) &&
4877       HasPreprocessOutput(*(JA.getInputs()[0])))
4878     return true;
4879   return false;
4880 }
4881 
4882 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4883                                        const char *BaseInput,
4884                                        StringRef OrigBoundArch, bool AtTopLevel,
4885                                        bool MultipleArchs,
4886                                        StringRef OffloadingPrefix) const {
4887   std::string BoundArch = OrigBoundArch.str();
4888 #if defined(_WIN32)
4889   // BoundArch may contains ':', which is invalid in file names on Windows,
4890   // therefore replace it with '%'.
4891   std::replace(BoundArch.begin(), BoundArch.end(), ':', '@');
4892 #endif
4893 
4894   llvm::PrettyStackTraceString CrashInfo("Computing output path");
4895   // Output to a user requested destination?
4896   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
4897     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4898       return C.addResultFile(FinalOutput->getValue(), &JA);
4899   }
4900 
4901   // For /P, preprocess to file named after BaseInput.
4902   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4903     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4904     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4905     StringRef NameArg;
4906     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4907       NameArg = A->getValue();
4908     return C.addResultFile(
4909         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4910         &JA);
4911   }
4912 
4913   // Default to writing to stdout?
4914   if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
4915     return "-";
4916   }
4917 
4918   if (JA.getType() == types::TY_ModuleFile &&
4919       C.getArgs().getLastArg(options::OPT_module_file_info)) {
4920     return "-";
4921   }
4922 
4923   // Is this the assembly listing for /FA?
4924   if (JA.getType() == types::TY_PP_Asm &&
4925       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4926        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4927     // Use /Fa and the input filename to determine the asm file name.
4928     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4929     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4930     return C.addResultFile(
4931         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4932         &JA);
4933   }
4934 
4935   // Output to a temporary file?
4936   if ((!AtTopLevel && !isSaveTempsEnabled() &&
4937        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4938       CCGenDiagnostics) {
4939     StringRef Name = llvm::sys::path::filename(BaseInput);
4940     std::pair<StringRef, StringRef> Split = Name.split('.');
4941     SmallString<128> TmpName;
4942     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4943     Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4944     if (CCGenDiagnostics && A) {
4945       SmallString<128> CrashDirectory(A->getValue());
4946       if (!getVFS().exists(CrashDirectory))
4947         llvm::sys::fs::create_directories(CrashDirectory);
4948       llvm::sys::path::append(CrashDirectory, Split.first);
4949       const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4950       std::error_code EC = llvm::sys::fs::createUniqueFile(
4951           CrashDirectory + Middle + Suffix, TmpName);
4952       if (EC) {
4953         Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4954         return "";
4955       }
4956     } else {
4957       TmpName = GetTemporaryPath(Split.first, Suffix);
4958     }
4959     return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4960   }
4961 
4962   SmallString<128> BasePath(BaseInput);
4963   SmallString<128> ExternalPath("");
4964   StringRef BaseName;
4965 
4966   // Dsymutil actions should use the full path.
4967   if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) {
4968     ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
4969     // We use posix style here because the tests (specifically
4970     // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
4971     // even on Windows and if we don't then the similar test covering this
4972     // fails.
4973     llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
4974                             llvm::sys::path::filename(BasePath));
4975     BaseName = ExternalPath;
4976   } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4977     BaseName = BasePath;
4978   else
4979     BaseName = llvm::sys::path::filename(BasePath);
4980 
4981   // Determine what the derived output name should be.
4982   const char *NamedOutput;
4983 
4984   if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4985       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4986     // The /Fo or /o flag decides the object filename.
4987     StringRef Val =
4988         C.getArgs()
4989             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4990             ->getValue();
4991     NamedOutput =
4992         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4993   } else if (JA.getType() == types::TY_Image &&
4994              C.getArgs().hasArg(options::OPT__SLASH_Fe,
4995                                 options::OPT__SLASH_o)) {
4996     // The /Fe or /o flag names the linked file.
4997     StringRef Val =
4998         C.getArgs()
4999             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
5000             ->getValue();
5001     NamedOutput =
5002         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
5003   } else if (JA.getType() == types::TY_Image) {
5004     if (IsCLMode()) {
5005       // clang-cl uses BaseName for the executable name.
5006       NamedOutput =
5007           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
5008     } else {
5009       SmallString<128> Output(getDefaultImageName());
5010       // HIP image for device compilation with -fno-gpu-rdc is per compilation
5011       // unit.
5012       bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5013                         !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
5014                                              options::OPT_fno_gpu_rdc, false);
5015       if (IsHIPNoRDC) {
5016         Output = BaseName;
5017         llvm::sys::path::replace_extension(Output, "");
5018       }
5019       Output += OffloadingPrefix;
5020       if (MultipleArchs && !BoundArch.empty()) {
5021         Output += "-";
5022         Output.append(BoundArch);
5023       }
5024       if (IsHIPNoRDC)
5025         Output += ".out";
5026       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
5027     }
5028   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
5029     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
5030   } else {
5031     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
5032     assert(Suffix && "All types used for output should have a suffix.");
5033 
5034     std::string::size_type End = std::string::npos;
5035     if (!types::appendSuffixForType(JA.getType()))
5036       End = BaseName.rfind('.');
5037     SmallString<128> Suffixed(BaseName.substr(0, End));
5038     Suffixed += OffloadingPrefix;
5039     if (MultipleArchs && !BoundArch.empty()) {
5040       Suffixed += "-";
5041       Suffixed.append(BoundArch);
5042     }
5043     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
5044     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
5045     // optimized bitcode output.
5046     auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
5047                                      const llvm::opt::DerivedArgList &Args) {
5048       // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
5049       // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
5050       // phase.)
5051       return isa<CompileJobAction>(JA) &&
5052              JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5053              Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5054                           false);
5055     };
5056     if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
5057         (C.getArgs().hasArg(options::OPT_emit_llvm) ||
5058          IsHIPRDCInCompilePhase(JA, C.getArgs())))
5059       Suffixed += ".tmp";
5060     Suffixed += '.';
5061     Suffixed += Suffix;
5062     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
5063   }
5064 
5065   // Prepend object file path if -save-temps=obj
5066   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
5067       JA.getType() != types::TY_PCH) {
5068     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
5069     SmallString<128> TempPath(FinalOutput->getValue());
5070     llvm::sys::path::remove_filename(TempPath);
5071     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
5072     llvm::sys::path::append(TempPath, OutputFileName);
5073     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
5074   }
5075 
5076   // If we're saving temps and the temp file conflicts with the input file,
5077   // then avoid overwriting input file.
5078   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
5079     bool SameFile = false;
5080     SmallString<256> Result;
5081     llvm::sys::fs::current_path(Result);
5082     llvm::sys::path::append(Result, BaseName);
5083     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
5084     // Must share the same path to conflict.
5085     if (SameFile) {
5086       StringRef Name = llvm::sys::path::filename(BaseInput);
5087       std::pair<StringRef, StringRef> Split = Name.split('.');
5088       std::string TmpName = GetTemporaryPath(
5089           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
5090       return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5091     }
5092   }
5093 
5094   // As an annoying special case, PCH generation doesn't strip the pathname.
5095   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
5096     llvm::sys::path::remove_filename(BasePath);
5097     if (BasePath.empty())
5098       BasePath = NamedOutput;
5099     else
5100       llvm::sys::path::append(BasePath, NamedOutput);
5101     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
5102   } else {
5103     return C.addResultFile(NamedOutput, &JA);
5104   }
5105 }
5106 
5107 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
5108   // Search for Name in a list of paths.
5109   auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
5110       -> llvm::Optional<std::string> {
5111     // Respect a limited subset of the '-Bprefix' functionality in GCC by
5112     // attempting to use this prefix when looking for file paths.
5113     for (const auto &Dir : P) {
5114       if (Dir.empty())
5115         continue;
5116       SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
5117       llvm::sys::path::append(P, Name);
5118       if (llvm::sys::fs::exists(Twine(P)))
5119         return std::string(P);
5120     }
5121     return None;
5122   };
5123 
5124   if (auto P = SearchPaths(PrefixDirs))
5125     return *P;
5126 
5127   SmallString<128> R(ResourceDir);
5128   llvm::sys::path::append(R, Name);
5129   if (llvm::sys::fs::exists(Twine(R)))
5130     return std::string(R.str());
5131 
5132   SmallString<128> P(TC.getCompilerRTPath());
5133   llvm::sys::path::append(P, Name);
5134   if (llvm::sys::fs::exists(Twine(P)))
5135     return std::string(P.str());
5136 
5137   SmallString<128> D(Dir);
5138   llvm::sys::path::append(D, "..", Name);
5139   if (llvm::sys::fs::exists(Twine(D)))
5140     return std::string(D.str());
5141 
5142   if (auto P = SearchPaths(TC.getLibraryPaths()))
5143     return *P;
5144 
5145   if (auto P = SearchPaths(TC.getFilePaths()))
5146     return *P;
5147 
5148   return std::string(Name);
5149 }
5150 
5151 void Driver::generatePrefixedToolNames(
5152     StringRef Tool, const ToolChain &TC,
5153     SmallVectorImpl<std::string> &Names) const {
5154   // FIXME: Needs a better variable than TargetTriple
5155   Names.emplace_back((TargetTriple + "-" + Tool).str());
5156   Names.emplace_back(Tool);
5157 }
5158 
5159 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
5160   llvm::sys::path::append(Dir, Name);
5161   if (llvm::sys::fs::can_execute(Twine(Dir)))
5162     return true;
5163   llvm::sys::path::remove_filename(Dir);
5164   return false;
5165 }
5166 
5167 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
5168   SmallVector<std::string, 2> TargetSpecificExecutables;
5169   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
5170 
5171   // Respect a limited subset of the '-Bprefix' functionality in GCC by
5172   // attempting to use this prefix when looking for program paths.
5173   for (const auto &PrefixDir : PrefixDirs) {
5174     if (llvm::sys::fs::is_directory(PrefixDir)) {
5175       SmallString<128> P(PrefixDir);
5176       if (ScanDirForExecutable(P, Name))
5177         return std::string(P.str());
5178     } else {
5179       SmallString<128> P((PrefixDir + Name).str());
5180       if (llvm::sys::fs::can_execute(Twine(P)))
5181         return std::string(P.str());
5182     }
5183   }
5184 
5185   const ToolChain::path_list &List = TC.getProgramPaths();
5186   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
5187     // For each possible name of the tool look for it in
5188     // program paths first, then the path.
5189     // Higher priority names will be first, meaning that
5190     // a higher priority name in the path will be found
5191     // instead of a lower priority name in the program path.
5192     // E.g. <triple>-gcc on the path will be found instead
5193     // of gcc in the program path
5194     for (const auto &Path : List) {
5195       SmallString<128> P(Path);
5196       if (ScanDirForExecutable(P, TargetSpecificExecutable))
5197         return std::string(P.str());
5198     }
5199 
5200     // Fall back to the path
5201     if (llvm::ErrorOr<std::string> P =
5202             llvm::sys::findProgramByName(TargetSpecificExecutable))
5203       return *P;
5204   }
5205 
5206   return std::string(Name);
5207 }
5208 
5209 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
5210   SmallString<128> Path;
5211   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
5212   if (EC) {
5213     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5214     return "";
5215   }
5216 
5217   return std::string(Path.str());
5218 }
5219 
5220 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
5221   SmallString<128> Path;
5222   std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
5223   if (EC) {
5224     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5225     return "";
5226   }
5227 
5228   return std::string(Path.str());
5229 }
5230 
5231 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
5232   SmallString<128> Output;
5233   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
5234     // FIXME: If anybody needs it, implement this obscure rule:
5235     // "If you specify a directory without a file name, the default file name
5236     // is VCx0.pch., where x is the major version of Visual C++ in use."
5237     Output = FpArg->getValue();
5238 
5239     // "If you do not specify an extension as part of the path name, an
5240     // extension of .pch is assumed. "
5241     if (!llvm::sys::path::has_extension(Output))
5242       Output += ".pch";
5243   } else {
5244     if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
5245       Output = YcArg->getValue();
5246     if (Output.empty())
5247       Output = BaseName;
5248     llvm::sys::path::replace_extension(Output, ".pch");
5249   }
5250   return std::string(Output.str());
5251 }
5252 
5253 const ToolChain &Driver::getToolChain(const ArgList &Args,
5254                                       const llvm::Triple &Target) const {
5255 
5256   auto &TC = ToolChains[Target.str()];
5257   if (!TC) {
5258     switch (Target.getOS()) {
5259     case llvm::Triple::AIX:
5260       TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
5261       break;
5262     case llvm::Triple::Haiku:
5263       TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
5264       break;
5265     case llvm::Triple::Ananas:
5266       TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
5267       break;
5268     case llvm::Triple::CloudABI:
5269       TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
5270       break;
5271     case llvm::Triple::Darwin:
5272     case llvm::Triple::MacOSX:
5273     case llvm::Triple::IOS:
5274     case llvm::Triple::TvOS:
5275     case llvm::Triple::WatchOS:
5276       TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
5277       break;
5278     case llvm::Triple::DragonFly:
5279       TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
5280       break;
5281     case llvm::Triple::OpenBSD:
5282       TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
5283       break;
5284     case llvm::Triple::NetBSD:
5285       TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
5286       break;
5287     case llvm::Triple::FreeBSD:
5288       TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
5289       break;
5290     case llvm::Triple::Minix:
5291       TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
5292       break;
5293     case llvm::Triple::Linux:
5294     case llvm::Triple::ELFIAMCU:
5295       if (Target.getArch() == llvm::Triple::hexagon)
5296         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5297                                                              Args);
5298       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
5299                !Target.hasEnvironment())
5300         TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
5301                                                               Args);
5302       else if (Target.isPPC())
5303         TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
5304                                                               Args);
5305       else if (Target.getArch() == llvm::Triple::ve)
5306         TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5307 
5308       else
5309         TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
5310       break;
5311     case llvm::Triple::NaCl:
5312       TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
5313       break;
5314     case llvm::Triple::Fuchsia:
5315       TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
5316       break;
5317     case llvm::Triple::Solaris:
5318       TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
5319       break;
5320     case llvm::Triple::AMDHSA:
5321       TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
5322       break;
5323     case llvm::Triple::AMDPAL:
5324     case llvm::Triple::Mesa3D:
5325       TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
5326       break;
5327     case llvm::Triple::Win32:
5328       switch (Target.getEnvironment()) {
5329       default:
5330         if (Target.isOSBinFormatELF())
5331           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5332         else if (Target.isOSBinFormatMachO())
5333           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5334         else
5335           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5336         break;
5337       case llvm::Triple::GNU:
5338         TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
5339         break;
5340       case llvm::Triple::Itanium:
5341         TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
5342                                                                   Args);
5343         break;
5344       case llvm::Triple::MSVC:
5345       case llvm::Triple::UnknownEnvironment:
5346         if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
5347                 .startswith_insensitive("bfd"))
5348           TC = std::make_unique<toolchains::CrossWindowsToolChain>(
5349               *this, Target, Args);
5350         else
5351           TC =
5352               std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
5353         break;
5354       }
5355       break;
5356     case llvm::Triple::PS4:
5357       TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
5358       break;
5359     case llvm::Triple::Contiki:
5360       TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
5361       break;
5362     case llvm::Triple::Hurd:
5363       TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
5364       break;
5365     case llvm::Triple::ZOS:
5366       TC = std::make_unique<toolchains::ZOS>(*this, Target, Args);
5367       break;
5368     default:
5369       // Of these targets, Hexagon is the only one that might have
5370       // an OS of Linux, in which case it got handled above already.
5371       switch (Target.getArch()) {
5372       case llvm::Triple::tce:
5373         TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
5374         break;
5375       case llvm::Triple::tcele:
5376         TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
5377         break;
5378       case llvm::Triple::hexagon:
5379         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5380                                                              Args);
5381         break;
5382       case llvm::Triple::lanai:
5383         TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
5384         break;
5385       case llvm::Triple::xcore:
5386         TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
5387         break;
5388       case llvm::Triple::wasm32:
5389       case llvm::Triple::wasm64:
5390         TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
5391         break;
5392       case llvm::Triple::avr:
5393         TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
5394         break;
5395       case llvm::Triple::msp430:
5396         TC =
5397             std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
5398         break;
5399       case llvm::Triple::riscv32:
5400       case llvm::Triple::riscv64:
5401         if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
5402           TC =
5403               std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
5404         else
5405           TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
5406         break;
5407       case llvm::Triple::ve:
5408         TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5409         break;
5410       default:
5411         if (Target.getVendor() == llvm::Triple::Myriad)
5412           TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
5413                                                               Args);
5414         else if (toolchains::BareMetal::handlesTarget(Target))
5415           TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
5416         else if (Target.isOSBinFormatELF())
5417           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5418         else if (Target.isOSBinFormatMachO())
5419           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5420         else
5421           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5422       }
5423     }
5424   }
5425 
5426   // Intentionally omitted from the switch above: llvm::Triple::CUDA.  CUDA
5427   // compiles always need two toolchains, the CUDA toolchain and the host
5428   // toolchain.  So the only valid way to create a CUDA toolchain is via
5429   // CreateOffloadingDeviceToolChains.
5430 
5431   return *TC;
5432 }
5433 
5434 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
5435   // Say "no" if there is not exactly one input of a type clang understands.
5436   if (JA.size() != 1 ||
5437       !types::isAcceptedByClang((*JA.input_begin())->getType()))
5438     return false;
5439 
5440   // And say "no" if this is not a kind of action clang understands.
5441   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
5442       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5443     return false;
5444 
5445   return true;
5446 }
5447 
5448 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
5449   // Say "no" if there is not exactly one input of a type flang understands.
5450   if (JA.size() != 1 ||
5451       !types::isFortran((*JA.input_begin())->getType()))
5452     return false;
5453 
5454   // And say "no" if this is not a kind of action flang understands.
5455   if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5456     return false;
5457 
5458   return true;
5459 }
5460 
5461 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
5462   // Only emit static library if the flag is set explicitly.
5463   if (Args.hasArg(options::OPT_emit_static_lib))
5464     return true;
5465   return false;
5466 }
5467 
5468 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
5469 /// grouped values as integers. Numbers which are not provided are set to 0.
5470 ///
5471 /// \return True if the entire string was parsed (9.2), or all groups were
5472 /// parsed (10.3.5extrastuff).
5473 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
5474                                unsigned &Micro, bool &HadExtra) {
5475   HadExtra = false;
5476 
5477   Major = Minor = Micro = 0;
5478   if (Str.empty())
5479     return false;
5480 
5481   if (Str.consumeInteger(10, Major))
5482     return false;
5483   if (Str.empty())
5484     return true;
5485   if (Str[0] != '.')
5486     return false;
5487 
5488   Str = Str.drop_front(1);
5489 
5490   if (Str.consumeInteger(10, Minor))
5491     return false;
5492   if (Str.empty())
5493     return true;
5494   if (Str[0] != '.')
5495     return false;
5496   Str = Str.drop_front(1);
5497 
5498   if (Str.consumeInteger(10, Micro))
5499     return false;
5500   if (!Str.empty())
5501     HadExtra = true;
5502   return true;
5503 }
5504 
5505 /// Parse digits from a string \p Str and fulfill \p Digits with
5506 /// the parsed numbers. This method assumes that the max number of
5507 /// digits to look for is equal to Digits.size().
5508 ///
5509 /// \return True if the entire string was parsed and there are
5510 /// no extra characters remaining at the end.
5511 bool Driver::GetReleaseVersion(StringRef Str,
5512                                MutableArrayRef<unsigned> Digits) {
5513   if (Str.empty())
5514     return false;
5515 
5516   unsigned CurDigit = 0;
5517   while (CurDigit < Digits.size()) {
5518     unsigned Digit;
5519     if (Str.consumeInteger(10, Digit))
5520       return false;
5521     Digits[CurDigit] = Digit;
5522     if (Str.empty())
5523       return true;
5524     if (Str[0] != '.')
5525       return false;
5526     Str = Str.drop_front(1);
5527     CurDigit++;
5528   }
5529 
5530   // More digits than requested, bail out...
5531   return false;
5532 }
5533 
5534 std::pair<unsigned, unsigned>
5535 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
5536   unsigned IncludedFlagsBitmask = 0;
5537   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
5538 
5539   if (IsClCompatMode) {
5540     // Include CL and Core options.
5541     IncludedFlagsBitmask |= options::CLOption;
5542     IncludedFlagsBitmask |= options::CoreOption;
5543   } else {
5544     ExcludedFlagsBitmask |= options::CLOption;
5545   }
5546 
5547   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
5548 }
5549 
5550 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
5551   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
5552 }
5553 
5554 bool clang::driver::willEmitRemarks(const ArgList &Args) {
5555   // -fsave-optimization-record enables it.
5556   if (Args.hasFlag(options::OPT_fsave_optimization_record,
5557                    options::OPT_fno_save_optimization_record, false))
5558     return true;
5559 
5560   // -fsave-optimization-record=<format> enables it as well.
5561   if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5562                    options::OPT_fno_save_optimization_record, false))
5563     return true;
5564 
5565   // -foptimization-record-file alone enables it too.
5566   if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
5567                    options::OPT_fno_save_optimization_record, false))
5568     return true;
5569 
5570   // -foptimization-record-passes alone enables it too.
5571   if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5572                    options::OPT_fno_save_optimization_record, false))
5573     return true;
5574   return false;
5575 }
5576