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