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