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