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