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