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