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