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