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