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