clang  16.0.0git
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 "ToolChains/AIX.h"
11 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
17 #include "ToolChains/Clang.h"
18 #include "ToolChains/CloudABI.h"
19 #include "ToolChains/Contiki.h"
21 #include "ToolChains/Cuda.h"
22 #include "ToolChains/Darwin.h"
23 #include "ToolChains/DragonFly.h"
24 #include "ToolChains/FreeBSD.h"
25 #include "ToolChains/Fuchsia.h"
26 #include "ToolChains/Gnu.h"
27 #include "ToolChains/HIPAMD.h"
28 #include "ToolChains/HIPSPV.h"
29 #include "ToolChains/HLSL.h"
30 #include "ToolChains/Haiku.h"
31 #include "ToolChains/Hexagon.h"
32 #include "ToolChains/Hurd.h"
33 #include "ToolChains/Lanai.h"
34 #include "ToolChains/Linux.h"
35 #include "ToolChains/MSP430.h"
36 #include "ToolChains/MSVC.h"
37 #include "ToolChains/MinGW.h"
38 #include "ToolChains/Minix.h"
39 #include "ToolChains/MipsLinux.h"
40 #include "ToolChains/Myriad.h"
41 #include "ToolChains/NaCl.h"
42 #include "ToolChains/NetBSD.h"
43 #include "ToolChains/OpenBSD.h"
44 #include "ToolChains/PPCFreeBSD.h"
45 #include "ToolChains/PPCLinux.h"
46 #include "ToolChains/PS4CPU.h"
48 #include "ToolChains/SPIRV.h"
49 #include "ToolChains/Solaris.h"
50 #include "ToolChains/TCE.h"
51 #include "ToolChains/VEToolchain.h"
52 #include "ToolChains/WebAssembly.h"
53 #include "ToolChains/XCore.h"
54 #include "ToolChains/ZOS.h"
55 #include "clang/Basic/TargetID.h"
56 #include "clang/Basic/Version.h"
57 #include "clang/Config/config.h"
58 #include "clang/Driver/Action.h"
61 #include "clang/Driver/InputInfo.h"
62 #include "clang/Driver/Job.h"
63 #include "clang/Driver/Options.h"
64 #include "clang/Driver/Phases.h"
66 #include "clang/Driver/Tool.h"
67 #include "clang/Driver/ToolChain.h"
68 #include "clang/Driver/Types.h"
69 #include "llvm/ADT/ArrayRef.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/StringExtras.h"
73 #include "llvm/ADT/StringRef.h"
74 #include "llvm/ADT/StringSet.h"
75 #include "llvm/ADT/StringSwitch.h"
76 #include "llvm/Config/llvm-config.h"
77 #include "llvm/MC/TargetRegistry.h"
78 #include "llvm/Option/Arg.h"
79 #include "llvm/Option/ArgList.h"
80 #include "llvm/Option/OptSpecifier.h"
81 #include "llvm/Option/OptTable.h"
82 #include "llvm/Option/Option.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/ExitCodes.h"
86 #include "llvm/Support/FileSystem.h"
87 #include "llvm/Support/FormatVariadic.h"
88 #include "llvm/Support/Host.h"
89 #include "llvm/Support/MD5.h"
90 #include "llvm/Support/Path.h"
91 #include "llvm/Support/PrettyStackTrace.h"
92 #include "llvm/Support/Process.h"
93 #include "llvm/Support/Program.h"
94 #include "llvm/Support/StringSaver.h"
95 #include "llvm/Support/VirtualFileSystem.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include <cstdlib> // ::getenv
98 #include <map>
99 #include <memory>
100 #include <utility>
101 #if LLVM_ON_UNIX
102 #include <unistd.h> // getpid
103 #endif
104 
105 using namespace clang::driver;
106 using namespace clang;
107 using namespace llvm::opt;
108 
110 getOffloadTargetTriple(const Driver &D, const ArgList &Args) {
111  auto OffloadTargets = Args.getAllArgValues(options::OPT_offload_EQ);
112  // Offload compilation flow does not support multiple targets for now. We
113  // need the HIPActionBuilder (and possibly the CudaActionBuilder{,Base}too)
114  // to support multiple tool chains first.
115  switch (OffloadTargets.size()) {
116  default:
117  D.Diag(diag::err_drv_only_one_offload_target_supported);
118  return llvm::None;
119  case 0:
120  D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << "";
121  return llvm::None;
122  case 1:
123  break;
124  }
125  return llvm::Triple(OffloadTargets[0]);
126 }
127 
129 getNVIDIAOffloadTargetTriple(const Driver &D, const ArgList &Args,
130  const llvm::Triple &HostTriple) {
131  if (!Args.hasArg(options::OPT_offload_EQ)) {
132  return llvm::Triple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
133  : "nvptx-nvidia-cuda");
134  }
135  auto TT = getOffloadTargetTriple(D, Args);
136  if (TT && (TT->getArch() == llvm::Triple::spirv32 ||
137  TT->getArch() == llvm::Triple::spirv64)) {
138  if (Args.hasArg(options::OPT_emit_llvm))
139  return TT;
140  D.Diag(diag::err_drv_cuda_offload_only_emit_bc);
141  return llvm::None;
142  }
143  D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
144  return llvm::None;
145 }
147 getHIPOffloadTargetTriple(const Driver &D, const ArgList &Args) {
148  if (!Args.hasArg(options::OPT_offload_EQ)) {
149  return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple.
150  }
151  auto TT = getOffloadTargetTriple(D, Args);
152  if (!TT)
153  return llvm::None;
154  if (TT->getArch() == llvm::Triple::amdgcn &&
155  TT->getVendor() == llvm::Triple::AMD &&
156  TT->getOS() == llvm::Triple::AMDHSA)
157  return TT;
158  if (TT->getArch() == llvm::Triple::spirv64)
159  return TT;
160  D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
161  return llvm::None;
162 }
163 
164 // static
166  StringRef CustomResourceDir) {
167  // Since the resource directory is embedded in the module hash, it's important
168  // that all places that need it call this function, so that they get the
169  // exact same string ("a/../b/" and "b/" get different hashes, for example).
170 
171  // Dir is bin/ or lib/, depending on where BinaryPath is.
172  std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
173 
174  SmallString<128> P(Dir);
175  if (CustomResourceDir != "") {
176  llvm::sys::path::append(P, CustomResourceDir);
177  } else {
178  // On Windows, libclang.dll is in bin/.
179  // On non-Windows, libclang.so/.dylib is in lib/.
180  // With a static-library build of libclang, LibClangPath will contain the
181  // path of the embedding binary, which for LLVM binaries will be in bin/.
182  // ../lib gets us to lib/ in both cases.
183  P = llvm::sys::path::parent_path(Dir);
184  llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
185  CLANG_VERSION_MAJOR_STRING);
186  }
187 
188  return std::string(P.str());
189 }
190 
191 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
192  DiagnosticsEngine &Diags, std::string Title,
194  : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
195  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
196  Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None),
197  ModulesModeCXX20(false), LTOMode(LTOK_None),
198  ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
199  DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
200  CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
201  CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
202  CheckInputsExist(true), ProbePrecompiled(true),
203  SuppressMissingInputWarning(false) {
204  // Provide a sane fallback if no VFS is specified.
205  if (!this->VFS)
206  this->VFS = llvm::vfs::getRealFileSystem();
207 
208  Name = std::string(llvm::sys::path::filename(ClangExecutable));
209  Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
210  InstalledDir = Dir; // Provide a sensible default installed dir.
211 
212  if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
213  // Prepend InstalledDir if SysRoot is relative
215  llvm::sys::path::append(P, SysRoot);
216  SysRoot = std::string(P);
217  }
218 
219 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
220  SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
221 #endif
222 #if defined(CLANG_CONFIG_FILE_USER_DIR)
223  {
225  llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR, P);
226  UserConfigDir = static_cast<std::string>(P);
227  }
228 #endif
229 
230  // Compute the path to the resource directory.
231  ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
232 }
233 
234 void Driver::setDriverMode(StringRef Value) {
235  static const std::string OptName =
236  getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
237  if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
238  .Case("gcc", GCCMode)
239  .Case("g++", GXXMode)
240  .Case("cpp", CPPMode)
241  .Case("cl", CLMode)
242  .Case("flang", FlangMode)
243  .Case("dxc", DXCMode)
244  .Default(None))
245  Mode = *M;
246  else
247  Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
248 }
249 
251  bool IsClCompatMode,
252  bool &ContainsError) {
253  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
254  ContainsError = false;
255 
256  unsigned IncludedFlagsBitmask;
257  unsigned ExcludedFlagsBitmask;
258  std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
259  getIncludeExcludeOptionFlagMasks(IsClCompatMode);
260 
261  // Make sure that Flang-only options don't pollute the Clang output
262  // TODO: Make sure that Clang-only options don't pollute Flang output
263  if (!IsFlangMode())
264  ExcludedFlagsBitmask |= options::FlangOnlyOption;
265 
266  unsigned MissingArgIndex, MissingArgCount;
267  InputArgList Args =
268  getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
269  IncludedFlagsBitmask, ExcludedFlagsBitmask);
270 
271  // Check for missing argument error.
272  if (MissingArgCount) {
273  Diag(diag::err_drv_missing_argument)
274  << Args.getArgString(MissingArgIndex) << MissingArgCount;
275  ContainsError |=
276  Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
278  }
279 
280  // Check for unsupported options.
281  for (const Arg *A : Args) {
282  if (A->getOption().hasFlag(options::Unsupported)) {
283  unsigned DiagID;
284  auto ArgString = A->getAsString(Args);
285  std::string Nearest;
286  if (getOpts().findNearest(
287  ArgString, Nearest, IncludedFlagsBitmask,
288  ExcludedFlagsBitmask | options::Unsupported) > 1) {
289  DiagID = diag::err_drv_unsupported_opt;
290  Diag(DiagID) << ArgString;
291  } else {
292  DiagID = diag::err_drv_unsupported_opt_with_suggestion;
293  Diag(DiagID) << ArgString << Nearest;
294  }
295  ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
297  continue;
298  }
299 
300  // Warn about -mcpu= without an argument.
301  if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
302  Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
303  ContainsError |= Diags.getDiagnosticLevel(
304  diag::warn_drv_empty_joined_argument,
306  }
307  }
308 
309  for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
310  unsigned DiagID;
311  auto ArgString = A->getAsString(Args);
312  std::string Nearest;
313  if (getOpts().findNearest(ArgString, Nearest, IncludedFlagsBitmask,
314  ExcludedFlagsBitmask) > 1) {
315  if (getOpts().findNearest(ArgString, Nearest, options::CC1Option) == 0 &&
316  !IsCLMode()) {
317  DiagID = diag::err_drv_unknown_argument_with_suggestion;
318  Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
319  } else {
320  DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
321  : diag::err_drv_unknown_argument;
322  Diags.Report(DiagID) << ArgString;
323  }
324  } else {
325  DiagID = IsCLMode()
326  ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
327  : diag::err_drv_unknown_argument_with_suggestion;
328  Diags.Report(DiagID) << ArgString << Nearest;
329  }
330  ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
332  }
333 
334  for (const Arg *A : Args.filtered(options::OPT_o)) {
335  if (ArgStrings[A->getIndex()] == A->getSpelling())
336  continue;
337 
338  // Warn on joined arguments that are similar to a long argument.
339  std::string ArgString = ArgStrings[A->getIndex()];
340  std::string Nearest;
341  if (getOpts().findNearest("-" + ArgString, Nearest, IncludedFlagsBitmask,
342  ExcludedFlagsBitmask) == 0)
343  Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument)
344  << A->getAsString(Args) << Nearest;
345  }
346 
347  return Args;
348 }
349 
350 // Determine which compilation mode we are in. We look for options which
351 // affect the phase, starting with the earliest phases, and record which
352 // option we used to determine the final phase.
353 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
354  Arg **FinalPhaseArg) const {
355  Arg *PhaseArg = nullptr;
356  phases::ID FinalPhase;
357 
358  // -{E,EP,P,M,MM} only run the preprocessor.
359  if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
360  (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
361  (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
362  (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) ||
364  FinalPhase = phases::Preprocess;
365 
366  // --precompile only runs up to precompilation.
367  // Options that cause the output of C++20 compiled module interfaces or
368  // header units have the same effect.
369  } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
370  (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
371  (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
372  options::OPT_fmodule_header_EQ))) {
373  FinalPhase = phases::Precompile;
374  // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
375  } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
376  (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
377  (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
378  (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
379  (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
380  (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
381  (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
382  (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
383  (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
384  FinalPhase = phases::Compile;
385 
386  // -S only runs up to the backend.
387  } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
388  FinalPhase = phases::Backend;
389 
390  // -c compilation only runs up to the assembler.
391  } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
392  FinalPhase = phases::Assemble;
393 
394  } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) {
395  FinalPhase = phases::IfsMerge;
396 
397  // Otherwise do everything.
398  } else
399  FinalPhase = phases::Link;
400 
401  if (FinalPhaseArg)
402  *FinalPhaseArg = PhaseArg;
403 
404  return FinalPhase;
405 }
406 
407 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
408  StringRef Value, bool Claim = true) {
409  Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
410  Args.getBaseArgs().MakeIndex(Value), Value.data());
411  Args.AddSynthesizedArg(A);
412  if (Claim)
413  A->claim();
414  return A;
415 }
416 
417 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
418  const llvm::opt::OptTable &Opts = getOpts();
419  DerivedArgList *DAL = new DerivedArgList(Args);
420 
421  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
422  bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
423  bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
424  bool IgnoreUnused = false;
425  for (Arg *A : Args) {
426  if (IgnoreUnused)
427  A->claim();
428 
429  if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
430  IgnoreUnused = true;
431  continue;
432  }
433  if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
434  IgnoreUnused = false;
435  continue;
436  }
437 
438  // Unfortunately, we have to parse some forwarding options (-Xassembler,
439  // -Xlinker, -Xpreprocessor) because we either integrate their functionality
440  // (assembler and preprocessor), or bypass a previous driver ('collect2').
441 
442  // Rewrite linker options, to replace --no-demangle with a custom internal
443  // option.
444  if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
445  A->getOption().matches(options::OPT_Xlinker)) &&
446  A->containsValue("--no-demangle")) {
447  // Add the rewritten no-demangle argument.
448  DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
449 
450  // Add the remaining values as Xlinker arguments.
451  for (StringRef Val : A->getValues())
452  if (Val != "--no-demangle")
453  DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
454 
455  continue;
456  }
457 
458  // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
459  // some build systems. We don't try to be complete here because we don't
460  // care to encourage this usage model.
461  if (A->getOption().matches(options::OPT_Wp_COMMA) &&
462  (A->getValue(0) == StringRef("-MD") ||
463  A->getValue(0) == StringRef("-MMD"))) {
464  // Rewrite to -MD/-MMD along with -MF.
465  if (A->getValue(0) == StringRef("-MD"))
466  DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
467  else
468  DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
469  if (A->getNumValues() == 2)
470  DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
471  continue;
472  }
473 
474  // Rewrite reserved library names.
475  if (A->getOption().matches(options::OPT_l)) {
476  StringRef Value = A->getValue();
477 
478  // Rewrite unless -nostdlib is present.
479  if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
480  Value == "stdc++") {
481  DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
482  continue;
483  }
484 
485  // Rewrite unconditionally.
486  if (Value == "cc_kext") {
487  DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
488  continue;
489  }
490  }
491 
492  // Pick up inputs via the -- option.
493  if (A->getOption().matches(options::OPT__DASH_DASH)) {
494  A->claim();
495  for (StringRef Val : A->getValues())
496  DAL->append(MakeInputArg(*DAL, Opts, Val, false));
497  continue;
498  }
499 
500  DAL->append(A);
501  }
502 
503  // Enforce -static if -miamcu is present.
504  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
505  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static));
506 
507 // Add a default value of -mlinker-version=, if one was given and the user
508 // didn't specify one.
509 #if defined(HOST_LINK_VERSION)
510  if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
511  strlen(HOST_LINK_VERSION) > 0) {
512  DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
513  HOST_LINK_VERSION);
514  DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
515  }
516 #endif
517 
518  return DAL;
519 }
520 
521 /// Compute target triple from args.
522 ///
523 /// This routine provides the logic to compute a target triple from various
524 /// args passed to the driver and the default triple string.
525 static llvm::Triple computeTargetTriple(const Driver &D,
526  StringRef TargetTriple,
527  const ArgList &Args,
528  StringRef DarwinArchName = "") {
529  // FIXME: Already done in Compilation *Driver::BuildCompilation
530  if (const Arg *A = Args.getLastArg(options::OPT_target))
531  TargetTriple = A->getValue();
532 
533  llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
534 
535  // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
536  // -gnu* only, and we can not change this, so we have to detect that case as
537  // being the Hurd OS.
538  if (TargetTriple.contains("-unknown-gnu") || TargetTriple.contains("-pc-gnu"))
539  Target.setOSName("hurd");
540 
541  // Handle Apple-specific options available here.
542  if (Target.isOSBinFormatMachO()) {
543  // If an explicit Darwin arch name is given, that trumps all.
544  if (!DarwinArchName.empty()) {
546  return Target;
547  }
548 
549  // Handle the Darwin '-arch' flag.
550  if (Arg *A = Args.getLastArg(options::OPT_arch)) {
551  StringRef ArchName = A->getValue();
553  }
554  }
555 
556  // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
557  // '-mbig-endian'/'-EB'.
558  if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
559  options::OPT_mbig_endian)) {
560  if (A->getOption().matches(options::OPT_mlittle_endian)) {
561  llvm::Triple LE = Target.getLittleEndianArchVariant();
562  if (LE.getArch() != llvm::Triple::UnknownArch)
563  Target = std::move(LE);
564  } else {
565  llvm::Triple BE = Target.getBigEndianArchVariant();
566  if (BE.getArch() != llvm::Triple::UnknownArch)
567  Target = std::move(BE);
568  }
569  }
570 
571  // Skip further flag support on OSes which don't support '-m32' or '-m64'.
572  if (Target.getArch() == llvm::Triple::tce ||
573  Target.getOS() == llvm::Triple::Minix)
574  return Target;
575 
576  // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
577  if (Target.isOSAIX()) {
578  if (Optional<std::string> ObjectModeValue =
579  llvm::sys::Process::GetEnv("OBJECT_MODE")) {
580  StringRef ObjectMode = *ObjectModeValue;
581  llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
582 
583  if (ObjectMode.equals("64")) {
584  AT = Target.get64BitArchVariant().getArch();
585  } else if (ObjectMode.equals("32")) {
586  AT = Target.get32BitArchVariant().getArch();
587  } else {
588  D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
589  }
590 
591  if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
592  Target.setArch(AT);
593  }
594  }
595 
596  // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
597  Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
598  options::OPT_m32, options::OPT_m16);
599  if (A) {
600  llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
601 
602  if (A->getOption().matches(options::OPT_m64)) {
603  AT = Target.get64BitArchVariant().getArch();
604  if (Target.getEnvironment() == llvm::Triple::GNUX32)
605  Target.setEnvironment(llvm::Triple::GNU);
606  else if (Target.getEnvironment() == llvm::Triple::MuslX32)
607  Target.setEnvironment(llvm::Triple::Musl);
608  } else if (A->getOption().matches(options::OPT_mx32) &&
609  Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
610  AT = llvm::Triple::x86_64;
611  if (Target.getEnvironment() == llvm::Triple::Musl)
612  Target.setEnvironment(llvm::Triple::MuslX32);
613  else
614  Target.setEnvironment(llvm::Triple::GNUX32);
615  } else if (A->getOption().matches(options::OPT_m32)) {
616  AT = Target.get32BitArchVariant().getArch();
617  if (Target.getEnvironment() == llvm::Triple::GNUX32)
618  Target.setEnvironment(llvm::Triple::GNU);
619  else if (Target.getEnvironment() == llvm::Triple::MuslX32)
620  Target.setEnvironment(llvm::Triple::Musl);
621  } else if (A->getOption().matches(options::OPT_m16) &&
622  Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
623  AT = llvm::Triple::x86;
624  Target.setEnvironment(llvm::Triple::CODE16);
625  }
626 
627  if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) {
628  Target.setArch(AT);
629  if (Target.isWindowsGNUEnvironment())
631  }
632  }
633 
634  // Handle -miamcu flag.
635  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
636  if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
637  D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
638  << Target.str();
639 
640  if (A && !A->getOption().matches(options::OPT_m32))
641  D.Diag(diag::err_drv_argument_not_allowed_with)
642  << "-miamcu" << A->getBaseArg().getAsString(Args);
643 
644  Target.setArch(llvm::Triple::x86);
645  Target.setArchName("i586");
646  Target.setEnvironment(llvm::Triple::UnknownEnvironment);
647  Target.setEnvironmentName("");
648  Target.setOS(llvm::Triple::ELFIAMCU);
649  Target.setVendor(llvm::Triple::UnknownVendor);
650  Target.setVendorName("intel");
651  }
652 
653  // If target is MIPS adjust the target triple
654  // accordingly to provided ABI name.
655  if (Target.isMIPS()) {
656  if ((A = Args.getLastArg(options::OPT_mabi_EQ))) {
657  StringRef ABIName = A->getValue();
658  if (ABIName == "32") {
659  Target = Target.get32BitArchVariant();
660  if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
661  Target.getEnvironment() == llvm::Triple::GNUABIN32)
662  Target.setEnvironment(llvm::Triple::GNU);
663  } else if (ABIName == "n32") {
664  Target = Target.get64BitArchVariant();
665  if (Target.getEnvironment() == llvm::Triple::GNU ||
666  Target.getEnvironment() == llvm::Triple::GNUABI64)
667  Target.setEnvironment(llvm::Triple::GNUABIN32);
668  } else if (ABIName == "64") {
669  Target = Target.get64BitArchVariant();
670  if (Target.getEnvironment() == llvm::Triple::GNU ||
671  Target.getEnvironment() == llvm::Triple::GNUABIN32)
672  Target.setEnvironment(llvm::Triple::GNUABI64);
673  }
674  }
675  }
676 
677  // If target is RISC-V adjust the target triple according to
678  // provided architecture name
679  if (Target.isRISCV()) {
680  if ((A = Args.getLastArg(options::OPT_march_EQ))) {
681  StringRef ArchName = A->getValue();
682  if (ArchName.startswith_insensitive("rv32"))
683  Target.setArch(llvm::Triple::riscv32);
684  else if (ArchName.startswith_insensitive("rv64"))
685  Target.setArch(llvm::Triple::riscv64);
686  }
687  }
688 
689  return Target;
690 }
691 
692 // Parse the LTO options and record the type of LTO compilation
693 // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)?
694 // option occurs last.
695 static driver::LTOKind parseLTOMode(Driver &D, const llvm::opt::ArgList &Args,
696  OptSpecifier OptEq, OptSpecifier OptNeg) {
697  if (!Args.hasFlag(OptEq, OptNeg, false))
698  return LTOK_None;
699 
700  const Arg *A = Args.getLastArg(OptEq);
701  StringRef LTOName = A->getValue();
702 
703  driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
704  .Case("full", LTOK_Full)
705  .Case("thin", LTOK_Thin)
706  .Default(LTOK_Unknown);
707 
708  if (LTOMode == LTOK_Unknown) {
709  D.Diag(diag::err_drv_unsupported_option_argument)
710  << A->getSpelling() << A->getValue();
711  return LTOK_None;
712  }
713  return LTOMode;
714 }
715 
716 // Parse the LTO options.
717 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
718  LTOMode =
719  parseLTOMode(*this, Args, options::OPT_flto_EQ, options::OPT_fno_lto);
720 
721  OffloadLTOMode = parseLTOMode(*this, Args, options::OPT_foffload_lto_EQ,
722  options::OPT_fno_offload_lto);
723 }
724 
725 /// Compute the desired OpenMP runtime from the flags provided.
727  StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
728 
729  const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
730  if (A)
731  RuntimeName = A->getValue();
732 
733  auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
734  .Case("libomp", OMPRT_OMP)
735  .Case("libgomp", OMPRT_GOMP)
736  .Case("libiomp5", OMPRT_IOMP5)
737  .Default(OMPRT_Unknown);
738 
739  if (RT == OMPRT_Unknown) {
740  if (A)
741  Diag(diag::err_drv_unsupported_option_argument)
742  << A->getSpelling() << A->getValue();
743  else
744  // FIXME: We could use a nicer diagnostic here.
745  Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
746  }
747 
748  return RT;
749 }
750 
752  InputList &Inputs) {
753 
754  //
755  // CUDA/HIP
756  //
757  // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
758  // or HIP type. However, mixed CUDA/HIP compilation is not supported.
759  bool IsCuda =
760  llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
761  return types::isCuda(I.first);
762  });
763  bool IsHIP =
764  llvm::any_of(Inputs,
765  [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
766  return types::isHIP(I.first);
767  }) ||
768  C.getInputArgs().hasArg(options::OPT_hip_link);
769  if (IsCuda && IsHIP) {
770  Diag(clang::diag::err_drv_mix_cuda_hip);
771  return;
772  }
773  if (IsCuda) {
774  const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
775  const llvm::Triple &HostTriple = HostTC->getTriple();
776  auto OFK = Action::OFK_Cuda;
777  auto CudaTriple =
778  getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple);
779  if (!CudaTriple)
780  return;
781  // Use the CUDA and host triples as the key into the ToolChains map,
782  // because the device toolchain we create depends on both.
783  auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()];
784  if (!CudaTC) {
785  CudaTC = std::make_unique<toolchains::CudaToolChain>(
786  *this, *CudaTriple, *HostTC, C.getInputArgs());
787  }
788  C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
789  } else if (IsHIP) {
790  if (auto *OMPTargetArg =
791  C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
792  Diag(clang::diag::err_drv_unsupported_opt_for_language_mode)
793  << OMPTargetArg->getSpelling() << "HIP";
794  return;
795  }
796  const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
797  auto OFK = Action::OFK_HIP;
798  auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
799  if (!HIPTriple)
800  return;
801  auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple,
802  *HostTC, OFK);
803  assert(HIPTC && "Could not create offloading device tool chain.");
804  C.addOffloadDeviceToolChain(HIPTC, OFK);
805  }
806 
807  //
808  // OpenMP
809  //
810  // We need to generate an OpenMP toolchain if the user specified targets with
811  // the -fopenmp-targets option or used --offload-arch with OpenMP enabled.
812  bool IsOpenMPOffloading =
813  C.getInputArgs().hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
814  options::OPT_fno_openmp, false) &&
815  (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ) ||
816  C.getInputArgs().hasArg(options::OPT_offload_arch_EQ));
817  if (IsOpenMPOffloading) {
818  // We expect that -fopenmp-targets is always used in conjunction with the
819  // option -fopenmp specifying a valid runtime with offloading support, i.e.
820  // libomp or libiomp.
821  OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(C.getInputArgs());
822  if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) {
823  Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
824  return;
825  }
826 
827  llvm::StringMap<llvm::DenseSet<StringRef>> DerivedArchs;
828  llvm::StringMap<StringRef> FoundNormalizedTriples;
829  llvm::SmallVector<StringRef, 4> OpenMPTriples;
830 
831  // If the user specified -fopenmp-targets= we create a toolchain for each
832  // valid triple. Otherwise, if only --offload-arch= was specified we instead
833  // attempt to derive the appropriate toolchains from the arguments.
834  if (Arg *OpenMPTargets =
835  C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
836  if (OpenMPTargets && !OpenMPTargets->getNumValues()) {
837  Diag(clang::diag::warn_drv_empty_joined_argument)
838  << OpenMPTargets->getAsString(C.getInputArgs());
839  return;
840  }
841  llvm::copy(OpenMPTargets->getValues(), std::back_inserter(OpenMPTriples));
842  } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) &&
843  !IsHIP && !IsCuda) {
844  const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
845  auto AMDTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
846  auto NVPTXTriple = getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(),
847  HostTC->getTriple());
848 
849  // Attempt to deduce the offloading triple from the set of architectures.
850  // We can only correctly deduce NVPTX / AMDGPU triples currently.
852  getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr);
853  for (StringRef Arch : Archs) {
854  if (NVPTXTriple && IsNVIDIAGpuArch(StringToCudaArch(
855  getProcessorFromTargetID(*NVPTXTriple, Arch)))) {
856  DerivedArchs[NVPTXTriple->getTriple()].insert(Arch);
857  } else if (AMDTriple &&
859  getProcessorFromTargetID(*AMDTriple, Arch)))) {
860  DerivedArchs[AMDTriple->getTriple()].insert(Arch);
861  } else {
862  Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) << Arch;
863  return;
864  }
865  }
866 
867  for (const auto &TripleAndArchs : DerivedArchs)
868  OpenMPTriples.push_back(TripleAndArchs.first());
869  }
870 
871  for (StringRef Val : OpenMPTriples) {
872  llvm::Triple TT(ToolChain::getOpenMPTriple(Val));
873  std::string NormalizedName = TT.normalize();
874 
875  // Make sure we don't have a duplicate triple.
876  auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
877  if (Duplicate != FoundNormalizedTriples.end()) {
878  Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
879  << Val << Duplicate->second;
880  continue;
881  }
882 
883  // Store the current triple so that we can check for duplicates in the
884  // following iterations.
885  FoundNormalizedTriples[NormalizedName] = Val;
886 
887  // If the specified target is invalid, emit a diagnostic.
888  if (TT.getArch() == llvm::Triple::UnknownArch)
889  Diag(clang::diag::err_drv_invalid_omp_target) << Val;
890  else {
891  const ToolChain *TC;
892  // Device toolchains have to be selected differently. They pair host
893  // and device in their implementation.
894  if (TT.isNVPTX() || TT.isAMDGCN()) {
895  const ToolChain *HostTC =
896  C.getSingleOffloadToolChain<Action::OFK_Host>();
897  assert(HostTC && "Host toolchain should be always defined.");
898  auto &DeviceTC =
899  ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
900  if (!DeviceTC) {
901  if (TT.isNVPTX())
902  DeviceTC = std::make_unique<toolchains::CudaToolChain>(
903  *this, TT, *HostTC, C.getInputArgs());
904  else if (TT.isAMDGCN())
905  DeviceTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
906  *this, TT, *HostTC, C.getInputArgs());
907  else
908  assert(DeviceTC && "Device toolchain not defined.");
909  }
910 
911  TC = DeviceTC.get();
912  } else
913  TC = &getToolChain(C.getInputArgs(), TT);
914  C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
915  if (DerivedArchs.find(TT.getTriple()) != DerivedArchs.end())
916  KnownArchs[TC] = DerivedArchs[TT.getTriple()];
917  }
918  }
919  } else if (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)) {
920  Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
921  return;
922  }
923 
924  //
925  // TODO: Add support for other offloading programming models here.
926  //
927 }
928 
929 static void appendOneArg(InputArgList &Args, const Arg *Opt,
930  const Arg *BaseArg) {
931  // The args for config files or /clang: flags belong to different InputArgList
932  // objects than Args. This copies an Arg from one of those other InputArgLists
933  // to the ownership of Args.
934  unsigned Index = Args.MakeIndex(Opt->getSpelling());
935  Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index),
936  Index, BaseArg);
937  Copy->getValues() = Opt->getValues();
938  if (Opt->isClaimed())
939  Copy->claim();
940  Copy->setOwnsValues(Opt->getOwnsValues());
941  Opt->setOwnsValues(false);
942  Args.append(Copy);
943 }
944 
945 bool Driver::readConfigFile(StringRef FileName,
946  llvm::cl::ExpansionContext &ExpCtx) {
947  // Try opening the given file.
948  auto Status = getVFS().status(FileName);
949  if (!Status) {
950  Diag(diag::err_drv_cannot_open_config_file)
951  << FileName << Status.getError().message();
952  return true;
953  }
954  if (Status->getType() != llvm::sys::fs::file_type::regular_file) {
955  Diag(diag::err_drv_cannot_open_config_file)
956  << FileName << "not a regular file";
957  return true;
958  }
959 
960  // Try reading the given file.
962  if (llvm::Error Err = ExpCtx.readConfigFile(FileName, NewCfgArgs)) {
963  Diag(diag::err_drv_cannot_read_config_file)
964  << FileName << toString(std::move(Err));
965  return true;
966  }
967 
968  // Read options from config file.
969  llvm::SmallString<128> CfgFileName(FileName);
970  llvm::sys::path::native(CfgFileName);
971  bool ContainErrors;
972  std::unique_ptr<InputArgList> NewOptions = std::make_unique<InputArgList>(
973  ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
974  if (ContainErrors)
975  return true;
976 
977  // Claim all arguments that come from a configuration file so that the driver
978  // does not warn on any that is unused.
979  for (Arg *A : *NewOptions)
980  A->claim();
981 
982  if (!CfgOptions)
983  CfgOptions = std::move(NewOptions);
984  else {
985  // If this is a subsequent config file, append options to the previous one.
986  for (auto *Opt : *NewOptions) {
987  const Arg *BaseArg = &Opt->getBaseArg();
988  if (BaseArg == Opt)
989  BaseArg = nullptr;
990  appendOneArg(*CfgOptions, Opt, BaseArg);
991  }
992  }
993  ConfigFiles.push_back(std::string(CfgFileName));
994  return false;
995 }
996 
997 bool Driver::loadConfigFiles() {
998  llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(),
999  llvm::cl::tokenizeConfigFile);
1000  ExpCtx.setVFS(&getVFS());
1001 
1002  // Process options that change search path for config files.
1003  if (CLOptions) {
1004  if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
1005  SmallString<128> CfgDir;
1006  CfgDir.append(
1007  CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
1008  if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
1009  SystemConfigDir.clear();
1010  else
1011  SystemConfigDir = static_cast<std::string>(CfgDir);
1012  }
1013  if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
1014  SmallString<128> CfgDir;
1015  llvm::sys::fs::expand_tilde(
1016  CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ), CfgDir);
1017  if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
1018  UserConfigDir.clear();
1019  else
1020  UserConfigDir = static_cast<std::string>(CfgDir);
1021  }
1022  }
1023 
1024  // Prepare list of directories where config file is searched for.
1025  StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir};
1026  ExpCtx.setSearchDirs(CfgFileSearchDirs);
1027 
1028  // First try to load configuration from the default files, return on error.
1029  if (loadDefaultConfigFiles(ExpCtx))
1030  return true;
1031 
1032  // Then load configuration files specified explicitly.
1033  SmallString<128> CfgFilePath;
1034  if (CLOptions) {
1035  for (auto CfgFileName : CLOptions->getAllArgValues(options::OPT_config)) {
1036  // If argument contains directory separator, treat it as a path to
1037  // configuration file.
1038  if (llvm::sys::path::has_parent_path(CfgFileName)) {
1039  CfgFilePath.assign(CfgFileName);
1040  if (llvm::sys::path::is_relative(CfgFilePath)) {
1041  if (getVFS().makeAbsolute(CfgFilePath)) {
1042  Diag(diag::err_drv_cannot_open_config_file)
1043  << CfgFilePath << "cannot get absolute path";
1044  return true;
1045  }
1046  }
1047  } else if (!ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1048  // Report an error that the config file could not be found.
1049  Diag(diag::err_drv_config_file_not_found) << CfgFileName;
1050  for (const StringRef &SearchDir : CfgFileSearchDirs)
1051  if (!SearchDir.empty())
1052  Diag(diag::note_drv_config_file_searched_in) << SearchDir;
1053  return true;
1054  }
1055 
1056  // Try to read the config file, return on error.
1057  if (readConfigFile(CfgFilePath, ExpCtx))
1058  return true;
1059  }
1060  }
1061 
1062  // No error occurred.
1063  return false;
1064 }
1065 
1066 bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) {
1067  // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty
1068  // value.
1069  if (const char *NoConfigEnv = ::getenv("CLANG_NO_DEFAULT_CONFIG")) {
1070  if (*NoConfigEnv)
1071  return false;
1072  }
1073  if (CLOptions && CLOptions->hasArg(options::OPT_no_default_config))
1074  return false;
1075 
1076  std::string RealMode = getExecutableForDriverMode(Mode);
1077  std::string Triple;
1078 
1079  // If name prefix is present, no --target= override was passed via CLOptions
1080  // and the name prefix is not a valid triple, force it for backwards
1081  // compatibility.
1082  if (!ClangNameParts.TargetPrefix.empty() &&
1083  computeTargetTriple(*this, "/invalid/", *CLOptions).str() ==
1084  "/invalid/") {
1085  llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix};
1086  if (PrefixTriple.getArch() == llvm::Triple::UnknownArch ||
1087  PrefixTriple.isOSUnknown())
1088  Triple = PrefixTriple.str();
1089  }
1090 
1091  // Otherwise, use the real triple as used by the driver.
1092  if (Triple.empty()) {
1093  llvm::Triple RealTriple =
1094  computeTargetTriple(*this, TargetTriple, *CLOptions);
1095  Triple = RealTriple.str();
1096  assert(!Triple.empty());
1097  }
1098 
1099  // Search for config files in the following order:
1100  // 1. <triple>-<mode>.cfg using real driver mode
1101  // (e.g. i386-pc-linux-gnu-clang++.cfg).
1102  // 2. <triple>-<mode>.cfg using executable suffix
1103  // (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++).
1104  // 3. <triple>.cfg + <mode>.cfg using real driver mode
1105  // (e.g. i386-pc-linux-gnu.cfg + clang++.cfg).
1106  // 4. <triple>.cfg + <mode>.cfg using executable suffix
1107  // (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++).
1108 
1109  // Try loading <triple>-<mode>.cfg, and return if we find a match.
1110  SmallString<128> CfgFilePath;
1111  std::string CfgFileName = Triple + '-' + RealMode + ".cfg";
1112  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1113  return readConfigFile(CfgFilePath, ExpCtx);
1114 
1115  bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() &&
1116  ClangNameParts.ModeSuffix != RealMode;
1117  if (TryModeSuffix) {
1118  CfgFileName = Triple + '-' + ClangNameParts.ModeSuffix + ".cfg";
1119  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1120  return readConfigFile(CfgFilePath, ExpCtx);
1121  }
1122 
1123  // Try loading <mode>.cfg, and return if loading failed. If a matching file
1124  // was not found, still proceed on to try <triple>.cfg.
1125  CfgFileName = RealMode + ".cfg";
1126  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1127  if (readConfigFile(CfgFilePath, ExpCtx))
1128  return true;
1129  } else if (TryModeSuffix) {
1130  CfgFileName = ClangNameParts.ModeSuffix + ".cfg";
1131  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath) &&
1132  readConfigFile(CfgFilePath, ExpCtx))
1133  return true;
1134  }
1135 
1136  // Try loading <triple>.cfg and return if we find a match.
1137  CfgFileName = Triple + ".cfg";
1138  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1139  return readConfigFile(CfgFilePath, ExpCtx);
1140 
1141  // If we were unable to find a config file deduced from executable name,
1142  // that is not an error.
1143  return false;
1144 }
1145 
1147  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
1148 
1149  // FIXME: Handle environment options which affect driver behavior, somewhere
1150  // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
1151 
1152  // We look for the driver mode option early, because the mode can affect
1153  // how other options are parsed.
1154 
1155  auto DriverMode = getDriverMode(ClangExecutable, ArgList.slice(1));
1156  if (!DriverMode.empty())
1157  setDriverMode(DriverMode);
1158 
1159  // FIXME: What are we going to do with -V and -b?
1160 
1161  // Arguments specified in command line.
1162  bool ContainsError;
1163  CLOptions = std::make_unique<InputArgList>(
1164  ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
1165 
1166  // Try parsing configuration file.
1167  if (!ContainsError)
1168  ContainsError = loadConfigFiles();
1169  bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
1170 
1171  // All arguments, from both config file and command line.
1172  InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
1173  : std::move(*CLOptions));
1174 
1175  if (HasConfigFile)
1176  for (auto *Opt : *CLOptions) {
1177  if (Opt->getOption().matches(options::OPT_config))
1178  continue;
1179  const Arg *BaseArg = &Opt->getBaseArg();
1180  if (BaseArg == Opt)
1181  BaseArg = nullptr;
1182  appendOneArg(Args, Opt, BaseArg);
1183  }
1184 
1185  // In CL mode, look for any pass-through arguments
1186  if (IsCLMode() && !ContainsError) {
1187  SmallVector<const char *, 16> CLModePassThroughArgList;
1188  for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1189  A->claim();
1190  CLModePassThroughArgList.push_back(A->getValue());
1191  }
1192 
1193  if (!CLModePassThroughArgList.empty()) {
1194  // Parse any pass through args using default clang processing rather
1195  // than clang-cl processing.
1196  auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1197  ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1198 
1199  if (!ContainsError)
1200  for (auto *Opt : *CLModePassThroughOptions) {
1201  appendOneArg(Args, Opt, nullptr);
1202  }
1203  }
1204  }
1205 
1206  // Check for working directory option before accessing any files
1207  if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1208  if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1209  Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1210 
1211  // FIXME: This stuff needs to go into the Compilation, not the driver.
1212  bool CCCPrintPhases;
1213 
1214  // Silence driver warnings if requested
1215  Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1216 
1217  // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
1218  Args.ClaimAllArgs(options::OPT_canonical_prefixes);
1219  Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1220 
1221  // f(no-)integated-cc1 is also used very early in main.
1222  Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1223  Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1224 
1225  // Ignore -pipe.
1226  Args.ClaimAllArgs(options::OPT_pipe);
1227 
1228  // Extract -ccc args.
1229  //
1230  // FIXME: We need to figure out where this behavior should live. Most of it
1231  // should be outside in the client; the parts that aren't should have proper
1232  // options, either by introducing new ones or by overloading gcc ones like -V
1233  // or -b.
1234  CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1235  CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1236  if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1237  CCCGenericGCCName = A->getValue();
1238 
1239  // Process -fproc-stat-report options.
1240  if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) {
1241  CCPrintProcessStats = true;
1242  CCPrintStatReportFilename = A->getValue();
1243  }
1244  if (Args.hasArg(options::OPT_fproc_stat_report))
1245  CCPrintProcessStats = true;
1246 
1247  // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1248  // and getToolChain is const.
1249  if (IsCLMode()) {
1250  // clang-cl targets MSVC-style Win32.
1251  llvm::Triple T(TargetTriple);
1252  T.setOS(llvm::Triple::Win32);
1253  T.setVendor(llvm::Triple::PC);
1254  T.setEnvironment(llvm::Triple::MSVC);
1255  T.setObjectFormat(llvm::Triple::COFF);
1256  if (Args.hasArg(options::OPT__SLASH_arm64EC))
1257  T.setArch(llvm::Triple::aarch64, llvm::Triple::AArch64SubArch_arm64ec);
1258  TargetTriple = T.str();
1259  } else if (IsDXCMode()) {
1260  // Build TargetTriple from target_profile option for clang-dxc.
1261  if (const Arg *A = Args.getLastArg(options::OPT_target_profile)) {
1262  StringRef TargetProfile = A->getValue();
1263  if (auto Triple =
1265  TargetTriple = *Triple;
1266  else
1267  Diag(diag::err_drv_invalid_directx_shader_module) << TargetProfile;
1268 
1269  A->claim();
1270  } else {
1271  Diag(diag::err_drv_dxc_missing_target_profile);
1272  }
1273  }
1274 
1275  if (const Arg *A = Args.getLastArg(options::OPT_target))
1276  TargetTriple = A->getValue();
1277  if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1278  Dir = InstalledDir = A->getValue();
1279  for (const Arg *A : Args.filtered(options::OPT_B)) {
1280  A->claim();
1281  PrefixDirs.push_back(A->getValue(0));
1282  }
1283  if (Optional<std::string> CompilerPathValue =
1284  llvm::sys::Process::GetEnv("COMPILER_PATH")) {
1285  StringRef CompilerPath = *CompilerPathValue;
1286  while (!CompilerPath.empty()) {
1287  std::pair<StringRef, StringRef> Split =
1288  CompilerPath.split(llvm::sys::EnvPathSeparator);
1289  PrefixDirs.push_back(std::string(Split.first));
1290  CompilerPath = Split.second;
1291  }
1292  }
1293  if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1294  SysRoot = A->getValue();
1295  if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1296  DyldPrefix = A->getValue();
1297 
1298  if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1299  ResourceDir = A->getValue();
1300 
1301  if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1302  SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1303  .Case("cwd", SaveTempsCwd)
1304  .Case("obj", SaveTempsObj)
1305  .Default(SaveTempsCwd);
1306  }
1307 
1308  if (const Arg *A = Args.getLastArg(options::OPT_offload_host_only,
1309  options::OPT_offload_device_only,
1310  options::OPT_offload_host_device)) {
1311  if (A->getOption().matches(options::OPT_offload_host_only))
1312  Offload = OffloadHost;
1313  else if (A->getOption().matches(options::OPT_offload_device_only))
1314  Offload = OffloadDevice;
1315  else
1316  Offload = OffloadHostDevice;
1317  }
1318 
1319  setLTOMode(Args);
1320 
1321  // Process -fembed-bitcode= flags.
1322  if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1323  StringRef Name = A->getValue();
1324  unsigned Model = llvm::StringSwitch<unsigned>(Name)
1325  .Case("off", EmbedNone)
1326  .Case("all", EmbedBitcode)
1327  .Case("bitcode", EmbedBitcode)
1328  .Case("marker", EmbedMarker)
1329  .Default(~0U);
1330  if (Model == ~0U) {
1331  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1332  << Name;
1333  } else
1334  BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1335  }
1336 
1337  // Remove existing compilation database so that each job can append to it.
1338  if (Arg *A = Args.getLastArg(options::OPT_MJ))
1339  llvm::sys::fs::remove(A->getValue());
1340 
1341  // Setting up the jobs for some precompile cases depends on whether we are
1342  // treating them as PCH, implicit modules or C++20 ones.
1343  // TODO: inferring the mode like this seems fragile (it meets the objective
1344  // of not requiring anything new for operation, however).
1345  const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
1346  ModulesModeCXX20 =
1347  !Args.hasArg(options::OPT_fmodules) && Std &&
1348  (Std->containsValue("c++20") || Std->containsValue("c++2b") ||
1349  Std->containsValue("c++2a") || Std->containsValue("c++latest"));
1350 
1351  // Process -fmodule-header{=} flags.
1352  if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ,
1353  options::OPT_fmodule_header)) {
1354  // These flags force C++20 handling of headers.
1355  ModulesModeCXX20 = true;
1356  if (A->getOption().matches(options::OPT_fmodule_header))
1357  CXX20HeaderType = HeaderMode_Default;
1358  else {
1359  StringRef ArgName = A->getValue();
1360  unsigned Kind = llvm::StringSwitch<unsigned>(ArgName)
1361  .Case("user", HeaderMode_User)
1362  .Case("system", HeaderMode_System)
1363  .Default(~0U);
1364  if (Kind == ~0U) {
1365  Diags.Report(diag::err_drv_invalid_value)
1366  << A->getAsString(Args) << ArgName;
1367  } else
1368  CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind);
1369  }
1370  }
1371 
1372  std::unique_ptr<llvm::opt::InputArgList> UArgs =
1373  std::make_unique<InputArgList>(std::move(Args));
1374 
1375  // Perform the default argument translations.
1376  DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1377 
1378  // Owned by the host.
1379  const ToolChain &TC = getToolChain(
1380  *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1381 
1382  // Report warning when arm64EC option is overridden by specified target
1383  if ((TC.getTriple().getArch() != llvm::Triple::aarch64 ||
1384  TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) &&
1385  UArgs->hasArg(options::OPT__SLASH_arm64EC)) {
1386  getDiags().Report(clang::diag::warn_target_override_arm64ec)
1387  << TC.getTriple().str();
1388  }
1389 
1390  // The compilation takes ownership of Args.
1391  Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1392  ContainsError);
1393 
1394  if (!HandleImmediateArgs(*C))
1395  return C;
1396 
1397  // Construct the list of inputs.
1398  InputList Inputs;
1399  BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1400 
1401  // Populate the tool chains for the offloading devices, if any.
1403 
1404  // Construct the list of abstract actions to perform for this compilation. On
1405  // MachO targets this uses the driver-driver and universal actions.
1406  if (TC.getTriple().isOSBinFormatMachO())
1407  BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1408  else
1409  BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1410 
1411  if (CCCPrintPhases) {
1412  PrintActions(*C);
1413  return C;
1414  }
1415 
1416  BuildJobs(*C);
1417 
1418  return C;
1419 }
1420 
1421 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1422  llvm::opt::ArgStringList ASL;
1423  for (const auto *A : Args) {
1424  // Use user's original spelling of flags. For example, use
1425  // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
1426  // wrote the former.
1427  while (A->getAlias())
1428  A = A->getAlias();
1429  A->render(Args, ASL);
1430  }
1431 
1432  for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1433  if (I != ASL.begin())
1434  OS << ' ';
1435  llvm::sys::printArg(OS, *I, true);
1436  }
1437  OS << '\n';
1438 }
1439 
1440 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1441  SmallString<128> &CrashDiagDir) {
1442  using namespace llvm::sys;
1443  assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1444  "Only knows about .crash files on Darwin");
1445 
1446  // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1447  // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1448  // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1449  path::home_directory(CrashDiagDir);
1450  if (CrashDiagDir.startswith("/var/root"))
1451  CrashDiagDir = "/";
1452  path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1453  int PID =
1454 #if LLVM_ON_UNIX
1455  getpid();
1456 #else
1457  0;
1458 #endif
1459  std::error_code EC;
1460  fs::file_status FileStatus;
1461  TimePoint<> LastAccessTime;
1462  SmallString<128> CrashFilePath;
1463  // Lookup the .crash files and get the one generated by a subprocess spawned
1464  // by this driver invocation.
1465  for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1466  File != FileEnd && !EC; File.increment(EC)) {
1467  StringRef FileName = path::filename(File->path());
1468  if (!FileName.startswith(Name))
1469  continue;
1470  if (fs::status(File->path(), FileStatus))
1471  continue;
1472  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1473  llvm::MemoryBuffer::getFile(File->path());
1474  if (!CrashFile)
1475  continue;
1476  // The first line should start with "Process:", otherwise this isn't a real
1477  // .crash file.
1478  StringRef Data = CrashFile.get()->getBuffer();
1479  if (!Data.startswith("Process:"))
1480  continue;
1481  // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1482  size_t ParentProcPos = Data.find("Parent Process:");
1483  if (ParentProcPos == StringRef::npos)
1484  continue;
1485  size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1486  if (LineEnd == StringRef::npos)
1487  continue;
1488  StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1489  int OpenBracket = -1, CloseBracket = -1;
1490  for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1491  if (ParentProcess[i] == '[')
1492  OpenBracket = i;
1493  if (ParentProcess[i] == ']')
1494  CloseBracket = i;
1495  }
1496  // Extract the parent process PID from the .crash file and check whether
1497  // it matches this driver invocation pid.
1498  int CrashPID;
1499  if (OpenBracket < 0 || CloseBracket < 0 ||
1500  ParentProcess.slice(OpenBracket + 1, CloseBracket)
1501  .getAsInteger(10, CrashPID) || CrashPID != PID) {
1502  continue;
1503  }
1504 
1505  // Found a .crash file matching the driver pid. To avoid getting an older
1506  // and misleading crash file, continue looking for the most recent.
1507  // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1508  // multiple crashes poiting to the same parent process. Since the driver
1509  // does not collect pid information for the dispatched invocation there's
1510  // currently no way to distinguish among them.
1511  const auto FileAccessTime = FileStatus.getLastModificationTime();
1512  if (FileAccessTime > LastAccessTime) {
1513  CrashFilePath.assign(File->path());
1514  LastAccessTime = FileAccessTime;
1515  }
1516  }
1517 
1518  // If found, copy it over to the location of other reproducer files.
1519  if (!CrashFilePath.empty()) {
1520  EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1521  if (EC)
1522  return false;
1523  return true;
1524  }
1525 
1526  return false;
1527 }
1528 
1529 static const char BugReporMsg[] =
1530  "\n********************\n\n"
1531  "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1532  "Preprocessed source(s) and associated run script(s) are located at:";
1533 
1534 // When clang crashes, produce diagnostic information including the fully
1535 // preprocessed source file(s). Request that the developer attach the
1536 // diagnostic information to a bug report.
1538  Compilation &C, const Command &FailingCommand,
1539  StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1540  if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1541  return;
1542 
1543  unsigned Level = 1;
1544  if (Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ)) {
1545  Level = llvm::StringSwitch<unsigned>(A->getValue())
1546  .Case("off", 0)
1547  .Case("compiler", 1)
1548  .Case("all", 2)
1549  .Default(1);
1550  }
1551  if (!Level)
1552  return;
1553 
1554  // Don't try to generate diagnostics for dsymutil jobs.
1555  if (FailingCommand.getCreator().isDsymutilJob())
1556  return;
1557 
1558  bool IsLLD = false;
1559  ArgStringList SavedTemps;
1560  if (FailingCommand.getCreator().isLinkJob()) {
1561  C.getDefaultToolChain().GetLinkerPath(&IsLLD);
1562  if (!IsLLD || Level < 2)
1563  return;
1564 
1565  // If lld crashed, we will re-run the same command with the input it used
1566  // to have. In that case we should not remove temp files in
1567  // initCompilationForDiagnostics yet. They will be added back and removed
1568  // later.
1569  SavedTemps = std::move(C.getTempFiles());
1570  assert(!C.getTempFiles().size());
1571  }
1572 
1573  // Print the version of the compiler.
1574  PrintVersion(C, llvm::errs());
1575 
1576  // Suppress driver output and emit preprocessor output to temp file.
1577  CCGenDiagnostics = true;
1578 
1579  // Save the original job command(s).
1580  Command Cmd = FailingCommand;
1581 
1582  // Keep track of whether we produce any errors while trying to produce
1583  // preprocessed sources.
1584  DiagnosticErrorTrap Trap(Diags);
1585 
1586  // Suppress tool output.
1587  C.initCompilationForDiagnostics();
1588 
1589  // If lld failed, rerun it again with --reproduce.
1590  if (IsLLD) {
1591  const char *TmpName = CreateTempFile(C, "linker-crash", "tar");
1592  Command NewLLDInvocation = Cmd;
1593  llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments();
1594  StringRef ReproduceOption =
1595  C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment()
1596  ? "/reproduce:"
1597  : "--reproduce=";
1598  ArgList.push_back(Saver.save(Twine(ReproduceOption) + TmpName).data());
1599  NewLLDInvocation.replaceArguments(std::move(ArgList));
1600 
1601  // Redirect stdout/stderr to /dev/null.
1602  NewLLDInvocation.Execute({None, {""}, {""}}, nullptr, nullptr);
1603  Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg;
1604  Diag(clang::diag::note_drv_command_failed_diag_msg) << TmpName;
1605  Diag(clang::diag::note_drv_command_failed_diag_msg)
1606  << "\n\n********************";
1607  if (Report)
1608  Report->TemporaryFiles.push_back(TmpName);
1609  return;
1610  }
1611 
1612  // Construct the list of inputs.
1613  InputList Inputs;
1614  BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1615 
1616  for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1617  bool IgnoreInput = false;
1618 
1619  // Ignore input from stdin or any inputs that cannot be preprocessed.
1620  // Check type first as not all linker inputs have a value.
1621  if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1622  IgnoreInput = true;
1623  } else if (!strcmp(it->second->getValue(), "-")) {
1624  Diag(clang::diag::note_drv_command_failed_diag_msg)
1625  << "Error generating preprocessed source(s) - "
1626  "ignoring input from stdin.";
1627  IgnoreInput = true;
1628  }
1629 
1630  if (IgnoreInput) {
1631  it = Inputs.erase(it);
1632  ie = Inputs.end();
1633  } else {
1634  ++it;
1635  }
1636  }
1637 
1638  if (Inputs.empty()) {
1639  Diag(clang::diag::note_drv_command_failed_diag_msg)
1640  << "Error generating preprocessed source(s) - "
1641  "no preprocessable inputs.";
1642  return;
1643  }
1644 
1645  // Don't attempt to generate preprocessed files if multiple -arch options are
1646  // used, unless they're all duplicates.
1647  llvm::StringSet<> ArchNames;
1648  for (const Arg *A : C.getArgs()) {
1649  if (A->getOption().matches(options::OPT_arch)) {
1650  StringRef ArchName = A->getValue();
1651  ArchNames.insert(ArchName);
1652  }
1653  }
1654  if (ArchNames.size() > 1) {
1655  Diag(clang::diag::note_drv_command_failed_diag_msg)
1656  << "Error generating preprocessed source(s) - cannot generate "
1657  "preprocessed source with multiple -arch options.";
1658  return;
1659  }
1660 
1661  // Construct the list of abstract actions to perform for this compilation. On
1662  // Darwin OSes this uses the driver-driver and builds universal actions.
1663  const ToolChain &TC = C.getDefaultToolChain();
1664  if (TC.getTriple().isOSBinFormatMachO())
1665  BuildUniversalActions(C, TC, Inputs);
1666  else
1667  BuildActions(C, C.getArgs(), Inputs, C.getActions());
1668 
1669  BuildJobs(C);
1670 
1671  // If there were errors building the compilation, quit now.
1672  if (Trap.hasErrorOccurred()) {
1673  Diag(clang::diag::note_drv_command_failed_diag_msg)
1674  << "Error generating preprocessed source(s).";
1675  return;
1676  }
1677 
1678  // Generate preprocessed output.
1679  SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1680  C.ExecuteJobs(C.getJobs(), FailingCommands);
1681 
1682  // If any of the preprocessing commands failed, clean up and exit.
1683  if (!FailingCommands.empty()) {
1684  Diag(clang::diag::note_drv_command_failed_diag_msg)
1685  << "Error generating preprocessed source(s).";
1686  return;
1687  }
1688 
1689  const ArgStringList &TempFiles = C.getTempFiles();
1690  if (TempFiles.empty()) {
1691  Diag(clang::diag::note_drv_command_failed_diag_msg)
1692  << "Error generating preprocessed source(s).";
1693  return;
1694  }
1695 
1696  Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg;
1697 
1698  SmallString<128> VFS;
1699  SmallString<128> ReproCrashFilename;
1700  for (const char *TempFile : TempFiles) {
1701  Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1702  if (Report)
1703  Report->TemporaryFiles.push_back(TempFile);
1704  if (ReproCrashFilename.empty()) {
1705  ReproCrashFilename = TempFile;
1706  llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1707  }
1708  if (StringRef(TempFile).endswith(".cache")) {
1709  // In some cases (modules) we'll dump extra data to help with reproducing
1710  // the crash into a directory next to the output.
1711  VFS = llvm::sys::path::filename(TempFile);
1712  llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1713  }
1714  }
1715 
1716  for (const char *TempFile : SavedTemps)
1717  C.addTempFile(TempFile);
1718 
1719  // Assume associated files are based off of the first temporary file.
1720  CrashReportInfo CrashInfo(TempFiles[0], VFS);
1721 
1722  llvm::SmallString<128> Script(CrashInfo.Filename);
1723  llvm::sys::path::replace_extension(Script, "sh");
1724  std::error_code EC;
1725  llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew,
1726  llvm::sys::fs::FA_Write,
1727  llvm::sys::fs::OF_Text);
1728  if (EC) {
1729  Diag(clang::diag::note_drv_command_failed_diag_msg)
1730  << "Error generating run script: " << Script << " " << EC.message();
1731  } else {
1732  ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1733  << "# Driver args: ";
1734  printArgList(ScriptOS, C.getInputArgs());
1735  ScriptOS << "# Original command: ";
1736  Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1737  Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1738  if (!AdditionalInformation.empty())
1739  ScriptOS << "\n# Additional information: " << AdditionalInformation
1740  << "\n";
1741  if (Report)
1742  Report->TemporaryFiles.push_back(std::string(Script.str()));
1743  Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1744  }
1745 
1746  // On darwin, provide information about the .crash diagnostic report.
1747  if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1748  SmallString<128> CrashDiagDir;
1749  if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1750  Diag(clang::diag::note_drv_command_failed_diag_msg)
1751  << ReproCrashFilename.str();
1752  } else { // Suggest a directory for the user to look for .crash files.
1753  llvm::sys::path::append(CrashDiagDir, Name);
1754  CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1755  Diag(clang::diag::note_drv_command_failed_diag_msg)
1756  << "Crash backtrace is located in";
1757  Diag(clang::diag::note_drv_command_failed_diag_msg)
1758  << CrashDiagDir.str();
1759  Diag(clang::diag::note_drv_command_failed_diag_msg)
1760  << "(choose the .crash file that corresponds to your crash)";
1761  }
1762  }
1763 
1764  for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file_EQ))
1765  Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1766 
1767  Diag(clang::diag::note_drv_command_failed_diag_msg)
1768  << "\n\n********************";
1769 }
1770 
1771 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1772  // Since commandLineFitsWithinSystemLimits() may underestimate system's
1773  // capacity if the tool does not support response files, there is a chance/
1774  // that things will just work without a response file, so we silently just
1775  // skip it.
1776  if (Cmd.getResponseFileSupport().ResponseKind ==
1778  llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1779  Cmd.getArguments()))
1780  return;
1781 
1782  std::string TmpName = GetTemporaryPath("response", "txt");
1783  Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1784 }
1785 
1787  Compilation &C,
1788  SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1789  if (C.getArgs().hasArg(options::OPT_fdriver_only)) {
1790  if (C.getArgs().hasArg(options::OPT_v))
1791  C.getJobs().Print(llvm::errs(), "\n", true);
1792 
1793  C.ExecuteJobs(C.getJobs(), FailingCommands, /*LogOnly=*/true);
1794 
1795  // If there were errors building the compilation, quit now.
1796  if (!FailingCommands.empty() || Diags.hasErrorOccurred())
1797  return 1;
1798 
1799  return 0;
1800  }
1801 
1802  // Just print if -### was present.
1803  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1804  C.getJobs().Print(llvm::errs(), "\n", true);
1805  return 0;
1806  }
1807 
1808  // If there were errors building the compilation, quit now.
1809  if (Diags.hasErrorOccurred())
1810  return 1;
1811 
1812  // Set up response file names for each command, if necessary.
1813  for (auto &Job : C.getJobs())
1814  setUpResponseFiles(C, Job);
1815 
1816  C.ExecuteJobs(C.getJobs(), FailingCommands);
1817 
1818  // If the command succeeded, we are done.
1819  if (FailingCommands.empty())
1820  return 0;
1821 
1822  // Otherwise, remove result files and print extra information about abnormal
1823  // failures.
1824  int Res = 0;
1825  for (const auto &CmdPair : FailingCommands) {
1826  int CommandRes = CmdPair.first;
1827  const Command *FailingCommand = CmdPair.second;
1828 
1829  // Remove result files if we're not saving temps.
1830  if (!isSaveTempsEnabled()) {
1831  const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1832  C.CleanupFileMap(C.getResultFiles(), JA, true);
1833 
1834  // Failure result files are valid unless we crashed.
1835  if (CommandRes < 0)
1836  C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1837  }
1838 
1839 #if LLVM_ON_UNIX
1840  // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1841  // for SIGPIPE. Do not print diagnostics for this case.
1842  if (CommandRes == EX_IOERR) {
1843  Res = CommandRes;
1844  continue;
1845  }
1846 #endif
1847 
1848  // Print extra information about abnormal failures, if possible.
1849  //
1850  // This is ad-hoc, but we don't want to be excessively noisy. If the result
1851  // status was 1, assume the command failed normally. In particular, if it
1852  // was the compiler then assume it gave a reasonable error code. Failures
1853  // in other tools are less common, and they generally have worse
1854  // diagnostics, so always print the diagnostic there.
1855  const Tool &FailingTool = FailingCommand->getCreator();
1856 
1857  if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1858  // FIXME: See FIXME above regarding result code interpretation.
1859  if (CommandRes < 0)
1860  Diag(clang::diag::err_drv_command_signalled)
1861  << FailingTool.getShortName();
1862  else
1863  Diag(clang::diag::err_drv_command_failed)
1864  << FailingTool.getShortName() << CommandRes;
1865  }
1866  }
1867  return Res;
1868 }
1869 
1870 void Driver::PrintHelp(bool ShowHidden) const {
1871  unsigned IncludedFlagsBitmask;
1872  unsigned ExcludedFlagsBitmask;
1873  std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1874  getIncludeExcludeOptionFlagMasks(IsCLMode());
1875 
1876  ExcludedFlagsBitmask |= options::NoDriverOption;
1877  if (!ShowHidden)
1878  ExcludedFlagsBitmask |= HelpHidden;
1879 
1880  if (IsFlangMode())
1881  IncludedFlagsBitmask |= options::FlangOption;
1882  else
1883  ExcludedFlagsBitmask |= options::FlangOnlyOption;
1884 
1885  std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1886  getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1887  IncludedFlagsBitmask, ExcludedFlagsBitmask,
1888  /*ShowAllAliases=*/false);
1889 }
1890 
1891 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1892  if (IsFlangMode()) {
1893  OS << getClangToolFullVersion("flang-new") << '\n';
1894  } else {
1895  // FIXME: The following handlers should use a callback mechanism, we don't
1896  // know what the client would like to do.
1897  OS << getClangFullVersion() << '\n';
1898  }
1899  const ToolChain &TC = C.getDefaultToolChain();
1900  OS << "Target: " << TC.getTripleString() << '\n';
1901 
1902  // Print the threading model.
1903  if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1904  // Don't print if the ToolChain would have barfed on it already
1905  if (TC.isThreadModelSupported(A->getValue()))
1906  OS << "Thread model: " << A->getValue();
1907  } else
1908  OS << "Thread model: " << TC.getThreadModel();
1909  OS << '\n';
1910 
1911  // Print out the install directory.
1912  OS << "InstalledDir: " << InstalledDir << '\n';
1913 
1914  // If configuration files were used, print their paths.
1915  for (auto ConfigFile : ConfigFiles)
1916  OS << "Configuration file: " << ConfigFile << '\n';
1917 }
1918 
1919 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1920 /// option.
1921 static void PrintDiagnosticCategories(raw_ostream &OS) {
1922  // Skip the empty category.
1923  for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1924  ++i)
1925  OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1926 }
1927 
1928 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1929  if (PassedFlags == "")
1930  return;
1931  // Print out all options that start with a given argument. This is used for
1932  // shell autocompletion.
1933  std::vector<std::string> SuggestedCompletions;
1934  std::vector<std::string> Flags;
1935 
1936  unsigned int DisableFlags =
1938 
1939  // Make sure that Flang-only options don't pollute the Clang output
1940  // TODO: Make sure that Clang-only options don't pollute Flang output
1941  if (!IsFlangMode())
1942  DisableFlags |= options::FlangOnlyOption;
1943 
1944  // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1945  // because the latter indicates that the user put space before pushing tab
1946  // which should end up in a file completion.
1947  const bool HasSpace = PassedFlags.endswith(",");
1948 
1949  // Parse PassedFlags by "," as all the command-line flags are passed to this
1950  // function separated by ","
1951  StringRef TargetFlags = PassedFlags;
1952  while (TargetFlags != "") {
1953  StringRef CurFlag;
1954  std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1955  Flags.push_back(std::string(CurFlag));
1956  }
1957 
1958  // We want to show cc1-only options only when clang is invoked with -cc1 or
1959  // -Xclang.
1960  if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1961  DisableFlags &= ~options::NoDriverOption;
1962 
1963  const llvm::opt::OptTable &Opts = getOpts();
1964  StringRef Cur;
1965  Cur = Flags.at(Flags.size() - 1);
1966  StringRef Prev;
1967  if (Flags.size() >= 2) {
1968  Prev = Flags.at(Flags.size() - 2);
1969  SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1970  }
1971 
1972  if (SuggestedCompletions.empty())
1973  SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1974 
1975  // If Flags were empty, it means the user typed `clang [tab]` where we should
1976  // list all possible flags. If there was no value completion and the user
1977  // pressed tab after a space, we should fall back to a file completion.
1978  // We're printing a newline to be consistent with what we print at the end of
1979  // this function.
1980  if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1981  llvm::outs() << '\n';
1982  return;
1983  }
1984 
1985  // When flag ends with '=' and there was no value completion, return empty
1986  // string and fall back to the file autocompletion.
1987  if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1988  // If the flag is in the form of "--autocomplete=-foo",
1989  // we were requested to print out all option names that start with "-foo".
1990  // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1991  SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1992 
1993  // We have to query the -W flags manually as they're not in the OptTable.
1994  // TODO: Find a good way to add them to OptTable instead and them remove
1995  // this code.
1996  for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1997  if (S.startswith(Cur))
1998  SuggestedCompletions.push_back(std::string(S));
1999  }
2000 
2001  // Sort the autocomplete candidates so that shells print them out in a
2002  // deterministic order. We could sort in any way, but we chose
2003  // case-insensitive sorting for consistency with the -help option
2004  // which prints out options in the case-insensitive alphabetical order.
2005  llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
2006  if (int X = A.compare_insensitive(B))
2007  return X < 0;
2008  return A.compare(B) > 0;
2009  });
2010 
2011  llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
2012 }
2013 
2015  // The order these options are handled in gcc is all over the place, but we
2016  // don't expect inconsistencies w.r.t. that to matter in practice.
2017 
2018  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
2019  llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
2020  return false;
2021  }
2022 
2023  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
2024  // Since -dumpversion is only implemented for pedantic GCC compatibility, we
2025  // return an answer which matches our definition of __VERSION__.
2026  llvm::outs() << CLANG_VERSION_STRING << "\n";
2027  return false;
2028  }
2029 
2030  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
2031  PrintDiagnosticCategories(llvm::outs());
2032  return false;
2033  }
2034 
2035  if (C.getArgs().hasArg(options::OPT_help) ||
2036  C.getArgs().hasArg(options::OPT__help_hidden)) {
2037  PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
2038  return false;
2039  }
2040 
2041  if (C.getArgs().hasArg(options::OPT__version)) {
2042  // Follow gcc behavior and use stdout for --version and stderr for -v.
2043  PrintVersion(C, llvm::outs());
2044  return false;
2045  }
2046 
2047  if (C.getArgs().hasArg(options::OPT_v) ||
2048  C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
2049  C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
2050  PrintVersion(C, llvm::errs());
2051  SuppressMissingInputWarning = true;
2052  }
2053 
2054  if (C.getArgs().hasArg(options::OPT_v)) {
2055  if (!SystemConfigDir.empty())
2056  llvm::errs() << "System configuration file directory: "
2057  << SystemConfigDir << "\n";
2058  if (!UserConfigDir.empty())
2059  llvm::errs() << "User configuration file directory: "
2060  << UserConfigDir << "\n";
2061  }
2062 
2063  const ToolChain &TC = C.getDefaultToolChain();
2064 
2065  if (C.getArgs().hasArg(options::OPT_v))
2066  TC.printVerboseInfo(llvm::errs());
2067 
2068  if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
2069  llvm::outs() << ResourceDir << '\n';
2070  return false;
2071  }
2072 
2073  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
2074  llvm::outs() << "programs: =";
2075  bool separator = false;
2076  // Print -B and COMPILER_PATH.
2077  for (const std::string &Path : PrefixDirs) {
2078  if (separator)
2079  llvm::outs() << llvm::sys::EnvPathSeparator;
2080  llvm::outs() << Path;
2081  separator = true;
2082  }
2083  for (const std::string &Path : TC.getProgramPaths()) {
2084  if (separator)
2085  llvm::outs() << llvm::sys::EnvPathSeparator;
2086  llvm::outs() << Path;
2087  separator = true;
2088  }
2089  llvm::outs() << "\n";
2090  llvm::outs() << "libraries: =" << ResourceDir;
2091 
2092  StringRef sysroot = C.getSysRoot();
2093 
2094  for (const std::string &Path : TC.getFilePaths()) {
2095  // Always print a separator. ResourceDir was the first item shown.
2096  llvm::outs() << llvm::sys::EnvPathSeparator;
2097  // Interpretation of leading '=' is needed only for NetBSD.
2098  if (Path[0] == '=')
2099  llvm::outs() << sysroot << Path.substr(1);
2100  else
2101  llvm::outs() << Path;
2102  }
2103  llvm::outs() << "\n";
2104  return false;
2105  }
2106 
2107  if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) {
2108  std::string RuntimePath;
2109  // Get the first existing path, if any.
2110  for (auto Path : TC.getRuntimePaths()) {
2111  if (getVFS().exists(Path)) {
2112  RuntimePath = Path;
2113  break;
2114  }
2115  }
2116  if (!RuntimePath.empty())
2117  llvm::outs() << RuntimePath << '\n';
2118  else
2119  llvm::outs() << TC.getCompilerRTPath() << '\n';
2120  return false;
2121  }
2122 
2123  if (C.getArgs().hasArg(options::OPT_print_diagnostic_options)) {
2124  std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags();
2125  for (std::size_t I = 0; I != Flags.size(); I += 2)
2126  llvm::outs() << " " << Flags[I] << "\n " << Flags[I + 1] << "\n\n";
2127  return false;
2128  }
2129 
2130  // FIXME: The following handlers should use a callback mechanism, we don't
2131  // know what the client would like to do.
2132  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
2133  llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
2134  return false;
2135  }
2136 
2137  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
2138  StringRef ProgName = A->getValue();
2139 
2140  // Null program name cannot have a path.
2141  if (! ProgName.empty())
2142  llvm::outs() << GetProgramPath(ProgName, TC);
2143 
2144  llvm::outs() << "\n";
2145  return false;
2146  }
2147 
2148  if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
2149  StringRef PassedFlags = A->getValue();
2150  HandleAutocompletions(PassedFlags);
2151  return false;
2152  }
2153 
2154  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
2155  ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
2156  const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2157  RegisterEffectiveTriple TripleRAII(TC, Triple);
2158  switch (RLT) {
2160  llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
2161  break;
2162  case ToolChain::RLT_Libgcc:
2163  llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
2164  break;
2165  }
2166  return false;
2167  }
2168 
2169  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
2170  for (const Multilib &Multilib : TC.getMultilibs())
2171  llvm::outs() << Multilib << "\n";
2172  return false;
2173  }
2174 
2175  if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
2176  const Multilib &Multilib = TC.getMultilib();
2177  if (Multilib.gccSuffix().empty())
2178  llvm::outs() << ".\n";
2179  else {
2180  StringRef Suffix(Multilib.gccSuffix());
2181  assert(Suffix.front() == '/');
2182  llvm::outs() << Suffix.substr(1) << "\n";
2183  }
2184  return false;
2185  }
2186 
2187  if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
2188  llvm::outs() << TC.getTripleString() << "\n";
2189  return false;
2190  }
2191 
2192  if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
2193  const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2194  llvm::outs() << Triple.getTriple() << "\n";
2195  return false;
2196  }
2197 
2198  if (C.getArgs().hasArg(options::OPT_print_targets)) {
2199  llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
2200  return false;
2201  }
2202 
2203  return true;
2204 }
2205 
2206 enum {
2210 };
2211 
2212 // Display an action graph human-readably. Action A is the "sink" node
2213 // and latest-occuring action. Traversal is in pre-order, visiting the
2214 // inputs to each action before printing the action itself.
2215 static unsigned PrintActions1(const Compilation &C, Action *A,
2216  std::map<Action *, unsigned> &Ids,
2217  Twine Indent = {}, int Kind = TopLevelAction) {
2218  if (Ids.count(A)) // A was already visited.
2219  return Ids[A];
2220 
2221  std::string str;
2222  llvm::raw_string_ostream os(str);
2223 
2224  auto getSibIndent = [](int K) -> Twine {
2225  return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "";
2226  };
2227 
2228  Twine SibIndent = Indent + getSibIndent(Kind);
2229  int SibKind = HeadSibAction;
2230  os << Action::getClassName(A->getKind()) << ", ";
2231  if (InputAction *IA = dyn_cast<InputAction>(A)) {
2232  os << "\"" << IA->getInputArg().getValue() << "\"";
2233  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
2234  os << '"' << BIA->getArchName() << '"' << ", {"
2235  << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
2236  } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2237  bool IsFirst = true;
2238  OA->doOnEachDependence(
2239  [&](Action *A, const ToolChain *TC, const char *BoundArch) {
2240  assert(TC && "Unknown host toolchain");
2241  // E.g. for two CUDA device dependences whose bound arch is sm_20 and
2242  // sm_35 this will generate:
2243  // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
2244  // (nvptx64-nvidia-cuda:sm_35) {#ID}
2245  if (!IsFirst)
2246  os << ", ";
2247  os << '"';
2248  os << A->getOffloadingKindPrefix();
2249  os << " (";
2250  os << TC->getTriple().normalize();
2251  if (BoundArch)
2252  os << ":" << BoundArch;
2253  os << ")";
2254  os << '"';
2255  os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
2256  IsFirst = false;
2257  SibKind = OtherSibAction;
2258  });
2259  } else {
2260  const ActionList *AL = &A->getInputs();
2261 
2262  if (AL->size()) {
2263  const char *Prefix = "{";
2264  for (Action *PreRequisite : *AL) {
2265  os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
2266  Prefix = ", ";
2267  SibKind = OtherSibAction;
2268  }
2269  os << "}";
2270  } else
2271  os << "{}";
2272  }
2273 
2274  // Append offload info for all options other than the offloading action
2275  // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
2276  std::string offload_str;
2277  llvm::raw_string_ostream offload_os(offload_str);
2278  if (!isa<OffloadAction>(A)) {
2279  auto S = A->getOffloadingKindPrefix();
2280  if (!S.empty()) {
2281  offload_os << ", (" << S;
2282  if (A->getOffloadingArch())
2283  offload_os << ", " << A->getOffloadingArch();
2284  offload_os << ")";
2285  }
2286  }
2287 
2288  auto getSelfIndent = [](int K) -> Twine {
2289  return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
2290  };
2291 
2292  unsigned Id = Ids.size();
2293  Ids[A] = Id;
2294  llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
2295  << types::getTypeName(A->getType()) << offload_os.str() << "\n";
2296 
2297  return Id;
2298 }
2299 
2300 // Print the action graphs in a compilation C.
2301 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
2302 void Driver::PrintActions(const Compilation &C) const {
2303  std::map<Action *, unsigned> Ids;
2304  for (Action *A : C.getActions())
2305  PrintActions1(C, A, Ids);
2306 }
2307 
2308 /// Check whether the given input tree contains any compilation or
2309 /// assembly actions.
2311  if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
2312  isa<AssembleJobAction>(A))
2313  return true;
2314 
2315  return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction);
2316 }
2317 
2319  const InputList &BAInputs) const {
2320  DerivedArgList &Args = C.getArgs();
2321  ActionList &Actions = C.getActions();
2322  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2323  // Collect the list of architectures. Duplicates are allowed, but should only
2324  // be handled once (in the order seen).
2325  llvm::StringSet<> ArchNames;
2327  for (Arg *A : Args) {
2328  if (A->getOption().matches(options::OPT_arch)) {
2329  // Validate the option here; we don't save the type here because its
2330  // particular spelling may participate in other driver choices.
2331  llvm::Triple::ArchType Arch =
2333  if (Arch == llvm::Triple::UnknownArch) {
2334  Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2335  continue;
2336  }
2337 
2338  A->claim();
2339  if (ArchNames.insert(A->getValue()).second)
2340  Archs.push_back(A->getValue());
2341  }
2342  }
2343 
2344  // When there is no explicit arch for this platform, make sure we still bind
2345  // the architecture (to the default) so that -Xarch_ is handled correctly.
2346  if (!Archs.size())
2347  Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
2348 
2349  ActionList SingleActions;
2350  BuildActions(C, Args, BAInputs, SingleActions);
2351 
2352  // Add in arch bindings for every top level action, as well as lipo and
2353  // dsymutil steps if needed.
2354  for (Action* Act : SingleActions) {
2355  // Make sure we can lipo this kind of output. If not (and it is an actual
2356  // output) then we disallow, since we can't create an output file with the
2357  // right name without overwriting it. We could remove this oddity by just
2358  // changing the output names to include the arch, which would also fix
2359  // -save-temps. Compatibility wins for now.
2360 
2361  if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
2362  Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
2363  << types::getTypeName(Act->getType());
2364 
2365  ActionList Inputs;
2366  for (unsigned i = 0, e = Archs.size(); i != e; ++i)
2367  Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
2368 
2369  // Lipo if necessary, we do it this way because we need to set the arch flag
2370  // so that -Xarch_ gets overwritten.
2371  if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2372  Actions.append(Inputs.begin(), Inputs.end());
2373  else
2374  Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2375 
2376  // Handle debug info queries.
2377  Arg *A = Args.getLastArg(options::OPT_g_Group);
2378  bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2379  !A->getOption().matches(options::OPT_gstabs);
2380  if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2381  ContainsCompileOrAssembleAction(Actions.back())) {
2382 
2383  // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2384  // have a compile input. We need to run 'dsymutil' ourselves in such cases
2385  // because the debug info will refer to a temporary object file which
2386  // will be removed at the end of the compilation process.
2387  if (Act->getType() == types::TY_Image) {
2388  ActionList Inputs;
2389  Inputs.push_back(Actions.back());
2390  Actions.pop_back();
2391  Actions.push_back(
2392  C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2393  }
2394 
2395  // Verify the debug info output.
2396  if (Args.hasArg(options::OPT_verify_debug_info)) {
2397  Action* LastAction = Actions.back();
2398  Actions.pop_back();
2399  Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2400  LastAction, types::TY_Nothing));
2401  }
2402  }
2403  }
2404 }
2405 
2406 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2407  types::ID Ty, bool TypoCorrect) const {
2408  if (!getCheckInputsExist())
2409  return true;
2410 
2411  // stdin always exists.
2412  if (Value == "-")
2413  return true;
2414 
2415  // If it's a header to be found in the system or user search path, then defer
2416  // complaints about its absence until those searches can be done. When we
2417  // are definitely processing headers for C++20 header units, extend this to
2418  // allow the user to put "-fmodule-header -xc++-header vector" for example.
2419  if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader ||
2420  (ModulesModeCXX20 && Ty == types::TY_CXXHeader))
2421  return true;
2422 
2423  if (getVFS().exists(Value))
2424  return true;
2425 
2426  if (TypoCorrect) {
2427  // Check if the filename is a typo for an option flag. OptTable thinks
2428  // that all args that are not known options and that start with / are
2429  // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2430  // the option `/diagnostics:caret` than a reference to a file in the root
2431  // directory.
2432  unsigned IncludedFlagsBitmask;
2433  unsigned ExcludedFlagsBitmask;
2434  std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2435  getIncludeExcludeOptionFlagMasks(IsCLMode());
2436  std::string Nearest;
2437  if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2438  ExcludedFlagsBitmask) <= 1) {
2439  Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2440  << Value << Nearest;
2441  return false;
2442  }
2443  }
2444 
2445  // In CL mode, don't error on apparently non-existent linker inputs, because
2446  // they can be influenced by linker flags the clang driver might not
2447  // understand.
2448  // Examples:
2449  // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver
2450  // module look for an MSVC installation in the registry. (We could ask
2451  // the MSVCToolChain object if it can find `ole32.lib`, but the logic to
2452  // look in the registry might move into lld-link in the future so that
2453  // lld-link invocations in non-MSVC shells just work too.)
2454  // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
2455  // including /libpath:, which is used to find .lib and .obj files.
2456  // So do not diagnose this on the driver level. Rely on the linker diagnosing
2457  // it. (If we don't end up invoking the linker, this means we'll emit a
2458  // "'linker' input unused [-Wunused-command-line-argument]" warning instead
2459  // of an error.)
2460  //
2461  // Only do this skip after the typo correction step above. `/Brepo` is treated
2462  // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit
2463  // an error if we have a flag that's within an edit distance of 1 from a
2464  // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
2465  // driver in the unlikely case they run into this.)
2466  //
2467  // Don't do this for inputs that start with a '/', else we'd pass options
2468  // like /libpath: through to the linker silently.
2469  //
2470  // Emitting an error for linker inputs can also cause incorrect diagnostics
2471  // with the gcc driver. The command
2472  // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
2473  // will make lld look for some/dir/file.o, while we will diagnose here that
2474  // `/file.o` does not exist. However, configure scripts check if
2475  // `clang /GR-` compiles without error to see if the compiler is cl.exe,
2476  // so we can't downgrade diagnostics for `/GR-` from an error to a warning
2477  // in cc mode. (We can in cl mode because cl.exe itself only warns on
2478  // unknown flags.)
2479  if (IsCLMode() && Ty == types::TY_Object && !Value.startswith("/"))
2480  return true;
2481 
2482  Diag(clang::diag::err_drv_no_such_file) << Value;
2483  return false;
2484 }
2485 
2486 // Get the C++20 Header Unit type corresponding to the input type.
2488  switch (HM) {
2489  case HeaderMode_User:
2490  return types::TY_CXXUHeader;
2491  case HeaderMode_System:
2492  return types::TY_CXXSHeader;
2493  case HeaderMode_Default:
2494  break;
2495  case HeaderMode_None:
2496  llvm_unreachable("should not be called in this case");
2497  }
2498  return types::TY_CXXHUHeader;
2499 }
2500 
2501 // Construct a the list of inputs and their types.
2502 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2503  InputList &Inputs) const {
2504  const llvm::opt::OptTable &Opts = getOpts();
2505  // Track the current user specified (-x) input. We also explicitly track the
2506  // argument used to set the type; we only want to claim the type when we
2507  // actually use it, so we warn about unused -x arguments.
2508  types::ID InputType = types::TY_Nothing;
2509  Arg *InputTypeArg = nullptr;
2510 
2511  // The last /TC or /TP option sets the input type to C or C++ globally.
2512  if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2513  options::OPT__SLASH_TP)) {
2514  InputTypeArg = TCTP;
2515  InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2516  ? types::TY_C
2517  : types::TY_CXX;
2518 
2519  Arg *Previous = nullptr;
2520  bool ShowNote = false;
2521  for (Arg *A :
2522  Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2523  if (Previous) {
2524  Diag(clang::diag::warn_drv_overriding_flag_option)
2525  << Previous->getSpelling() << A->getSpelling();
2526  ShowNote = true;
2527  }
2528  Previous = A;
2529  }
2530  if (ShowNote)
2531  Diag(clang::diag::note_drv_t_option_is_global);
2532 
2533  // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2534  assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2535  }
2536 
2537  // Warn -x after last input file has no effect
2538  {
2539  Arg *LastXArg = Args.getLastArgNoClaim(options::OPT_x);
2540  Arg *LastInputArg = Args.getLastArgNoClaim(options::OPT_INPUT);
2541  if (LastXArg && LastInputArg && LastInputArg->getIndex() < LastXArg->getIndex())
2542  Diag(clang::diag::warn_drv_unused_x) << LastXArg->getValue();
2543  }
2544 
2545  for (Arg *A : Args) {
2546  if (A->getOption().getKind() == Option::InputClass) {
2547  const char *Value = A->getValue();
2549 
2550  // Infer the input type if necessary.
2551  if (InputType == types::TY_Nothing) {
2552  // If there was an explicit arg for this, claim it.
2553  if (InputTypeArg)
2554  InputTypeArg->claim();
2555 
2556  // stdin must be handled specially.
2557  if (memcmp(Value, "-", 2) == 0) {
2558  if (IsFlangMode()) {
2559  Ty = types::TY_Fortran;
2560  } else {
2561  // If running with -E, treat as a C input (this changes the
2562  // builtin macros, for example). This may be overridden by -ObjC
2563  // below.
2564  //
2565  // Otherwise emit an error but still use a valid type to avoid
2566  // spurious errors (e.g., no inputs).
2567  assert(!CCGenDiagnostics && "stdin produces no crash reproducer");
2568  if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2569  Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2570  : clang::diag::err_drv_unknown_stdin_type);
2571  Ty = types::TY_C;
2572  }
2573  } else {
2574  // Otherwise lookup by extension.
2575  // Fallback is C if invoked as C preprocessor, C++ if invoked with
2576  // clang-cl /E, or Object otherwise.
2577  // We use a host hook here because Darwin at least has its own
2578  // idea of what .s is.
2579  if (const char *Ext = strrchr(Value, '.'))
2580  Ty = TC.LookupTypeForExtension(Ext + 1);
2581 
2582  if (Ty == types::TY_INVALID) {
2583  if (IsCLMode() && (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics))
2584  Ty = types::TY_CXX;
2585  else if (CCCIsCPP() || CCGenDiagnostics)
2586  Ty = types::TY_C;
2587  else
2588  Ty = types::TY_Object;
2589  }
2590 
2591  // If the driver is invoked as C++ compiler (like clang++ or c++) it
2592  // should autodetect some input files as C++ for g++ compatibility.
2593  if (CCCIsCXX()) {
2594  types::ID OldTy = Ty;
2596 
2597  // Do not complain about foo.h, when we are known to be processing
2598  // it as a C++20 header unit.
2599  if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode()))
2600  Diag(clang::diag::warn_drv_treating_input_as_cxx)
2601  << getTypeName(OldTy) << getTypeName(Ty);
2602  }
2603 
2604  // If running with -fthinlto-index=, extensions that normally identify
2605  // native object files actually identify LLVM bitcode files.
2606  if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2607  Ty == types::TY_Object)
2608  Ty = types::TY_LLVM_BC;
2609  }
2610 
2611  // -ObjC and -ObjC++ override the default language, but only for "source
2612  // files". We just treat everything that isn't a linker input as a
2613  // source file.
2614  //
2615  // FIXME: Clean this up if we move the phase sequence into the type.
2616  if (Ty != types::TY_Object) {
2617  if (Args.hasArg(options::OPT_ObjC))
2618  Ty = types::TY_ObjC;
2619  else if (Args.hasArg(options::OPT_ObjCXX))
2620  Ty = types::TY_ObjCXX;
2621  }
2622 
2623  // Disambiguate headers that are meant to be header units from those
2624  // intended to be PCH. Avoid missing '.h' cases that are counted as
2625  // C headers by default - we know we are in C++ mode and we do not
2626  // want to issue a complaint about compiling things in the wrong mode.
2627  if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
2628  hasHeaderMode())
2629  Ty = CXXHeaderUnitType(CXX20HeaderType);
2630  } else {
2631  assert(InputTypeArg && "InputType set w/o InputTypeArg");
2632  if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2633  // If emulating cl.exe, make sure that /TC and /TP don't affect input
2634  // object files.
2635  const char *Ext = strrchr(Value, '.');
2636  if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2637  Ty = types::TY_Object;
2638  }
2639  if (Ty == types::TY_INVALID) {
2640  Ty = InputType;
2641  InputTypeArg->claim();
2642  }
2643  }
2644 
2645  if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2646  Inputs.push_back(std::make_pair(Ty, A));
2647 
2648  } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2649  StringRef Value = A->getValue();
2650  if (DiagnoseInputExistence(Args, Value, types::TY_C,
2651  /*TypoCorrect=*/false)) {
2652  Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2653  Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2654  }
2655  A->claim();
2656  } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2657  StringRef Value = A->getValue();
2658  if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2659  /*TypoCorrect=*/false)) {
2660  Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2661  Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2662  }
2663  A->claim();
2664  } else if (A->getOption().hasFlag(options::LinkerInput)) {
2665  // Just treat as object type, we could make a special type for this if
2666  // necessary.
2667  Inputs.push_back(std::make_pair(types::TY_Object, A));
2668 
2669  } else if (A->getOption().matches(options::OPT_x)) {
2670  InputTypeArg = A;
2671  InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2672  A->claim();
2673 
2674  // Follow gcc behavior and treat as linker input for invalid -x
2675  // options. Its not clear why we shouldn't just revert to unknown; but
2676  // this isn't very important, we might as well be bug compatible.
2677  if (!InputType) {
2678  Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2679  InputType = types::TY_Object;
2680  }
2681 
2682  // If the user has put -fmodule-header{,=} then we treat C++ headers as
2683  // header unit inputs. So we 'promote' -xc++-header appropriately.
2684  if (InputType == types::TY_CXXHeader && hasHeaderMode())
2685  InputType = CXXHeaderUnitType(CXX20HeaderType);
2686  } else if (A->getOption().getID() == options::OPT_U) {
2687  assert(A->getNumValues() == 1 && "The /U option has one value.");
2688  StringRef Val = A->getValue(0);
2689  if (Val.find_first_of("/\\") != StringRef::npos) {
2690  // Warn about e.g. "/Users/me/myfile.c".
2691  Diag(diag::warn_slash_u_filename) << Val;
2692  Diag(diag::note_use_dashdash);
2693  }
2694  }
2695  }
2696  if (CCCIsCPP() && Inputs.empty()) {
2697  // If called as standalone preprocessor, stdin is processed
2698  // if no other input is present.
2699  Arg *A = MakeInputArg(Args, Opts, "-");
2700  Inputs.push_back(std::make_pair(types::TY_C, A));
2701  }
2702 }
2703 
2704 namespace {
2705 /// Provides a convenient interface for different programming models to generate
2706 /// the required device actions.
2707 class OffloadingActionBuilder final {
2708  /// Flag used to trace errors in the builder.
2709  bool IsValid = false;
2710 
2711  /// The compilation that is using this builder.
2712  Compilation &C;
2713 
2714  /// Map between an input argument and the offload kinds used to process it.
2715  std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2716 
2717  /// Map between a host action and its originating input argument.
2718  std::map<Action *, const Arg *> HostActionToInputArgMap;
2719 
2720  /// Builder interface. It doesn't build anything or keep any state.
2721  class DeviceActionBuilder {
2722  public:
2723  typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2724 
2725  enum ActionBuilderReturnCode {
2726  // The builder acted successfully on the current action.
2727  ABRT_Success,
2728  // The builder didn't have to act on the current action.
2729  ABRT_Inactive,
2730  // The builder was successful and requested the host action to not be
2731  // generated.
2732  ABRT_Ignore_Host,
2733  };
2734 
2735  protected:
2736  /// Compilation associated with this builder.
2737  Compilation &C;
2738 
2739  /// Tool chains associated with this builder. The same programming
2740  /// model may have associated one or more tool chains.
2742 
2743  /// The derived arguments associated with this builder.
2744  DerivedArgList &Args;
2745 
2746  /// The inputs associated with this builder.
2747  const Driver::InputList &Inputs;
2748 
2749  /// The associated offload kind.
2750  Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2751 
2752  public:
2753  DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2754  const Driver::InputList &Inputs,
2755  Action::OffloadKind AssociatedOffloadKind)
2756  : C(C), Args(Args), Inputs(Inputs),
2757  AssociatedOffloadKind(AssociatedOffloadKind) {}
2758  virtual ~DeviceActionBuilder() {}
2759 
2760  /// Fill up the array \a DA with all the device dependences that should be
2761  /// added to the provided host action \a HostAction. By default it is
2762  /// inactive.
2763  virtual ActionBuilderReturnCode
2764  getDeviceDependences(OffloadAction::DeviceDependences &DA,
2765  phases::ID CurPhase, phases::ID FinalPhase,
2766  PhasesTy &Phases) {
2767  return ABRT_Inactive;
2768  }
2769 
2770  /// Update the state to include the provided host action \a HostAction as a
2771  /// dependency of the current device action. By default it is inactive.
2772  virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) {
2773  return ABRT_Inactive;
2774  }
2775 
2776  /// Append top level actions generated by the builder.
2777  virtual void appendTopLevelActions(ActionList &AL) {}
2778 
2779  /// Append linker device actions generated by the builder.
2780  virtual void appendLinkDeviceActions(ActionList &AL) {}
2781 
2782  /// Append linker host action generated by the builder.
2783  virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2784 
2785  /// Append linker actions generated by the builder.
2786  virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2787 
2788  /// Initialize the builder. Return true if any initialization errors are
2789  /// found.
2790  virtual bool initialize() { return false; }
2791 
2792  /// Return true if the builder can use bundling/unbundling.
2793  virtual bool canUseBundlerUnbundler() const { return false; }
2794 
2795  /// Return true if this builder is valid. We have a valid builder if we have
2796  /// associated device tool chains.
2797  bool isValid() { return !ToolChains.empty(); }
2798 
2799  /// Return the associated offload kind.
2800  Action::OffloadKind getAssociatedOffloadKind() {
2801  return AssociatedOffloadKind;
2802  }
2803  };
2804 
2805  /// Base class for CUDA/HIP action builder. It injects device code in
2806  /// the host backend action.
2807  class CudaActionBuilderBase : public DeviceActionBuilder {
2808  protected:
2809  /// Flags to signal if the user requested host-only or device-only
2810  /// compilation.
2811  bool CompileHostOnly = false;
2812  bool CompileDeviceOnly = false;
2813  bool EmitLLVM = false;
2814  bool EmitAsm = false;
2815 
2816  /// ID to identify each device compilation. For CUDA it is simply the
2817  /// GPU arch string. For HIP it is either the GPU arch string or GPU
2818  /// arch string plus feature strings delimited by a plus sign, e.g.
2819  /// gfx906+xnack.
2820  struct TargetID {
2821  /// Target ID string which is persistent throughout the compilation.
2822  const char *ID;
2823  TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); }
2824  TargetID(const char *ID) : ID(ID) {}
2825  operator const char *() { return ID; }
2826  operator StringRef() { return StringRef(ID); }
2827  };
2828  /// List of GPU architectures to use in this compilation.
2829  SmallVector<TargetID, 4> GpuArchList;
2830 
2831  /// The CUDA actions for the current input.
2832  ActionList CudaDeviceActions;
2833 
2834  /// The CUDA fat binary if it was generated for the current input.
2835  Action *CudaFatBinary = nullptr;
2836 
2837  /// Flag that is set to true if this builder acted on the current input.
2838  bool IsActive = false;
2839 
2840  /// Flag for -fgpu-rdc.
2841  bool Relocatable = false;
2842 
2843  /// Default GPU architecture if there's no one specified.
2844  CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2845 
2846  /// Method to generate compilation unit ID specified by option
2847  /// '-fuse-cuid='.
2848  enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid };
2849  UseCUIDKind UseCUID = CUID_Hash;
2850 
2851  /// Compilation unit ID specified by option '-cuid='.
2852  StringRef FixedCUID;
2853 
2854  public:
2855  CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2856  const Driver::InputList &Inputs,
2857  Action::OffloadKind OFKind)
2858  : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2859 
2860  ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override {
2861  // While generating code for CUDA, we only depend on the host input action
2862  // to trigger the creation of all the CUDA device actions.
2863 
2864  // If we are dealing with an input action, replicate it for each GPU
2865  // architecture. If we are in host-only mode we return 'success' so that
2866  // the host uses the CUDA offload kind.
2867  if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2868  assert(!GpuArchList.empty() &&
2869  "We should have at least one GPU architecture.");
2870 
2871  // If the host input is not CUDA or HIP, we don't need to bother about
2872  // this input.
2873  if (!(IA->getType() == types::TY_CUDA ||
2874  IA->getType() == types::TY_HIP ||
2875  IA->getType() == types::TY_PP_HIP)) {
2876  // The builder will ignore this input.
2877  IsActive = false;
2878  return ABRT_Inactive;
2879  }
2880 
2881  // Set the flag to true, so that the builder acts on the current input.
2882  IsActive = true;
2883 
2884  if (CompileHostOnly)
2885  return ABRT_Success;
2886 
2887  // Replicate inputs for each GPU architecture.
2888  auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2889  : types::TY_CUDA_DEVICE;
2890  std::string CUID = FixedCUID.str();
2891  if (CUID.empty()) {
2892  if (UseCUID == CUID_Random)
2893  CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
2894  /*LowerCase=*/true);
2895  else if (UseCUID == CUID_Hash) {
2896  llvm::MD5 Hasher;
2897  llvm::MD5::MD5Result Hash;
2898  SmallString<256> RealPath;
2899  llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath,
2900  /*expand_tilde=*/true);
2901  Hasher.update(RealPath);
2902  for (auto *A : Args) {
2903  if (A->getOption().matches(options::OPT_INPUT))
2904  continue;
2905  Hasher.update(A->getAsString(Args));
2906  }
2907  Hasher.final(Hash);
2908  CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
2909  }
2910  }
2911  IA->setId(CUID);
2912 
2913  for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2914  CudaDeviceActions.push_back(
2915  C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId()));
2916  }
2917 
2918  return ABRT_Success;
2919  }
2920 
2921  // If this is an unbundling action use it as is for each CUDA toolchain.
2922  if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2923 
2924  // If -fgpu-rdc is disabled, should not unbundle since there is no
2925  // device code to link.
2926  if (UA->getType() == types::TY_Object && !Relocatable)
2927  return ABRT_Inactive;
2928 
2929  CudaDeviceActions.clear();
2930  auto *IA = cast<InputAction>(UA->getInputs().back());
2931  std::string FileName = IA->getInputArg().getAsString(Args);
2932  // Check if the type of the file is the same as the action. Do not
2933  // unbundle it if it is not. Do not unbundle .so files, for example,
2934  // which are not object files. Files with extension ".lib" is classified
2935  // as TY_Object but they are actually archives, therefore should not be
2936  // unbundled here as objects. They will be handled at other places.
2937  const StringRef LibFileExt = ".lib";
2938  if (IA->getType() == types::TY_Object &&
2939  (!llvm::sys::path::has_extension(FileName) ||
2941  llvm::sys::path::extension(FileName).drop_front()) !=
2942  types::TY_Object ||
2943  llvm::sys::path::extension(FileName) == LibFileExt))
2944  return ABRT_Inactive;
2945 
2946  for (auto Arch : GpuArchList) {
2947  CudaDeviceActions.push_back(UA);
2948  UA->registerDependentActionInfo(ToolChains[0], Arch,
2949  AssociatedOffloadKind);
2950  }
2951  IsActive = true;
2952  return ABRT_Success;
2953  }
2954 
2955  return IsActive ? ABRT_Success : ABRT_Inactive;
2956  }
2957 
2958  void appendTopLevelActions(ActionList &AL) override {
2959  // Utility to append actions to the top level list.
2960  auto AddTopLevel = [&](Action *A, TargetID TargetID) {
2962  Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind);
2963  AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2964  };
2965 
2966  // If we have a fat binary, add it to the list.
2967  if (CudaFatBinary) {
2968  AddTopLevel(CudaFatBinary, CudaArch::UNUSED);
2969  CudaDeviceActions.clear();
2970  CudaFatBinary = nullptr;
2971  return;
2972  }
2973 
2974  if (CudaDeviceActions.empty())
2975  return;
2976 
2977  // If we have CUDA actions at this point, that's because we have a have
2978  // partial compilation, so we should have an action for each GPU
2979  // architecture.
2980  assert(CudaDeviceActions.size() == GpuArchList.size() &&
2981  "Expecting one action per GPU architecture.");
2982  assert(ToolChains.size() == 1 &&
2983  "Expecting to have a single CUDA toolchain.");
2984  for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2985  AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2986 
2987  CudaDeviceActions.clear();
2988  }
2989 
2990  /// Get canonicalized offload arch option. \returns empty StringRef if the
2991  /// option is invalid.
2992  virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0;
2993 
2995  getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0;
2996 
2997  bool initialize() override {
2998  assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2999  AssociatedOffloadKind == Action::OFK_HIP);
3000 
3001  // We don't need to support CUDA.
3002  if (AssociatedOffloadKind == Action::OFK_Cuda &&
3003  !C.hasOffloadToolChain<Action::OFK_Cuda>())
3004  return false;
3005 
3006  // We don't need to support HIP.
3007  if (AssociatedOffloadKind == Action::OFK_HIP &&
3008  !C.hasOffloadToolChain<Action::OFK_HIP>())
3009  return false;
3010 
3011  Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
3012  options::OPT_fno_gpu_rdc, /*Default=*/false);
3013 
3014  const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
3015  assert(HostTC && "No toolchain for host compilation.");
3016  if (HostTC->getTriple().isNVPTX() ||
3017  HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
3018  // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
3019  // an error and abort pipeline construction early so we don't trip
3020  // asserts that assume device-side compilation.
3021  C.getDriver().Diag(diag::err_drv_cuda_host_arch)
3022  << HostTC->getTriple().getArchName();
3023  return true;
3024  }
3025 
3026  ToolChains.push_back(
3027  AssociatedOffloadKind == Action::OFK_Cuda
3028  ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3029  : C.getSingleOffloadToolChain<Action::OFK_HIP>());
3030 
3031  CompileHostOnly = C.getDriver().offloadHostOnly();
3032  CompileDeviceOnly = C.getDriver().offloadDeviceOnly();
3033  EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
3034  EmitAsm = Args.getLastArg(options::OPT_S);
3035  FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ);
3036  if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) {
3037  StringRef UseCUIDStr = A->getValue();
3038  UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr)
3039  .Case("hash", CUID_Hash)
3040  .Case("random", CUID_Random)
3041  .Case("none", CUID_None)
3042  .Default(CUID_Invalid);
3043  if (UseCUID == CUID_Invalid) {
3044  C.getDriver().Diag(diag::err_drv_invalid_value)
3045  << A->getAsString(Args) << UseCUIDStr;
3046  C.setContainsError();
3047  return true;
3048  }
3049  }
3050 
3051  // --offload and --offload-arch options are mutually exclusive.
3052  if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
3053  Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
3054  options::OPT_no_offload_arch_EQ)) {
3055  C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch"
3056  << "--offload";
3057  }
3058 
3059  // Collect all offload arch parameters, removing duplicates.
3060  std::set<StringRef> GpuArchs;
3061  bool Error = false;
3062  for (Arg *A : Args) {
3063  if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
3064  A->getOption().matches(options::OPT_no_offload_arch_EQ)))
3065  continue;
3066  A->claim();
3067 
3068  for (StringRef ArchStr : llvm::split(A->getValue(), ",")) {
3069  if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
3070  ArchStr == "all") {
3071  GpuArchs.clear();
3072  } else {
3073  ArchStr = getCanonicalOffloadArch(ArchStr);
3074  if (ArchStr.empty()) {
3075  Error = true;
3076  } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
3077  GpuArchs.insert(ArchStr);
3078  else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
3079  GpuArchs.erase(ArchStr);
3080  else
3081  llvm_unreachable("Unexpected option.");
3082  }
3083  }
3084  }
3085 
3086  auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs);
3087  if (ConflictingArchs) {
3088  C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
3089  << ConflictingArchs->first << ConflictingArchs->second;
3090  C.setContainsError();
3091  return true;
3092  }
3093 
3094  // Collect list of GPUs remaining in the set.
3095  for (auto Arch : GpuArchs)
3096  GpuArchList.push_back(Arch.data());
3097 
3098  // Default to sm_20 which is the lowest common denominator for
3099  // supported GPUs. sm_20 code should work correctly, if
3100  // suboptimally, on all newer GPUs.
3101  if (GpuArchList.empty()) {
3102  if (ToolChains.front()->getTriple().isSPIRV())
3103  GpuArchList.push_back(CudaArch::Generic);
3104  else
3105  GpuArchList.push_back(DefaultCudaArch);
3106  }
3107 
3108  return Error;
3109  }
3110  };
3111 
3112  /// \brief CUDA action builder. It injects device code in the host backend
3113  /// action.
3114  class CudaActionBuilder final : public CudaActionBuilderBase {
3115  public:
3116  CudaActionBuilder(Compilation &C, DerivedArgList &Args,
3117  const Driver::InputList &Inputs)
3118  : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
3119  DefaultCudaArch = CudaArch::SM_35;
3120  }
3121 
3122  StringRef getCanonicalOffloadArch(StringRef ArchStr) override {
3123  CudaArch Arch = StringToCudaArch(ArchStr);
3124  if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) {
3125  C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
3126  return StringRef();
3127  }
3128  return CudaArchToString(Arch);
3129  }
3130 
3133  const std::set<StringRef> &GpuArchs) override {
3134  return llvm::None;
3135  }
3136 
3137  ActionBuilderReturnCode
3138  getDeviceDependences(OffloadAction::DeviceDependences &DA,
3139  phases::ID CurPhase, phases::ID FinalPhase,
3140  PhasesTy &Phases) override {
3141  if (!IsActive)
3142  return ABRT_Inactive;
3143 
3144  // If we don't have more CUDA actions, we don't have any dependences to
3145  // create for the host.
3146  if (CudaDeviceActions.empty())
3147  return ABRT_Success;
3148 
3149  assert(CudaDeviceActions.size() == GpuArchList.size() &&
3150  "Expecting one action per GPU architecture.");
3151  assert(!CompileHostOnly &&
3152  "Not expecting CUDA actions in host-only compilation.");
3153 
3154  // If we are generating code for the device or we are in a backend phase,
3155  // we attempt to generate the fat binary. We compile each arch to ptx and
3156  // assemble to cubin, then feed the cubin *and* the ptx into a device
3157  // "link" action, which uses fatbinary to combine these cubins into one
3158  // fatbin. The fatbin is then an input to the host action if not in
3159  // device-only mode.
3160  if (CompileDeviceOnly || CurPhase == phases::Backend) {
3161  ActionList DeviceActions;
3162  for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3163  // Produce the device action from the current phase up to the assemble
3164  // phase.
3165  for (auto Ph : Phases) {
3166  // Skip the phases that were already dealt with.
3167  if (Ph < CurPhase)
3168  continue;
3169  // We have to be consistent with the host final phase.
3170  if (Ph > FinalPhase)
3171  break;
3172 
3173  CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
3174  C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
3175 
3176  if (Ph == phases::Assemble)
3177  break;
3178  }
3179 
3180  // If we didn't reach the assemble phase, we can't generate the fat
3181  // binary. We don't need to generate the fat binary if we are not in
3182  // device-only mode.
3183  if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
3184  CompileDeviceOnly)
3185  continue;
3186 
3187  Action *AssembleAction = CudaDeviceActions[I];
3188  assert(AssembleAction->getType() == types::TY_Object);
3189  assert(AssembleAction->getInputs().size() == 1);
3190 
3191  Action *BackendAction = AssembleAction->getInputs()[0];
3192  assert(BackendAction->getType() == types::TY_PP_Asm);
3193 
3194  for (auto &A : {AssembleAction, BackendAction}) {
3196  DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda);
3197  DeviceActions.push_back(
3198  C.MakeAction<OffloadAction>(DDep, A->getType()));
3199  }
3200  }
3201 
3202  // We generate the fat binary if we have device input actions.
3203  if (!DeviceActions.empty()) {
3204  CudaFatBinary =
3205  C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
3206 
3207  if (!CompileDeviceOnly) {
3208  DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3210  // Clear the fat binary, it is already a dependence to an host
3211  // action.
3212  CudaFatBinary = nullptr;
3213  }
3214 
3215  // Remove the CUDA actions as they are already connected to an host
3216  // action or fat binary.
3217  CudaDeviceActions.clear();
3218  }
3219 
3220  // We avoid creating host action in device-only mode.
3221  return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3222  } else if (CurPhase > phases::Backend) {
3223  // If we are past the backend phase and still have a device action, we
3224  // don't have to do anything as this action is already a device
3225  // top-level action.
3226  return ABRT_Success;
3227  }
3228 
3229  assert(CurPhase < phases::Backend && "Generating single CUDA "
3230  "instructions should only occur "
3231  "before the backend phase!");
3232 
3233  // By default, we produce an action for each device arch.
3234  for (Action *&A : CudaDeviceActions)
3235  A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
3236 
3237  return ABRT_Success;
3238  }
3239  };
3240  /// \brief HIP action builder. It injects device code in the host backend
3241  /// action.
3242  class HIPActionBuilder final : public CudaActionBuilderBase {
3243  /// The linker inputs obtained for each device arch.
3244  SmallVector<ActionList, 8> DeviceLinkerInputs;
3245  // The default bundling behavior depends on the type of output, therefore
3246  // BundleOutput needs to be tri-value: None, true, or false.
3247  // Bundle code objects except --no-gpu-output is specified for device
3248  // only compilation. Bundle other type of output files only if
3249  // --gpu-bundle-output is specified for device only compilation.
3250  Optional<bool> BundleOutput;
3251 
3252  public:
3253  HIPActionBuilder(Compilation &C, DerivedArgList &Args,
3254  const Driver::InputList &Inputs)
3255  : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
3256  DefaultCudaArch = CudaArch::GFX803;
3257  if (Args.hasArg(options::OPT_gpu_bundle_output,
3258  options::OPT_no_gpu_bundle_output))
3259  BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output,
3260  options::OPT_no_gpu_bundle_output, true);
3261  }
3262 
3263  bool canUseBundlerUnbundler() const override { return true; }
3264 
3265  StringRef getCanonicalOffloadArch(StringRef IdStr) override {
3266  llvm::StringMap<bool> Features;
3267  // getHIPOffloadTargetTriple() is known to return valid value as it has
3268  // been called successfully in the CreateOffloadingDeviceToolChains().
3269  auto ArchStr = parseTargetID(
3270  *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr,
3271  &Features);
3272  if (!ArchStr) {
3273  C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
3274  C.setContainsError();
3275  return StringRef();
3276  }
3277  auto CanId = getCanonicalTargetID(*ArchStr, Features);
3278  return Args.MakeArgStringRef(CanId);
3279  };
3280 
3283  const std::set<StringRef> &GpuArchs) override {
3284  return getConflictTargetIDCombination(GpuArchs);
3285  }
3286 
3287  ActionBuilderReturnCode
3288  getDeviceDependences(OffloadAction::DeviceDependences &DA,
3289  phases::ID CurPhase, phases::ID FinalPhase,
3290  PhasesTy &Phases) override {
3291  if (!IsActive)
3292  return ABRT_Inactive;
3293 
3294  // amdgcn does not support linking of object files, therefore we skip
3295  // backend and assemble phases to output LLVM IR. Except for generating
3296  // non-relocatable device code, where we generate fat binary for device
3297  // code and pass to host in Backend phase.
3298  if (CudaDeviceActions.empty())
3299  return ABRT_Success;
3300 
3301  assert(((CurPhase == phases::Link && Relocatable) ||
3302  CudaDeviceActions.size() == GpuArchList.size()) &&
3303  "Expecting one action per GPU architecture.");
3304  assert(!CompileHostOnly &&
3305  "Not expecting HIP actions in host-only compilation.");
3306 
3307  if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
3308  !EmitAsm) {
3309  // If we are in backend phase, we attempt to generate the fat binary.
3310  // We compile each arch to IR and use a link action to generate code
3311  // object containing ISA. Then we use a special "link" action to create
3312  // a fat binary containing all the code objects for different GPU's.
3313  // The fat binary is then an input to the host action.
3314  for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3315  if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) {
3316  // When LTO is enabled, skip the backend and assemble phases and
3317  // use lld to link the bitcode.
3318  ActionList AL;
3319  AL.push_back(CudaDeviceActions[I]);
3320  // Create a link action to link device IR with device library
3321  // and generate ISA.
3322  CudaDeviceActions[I] =
3323  C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3324  } else {
3325  // When LTO is not enabled, we follow the conventional
3326  // compiler phases, including backend and assemble phases.
3327  ActionList AL;
3328  Action *BackendAction = nullptr;
3329  if (ToolChains.front()->getTriple().isSPIRV()) {
3330  // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
3331  // (HIPSPVToolChain) runs post-link LLVM IR passes.
3332  types::ID Output = Args.hasArg(options::OPT_S)
3333  ? types::TY_LLVM_IR
3334  : types::TY_LLVM_BC;
3335  BackendAction =
3336  C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output);
3337  } else
3338  BackendAction = C.getDriver().ConstructPhaseAction(
3339  C, Args, phases::Backend, CudaDeviceActions[I],
3340  AssociatedOffloadKind);
3341  auto AssembleAction = C.getDriver().ConstructPhaseAction(
3342  C, Args, phases::Assemble, BackendAction,
3343  AssociatedOffloadKind);
3344  AL.push_back(AssembleAction);
3345  // Create a link action to link device IR with device library
3346  // and generate ISA.
3347  CudaDeviceActions[I] =
3348  C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3349  }
3350 
3351  // OffloadingActionBuilder propagates device arch until an offload
3352  // action. Since the next action for creating fatbin does
3353  // not have device arch, whereas the above link action and its input
3354  // have device arch, an offload action is needed to stop the null
3355  // device arch of the next action being propagated to the above link
3356  // action.
3358  DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3359  AssociatedOffloadKind);
3360  CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3361  DDep, CudaDeviceActions[I]->getType());
3362  }
3363 
3364  if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3365  // Create HIP fat binary with a special "link" action.
3366  CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions,
3367  types::TY_HIP_FATBIN);
3368 
3369  if (!CompileDeviceOnly) {
3370  DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3371  AssociatedOffloadKind);
3372  // Clear the fat binary, it is already a dependence to an host
3373  // action.
3374  CudaFatBinary = nullptr;
3375  }
3376 
3377  // Remove the CUDA actions as they are already connected to an host
3378  // action or fat binary.
3379  CudaDeviceActions.clear();
3380  }
3381 
3382  return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3383  } else if (CurPhase == phases::Link) {
3384  // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
3385  // This happens to each device action originated from each input file.
3386  // Later on, device actions in DeviceLinkerInputs are used to create
3387  // device link actions in appendLinkDependences and the created device
3388  // link actions are passed to the offload action as device dependence.
3389  DeviceLinkerInputs.resize(CudaDeviceActions.size());
3390  auto LI = DeviceLinkerInputs.begin();
3391  for (auto *A : CudaDeviceActions) {
3392  LI->push_back(A);
3393  ++LI;
3394  }
3395 
3396  // We will pass the device action as a host dependence, so we don't
3397  // need to do anything else with them.
3398  CudaDeviceActions.clear();
3399  return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3400  }
3401 
3402  // By default, we produce an action for each device arch.
3403  for (Action *&A : CudaDeviceActions)
3404  A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
3405  AssociatedOffloadKind);
3406 
3407  if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput &&
3408  BundleOutput.value()) {
3409  for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3411  DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3412  AssociatedOffloadKind);
3413  CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3414  DDep, CudaDeviceActions[I]->getType());
3415  }
3416  CudaFatBinary =
3417  C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions);
3418  CudaDeviceActions.clear();
3419  }
3420 
3421  return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
3422  : ABRT_Success;
3423  }
3424 
3425  void appendLinkDeviceActions(ActionList &AL) override {
3426  if (DeviceLinkerInputs.size() == 0)
3427  return;
3428 
3429  assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
3430  "Linker inputs and GPU arch list sizes do not match.");
3431 
3432  ActionList Actions;
3433  unsigned I = 0;
3434  // Append a new link action for each device.
3435  // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
3436  for (auto &LI : DeviceLinkerInputs) {
3437 
3438  types::ID Output = Args.hasArg(options::OPT_emit_llvm)
3439  ? types::TY_LLVM_BC
3440  : types::TY_Image;
3441 
3442  auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output);
3443  // Linking all inputs for the current GPU arch.
3444  // LI contains all the inputs for the linker.
3445  OffloadAction::DeviceDependences DeviceLinkDeps;
3446  DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
3447  GpuArchList[I], AssociatedOffloadKind);
3448  Actions.push_back(C.MakeAction<OffloadAction>(
3449  DeviceLinkDeps, DeviceLinkAction->getType()));
3450  ++I;
3451  }
3452  DeviceLinkerInputs.clear();
3453 
3454  // If emitting LLVM, do not generate final host/device compilation action
3455  if (Args.hasArg(options::OPT_emit_llvm)) {
3456  AL.append(Actions);
3457  return;
3458  }
3459 
3460  // Create a host object from all the device images by embedding them
3461  // in a fat binary for mixed host-device compilation. For device-only
3462  // compilation, creates a fat binary.
3464  if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3465  auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>(
3466  Actions,
3467  CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object);
3468  DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr,
3469  AssociatedOffloadKind);
3470  // Offload the host object to the host linker.
3471  AL.push_back(
3472  C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
3473  } else {
3474  AL.append(Actions);
3475  }
3476  }
3477 
3478  Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
3479 
3480  void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3481  };
3482 
3483  ///
3484  /// TODO: Add the implementation for other specialized builders here.
3485  ///
3486 
3487  /// Specialized builders being used by this offloading action builder.
3488  SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3489 
3490  /// Flag set to true if all valid builders allow file bundling/unbundling.
3491  bool CanUseBundler;
3492 
3493 public:
3494  OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3495  const Driver::InputList &Inputs)
3496  : C(C) {
3497  // Create a specialized builder for each device toolchain.
3498 
3499  IsValid = true;
3500 
3501  // Create a specialized builder for CUDA.
3502  SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3503 
3504  // Create a specialized builder for HIP.
3505  SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3506 
3507  //
3508  // TODO: Build other specialized builders here.
3509  //
3510 
3511  // Initialize all the builders, keeping track of errors. If all valid
3512  // builders agree that we can use bundling, set the flag to true.
3513  unsigned ValidBuilders = 0u;
3514  unsigned ValidBuildersSupportingBundling = 0u;
3515  for (auto *SB : SpecializedBuilders) {
3516  IsValid = IsValid && !SB->initialize();
3517 
3518  // Update the counters if the builder is valid.
3519  if (SB->isValid()) {
3520  ++ValidBuilders;
3521  if (SB->canUseBundlerUnbundler())
3522  ++ValidBuildersSupportingBundling;
3523  }
3524  }
3525  CanUseBundler =
3526  ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3527  }
3528 
3529  ~OffloadingActionBuilder() {
3530  for (auto *SB : SpecializedBuilders)
3531  delete SB;
3532  }
3533 
3534  /// Record a host action and its originating input argument.
3535  void recordHostAction(Action *HostAction, const Arg *InputArg) {
3536  assert(HostAction && "Invalid host action");
3537  assert(InputArg && "Invalid input argument");
3538  auto Loc = HostActionToInputArgMap.find(HostAction);
3539  if (Loc == HostActionToInputArgMap.end())
3540  HostActionToInputArgMap[HostAction] = InputArg;
3541  assert(HostActionToInputArgMap[HostAction] == InputArg &&
3542  "host action mapped to multiple input arguments");
3543  }
3544 
3545  /// Generate an action that adds device dependences (if any) to a host action.
3546  /// If no device dependence actions exist, just return the host action \a
3547  /// HostAction. If an error is found or if no builder requires the host action
3548  /// to be generated, return nullptr.
3549  Action *
3550  addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3551  phases::ID CurPhase, phases::ID FinalPhase,
3552  DeviceActionBuilder::PhasesTy &Phases) {
3553  if (!IsValid)
3554  return nullptr;
3555 
3556  if (SpecializedBuilders.empty())
3557  return HostAction;
3558 
3559  assert(HostAction && "Invalid host action!");
3560  recordHostAction(HostAction, InputArg);
3561 
3563  // Check if all the programming models agree we should not emit the host
3564  // action. Also, keep track of the offloading kinds employed.
3565  auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3566  unsigned InactiveBuilders = 0u;
3567  unsigned IgnoringBuilders = 0u;
3568  for (auto *SB : SpecializedBuilders) {
3569  if (!SB->isValid()) {
3570  ++InactiveBuilders;
3571  continue;
3572  }
3573 
3574  auto RetCode =
3575  SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3576 
3577  // If the builder explicitly says the host action should be ignored,
3578  // we need to increment the variable that tracks the builders that request
3579  // the host object to be ignored.
3580  if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3581  ++IgnoringBuilders;
3582 
3583  // Unless the builder was inactive for this action, we have to record the
3584  // offload kind because the host will have to use it.
3585  if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3586  OffloadKind |= SB->getAssociatedOffloadKind();
3587  }
3588 
3589  // If all builders agree that the host object should be ignored, just return
3590  // nullptr.
3591  if (IgnoringBuilders &&
3592  SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3593  return nullptr;
3594 
3595  if (DDeps.getActions().empty())
3596  return HostAction;
3597 
3598  // We have dependences we need to bundle together. We use an offload action
3599  // for that.
3601  *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3602  /*BoundArch=*/nullptr, DDeps);
3603  return C.MakeAction<OffloadAction>(HDep, DDeps);
3604  }
3605 
3606  /// Generate an action that adds a host dependence to a device action. The
3607  /// results will be kept in this action builder. Return true if an error was
3608  /// found.
3609  bool addHostDependenceToDeviceActions(Action *&HostAction,
3610  const Arg *InputArg) {
3611  if (!IsValid)
3612  return true;
3613 
3614  recordHostAction(HostAction, InputArg);
3615 
3616  // If we are supporting bundling/unbundling and the current action is an
3617  // input action of non-source file, we replace the host action by the
3618  // unbundling action. The bundler tool has the logic to detect if an input
3619  // is a bundle or not and if the input is not a bundle it assumes it is a
3620  // host file. Therefore it is safe to create an unbundling action even if
3621  // the input is not a bundle.
3622  if (CanUseBundler && isa<InputAction>(HostAction) &&
3623  InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3624  (!types::isSrcFile(HostAction->getType()) ||
3625  HostAction->getType() == types::TY_PP_HIP)) {
3626  auto UnbundlingHostAction =
3627  C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3628  UnbundlingHostAction->registerDependentActionInfo(
3629  C.getSingleOffloadToolChain<Action::OFK_Host>(),
3630  /*BoundArch=*/StringRef(), Action::OFK_Host);
3631  HostAction = UnbundlingHostAction;
3632  recordHostAction(HostAction, InputArg);
3633  }
3634 
3635  assert(HostAction && "Invalid host action!");
3636 
3637  // Register the offload kinds that are used.
3638  auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3639  for (auto *SB : SpecializedBuilders) {
3640  if (!SB->isValid())
3641  continue;
3642 
3643  auto RetCode = SB->addDeviceDependences(HostAction);
3644 
3645  // Host dependences for device actions are not compatible with that same
3646  // action being ignored.
3647  assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3648  "Host dependence not expected to be ignored.!");
3649 
3650  // Unless the builder was inactive for this action, we have to record the
3651  // offload kind because the host will have to use it.
3652  if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3653  OffloadKind |= SB->getAssociatedOffloadKind();
3654  }
3655 
3656  // Do not use unbundler if the Host does not depend on device action.
3657  if (OffloadKind == Action::OFK_None && CanUseBundler)
3658  if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3659  HostAction = UA->getInputs().back();
3660 
3661  return false;
3662  }
3663 
3664  /// Add the offloading top level actions to the provided action list. This
3665  /// function can replace the host action by a bundling action if the
3666  /// programming models allow it.
3667  bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3668  const Arg *InputArg) {
3669  if (HostAction)
3670  recordHostAction(HostAction, InputArg);
3671 
3672  // Get the device actions to be appended.
3673  ActionList OffloadAL;
3674  for (auto *SB : SpecializedBuilders) {
3675  if (!SB->isValid())
3676  continue;
3677  SB->appendTopLevelActions(OffloadAL);
3678  }
3679 
3680  // If we can use the bundler, replace the host action by the bundling one in
3681  // the resulting list. Otherwise, just append the device actions. For
3682  // device only compilation, HostAction is a null pointer, therefore only do
3683  // this when HostAction is not a null pointer.
3684  if (CanUseBundler && HostAction &&
3685  HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3686  // Add the host action to the list in order to create the bundling action.
3687  OffloadAL.push_back(HostAction);
3688 
3689  // We expect that the host action was just appended to the action list
3690  // before this method was called.
3691  assert(HostAction == AL.back() && "Host action not in the list??");
3692  HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3693  recordHostAction(HostAction, InputArg);
3694  AL.back() = HostAction;
3695  } else
3696  AL.append(OffloadAL.begin(), OffloadAL.end());
3697 
3698  // Propagate to the current host action (if any) the offload information
3699  // associated with the current input.
3700  if (HostAction)
3701  HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3702  /*BoundArch=*/nullptr);
3703  return false;
3704  }
3705 
3706  void appendDeviceLinkActions(ActionList &AL) {
3707  for (DeviceActionBuilder *SB : SpecializedBuilders) {
3708  if (!SB->isValid())
3709  continue;
3710  SB->appendLinkDeviceActions(AL);
3711  }
3712  }
3713 
3714  Action *makeHostLinkAction() {
3715  // Build a list of device linking actions.
3716  ActionList DeviceAL;
3717  appendDeviceLinkActions(DeviceAL);
3718  if (DeviceAL.empty())
3719  return nullptr;
3720 
3721  // Let builders add host linking actions.
3722  Action* HA = nullptr;
3723  for (DeviceActionBuilder *SB : SpecializedBuilders) {
3724  if (!SB->isValid())
3725  continue;
3726  HA = SB->appendLinkHostActions(DeviceAL);
3727  // This created host action has no originating input argument, therefore
3728  // needs to set its offloading kind directly.
3729  if (HA)
3730  HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(),
3731  /*BoundArch=*/nullptr);
3732  }
3733  return HA;
3734  }
3735 
3736  /// Processes the host linker action. This currently consists of replacing it
3737  /// with an offload action if there are device link objects and propagate to
3738  /// the host action all the offload kinds used in the current compilation. The
3739  /// resulting action is returned.
3740  Action *processHostLinkAction(Action *HostAction) {
3741  // Add all the dependences from the device linking actions.
3743  for (auto *SB : SpecializedBuilders) {
3744  if (!SB->isValid())
3745  continue;
3746 
3747  SB->appendLinkDependences(DDeps);
3748  }
3749 
3750  // Calculate all the offload kinds used in the current compilation.
3751  unsigned ActiveOffloadKinds = 0u;
3752  for (auto &I : InputArgToOffloadKindMap)
3753  ActiveOffloadKinds |= I.second;
3754 
3755  // If we don't have device dependencies, we don't have to create an offload
3756  // action.
3757  if (DDeps.getActions().empty()) {
3758  // Set all the active offloading kinds to the link action. Given that it
3759  // is a link action it is assumed to depend on all actions generated so
3760  // far.
3761  HostAction->setHostOffloadInfo(ActiveOffloadKinds,
3762  /*BoundArch=*/nullptr);
3763  // Propagate active offloading kinds for each input to the link action.
3764  // Each input may have different active offloading kind.
3765  for (auto *A : HostAction->inputs()) {
3766  auto ArgLoc = HostActionToInputArgMap.find(A);
3767  if (ArgLoc == HostActionToInputArgMap.end())
3768  continue;
3769  auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second);
3770  if (OFKLoc == InputArgToOffloadKindMap.end())
3771  continue;
3772  A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr);
3773  }
3774  return HostAction;
3775  }
3776 
3777  // Create the offload action with all dependences. When an offload action
3778  // is created the kinds are propagated to the host action, so we don't have
3779  // to do that explicitly here.
3781  *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3782  /*BoundArch*/ nullptr, ActiveOffloadKinds);
3783  return C.MakeAction<OffloadAction>(HDep, DDeps);
3784  }
3785 };
3786 } // anonymous namespace.
3787 
3788 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3789  const InputList &Inputs,
3790  ActionList &Actions) const {
3791 
3792  // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3793  Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3794  Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3795  if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3796  Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3797  Args.eraseArg(options::OPT__SLASH_Yc);
3798  Args.eraseArg(options::OPT__SLASH_Yu);
3799  YcArg = YuArg = nullptr;
3800  }
3801  if (YcArg && Inputs.size() > 1) {
3802  Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3803  Args.eraseArg(options::OPT__SLASH_Yc);
3804  YcArg = nullptr;
3805  }
3806 
3807  Arg *FinalPhaseArg;
3808  phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3809 
3810  if (FinalPhase == phases::Link) {
3811  // Emitting LLVM while linking disabled except in HIPAMD Toolchain
3812  if (Args.hasArg(options::OPT_emit_llvm) && !Args.hasArg(options::OPT_hip_link))
3813  Diag(clang::diag::err_drv_emit_llvm_link);
3814  if (IsCLMode() && LTOMode != LTOK_None &&
3815  !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
3816  .equals_insensitive("lld"))
3817  Diag(clang::diag::err_drv_lto_without_lld);
3818  }
3819 
3820  if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3821  // If only preprocessing or /Y- is used, all pch handling is disabled.
3822  // Rather than check for it everywhere, just remove clang-cl pch-related
3823  // flags here.
3824  Args.eraseArg(options::OPT__SLASH_Fp);
3825  Args.eraseArg(options::OPT__SLASH_Yc);
3826  Args.eraseArg(options::OPT__SLASH_Yu);
3827  YcArg = YuArg = nullptr;
3828  }
3829 
3830  unsigned LastPLSize = 0;
3831  for (auto &I : Inputs) {
3832  types::ID InputType = I.first;
3833  const Arg *InputArg = I.second;
3834 
3835  auto PL = types::getCompilationPhases(InputType);
3836  LastPLSize = PL.size();
3837 
3838  // If the first step comes after the final phase we are doing as part of
3839  // this compilation, warn the user about it.
3840  phases::ID InitialPhase = PL[0];
3841  if (InitialPhase > FinalPhase) {
3842  if (InputArg->isClaimed())
3843  continue;
3844 
3845  // Claim here to avoid the more general unused warning.
3846  InputArg->claim();
3847 
3848  // Suppress all unused style warnings with -Qunused-arguments
3849  if (Args.hasArg(options::OPT_Qunused_arguments))
3850  continue;
3851 
3852  // Special case when final phase determined by binary name, rather than
3853  // by a command-line argument with a corresponding Arg.
3854  if (CCCIsCPP())
3855  Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3856  << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3857  // Special case '-E' warning on a previously preprocessed file to make
3858  // more sense.
3859  else if (InitialPhase == phases::Compile &&
3860  (Args.getLastArg(options::OPT__SLASH_EP,
3861  options::OPT__SLASH_P) ||
3862  Args.getLastArg(options::OPT_E) ||
3863  Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3864  getPreprocessedType(InputType) == types::TY_INVALID)
3865  Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3866  << InputArg->getAsString(Args) << !!FinalPhaseArg
3867  << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3868  else
3869  Diag(clang::diag::warn_drv_input_file_unused)
3870  << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3871  << !!FinalPhaseArg
3872  << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3873  continue;
3874  }
3875 
3876  if (YcArg) {
3877  // Add a separate precompile phase for the compile phase.
3878  if (FinalPhase >= phases::Compile) {
3879  const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3880  // Build the pipeline for the pch file.
3881  Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3882  for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3883  ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3884  assert(ClangClPch);
3885  Actions.push_back(ClangClPch);
3886  // The driver currently exits after the first failed command. This
3887  // relies on that behavior, to make sure if the pch generation fails,
3888  // the main compilation won't run.
3889  // FIXME: If the main compilation fails, the PCH generation should
3890  // probably not be considered successful either.
3891  }
3892  }
3893  }
3894 
3895  // If we are linking, claim any options which are obviously only used for
3896  // compilation.
3897  // FIXME: Understand why the last Phase List length is used here.
3898  if (FinalPhase == phases::Link && LastPLSize == 1) {
3899  Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3900  Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3901  }
3902 }
3903 
3904 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3905  const InputList &Inputs, ActionList &Actions) const {
3906  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3907 
3908  if (!SuppressMissingInputWarning && Inputs.empty()) {
3909  Diag(clang::diag::err_drv_no_input_files);
3910  return;
3911  }
3912 
3913  // Diagnose misuse of /Fo.
3914  if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3915  StringRef V = A->getValue();
3916  if (Inputs.size() > 1 && !V.empty() &&
3917  !llvm::sys::path::is_separator(V.back())) {
3918  // Check whether /Fo tries to name an output file for multiple inputs.
3919  Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3920  << A->getSpelling() << V;
3921  Args.eraseArg(options::OPT__SLASH_Fo);
3922  }
3923  }
3924 
3925  // Diagnose misuse of /Fa.
3926  if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3927  StringRef V = A->getValue();
3928  if (Inputs.size() > 1 && !V.empty() &&
3929  !llvm::sys::path::is_separator(V.back())) {
3930  // Check whether /Fa tries to name an asm file for multiple inputs.
3931  Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3932  << A->getSpelling() << V;
3933  Args.eraseArg(options::OPT__SLASH_Fa);
3934  }
3935  }
3936 
3937  // Diagnose misuse of /o.
3938  if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3939  if (A->getValue()[0] == '\0') {
3940  // It has to have a value.
3941  Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3942  Args.eraseArg(options::OPT__SLASH_o);
3943  }
3944  }
3945 
3946  handleArguments(C, Args, Inputs, Actions);
3947 
3948  bool UseNewOffloadingDriver =
3949  C.isOffloadingHostKind(Action::OFK_OpenMP) ||
3950  Args.hasFlag(options::OPT_offload_new_driver,
3951  options::OPT_no_offload_new_driver, false);
3952 
3953  // Builder to be used to build offloading actions.
3954  std::unique_ptr<OffloadingActionBuilder> OffloadBuilder =
3955  !UseNewOffloadingDriver
3956  ? std::make_unique<OffloadingActionBuilder>(C, Args, Inputs)
3957  : nullptr;
3958 
3959  // Construct the actions to perform.
3961  ActionList LinkerInputs;
3962  ActionList MergerInputs;
3963 
3964  for (auto &I : Inputs) {
3965  types::ID InputType = I.first;
3966  const Arg *InputArg = I.second;
3967 
3968  auto PL = types::getCompilationPhases(*this, Args, InputType);
3969  if (PL.empty())
3970  continue;
3971 
3972  auto FullPL = types::getCompilationPhases(InputType);
3973 
3974  // Build the pipeline for this file.
3975  Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3976 
3977  // Use the current host action in any of the offloading actions, if
3978  // required.
3979  if (!UseNewOffloadingDriver)
3980  if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
3981  break;
3982 
3983  for (phases::ID Phase : PL) {
3984 
3985  // Add any offload action the host action depends on.
3986  if (!UseNewOffloadingDriver)
3987  Current = OffloadBuilder->addDeviceDependencesToHostAction(
3988  Current, InputArg, Phase, PL.back(), FullPL);
3989  if (!Current)
3990  break;
3991 
3992  // Queue linker inputs.
3993  if (Phase == phases::Link) {
3994  assert(Phase == PL.back() && "linking must be final compilation step.");
3995  // We don't need to generate additional link commands if emitting AMD bitcode
3996  if (!(C.getInputArgs().hasArg(options::OPT_hip_link) &&
3997  (C.getInputArgs().hasArg(options::OPT_emit_llvm))))
3998  LinkerInputs.push_back(Current);
3999  Current = nullptr;
4000  break;
4001  }
4002 
4003  // TODO: Consider removing this because the merged may not end up being
4004  // the final Phase in the pipeline. Perhaps the merged could just merge
4005  // and then pass an artifact of some sort to the Link Phase.
4006  // Queue merger inputs.
4007  if (Phase == phases::IfsMerge) {
4008  assert(Phase == PL.back() && "merging must be final compilation step.");
4009  MergerInputs.push_back(Current);
4010  Current = nullptr;
4011  break;
4012  }
4013 
4014  if (Phase == phases::Precompile && ExtractAPIAction) {
4015  ExtractAPIAction->addHeaderInput(Current);
4016  Current = nullptr;
4017  break;
4018  }
4019 
4020  // FIXME: Should we include any prior module file outputs as inputs of
4021  // later actions in the same command line?
4022 
4023  // Otherwise construct the appropriate action.
4024  Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
4025 
4026  // We didn't create a new action, so we will just move to the next phase.
4027  if (NewCurrent == Current)
4028  continue;
4029 
4030  if (auto *EAA = dyn_cast<ExtractAPIJobAction>(NewCurrent))
4031  ExtractAPIAction = EAA;
4032 
4033  Current = NewCurrent;
4034 
4035  // Use the current host action in any of the offloading actions, if
4036  // required.
4037  if (!UseNewOffloadingDriver)
4038  if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
4039  break;
4040 
4041  // Try to build the offloading actions and add the result as a dependency
4042  // to the host.
4043  if (UseNewOffloadingDriver)
4044  Current = BuildOffloadingActions(C, Args, I, Current);
4045 
4046  if (Current->getType() == types::TY_Nothing)
4047  break;
4048  }
4049 
4050  // If we ended with something, add to the output list.
4051  if (Current)
4052  Actions.push_back(Current);
4053 
4054  // Add any top level actions generated for offloading.
4055  if (!UseNewOffloadingDriver)
4056  OffloadBuilder->appendTopLevelActions(Actions, Current, InputArg);
4057  else if (Current)
4058  Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4059  /*BoundArch=*/nullptr);
4060  }
4061 
4062  // Add a link action if necessary.
4063 
4064  if (LinkerInputs.empty()) {
4065  Arg *FinalPhaseArg;
4066  if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link)
4067  if (!UseNewOffloadingDriver)
4068  OffloadBuilder->appendDeviceLinkActions(Actions);
4069  }
4070 
4071  if (!LinkerInputs.empty()) {
4072  if (!UseNewOffloadingDriver)
4073  if (Action *Wrapper = OffloadBuilder->makeHostLinkAction())
4074  LinkerInputs.push_back(Wrapper);
4075  Action *LA;
4076  // Check if this Linker Job should emit a static library.
4077  if (ShouldEmitStaticLibrary(Args)) {
4078  LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
4079  } else if (UseNewOffloadingDriver ||
4080  Args.hasArg(options::OPT_offload_link)) {
4081  LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image);
4082  LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4083  /*BoundArch=*/nullptr);
4084  } else {
4085  LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
4086  }
4087  if (!UseNewOffloadingDriver)
4088  LA = OffloadBuilder->processHostLinkAction(LA);
4089  Actions.push_back(LA);
4090  }
4091 
4092  // Add an interface stubs merge action if necessary.
4093  if (!MergerInputs.empty())
4094  Actions.push_back(
4095  C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4096 
4097  if (Args.hasArg(options::OPT_emit_interface_stubs)) {
4098  auto PhaseList = types::getCompilationPhases(
4099  types::TY_IFS_CPP,
4100  Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge);
4101 
4102  ActionList MergerInputs;
4103 
4104  for (auto &I : Inputs) {
4105  types::ID InputType = I.first;
4106  const Arg *InputArg = I.second;
4107 
4108  // Currently clang and the llvm assembler do not support generating symbol
4109  // stubs from assembly, so we skip the input on asm files. For ifs files
4110  // we rely on the normal pipeline setup in the pipeline setup code above.
4111  if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
4112  InputType == types::TY_Asm)
4113  continue;
4114 
4115  Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4116 
4117  for (auto Phase : PhaseList) {
4118  switch (Phase) {
4119  default:
4120  llvm_unreachable(
4121  "IFS Pipeline can only consist of Compile followed by IfsMerge.");
4122  case phases::Compile: {
4123  // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
4124  // files where the .o file is located. The compile action can not
4125  // handle this.
4126  if (InputType == types::TY_Object)
4127  break;
4128 
4129  Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
4130  break;
4131  }
4132  case phases::IfsMerge: {
4133  assert(Phase == PhaseList.back() &&
4134  "merging must be final compilation step.");
4135  MergerInputs.push_back(Current);
4136  Current = nullptr;
4137  break;
4138  }
4139  }
4140  }
4141 
4142  // If we ended with something, add to the output list.
4143  if (Current)
4144  Actions.push_back(Current);
4145  }
4146 
4147  // Add an interface stubs merge action if necessary.
4148  if (!MergerInputs.empty())
4149  Actions.push_back(
4150  C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4151  }
4152 
4153  // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
4154  // Compile phase that prints out supported cpu models and quits.
4155  if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
4156  // Use the -mcpu=? flag as the dummy input to cc1.
4157  Actions.clear();
4158  Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
4159  Actions.push_back(
4160  C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
4161  for (auto &I : Inputs)
4162  I.second->claim();
4163  }
4164 
4165  // Claim ignored clang-cl options.
4166  Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
4167 }
4168 
4169 /// Returns the canonical name for the offloading architecture when using a HIP
4170 /// or CUDA architecture.
4172  const llvm::opt::DerivedArgList &Args,
4173  StringRef ArchStr,
4174  const llvm::Triple &Triple) {
4175  // Lookup the CUDA / HIP architecture string. Only report an error if we were
4176  // expecting the triple to be only NVPTX / AMDGPU.
4177  CudaArch Arch = StringToCudaArch(getProcessorFromTargetID(Triple, ArchStr));
4178  if (Triple.isNVPTX() &&
4179  (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch))) {
4180  C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4181  << "CUDA" << ArchStr;
4182  return StringRef();
4183  } else if (Triple.isAMDGPU() &&
4184  (Arch == CudaArch::UNKNOWN || !IsAMDGpuArch(Arch))) {
4185  C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4186  << "HIP" << ArchStr;
4187  return StringRef();
4188  }
4189 
4190  if (IsNVIDIAGpuArch(Arch))
4191  return Args.MakeArgStringRef(CudaArchToString(Arch));
4192 
4193  if (IsAMDGpuArch(Arch)) {
4194  llvm::StringMap<bool> Features;
4195  auto HIPTriple = getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs());
4196  if (!HIPTriple)
4197  return StringRef();
4198  auto Arch = parseTargetID(*HIPTriple, ArchStr, &Features);
4199  if (!Arch) {
4200  C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr;
4201  C.setContainsError();
4202  return StringRef();
4203  }
4204  return Args.MakeArgStringRef(getCanonicalTargetID(*Arch, Features));
4205  }
4206 
4207  // If the input isn't CUDA or HIP just return the architecture.
4208  return ArchStr;
4209 }
4210 
4211 /// Checks if the set offloading architectures does not conflict. Returns the
4212 /// incompatible pair if a conflict occurs.
4216  if (Kind != Action::OFK_HIP)
4217  return None;
4218 
4219  std::set<StringRef> ArchSet;
4220  llvm::copy(Archs, std::inserter(ArchSet, ArchSet.begin()));
4221  return getConflictTargetIDCombination(ArchSet);
4222 }
4223 
4225 Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
4226  Action::OffloadKind Kind, const ToolChain *TC) const {
4227  if (!TC)
4228  TC = &C.getDefaultToolChain();
4229 
4230  // --offload and --offload-arch options are mutually exclusive.
4231  if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
4232  Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
4233  options::OPT_no_offload_arch_EQ)) {
4234  C.getDriver().Diag(diag::err_opt_not_valid_with_opt)
4235  << "--offload"
4236  << (Args.hasArgNoClaim(options::OPT_offload_arch_EQ)
4237  ? "--offload-arch"
4238  : "--no-offload-arch");
4239  }
4240 
4241  if (KnownArchs.find(TC) != KnownArchs.end())
4242  return KnownArchs.lookup(TC);
4243 
4245  for (auto *Arg : Args) {
4246  // Extract any '--[no-]offload-arch' arguments intended for this toolchain.
4247  std::unique_ptr<llvm::opt::Arg> ExtractedArg = nullptr;
4248  if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) &&
4249  ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()) {
4250  Arg->claim();
4251  unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1));
4252  ExtractedArg = getOpts().ParseOneArg(Args, Index);
4253  Arg = ExtractedArg.get();
4254  }
4255 
4256  // Add or remove the seen architectures in order of appearance. If an
4257  // invalid architecture is given we simply exit.
4258  if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) {
4259  for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4260  StringRef ArchStr =
4261  getCanonicalArchString(C, Args, Arch, TC->getTriple());
4262  if (ArchStr.empty())
4263  return Archs;
4264  Archs.insert(ArchStr);
4265  }
4266  } else if (Arg->getOption().matches(options::OPT_no_offload_arch_EQ)) {
4267  for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4268  if (Arch == "all") {
4269  Archs.clear();
4270  } else {
4271  StringRef ArchStr =
4272  getCanonicalArchString(C, Args, Arch, TC->getTriple());
4273  if (ArchStr.empty())
4274  return Archs;
4275  Archs.erase(ArchStr);
4276  }
4277  }
4278  }
4279  }
4280 
4281  if (auto ConflictingArchs = getConflictOffloadArchCombination(Archs, Kind)) {
4282  C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
4283  << ConflictingArchs->first << ConflictingArchs->second;
4284  C.setContainsError();
4285  }
4286 
4287  if (Archs.empty()) {
4288  if (Kind == Action::OFK_Cuda)
4289  Archs.insert(CudaArchToString(CudaArch::CudaDefault));
4290  else if (Kind == Action::OFK_HIP)
4291  Archs.insert(CudaArchToString(CudaArch::HIPDefault));
4292  else if (Kind == Action::OFK_OpenMP)
4293  Archs.insert(StringRef());
4294  } else {
4295  Args.ClaimAllArgs(options::OPT_offload_arch_EQ);
4296  Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ);
4297  }
4298 
4299  return Archs;
4300 }
4301 
4303  llvm::opt::DerivedArgList &Args,
4304  const InputTy &Input,
4305  Action *HostAction) const {
4306  // Don't build offloading actions if explicitly disabled or we do not have a
4307  // valid source input and compile action to embed it in. If preprocessing only
4308  // ignore embedding.
4309  if (offloadHostOnly() || !types::isSrcFile(Input.first) ||
4310  !(isa<CompileJobAction>(HostAction) ||
4312  return HostAction;
4313 
4314  ActionList OffloadActions;
4316 
4317  const Action::OffloadKind OffloadKinds[] = {
4319 
4320  for (Action::OffloadKind Kind : OffloadKinds) {
4322  ActionList DeviceActions;
4323 
4324  auto TCRange = C.getOffloadToolChains(Kind);
4325  for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI)
4326  ToolChains.push_back(TI->second);
4327 
4328  if (ToolChains.empty())
4329  continue;
4330 
4331  types::ID InputType = Input.first;
4332  const Arg *InputArg = Input.second;
4333 
4334  // The toolchain can be active for unsupported file types.
4335  if ((Kind == Action::OFK_Cuda && !types::isCuda(InputType)) ||
4336  (Kind == Action::OFK_HIP && !types::isHIP(InputType)))
4337  continue;
4338 
4339  // Get the product of all bound architectures and toolchains.
4341  for (const ToolChain *TC : ToolChains)
4342  for (StringRef Arch : getOffloadArchs(C, Args, Kind, TC))
4343  TCAndArchs.push_back(std::make_pair(TC, Arch));
4344 
4345  for (unsigned I = 0, E = TCAndArchs.size(); I != E; ++I)
4346  DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType));
4347 
4348  if (DeviceActions.empty())
4349  return HostAction;
4350 
4351  auto PL = types::getCompilationPhases(*this, Args, InputType);
4352 
4353  for (phases::ID Phase : PL) {
4354  if (Phase == phases::Link) {
4355  assert(Phase == PL.back() && "linking must be final compilation step.");
4356  break;
4357  }
4358 
4359  auto TCAndArch = TCAndArchs.begin();
4360  for (Action *&A : DeviceActions) {
4361  if (A->getType() == types::TY_Nothing)
4362  continue;
4363 
4364  A = ConstructPhaseAction(C, Args, Phase, A, Kind);
4365 
4366  if (isa<CompileJobAction>(A) && isa<CompileJobAction>(HostAction) &&
4367  Kind == Action::OFK_OpenMP &&
4368  HostAction->getType() != types::TY_Nothing) {
4369  // OpenMP offloading has a dependency on the host compile action to
4370  // identify which declarations need to be emitted. This shouldn't be
4371  // collapsed with any other actions so we can use it in the device.
4374  *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4375  TCAndArch->second.data(), Kind);
4377  DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4378  A = C.MakeAction<OffloadAction>(HDep, DDep);
4379  }
4380  ++TCAndArch;
4381  }
4382  }
4383 
4384  // Compiling HIP in non-RDC mode requires linking each action individually.
4385  for (Action *&A : DeviceActions) {
4386  if ((A->getType() != types::TY_Object &&
4387  A->getType() != types::TY_LTO_BC) ||
4388  Kind != Action::OFK_HIP ||
4389  Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
4390  continue;
4391  ActionList LinkerInput = {A};
4392  A = C.MakeAction<LinkJobAction>(LinkerInput, types::TY_Image);
4393  }
4394 
4395  auto TCAndArch = TCAndArchs.begin();
4396  for (Action *A : DeviceActions) {
4397  DDeps.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4399  DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4400  OffloadActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType()));
4401  ++TCAndArch;
4402  }
4403  }
4404 
4405  if (offloadDeviceOnly())
4406  return C.MakeAction<OffloadAction>(DDeps, types::TY_Nothing);
4407 
4408  if (OffloadActions.empty())
4409  return HostAction;
4410 
4412  if (C.isOffloadingHostKind(Action::OFK_Cuda) &&
4413  !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) {
4414  // If we are not in RDC-mode we just emit the final CUDA fatbinary for
4415  // each translation unit without requiring any linking.
4416  Action *FatbinAction =
4417  C.MakeAction<LinkJobAction>(OffloadActions, types::TY_CUDA_FATBIN);
4418  DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_Cuda>(),
4419  nullptr, Action::OFK_Cuda);
4420  } else if (C.isOffloadingHostKind(Action::OFK_HIP) &&
4421  !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4422  false)) {
4423  // If we are not in RDC-mode we just emit the final HIP fatbinary for each
4424  // translation unit, linking each input individually.
4425  Action *FatbinAction =
4426  C.MakeAction<LinkJobAction>(OffloadActions, types::TY_HIP_FATBIN);
4427  DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_HIP>(),
4428  nullptr, Action::OFK_HIP);
4429  } else {
4430  // Package all the offloading actions into a single output that can be
4431  // embedded in the host and linked.
4432  Action *PackagerAction =
4433  C.MakeAction<OffloadPackagerJobAction>(OffloadActions, types::TY_Image);
4434  DDep.add(*PackagerAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4435  nullptr, C.getActiveOffloadKinds());
4436  }
4437 
4438  // If we are unable to embed a single device output into the host, we need to
4439  // add each device output as a host dependency to ensure they are still built.
4440  bool SingleDeviceOutput = !llvm::any_of(OffloadActions, [](Action *A) {
4441  return A->getType() == types::TY_Nothing;
4442  }) && isa<CompileJobAction>(HostAction);
4444  *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4445  /*BoundArch=*/nullptr, SingleDeviceOutput ? DDep : DDeps);
4446  return C.MakeAction<OffloadAction>(HDep, SingleDeviceOutput ? DDep : DDeps);
4447 }
4448 
4450  Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
4451  Action::OffloadKind TargetDeviceOffloadKind) const {
4452  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
4453 
4454  // Some types skip the assembler phase (e.g., llvm-bc), but we can't
4455  // encode this in the steps because the intermediate type depends on
4456  // arguments. Just special case here.
4457  if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
4458  return Input;
4459 
4460  // Build the appropriate action.
4461  switch (Phase) {
4462  case phases::Link:
4463  llvm_unreachable("link action invalid here.");
4464  case phases::IfsMerge:
4465  llvm_unreachable("ifsmerge action invalid here.");
4466  case phases::Preprocess: {
4467  types::ID OutputTy;
4468  // -M and -MM specify the dependency file name by altering the output type,
4469  // -if -MD and -MMD are not specified.
4470  if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
4471  !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
4472  OutputTy = types::TY_Dependencies;
4473  } else {
4474  OutputTy = Input->getType();
4475  // For these cases, the preprocessor is only translating forms, the Output
4476  // still needs preprocessing.
4477  if (!Args.hasFlag(options::OPT_frewrite_includes,
4478  options::OPT_fno_rewrite_includes, false) &&
4479  !Args.hasFlag(options::OPT_frewrite_imports,
4480  options::OPT_fno_rewrite_imports, false) &&
4481  !Args.hasFlag(options::OPT_fdirectives_only,
4482  options::OPT_fno_directives_only, false) &&
4484  OutputTy = types::getPreprocessedType(OutputTy);
4485  assert(OutputTy != types::TY_INVALID &&
4486  "Cannot preprocess this input type!");
4487  }
4488  return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
4489  }
4490  case phases::Precompile: {
4491  // API extraction should not generate an actual precompilation action.
4492  if (Args.hasArg(options::OPT_extract_api))
4493  return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4494 
4495  types::ID OutputTy = getPrecompiledType(Input->getType());
4496  assert(OutputTy != types::TY_INVALID &&
4497  "Cannot precompile this input type!");
4498 
4499  // If we're given a module name, precompile header file inputs as a
4500  // module, not as a precompiled header.
4501  const char *ModName = nullptr;
4502  if (OutputTy == types::TY_PCH) {
4503  if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
4504  ModName = A->getValue();
4505  if (ModName)
4506  OutputTy = types::TY_ModuleFile;
4507  }
4508 
4509  if (Args.hasArg(options::OPT_fsyntax_only)) {
4510  // Syntax checks should not emit a PCH file
4511  OutputTy = types::TY_Nothing;
4512  }
4513 
4514  return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
4515  }
4516  case phases::Compile: {
4517  if (Args.hasArg(options::OPT_fsyntax_only))
4518  return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
4519  if (Args.hasArg(options::OPT_rewrite_objc))
4520  return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
4521  if (Args.hasArg(options::OPT_rewrite_legacy_objc))
4522  return C.MakeAction<CompileJobAction>(Input,
4523  types::TY_RewrittenLegacyObjC);
4524  if (Args.hasArg(options::OPT__analyze))
4525  return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
4526  if (Args.hasArg(options::OPT__migrate))
4527  return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
4528  if (Args.hasArg(options::OPT_emit_ast))
4529  return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
4530  if (Args.hasArg(options::OPT_module_file_info))
4531  return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
4532  if (Args.hasArg(options::OPT_verify_pch))
4533  return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
4534  if (Args.hasArg(options::OPT_extract_api))
4535  return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4536  return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
4537  }
4538  case phases::Backend: {
4539  if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
4540  types::ID Output =
4541  Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4542  return C.MakeAction<BackendJobAction>(Input, Output);
4543  }
4544  if (isUsingLTO(/* IsOffload */ true) &&
4545  TargetDeviceOffloadKind != Action::OFK_None) {
4546  types::ID Output =
4547  Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4548  return C.MakeAction<BackendJobAction>(Input, Output);
4549  }
4550  if (Args.hasArg(options::OPT_emit_llvm) ||
4551  (TargetDeviceOffloadKind == Action::OFK_HIP &&
4552  Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4553  false))) {
4554  types::ID Output =
4555  Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
4556  return C.MakeAction<BackendJobAction>(Input, Output);
4557  }
4558  return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
4559  }
4560  case phases::Assemble:
4561  return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
4562  }
4563 
4564  llvm_unreachable("invalid phase in ConstructPhaseAction");
4565 }
4566 
4568  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4569 
4570  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4571 
4572  // It is an error to provide a -o option if we are making multiple output
4573  // files. There are exceptions:
4574  //
4575  // IfsMergeJob: when generating interface stubs enabled we want to be able to
4576  // generate the stub file at the same time that we generate the real
4577  // library/a.out. So when a .o, .so, etc are the output, with clang interface
4578  // stubs there will also be a .ifs and .ifso at the same location.
4579  //
4580  // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
4581  // and -c is passed, we still want to be able to generate a .ifs file while
4582  // we are also generating .o files. So we allow more than one output file in
4583  // this case as well.
4584  //
4585  // OffloadClass of type TY_Nothing: device-only output will place many outputs
4586  // into a single offloading action. We should count all inputs to the action
4587  // as outputs. Also ignore device-only outputs if we're compiling with
4588  // -fsyntax-only.
4589  if (FinalOutput) {
4590  unsigned NumOutputs = 0;
4591  unsigned NumIfsOutputs = 0;
4592  for (const Action *A : C.getActions()) {
4593  if (A->getType() != types::TY_Nothing &&
4594  !(A->getKind() == Action::IfsMergeJobClass ||
4595  (A->getType() == clang::driver::types::TY_IFS_CPP &&
4597  0 == NumIfsOutputs++) ||
4598  (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
4599  A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
4600  ++NumOutputs;
4601  else if (A->getKind() == Action::OffloadClass &&
4602  A->getType() == types::TY_Nothing &&
4603  !C.getArgs().hasArg(options::OPT_fsyntax_only))
4604  NumOutputs += A->size();
4605  }
4606 
4607  if (NumOutputs > 1) {
4608  Diag(clang::diag::err_drv_output_argument_with_multiple_files);
4609  FinalOutput = nullptr;
4610  }
4611  }
4612 
4613  const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
4614  if (RawTriple.isOSAIX()) {
4615  if (Arg *A = C.getArgs().getLastArg(options::OPT_G))
4616  Diag(diag::err_drv_unsupported_opt_for_target)
4617  << A->getSpelling() << RawTriple.str();
4618  if (LTOMode == LTOK_Thin)
4619  Diag(diag::err_drv_clang_unsupported) << "thinLTO on AIX";
4620  }
4621 
4622  // Collect the list of architectures.
4623  llvm::StringSet<> ArchNames;
4624  if (RawTriple.isOSBinFormatMachO())
4625  for (const Arg *A : C.getArgs())
4626  if (A->getOption().matches(options::OPT_arch))
4627  ArchNames.insert(A->getValue());
4628 
4629  // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
4630  std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults;
4631  for (Action *A : C.getActions()) {
4632  // If we are linking an image for multiple archs then the linker wants
4633  // -arch_multiple and -final_output <final image name>. Unfortunately, this
4634  // doesn't fit in cleanly because we have to pass this information down.
4635  //
4636  // FIXME: This is a hack; find a cleaner way to integrate this into the
4637  // process.
4638  const char *LinkingOutput = nullptr;
4639  if (isa<LipoJobAction>(A)) {
4640  if (FinalOutput)
4641  LinkingOutput = FinalOutput->getValue();
4642  else
4643  LinkingOutput = getDefaultImageName();
4644  }
4645 
4646  BuildJobsForAction(C, A, &C.getDefaultToolChain(),
4647  /*BoundArch*/ StringRef(),
4648  /*AtTopLevel*/ true,
4649  /*MultipleArchs*/ ArchNames.size() > 1,
4650  /*LinkingOutput*/ LinkingOutput, CachedResults,
4651  /*TargetDeviceOffloadKind*/ Action::OFK_None);
4652  }
4653 
4654  // If we have more than one job, then disable integrated-cc1 for now. Do this
4655  // also when we need to report process execution statistics.
4656  if (C.getJobs().size() > 1 || CCPrintProcessStats)
4657  for (auto &J : C.getJobs())
4658  J.InProcess = false;
4659 
4660  if (CCPrintProcessStats) {
4661  C.setPostCallback([=](const Command &Cmd, int Res) {
4663  Cmd.getProcessStatistics();
4664  if (!ProcStat)
4665  return;
4666 
4667  const char *LinkingOutput = nullptr;
4668  if (FinalOutput)
4669  LinkingOutput = FinalOutput->getValue();
4670  else if (!Cmd.getOutputFilenames().empty())
4671  LinkingOutput = Cmd.getOutputFilenames().front().c_str();
4672  else
4673  LinkingOutput = getDefaultImageName();
4674 
4675  if (CCPrintStatReportFilename.empty()) {
4676  using namespace llvm;
4677  // Human readable output.
4678  outs() << sys::path::filename(Cmd.getExecutable()) << ": "
4679  << "output=" << LinkingOutput;
4680  outs() << ", total="
4681  << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
4682  << ", user="
4683  << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
4684  << ", mem=" << ProcStat->PeakMemory << " Kb\n";
4685  } else {
4686  // CSV format.
4687  std::string Buffer;
4688  llvm::raw_string_ostream Out(Buffer);
4689  llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
4690  /*Quote*/ true);
4691  Out << ',';
4692  llvm::sys::printArg(Out, LinkingOutput, true);
4693  Out << ',' << ProcStat->TotalTime.count() << ','
4694  << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
4695  << '\n';
4696  Out.flush();
4697  std::error_code EC;
4698  llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
4699  llvm::sys::fs::OF_Append |
4700  llvm::sys::fs::OF_Text);
4701  if (EC)
4702  return;
4703  auto L = OS.lock();
4704  if (!L) {
4705  llvm::errs() << "ERROR: Cannot lock file "
4706  << CCPrintStatReportFilename << ": "
4707  << toString(L.takeError()) << "\n";
4708  return;
4709  }
4710  OS << Buffer;
4711  OS.flush();
4712  }
4713  });
4714  }
4715 
4716  // If the user passed -Qunused-arguments or there were errors, don't warn
4717  // about any unused arguments.
4718  if (Diags.hasErrorOccurred() ||
4719  C.getArgs().hasArg(options::OPT_Qunused_arguments))
4720  return;
4721 
4722  // Claim -fdriver-only here.
4723  (void)C.getArgs().hasArg(options::OPT_fdriver_only);
4724  // Claim -### here.
4725  (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4726 
4727  // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4728  (void)C.getArgs().hasArg(options::OPT_driver_mode);
4729  (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4730 
4731  for (Arg *A : C.getArgs()) {
4732  // FIXME: It would be nice to be able to send the argument to the
4733  // DiagnosticsEngine, so that extra values, position, and so on could be
4734  // printed.
4735  if (!A->isClaimed()) {
4736  if (A->getOption().hasFlag(options::NoArgumentUnused))
4737  continue;
4738 
4739  // Suppress the warning automatically if this is just a flag, and it is an
4740  // instance of an argument we already claimed.
4741  const Option &Opt = A->getOption();
4742  if (Opt.getKind() == Option::FlagClass) {
4743  bool DuplicateClaimed = false;
4744 
4745  for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4746  if (AA->isClaimed()) {
4747  DuplicateClaimed = true;
4748  break;
4749  }
4750  }
4751 
4752  if (DuplicateClaimed)
4753  continue;
4754  }
4755 
4756  // In clang-cl, don't mention unknown arguments here since they have
4757  // already been warned about.
4758  if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
4759  Diag(clang::diag::warn_drv_unused_argument)
4760  << A->getAsString(C.getArgs());
4761  }
4762  }
4763 }
4764 
4765 namespace {
4766 /// Utility class to control the collapse of dependent actions and select the
4767 /// tools accordingly.
4768 class ToolSelector final {
4769  /// The tool chain this selector refers to.
4770  const ToolChain &TC;
4771 
4772  /// The compilation this selector refers to.
4773  const Compilation &C;
4774 
4775  /// The base action this selector refers to.
4776  const JobAction *BaseAction;
4777 
4778  /// Set to true if the current toolchain refers to host actions.
4779  bool IsHostSelector;
4780 
4781  /// Set to true if save-temps and embed-bitcode functionalities are active.
4782  bool SaveTemps;
4783  bool EmbedBitcode;
4784 
4785  /// Get previous dependent action or null if that does not exist. If
4786  /// \a CanBeCollapsed is false, that action must be legal to collapse or
4787  /// null will be returned.
4788  const JobAction *getPrevDependentAction(const ActionList &Inputs,
4789  ActionList &SavedOffloadAction,
4790  bool CanBeCollapsed = true) {
4791  // An option can be collapsed only if it has a single input.
4792  if (Inputs.size() != 1)
4793  return nullptr;
4794 
4795  Action *CurAction = *Inputs.begin();
4796  if (CanBeCollapsed &&
4798  return nullptr;
4799 
4800  // If the input action is an offload action. Look through it and save any
4801  // offload action that can be dropped in the event of a collapse.
4802  if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
4803  // If the dependent action is a device action, we will attempt to collapse
4804  // only with other device actions. Otherwise, we would do the same but
4805  // with host actions only.
4806  if (!IsHostSelector) {
4807  if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
4808  CurAction =
4809  OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
4810  if (CanBeCollapsed &&
4812  return nullptr;
4813  SavedOffloadAction.push_back(OA);
4814  return dyn_cast<JobAction>(CurAction);
4815  }
4816  } else if (OA->hasHostDependence()) {
4817  CurAction = OA->getHostDependence();
4818  if (CanBeCollapsed &&
4820  return nullptr;
4821  SavedOffloadAction.push_back(OA);
4822  return dyn_cast<JobAction>(CurAction);
4823  }
4824  return nullptr;
4825  }
4826 
4827  return dyn_cast<JobAction>(CurAction);
4828  }
4829 
4830  /// Return true if an assemble action can be collapsed.
4831  bool canCollapseAssembleAction() const {
4832  return TC.useIntegratedAs() && !SaveTemps &&
4833  !C.getArgs().hasArg(options::OPT_via_file_asm) &&
4834  !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
4835  !C.getArgs().hasArg(options::OPT__SLASH_Fa);
4836  }
4837 
4838  /// Return true if a preprocessor action can be collapsed.
4839  bool canCollapsePreprocessorAction() const {
4840  return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
4841  !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
4842  !C.getArgs().hasArg(options::OPT_rewrite_objc);
4843  }
4844 
4845  /// Struct that relates an action with the offload actions that would be
4846  /// collapsed with it.
4847  struct JobActionInfo final {
4848  /// The action this info refers to.
4849  const JobAction *JA = nullptr;
4850  /// The offload actions we need to take care off if this action is
4851  /// collapsed.
4852  ActionList SavedOffloadAction;
4853  };
4854 
4855  /// Append collapsed offload actions from the give nnumber of elements in the
4856  /// action info array.
4857  static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
4858  ArrayRef<JobActionInfo> &ActionInfo,
4859  unsigned ElementNum) {
4860  assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
4861  for (unsigned I = 0; I < ElementNum; ++I)
4862  CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
4863  ActionInfo[I].SavedOffloadAction.end());
4864  }
4865 
4866  /// Functions that attempt to perform the combining. They detect if that is
4867  /// legal, and if so they update the inputs \a Inputs and the offload action
4868  /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
4869  /// the combined action is returned. If the combining is not legal or if the
4870  /// tool does not exist, null is returned.
4871  /// Currently three kinds of collapsing are supported:
4872  /// - Assemble + Backend + Compile;
4873  /// - Assemble + Backend ;
4874  /// - Backend + Compile.
4875  const Tool *
4876  combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4877  ActionList &Inputs,
4878  ActionList &CollapsedOffloadAction) {
4879  if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
4880  return nullptr;
4881  auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4882  auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4883  auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
4884  if (!AJ || !BJ || !CJ)
4885  return nullptr;
4886 
4887  // Get compiler tool.
4888  const Tool *T = TC.SelectTool(*CJ);
4889  if (!T)
4890  return nullptr;
4891 
4892  // Can't collapse if we don't have codegen support unless we are
4893  // emitting LLVM IR.
4894  bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
4895  if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
4896  return nullptr;
4897 
4898  // When using -fembed-bitcode, it is required to have the same tool (clang)
4899  // for both CompilerJA and BackendJA. Otherwise, combine two stages.
4900  if (EmbedBitcode) {
4901  const Tool *BT = TC.SelectTool(*BJ);
4902  if (BT == T)
4903  return nullptr;
4904  }
4905 
4906  if (!T->hasIntegratedAssembler())
4907  return nullptr;
4908 
4909  Inputs = CJ->getInputs();
4910  AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4911  /*NumElements=*/3);
4912  return T;
4913  }
4914  const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4915  ActionList &Inputs,
4916  ActionList &CollapsedOffloadAction) {
4917  if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4918  return nullptr;
4919  auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4920  auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4921  if (!AJ || !BJ)
4922  return nullptr;
4923 
4924  // Get backend tool.
4925  const Tool *T = TC.SelectTool(*BJ);
4926  if (!T)
4927  return nullptr;
4928 
4929  if (!T->hasIntegratedAssembler())
4930  return nullptr;
4931 
4932  Inputs = BJ->getInputs();
4933  AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4934  /*NumElements=*/2);
4935  return T;
4936  }
4937  const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4938  ActionList &Inputs,
4939  ActionList &CollapsedOffloadAction) {
4940  if (ActionInfo.size() < 2)
4941  return nullptr;
4942  auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4943  auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4944  if (!BJ || !CJ)
4945  return nullptr;
4946 
4947  // Check if the initial input (to the compile job or its predessor if one
4948  // exists) is LLVM bitcode. In that case, no preprocessor step is required
4949  // and we can still collapse the compile and backend jobs when we have
4950  // -save-temps. I.e. there is no need for a separate compile job just to
4951  // emit unoptimized bitcode.
4952  bool InputIsBitcode = true;
4953  for (size_t i = 1; i < ActionInfo.size(); i++)
4954  if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4955  ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4956  InputIsBitcode = false;
4957  break;
4958  }
4959  if (!InputIsBitcode && !canCollapsePreprocessorAction())
4960  return nullptr;
4961 
4962  // Get compiler tool.
4963  const Tool *T = TC.SelectTool(*CJ);
4964  if (!T)
4965  return nullptr;
4966 
4967  // Can't collapse if we don't have codegen support unless we are
4968  // emitting LLVM IR.
4969  bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
4970  if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
4971  return nullptr;
4972 
4973  if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4974  return nullptr;
4975 
4976  Inputs = CJ->getInputs();
4977  AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4978  /*NumElements=*/2);
4979  return T;
4980  }
4981 
4982  /// Updates the inputs if the obtained tool supports combining with
4983  /// preprocessor action, and the current input is indeed a preprocessor
4984  /// action. If combining results in the collapse of offloading actions, those
4985  /// are appended to \a CollapsedOffloadAction.
4986  void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4987  ActionList &CollapsedOffloadAction) {
4988  if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4989  return;
4990 
4991  // Attempt to get a preprocessor action dependence.
4992  ActionList PreprocessJobOffloadActions;
4993  ActionList NewInputs;
4994  for (Action *A : Inputs) {
4995  auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4996  if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4997  NewInputs.push_back(A);
4998  continue;
4999  }
5000 
5001  // This is legal to combine. Append any offload action we found and add the
5002  // current input to preprocessor inputs.
5003  CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
5004  PreprocessJobOffloadActions.end());
5005  NewInputs.append(PJ->input_begin(), PJ->input_end());
5006  }
5007  Inputs = NewInputs;
5008  }
5009 
5010 public:
5011  ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
5012  const Compilation &C, bool SaveTemps, bool EmbedBitcode)
5013  : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
5015  assert(BaseAction && "Invalid base action.");
5016  IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
5017  }
5018 
5019  /// Check if a chain of actions can be combined and return the tool that can
5020  /// handle the combination of actions. The pointer to the current inputs \a
5021  /// Inputs and the list of offload actions \a CollapsedOffloadActions
5022  /// connected to collapsed actions are updated accordingly. The latter enables
5023  /// the caller of the selector to process them afterwards instead of just
5024  /// dropping them. If no suitable tool is found, null will be returned.
5025  const Tool *getTool(ActionList &Inputs,
5026  ActionList &CollapsedOffloadAction) {
5027  //
5028  // Get the largest chain of actions that we could combine.
5029  //
5030 
5031  SmallVector<JobActionInfo, 5> ActionChain(1);
5032  ActionChain.back().JA = BaseAction;
5033  while (ActionChain.back().JA) {
5034  const Action *CurAction = ActionChain.back().JA;
5035 
5036  // Grow the chain by one element.
5037  ActionChain.resize(ActionChain.size() + 1);
5038  JobActionInfo &AI = ActionChain.back();
5039 
5040  // Attempt to fill it with the
5041  AI.JA =
5042  getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
5043  }
5044 
5045  // Pop the last action info as it could not be filled.
5046  ActionChain.pop_back();
5047 
5048  //
5049  // Attempt to combine actions. If all combining attempts failed, just return
5050  // the tool of the provided action. At the end we attempt to combine the
5051  // action with any preprocessor action it may depend on.
5052  //
5053 
5054  const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
5055  CollapsedOffloadAction);
5056  if (!T)
5057  T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
5058  if (!T)
5059  T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
5060  if (!T) {
5061  Inputs = BaseAction->getInputs();
5062  T = TC.SelectTool(*BaseAction);
5063  }
5064 
5065  combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
5066  return T;
5067  }
5068 };
5069 }
5070 
5071 /// Return a string that uniquely identifies the result of a job. The bound arch
5072 /// is not necessarily represented in the toolchain's triple -- for example,
5073 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
5074 /// Also, we need to add the offloading device kind, as the same tool chain can
5075 /// be used for host and device for some programming models, e.g. OpenMP.
5077  StringRef BoundArch,
5078  Action::OffloadKind OffloadKind) {
5079  std::string TriplePlusArch = TC->getTriple().normalize();
5080  if (!BoundArch.empty()) {
5081  TriplePlusArch += "-";
5082  TriplePlusArch += BoundArch;
5083  }
5084  TriplePlusArch += "-";
5085  TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
5086  return TriplePlusArch;
5087 }
5088 
5090  Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5091  bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5092  std::map<std::pair<const Action *, std::string>, InputInfoList>
5093  &CachedResults,
5094  Action::OffloadKind TargetDeviceOffloadKind) const {
5095  std::pair<const Action *, std::string> ActionTC = {
5096  A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5097  auto CachedResult = CachedResults.find(ActionTC);
5098  if (CachedResult != CachedResults.end()) {
5099  return CachedResult->second;
5100  }
5101  InputInfoList Result = BuildJobsForActionNoCache(
5102  C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
5103  CachedResults, TargetDeviceOffloadKind);
5104  CachedResults[ActionTC] = Result;
5105  return Result;
5106 }
5107 
5108 InputInfoList Driver::BuildJobsForActionNoCache(
5109  Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5110  bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5111  std::map<std::pair<const Action *, std::string>, InputInfoList>
5112  &CachedResults,
5113  Action::OffloadKind TargetDeviceOffloadKind) const {
5114  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
5115 
5116  InputInfoList OffloadDependencesInputInfo;
5117  bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
5118  if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
5119  // The 'Darwin' toolchain is initialized only when its arguments are
5120  // computed. Get the default arguments for OFK_None to ensure that
5121  // initialization is performed before processing the offload action.
5122  // FIXME: Remove when darwin's toolchain is initialized during construction.
5123  C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
5124 
5125  // The offload action is expected to be used in four different situations.
5126  //
5127  // a) Set a toolchain/architecture/kind for a host action:
5128  // Host Action 1 -> OffloadAction -> Host Action 2
5129  //
5130  // b) Set a toolchain/architecture/kind for a device action;
5131  // Device Action 1 -> OffloadAction -> Device Action 2
5132  //
5133  // c) Specify a device dependence to a host action;
5134  // Device Action 1 _
5135  // \
5136  // Host Action 1 ---> OffloadAction -> Host Action 2
5137  //
5138  // d) Specify a host dependence to a device action.
5139  // Host Action 1 _
5140  // \
5141  // Device Action 1 ---> OffloadAction -> Device Action 2
5142  //
5143  // For a) and b), we just return the job generated for the dependences. For
5144  // c) and d) we override the current action with the host/device dependence
5145  // if the current toolchain is host/device and set the offload dependences
5146  // info with the jobs obtained from the device/host dependence(s).
5147 
5148  // If there is a single device option or has no host action, just generate
5149  // the job for it.
5150  if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
5151  InputInfoList DevA;
5152  OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
5153  const char *DepBoundArch) {
5154  DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
5155  /*MultipleArchs*/ !!DepBoundArch,
5156  LinkingOutput, CachedResults,
5157  DepA->getOffloadingDeviceKind()));
5158  });
5159  return DevA;
5160  }
5161 
5162  // If 'Action 2' is host, we generate jobs for the device dependences and
5163  // override the current action with the host dependence. Otherwise, we
5164  // generate the host dependences and override the action with the device
5165  // dependence. The dependences can't therefore be a top-level action.
5166  OA->doOnEachDependence(
5167  /*IsHostDependence=*/BuildingForOffloadDevice,
5168  [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5169  OffloadDependencesInputInfo.append(BuildJobsForAction(
5170  C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
5171  /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
5172  DepA->getOffloadingDeviceKind()));
5173  });
5174 
5175  A = BuildingForOffloadDevice
5176  ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
5177  : OA->getHostDependence();
5178 
5179  // We may have already built this action as a part of the offloading
5180  // toolchain, return the cached input if so.
5181  std::pair<const Action *, std::string> ActionTC = {
5182  OA->getHostDependence(),
5183  GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5184  if (CachedResults.find(ActionTC) != CachedResults.end()) {
5185  InputInfoList Inputs = CachedResults[ActionTC];
5186  Inputs.append(OffloadDependencesInputInfo);
5187  return Inputs;
5188  }
5189  }
5190 
5191  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
5192  // FIXME: It would be nice to not claim this here; maybe the old scheme of
5193  // just using Args was better?
5194  const Arg &Input = IA->getInputArg();
5195  Input.claim();
5196  if (Input.getOption().matches(options::OPT_INPUT)) {
5197  const char *Name = Input.getValue();
5198  return {InputInfo(A, Name, /* _BaseInput = */ Name)};
5199  }
5200  return {InputInfo(A, &Input, /* _BaseInput = */ "")};
5201  }
5202 
5203  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
5204  const ToolChain *TC;
5205  StringRef ArchName = BAA->getArchName();
5206 
5207  if (!ArchName.empty())
5208  TC = &getToolChain(C.getArgs(),
5209  computeTargetTriple(*this, TargetTriple,
5210  C.getArgs(), ArchName));
5211  else
5212  TC = &C.getDefaultToolChain();
5213 
5214  return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
5215  MultipleArchs, LinkingOutput, CachedResults,
5216  TargetDeviceOffloadKind);
5217  }
5218 
5219 
5220  ActionList Inputs = A->getInputs();
5221 
5222  const JobAction *JA = cast<JobAction>(A);
5223  ActionList CollapsedOffloadActions;
5224 
5225  ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
5227  const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
5228 
5229  if (!T)
5230  return {InputInfo()};
5231 
5232  if (BuildingForOffloadDevice &&
5234  if (TC->getTriple().isAMDGCN()) {
5235  // AMDGCN treats backend and assemble actions as no-op because
5236  // linker does not support object files.
5237  if (const BackendJobAction *BA = dyn_cast<BackendJobAction>(A)) {
5238  return BuildJobsForAction(C, *BA->input_begin(), TC, BoundArch,
5239  AtTopLevel, MultipleArchs, LinkingOutput,
5240  CachedResults, TargetDeviceOffloadKind);
5241  }
5242 
5243  if (const AssembleJobAction *AA = dyn_cast<AssembleJobAction>(A)) {
5244  return BuildJobsForAction(C, *AA->input_begin(), TC, BoundArch,
5245  AtTopLevel, MultipleArchs, LinkingOutput,
5246  CachedResults, TargetDeviceOffloadKind);
5247  }
5248  }
5249  }
5250 
5251  // If we've collapsed action list that contained OffloadAction we
5252  // need to build jobs for host/device-side inputs it may have held.
5253  for (const auto *OA : CollapsedOffloadActions)
5254  cast<OffloadAction>(OA)->doOnEachDependence(
5255  /*IsHostDependence=*/BuildingForOffloadDevice,
5256  [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5257  OffloadDependencesInputInfo.append(BuildJobsForAction(
5258  C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
5259  /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
5260  DepA->getOffloadingDeviceKind()));
5261  });
5262 
5263  // Only use pipes when there is exactly one input.
5264  InputInfoList InputInfos;
5265  for (const Action *Input : Inputs) {
5266  // Treat dsymutil and verify sub-jobs as being at the top-level too, they
5267  // shouldn't get temporary output names.
5268  // FIXME: Clean this up.
5269  bool SubJobAtTopLevel =
5270  AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
5271  InputInfos.append(BuildJobsForAction(
5272  C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
5273  CachedResults, A->getOffloadingDeviceKind()));
5274  }
5275 
5276  // Always use the first file input as the base input.
5277  const char *BaseInput = InputInfos[0].getBaseInput();
5278  for (auto &Info : InputInfos) {
5279  if (Info.isFilename()) {
5280  BaseInput = Info.getBaseInput();
5281  break;
5282  }
5283  }
5284 
5285  // ... except dsymutil actions, which use their actual input as the base
5286  // input.
5287  if (JA->getType() == types::TY_dSYM)
5288  BaseInput = InputInfos[0].getFilename();
5289 
5290  // Append outputs of offload device jobs to the input list
5291  if (!OffloadDependencesInputInfo.empty())
5292  InputInfos.append(OffloadDependencesInputInfo.begin(),
5293  OffloadDependencesInputInfo.end());
5294 
5295  // Set the effective triple of the toolchain for the duration of this job.
5296  llvm::Triple EffectiveTriple;
5297  const ToolChain &ToolTC = T->getToolChain();
5298  const ArgList &Args =
5299  C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
5300  if (InputInfos.size() != 1) {
5301  EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
5302  } else {
5303  // Pass along the input type if it can be unambiguously determined.
5304  EffectiveTriple = llvm::Triple(
5305  ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
5306  }
5307  RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
5308 
5309  // Determine the place to write output to, if any.
5310  InputInfo Result;
5311  InputInfoList UnbundlingResults;
5312  if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
5313  // If we have an unbundling job, we need to create results for all the
5314  // outputs. We also update the results cache so that other actions using
5315  // this unbundling action can get the right results.
5316  for (auto &UI : UA->getDependentActionsInfo()) {
5317  assert(UI.DependentOffloadKind != Action::OFK_None &&
5318  "Unbundling with no offloading??");
5319 
5320  // Unbundling actions are never at the top level. When we generate the
5321  // offloading prefix, we also do that for the host file because the
5322  // unbundling action does not change the type of the output which can
5323  // cause a overwrite.
5325  UI.DependentOffloadKind,
5326  UI.DependentToolChain->getTriple().normalize(),
5327  /*CreatePrefixForHost=*/true);
5328  auto CurI = InputInfo(
5329  UA,
5330  GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
5331  /*AtTopLevel=*/false,
5332  MultipleArchs ||
5333  UI.DependentOffloadKind == Action::OFK_HIP,
5334  OffloadingPrefix),
5335  BaseInput);
5336  // Save the unbundling result.
5337  UnbundlingResults.push_back(CurI);
5338 
5339  // Get the unique string identifier for this dependence and cache the
5340  // result.
5341  StringRef Arch;
5342  if (TargetDeviceOffloadKind == Action::OFK_HIP) {
5343  if (UI.DependentOffloadKind == Action::OFK_Host)
5344  Arch = StringRef();
5345  else
5346  Arch = UI.DependentBoundArch;
5347  } else
5348  Arch = BoundArch;
5349 
5350  CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
5351  UI.DependentOffloadKind)}] = {
5352  CurI};
5353  }
5354 
5355  // Now that we have all the results generated, select the one that should be
5356  // returned for the current depending action.
5357  std::pair<const Action *, std::string> ActionTC = {
5358  A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5359  assert(CachedResults.find(ActionTC) != CachedResults.end() &&
5360  "Result does not exist??");
5361  Result = CachedResults[ActionTC].front();
5362  } else if (JA->getType() == types::TY_Nothing)
5363  Result = {InputInfo(A, BaseInput)};
5364  else {
5365  // We only have to generate a prefix for the host if this is not a top-level
5366  // action.
5368  A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
5369  /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) ||
5371  AtTopLevel));
5372  Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
5373  AtTopLevel, MultipleArchs,
5374  OffloadingPrefix),
5375  BaseInput);
5376  }
5377 
5379  llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
5380  << " - \"" << T->getName() << "\", inputs: [";
5381  for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
5382  llvm::errs() << InputInfos[i].getAsString();
5383  if (i + 1 != e)
5384  llvm::errs() << ", ";
5385  }
5386  if (UnbundlingResults.empty())
5387  llvm::errs() << "], output: " << Result.getAsString() << "\n";
5388  else {
5389  llvm::errs() << "], outputs: [";
5390  for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
5391  llvm::errs() << UnbundlingResults[i].getAsString();
5392  if (i + 1 != e)
5393  llvm::errs() << ", ";
5394  }
5395  llvm::errs() << "] \n";
5396  }
5397  } else {
5398  if (UnbundlingResults.empty())
5399  T->ConstructJob(
5400  C, *JA, Result, InputInfos,
5401  C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5402  LinkingOutput);
5403  else
5405  C, *JA, UnbundlingResults, InputInfos,
5406  C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5407  LinkingOutput);
5408  }
5409  return {Result};
5410 }
5411 
5412 const char *Driver::getDefaultImageName() const {
5413  llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
5414  return Target.isOSWindows() ? "a.exe" : "a.out";
5415 }
5416 
5417 /// Create output filename based on ArgValue, which could either be a
5418 /// full filename, filename without extension, or a directory. If ArgValue
5419 /// does not provide a filename, then use BaseName, and use the extension
5420 /// suitable for FileType.
5421 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
5422  StringRef BaseName,
5423  types::ID FileType) {
5424  SmallString<128> Filename = ArgValue;
5425 
5426  if (ArgValue.empty()) {
5427  // If the argument is empty, output to BaseName in the current dir.
5428  Filename = BaseName;
5429  } else if (llvm::sys::path::is_separator(Filename.back())) {
5430  // If the argument is a directory, output to BaseName in that dir.
5431  llvm::sys::path::append(Filename, BaseName);
5432  }
5433 
5434  if (!llvm::sys::path::has_extension(ArgValue)) {
5435  // If the argument didn't provide an extension, then set it.
5436  const char *Extension = types::getTypeTempSuffix(FileType, true);
5437 
5438  if (FileType == types::TY_Image &&
5439  Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
5440  // The output file is a dll.
5441  Extension = "dll";
5442  }
5443 
5444  llvm::sys::path::replace_extension(Filename, Extension);
5445  }
5446 
5447  return Args.MakeArgString(Filename.c_str());
5448 }
5449 
5450 static bool HasPreprocessOutput(const Action &JA) {
5451  if (isa<PreprocessJobAction>(JA))
5452  return true;
5453  if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0]))
5454  return true;
5455  if (isa<OffloadBundlingJobAction>(JA) &&
5456  HasPreprocessOutput(*(JA.getInputs()[0])))
5457  return true;
5458  return false;
5459 }
5460 
5461 const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix,
5462  StringRef Suffix, bool MultipleArchs,
5463  StringRef BoundArch) const {
5464  SmallString<128> TmpName;
5465  Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
5466  Optional<std::string> CrashDirectory =
5467  CCGenDiagnostics && A
5468  ? std::string(A->getValue())
5469  : llvm::sys::Process::GetEnv("CLANG_CRASH_DIAGNOSTICS_DIR");
5470  if (CrashDirectory) {
5471  if (!getVFS().exists(*CrashDirectory))
5472  llvm::sys::fs::create_directories(*CrashDirectory);
5473  SmallString<128> Path(*CrashDirectory);
5474  llvm::sys::path::append(Path, Prefix);
5475  const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%";
5476  if (std::error_code EC =
5477  llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) {
5478  Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5479  return "";
5480  }
5481  } else {
5482  if (MultipleArchs && !BoundArch.empty()) {
5483  TmpName = GetTemporaryDirectory(Prefix);
5484  llvm::sys::path::append(TmpName,
5485  Twine(Prefix) + "-" + BoundArch + "." + Suffix);
5486  } else {
5487  TmpName = GetTemporaryPath(Prefix, Suffix);
5488  }
5489  }
5490  return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5491 }
5492 
5494  const char *BaseInput,
5495  StringRef OrigBoundArch, bool AtTopLevel,
5496  bool MultipleArchs,
5497  StringRef OffloadingPrefix) const {
5498  std::string BoundArch = OrigBoundArch.str();
5499  if (is_style_windows(llvm::sys::path::Style::native)) {
5500  // BoundArch may contains ':', which is invalid in file names on Windows,
5501  // therefore replace it with '%'.
5502  std::replace(BoundArch.begin(), BoundArch.end(), ':', '@');
5503  }
5504 
5505  llvm::PrettyStackTraceString CrashInfo("Computing output path");
5506  // Output to a user requested destination?
5507  if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
5508  if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
5509  return C.addResultFile(FinalOutput->getValue(), &JA);
5510  }
5511 
5512  // For /P, preprocess to file named after BaseInput.
5513  if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
5514  assert(AtTopLevel && isa<PreprocessJobAction>(JA));
5515  StringRef BaseName = llvm::sys::path::filename(BaseInput);
5516  StringRef NameArg;
5517  if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
5518  NameArg = A->getValue();
5519  return C.addResultFile(
5520  MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
5521  &JA);
5522  }
5523 
5524  // Default to writing to stdout?
5525  if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
5526  return "-";
5527  }
5528 
5529  if (JA.getType() == types::TY_ModuleFile &&
5530  C.getArgs().getLastArg(options::OPT_module_file_info)) {
5531  return "-";
5532  }
5533 
5534  if (IsDXCMode() && !C.getArgs().hasArg(options::OPT_o))
5535  return "-";
5536 
5537  // Is this the assembly listing for /FA?
5538  if (JA.getType() == types::TY_PP_Asm &&
5539  (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
5540  C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
5541  // Use /Fa and the input filename to determine the asm file name.
5542  StringRef BaseName = llvm::sys::path::filename(BaseInput);
5543  StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
5544  return C.addResultFile(
5545  MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
5546  &JA);
5547  }
5548 
5549  // Output to a temporary file?
5550  if ((!AtTopLevel && !isSaveTempsEnabled() &&
5551  !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
5552  CCGenDiagnostics) {
5553  StringRef Name = llvm::sys::path::filename(BaseInput);
5554  std::pair<StringRef, StringRef> Split = Name.split('.');
5555  const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
5556  return CreateTempFile(C, Split.first, Suffix, MultipleArchs, BoundArch);
5557  }
5558 
5559  SmallString<128> BasePath(BaseInput);
5560  SmallString<128> ExternalPath("");
5561  StringRef BaseName;
5562 
5563  // Dsymutil actions should use the full path.
5564  if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) {
5565  ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
5566  // We use posix style here because the tests (specifically
5567  // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
5568  // even on Windows and if we don't then the similar test covering this
5569  // fails.
5570  llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
5571  llvm::sys::path::filename(BasePath));
5572  BaseName = ExternalPath;
5573  } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
5574  BaseName = BasePath;
5575  else
5576  BaseName = llvm::sys::path::filename(BasePath);
5577 
5578  // Determine what the derived output name should be.
5579  const char *NamedOutput;
5580 
5581  if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
5582  C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
5583  // The /Fo or /o flag decides the object filename.
5584  StringRef Val =
5585  C.getArgs()
5586  .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
5587  ->getValue();
5588  NamedOutput =
5589  MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5590  } else if (JA.getType() == types::TY_Image &&
5591  C.getArgs().hasArg(options::OPT__SLASH_Fe,
5592  options::OPT__SLASH_o)) {
5593  // The /Fe or /o flag names the linked file.
5594  StringRef Val =
5595  C.getArgs()
5596  .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
5597  ->getValue();
5598  NamedOutput =
5599  MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
5600  } else if (JA.getType() == types::TY_Image) {
5601  if (IsCLMode()) {
5602  // clang-cl uses BaseName for the executable name.
5603  NamedOutput =
5604  MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
5605  } else {
5607  // HIP image for device compilation with -fno-gpu-rdc is per compilation
5608  // unit.
5609  bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5610  !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
5611  options::OPT_fno_gpu_rdc, false);
5612  bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(JA);
5613  if (UseOutExtension) {
5614  Output = BaseName;
5615  llvm::sys::path::replace_extension(Output, "");
5616  }
5617  Output += OffloadingPrefix;
5618  if (MultipleArchs && !BoundArch.empty()) {
5619  Output += "-";
5620  Output.append(BoundArch);
5621  }
5622  if (UseOutExtension)
5623  Output += ".out";
5624  NamedOutput = C.getArgs().MakeArgString(Output.c_str());
5625  }
5626  } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
5627  NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
5628  } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) &&
5629  C.getArgs().hasArg(options::OPT__SLASH_o)) {
5630  StringRef Val =
5631  C.getArgs()
5632  .getLastArg(options::OPT__SLASH_o)
5633  ->getValue();
5634  NamedOutput =
5635  MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5636  } else {
5637  const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
5638  assert(Suffix && "All types used for output should have a suffix.");
5639 
5640  std::string::size_type End = std::string::npos;
5642  End = BaseName.rfind('.');
5643  SmallString<128> Suffixed(BaseName.substr(0, End));
5644  Suffixed += OffloadingPrefix;
5645  if (MultipleArchs && !BoundArch.empty()) {
5646  Suffixed += "-";
5647  Suffixed.append(BoundArch);
5648  }
5649  // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
5650  // the unoptimized bitcode so that it does not get overwritten by the ".bc"
5651  // optimized bitcode output.
5652  auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
5653  const llvm::opt::DerivedArgList &Args) {
5654  // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
5655  // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
5656  // phase.)
5657  return isa<CompileJobAction>(JA) &&
5659  Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5660  false);
5661  };
5662  if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
5663  (C.getArgs().hasArg(options::OPT_emit_llvm) ||
5664  IsHIPRDCInCompilePhase(JA, C.getArgs())))
5665  Suffixed += ".tmp";
5666  Suffixed += '.';
5667  Suffixed += Suffix;
5668  NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
5669  }
5670 
5671  // Prepend object file path if -save-temps=obj
5672  if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
5673  JA.getType() != types::TY_PCH) {
5674  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
5675  SmallString<128> TempPath(FinalOutput->getValue());
5676  llvm::sys::path::remove_filename(TempPath);
5677  StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
5678  llvm::sys::path::append(TempPath, OutputFileName);
5679  NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
5680  }
5681 
5682  // If we're saving temps and the temp file conflicts with the input file,
5683  // then avoid overwriting input file.
5684  if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
5685  bool SameFile = false;
5686  SmallString<256> Result;
5687  llvm::sys::fs::current_path(Result);
5688  llvm::sys::path::append(Result, BaseName);
5689  llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
5690  // Must share the same path to conflict.
5691  if (SameFile) {
5692  StringRef Name = llvm::sys::path::filename(BaseInput);
5693  std::pair<StringRef, StringRef> Split = Name.split('.');
5694  std::string TmpName = GetTemporaryPath(
5695  Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
5696  return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5697  }
5698  }
5699 
5700  // As an annoying special case, PCH generation doesn't strip the pathname.
5701  if (JA.getType() == types::TY_PCH && !IsCLMode()) {
5702  llvm::sys::path::remove_filename(BasePath);
5703  if (BasePath.empty())
5704  BasePath = NamedOutput;
5705  else
5706  llvm::sys::path::append(BasePath, NamedOutput);
5707  return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
5708  } else {
5709  return C.addResultFile(NamedOutput, &JA);
5710  }
5711 }
5712 
5713 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
5714  // Search for Name in a list of paths.
5715  auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
5717  // Respect a limited subset of the '-Bprefix' functionality in GCC by
5718  // attempting to use this prefix when looking for file paths.
5719  for (const auto &Dir : P) {
5720  if (Dir.empty())
5721  continue;
5722  SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
5723  llvm::sys::path::append(P, Name);
5724  if (llvm::sys::fs::exists(Twine(P)))
5725  return std::string(P);
5726  }
5727  return None;
5728  };
5729 
5730  if (auto P = SearchPaths(PrefixDirs))
5731  return *P;
5732 
5734  llvm::sys::path::append(R, Name);
5735  if (llvm::sys::fs::exists(Twine(R)))
5736  return std::string(R.str());
5737 
5739  llvm::sys::path::append(P, Name);
5740  if (llvm::sys::fs::exists(Twine(P)))
5741  return std::string(P.str());
5742 
5743  SmallString<128> D(Dir);
5744  llvm::sys::path::append(D, "..", Name);
5745  if (llvm::sys::fs::exists(Twine(D)))
5746  return std::string(D.str());
5747 
5748  if (auto P = SearchPaths(TC.getLibraryPaths()))
5749  return *P;
5750 
5751  if (auto P = SearchPaths(TC.getFilePaths()))
5752  return *P;
5753 
5754  return std::string(Name);
5755 }
5756 
5757 void Driver::generatePrefixedToolNames(
5758  StringRef Tool, const ToolChain &TC,
5759  SmallVectorImpl<std::string> &Names) const {
5760  // FIXME: Needs a better variable than TargetTriple
5761  Names.emplace_back((TargetTriple + "-" + Tool).str());
5762  Names.emplace_back(Tool);
5763 }
5764 
5765 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
5766  llvm::sys::path::append(Dir, Name);
5767  if (llvm::sys::fs::can_execute(Twine(Dir)))
5768  return true;
5769  llvm::sys::path::remove_filename(Dir);
5770  return false;
5771 }
5772 
5773 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
5774  SmallVector<std::string, 2> TargetSpecificExecutables;
5775  generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
5776 
5777  // Respect a limited subset of the '-Bprefix' functionality in GCC by
5778  // attempting to use this prefix when looking for program paths.
5779  for (const auto &PrefixDir : PrefixDirs) {
5780  if (llvm::sys::fs::is_directory(PrefixDir)) {
5781  SmallString<128> P(PrefixDir);
5782  if (ScanDirForExecutable(P, Name))
5783  return std::string(P.str());
5784  } else {
5785  SmallString<128> P((PrefixDir + Name).str());
5786  if (llvm::sys::fs::can_execute(Twine(P)))
5787  return std::string(P.str());
5788  }
5789  }
5790 
5791  const ToolChain::path_list &List = TC.getProgramPaths();
5792  for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
5793  // For each possible name of the tool look for it in
5794  // program paths first, then the path.
5795  // Higher priority names will be first, meaning that
5796  // a higher priority name in the path will be found
5797  // instead of a lower priority name in the program path.
5798  // E.g. <triple>-gcc on the path will be found instead
5799  // of gcc in the program path
5800  for (const auto &Path : List) {
5801  SmallString<128> P(Path);
5802  if (ScanDirForExecutable(P, TargetSpecificExecutable))
5803  return std::string(P.str());
5804  }
5805 
5806  // Fall back to the path
5807  if (llvm::ErrorOr<std::string> P =
5808  llvm::sys::findProgramByName(TargetSpecificExecutable))
5809  return *P;
5810  }
5811 
5812  return std::string(Name);
5813 }
5814 
5815 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
5816  SmallString<128> Path;
5817  std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
5818  if (EC) {
5819  Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5820  return "";
5821  }
5822 
5823  return std::string(Path.str());
5824 }
5825 
5827  SmallString<128> Path;
5828  std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
5829  if (EC) {
5830  Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5831  return "";
5832  }
5833 
5834  return std::string(Path.str());
5835 }
5836 
5837 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
5838  SmallString<128> Output;
5839  if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
5840  // FIXME: If anybody needs it, implement this obscure rule:
5841  // "If you specify a directory without a file name, the default file name
5842  // is VCx0.pch., where x is the major version of Visual C++ in use."
5843  Output = FpArg->getValue();
5844 
5845  // "If you do not specify an extension as part of the path name, an
5846  // extension of .pch is assumed. "
5847  if (!llvm::sys::path::has_extension(Output))
5848  Output += ".pch";
5849  } else {
5850  if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
5851  Output = YcArg->getValue();
5852  if (Output.empty())
5853  Output = BaseName;
5854  llvm::sys::path::replace_extension(Output, ".pch");
5855  }
5856  return std::string(Output.str());
5857 }
5858 
5859 const ToolChain &Driver::getToolChain(const ArgList &Args,
5860  const llvm::Triple &Target) const {
5861 
5862  auto &TC = ToolChains[Target.str()];
5863  if (!TC) {
5864  switch (Target.getOS()) {
5865  case llvm::Triple::AIX:
5866  TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
5867  break;
5868  case llvm::Triple::Haiku:
5869  TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
5870  break;
5871  case llvm::Triple::Ananas:
5872  TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
5873  break;
5874  case llvm::Triple::CloudABI:
5875  TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
5876  break;
5877  case llvm::Triple::Darwin:
5878  case llvm::Triple::MacOSX:
5879  case llvm::Triple::IOS:
5880  case llvm::Triple::TvOS:
5881  case llvm::Triple::WatchOS:
5882  case llvm::Triple::DriverKit:
5883  TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
5884  break;
5885  case llvm::Triple::DragonFly:
5886  TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
5887  break;
5888  case llvm::Triple::OpenBSD:
5889  TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
5890  break;
5891  case llvm::Triple::NetBSD:
5892  TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
5893  break;
5894  case llvm::Triple::FreeBSD:
5895  if (Target.isPPC())
5896  TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target,
5897  Args);
5898  else
5899  TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
5900  break;
5901  case llvm::Triple::Minix:
5902  TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
5903  break;
5904  case llvm::Triple::Linux:
5905  case llvm::Triple::ELFIAMCU:
5906  if (Target.getArch() == llvm::Triple::hexagon)
5907  TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5908  Args);
5909  else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
5910  !Target.hasEnvironment())
5911  TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
5912  Args);
5913  else if (Target.isPPC())
5914  TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
5915  Args);
5916  else if (Target.getArch() == llvm::Triple::ve)
5917  TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5918 
5919  else
5920  TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
5921  break;
5922  case llvm::Triple::NaCl:
5923  TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
5924  break;
5925  case llvm::Triple::Fuchsia:
5926  TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
5927  break;
5928  case llvm::Triple::Solaris:
5929  TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
5930  break;
5931  case llvm::Triple::AMDHSA:
5932  TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
5933  break;
5934  case llvm::Triple::AMDPAL:
5935  case llvm::Triple::Mesa3D:
5936  TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
5937  break;
5938  case llvm::Triple::Win32:
5939  switch (Target.getEnvironment()) {
5940  default:
5941  if (Target.isOSBinFormatELF())
5942  TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5943  else if (Target.isOSBinFormatMachO())
5944  TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5945  else
5946  TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5947  break;
5948  case llvm::Triple::GNU:
5949  TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
5950  break;
5951  case llvm::Triple::Itanium:
5952  TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
5953  Args);
5954  break;
5955  case llvm::Triple::MSVC:
5956  case llvm::Triple::UnknownEnvironment:
5957  if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
5958  .startswith_insensitive("bfd"))
5959  TC = std::make_unique<toolchains::CrossWindowsToolChain>(
5960  *this, Target, Args);
5961  else
5962  TC =
5963  std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
5964  break;
5965  }
5966  break;