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