clang  3.8.0
Tools.cpp
Go to the documentation of this file.
1 //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
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 "Tools.h"
11 #include "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
20 #include "clang/Driver/Driver.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
25 #include "clang/Driver/ToolChain.h"
26 #include "clang/Driver/Util.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/TargetParser.h"
45 
46 #ifdef LLVM_ON_UNIX
47 #include <unistd.h> // For getuid().
48 #endif
49 
50 using namespace clang::driver;
51 using namespace clang::driver::tools;
52 using namespace clang;
53 using namespace llvm::opt;
54 
55 static void handleTargetFeaturesGroup(const ArgList &Args,
56  std::vector<const char *> &Features,
57  OptSpecifier Group) {
58  for (const Arg *A : Args.filtered(Group)) {
59  StringRef Name = A->getOption().getName();
60  A->claim();
61 
62  // Skip over "-m".
63  assert(Name.startswith("m") && "Invalid feature name.");
64  Name = Name.substr(1);
65 
66  bool IsNegative = Name.startswith("no-");
67  if (IsNegative)
68  Name = Name.substr(3);
69  Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
70  }
71 }
72 
73 static const char *getSparcAsmModeForCPU(StringRef Name,
74  const llvm::Triple &Triple) {
75  if (Triple.getArch() == llvm::Triple::sparcv9) {
76  return llvm::StringSwitch<const char *>(Name)
77  .Case("niagara", "-Av9b")
78  .Case("niagara2", "-Av9b")
79  .Case("niagara3", "-Av9d")
80  .Case("niagara4", "-Av9d")
81  .Default("-Av9");
82  } else {
83  return llvm::StringSwitch<const char *>(Name)
84  .Case("v8", "-Av8")
85  .Case("supersparc", "-Av8")
86  .Case("sparclite", "-Asparclite")
87  .Case("f934", "-Asparclite")
88  .Case("hypersparc", "-Av8")
89  .Case("sparclite86x", "-Asparclite")
90  .Case("sparclet", "-Asparclet")
91  .Case("tsc701", "-Asparclet")
92  .Case("v9", "-Av8plus")
93  .Case("ultrasparc", "-Av8plus")
94  .Case("ultrasparc3", "-Av8plus")
95  .Case("niagara", "-Av8plusb")
96  .Case("niagara2", "-Av8plusb")
97  .Case("niagara3", "-Av8plusd")
98  .Case("niagara4", "-Av8plusd")
99  .Default("-Av8");
100  }
101 }
102 
103 /// CheckPreprocessingOptions - Perform some validation of preprocessing
104 /// arguments that is shared with gcc.
105 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
106  if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
107  if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
108  !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
109  D.Diag(diag::err_drv_argument_only_allowed_with)
110  << A->getBaseArg().getAsString(Args)
111  << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
112  }
113  }
114 }
115 
116 /// CheckCodeGenerationOptions - Perform some validation of code generation
117 /// arguments that is shared with gcc.
118 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
119  // In gcc, only ARM checks this, but it seems reasonable to check universally.
120  if (Args.hasArg(options::OPT_static))
121  if (const Arg *A =
122  Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
123  D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
124  << "-static";
125 }
126 
127 // Add backslashes to escape spaces and other backslashes.
128 // This is used for the space-separated argument list specified with
129 // the -dwarf-debug-flags option.
130 static void EscapeSpacesAndBackslashes(const char *Arg,
131  SmallVectorImpl<char> &Res) {
132  for (; *Arg; ++Arg) {
133  switch (*Arg) {
134  default:
135  break;
136  case ' ':
137  case '\\':
138  Res.push_back('\\');
139  break;
140  }
141  Res.push_back(*Arg);
142  }
143 }
144 
145 // Quote target names for inclusion in GNU Make dependency files.
146 // Only the characters '$', '#', ' ', '\t' are quoted.
147 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
148  for (unsigned i = 0, e = Target.size(); i != e; ++i) {
149  switch (Target[i]) {
150  case ' ':
151  case '\t':
152  // Escape the preceding backslashes
153  for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
154  Res.push_back('\\');
155 
156  // Escape the space/tab
157  Res.push_back('\\');
158  break;
159  case '$':
160  Res.push_back('$');
161  break;
162  case '#':
163  Res.push_back('\\');
164  break;
165  default:
166  break;
167  }
168 
169  Res.push_back(Target[i]);
170  }
171 }
172 
173 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
174  const char *ArgName, const char *EnvVar) {
175  const char *DirList = ::getenv(EnvVar);
176  bool CombinedArg = false;
177 
178  if (!DirList)
179  return; // Nothing to do.
180 
181  StringRef Name(ArgName);
182  if (Name.equals("-I") || Name.equals("-L"))
183  CombinedArg = true;
184 
185  StringRef Dirs(DirList);
186  if (Dirs.empty()) // Empty string should not add '.'.
187  return;
188 
189  StringRef::size_type Delim;
190  while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
191  if (Delim == 0) { // Leading colon.
192  if (CombinedArg) {
193  CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
194  } else {
195  CmdArgs.push_back(ArgName);
196  CmdArgs.push_back(".");
197  }
198  } else {
199  if (CombinedArg) {
200  CmdArgs.push_back(
201  Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
202  } else {
203  CmdArgs.push_back(ArgName);
204  CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
205  }
206  }
207  Dirs = Dirs.substr(Delim + 1);
208  }
209 
210  if (Dirs.empty()) { // Trailing colon.
211  if (CombinedArg) {
212  CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
213  } else {
214  CmdArgs.push_back(ArgName);
215  CmdArgs.push_back(".");
216  }
217  } else { // Add the last path.
218  if (CombinedArg) {
219  CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
220  } else {
221  CmdArgs.push_back(ArgName);
222  CmdArgs.push_back(Args.MakeArgString(Dirs));
223  }
224  }
225 }
226 
227 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
228  const ArgList &Args, ArgStringList &CmdArgs) {
229  const Driver &D = TC.getDriver();
230 
231  // Add extra linker input arguments which are not treated as inputs
232  // (constructed via -Xarch_).
233  Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
234 
235  for (const auto &II : Inputs) {
236  if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
237  // Don't try to pass LLVM inputs unless we have native support.
238  D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
239 
240  // Add filenames immediately.
241  if (II.isFilename()) {
242  CmdArgs.push_back(II.getFilename());
243  continue;
244  }
245 
246  // Otherwise, this is a linker input argument.
247  const Arg &A = II.getInputArg();
248 
249  // Handle reserved library options.
250  if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
251  TC.AddCXXStdlibLibArgs(Args, CmdArgs);
252  else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
253  TC.AddCCKextLibArgs(Args, CmdArgs);
254  else if (A.getOption().matches(options::OPT_z)) {
255  // Pass -z prefix for gcc linker compatibility.
256  A.claim();
257  A.render(Args, CmdArgs);
258  } else {
259  A.renderAsInput(Args, CmdArgs);
260  }
261  }
262 
263  // LIBRARY_PATH - included following the user specified library paths.
264  // and only supported on native toolchains.
265  if (!TC.isCrossCompiling())
266  addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
267 }
268 
269 /// \brief Determine whether Objective-C automated reference counting is
270 /// enabled.
271 static bool isObjCAutoRefCount(const ArgList &Args) {
272  return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
273 }
274 
275 /// \brief Determine whether we are linking the ObjC runtime.
276 static bool isObjCRuntimeLinked(const ArgList &Args) {
277  if (isObjCAutoRefCount(Args)) {
278  Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
279  return true;
280  }
281  return Args.hasArg(options::OPT_fobjc_link_runtime);
282 }
283 
284 static bool forwardToGCC(const Option &O) {
285  // Don't forward inputs from the original command line. They are added from
286  // InputInfoList.
287  return O.getKind() != Option::InputClass &&
288  !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
289 }
290 
291 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
292  const Driver &D, const ArgList &Args,
293  ArgStringList &CmdArgs,
294  const InputInfo &Output,
295  const InputInfoList &Inputs,
296  const ToolChain *AuxToolChain) const {
297  Arg *A;
298 
299  CheckPreprocessingOptions(D, Args);
300 
301  Args.AddLastArg(CmdArgs, options::OPT_C);
302  Args.AddLastArg(CmdArgs, options::OPT_CC);
303 
304  // Handle dependency file generation.
305  if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
306  (A = Args.getLastArg(options::OPT_MD)) ||
307  (A = Args.getLastArg(options::OPT_MMD))) {
308  // Determine the output location.
309  const char *DepFile;
310  if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
311  DepFile = MF->getValue();
312  C.addFailureResultFile(DepFile, &JA);
313  } else if (Output.getType() == types::TY_Dependencies) {
314  DepFile = Output.getFilename();
315  } else if (A->getOption().matches(options::OPT_M) ||
316  A->getOption().matches(options::OPT_MM)) {
317  DepFile = "-";
318  } else {
319  DepFile = getDependencyFileName(Args, Inputs);
320  C.addFailureResultFile(DepFile, &JA);
321  }
322  CmdArgs.push_back("-dependency-file");
323  CmdArgs.push_back(DepFile);
324 
325  // Add a default target if one wasn't specified.
326  if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
327  const char *DepTarget;
328 
329  // If user provided -o, that is the dependency target, except
330  // when we are only generating a dependency file.
331  Arg *OutputOpt = Args.getLastArg(options::OPT_o);
332  if (OutputOpt && Output.getType() != types::TY_Dependencies) {
333  DepTarget = OutputOpt->getValue();
334  } else {
335  // Otherwise derive from the base input.
336  //
337  // FIXME: This should use the computed output file location.
338  SmallString<128> P(Inputs[0].getBaseInput());
339  llvm::sys::path::replace_extension(P, "o");
340  DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
341  }
342 
343  CmdArgs.push_back("-MT");
345  QuoteTarget(DepTarget, Quoted);
346  CmdArgs.push_back(Args.MakeArgString(Quoted));
347  }
348 
349  if (A->getOption().matches(options::OPT_M) ||
350  A->getOption().matches(options::OPT_MD))
351  CmdArgs.push_back("-sys-header-deps");
352  if ((isa<PrecompileJobAction>(JA) &&
353  !Args.hasArg(options::OPT_fno_module_file_deps)) ||
354  Args.hasArg(options::OPT_fmodule_file_deps))
355  CmdArgs.push_back("-module-file-deps");
356  }
357 
358  if (Args.hasArg(options::OPT_MG)) {
359  if (!A || A->getOption().matches(options::OPT_MD) ||
360  A->getOption().matches(options::OPT_MMD))
361  D.Diag(diag::err_drv_mg_requires_m_or_mm);
362  CmdArgs.push_back("-MG");
363  }
364 
365  Args.AddLastArg(CmdArgs, options::OPT_MP);
366  Args.AddLastArg(CmdArgs, options::OPT_MV);
367 
368  // Convert all -MQ <target> args to -MT <quoted target>
369  for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
370  A->claim();
371 
372  if (A->getOption().matches(options::OPT_MQ)) {
373  CmdArgs.push_back("-MT");
375  QuoteTarget(A->getValue(), Quoted);
376  CmdArgs.push_back(Args.MakeArgString(Quoted));
377 
378  // -MT flag - no change
379  } else {
380  A->render(Args, CmdArgs);
381  }
382  }
383 
384  // Add -i* options, and automatically translate to
385  // -include-pch/-include-pth for transparent PCH support. It's
386  // wonky, but we include looking for .gch so we can support seamless
387  // replacement into a build system already set up to be generating
388  // .gch files.
389  bool RenderedImplicitInclude = false;
390  for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
391  if (A->getOption().matches(options::OPT_include)) {
392  bool IsFirstImplicitInclude = !RenderedImplicitInclude;
393  RenderedImplicitInclude = true;
394 
395  // Use PCH if the user requested it.
396  bool UsePCH = D.CCCUsePCH;
397 
398  bool FoundPTH = false;
399  bool FoundPCH = false;
400  SmallString<128> P(A->getValue());
401  // We want the files to have a name like foo.h.pch. Add a dummy extension
402  // so that replace_extension does the right thing.
403  P += ".dummy";
404  if (UsePCH) {
405  llvm::sys::path::replace_extension(P, "pch");
406  if (llvm::sys::fs::exists(P))
407  FoundPCH = true;
408  }
409 
410  if (!FoundPCH) {
411  llvm::sys::path::replace_extension(P, "pth");
412  if (llvm::sys::fs::exists(P))
413  FoundPTH = true;
414  }
415 
416  if (!FoundPCH && !FoundPTH) {
417  llvm::sys::path::replace_extension(P, "gch");
418  if (llvm::sys::fs::exists(P)) {
419  FoundPCH = UsePCH;
420  FoundPTH = !UsePCH;
421  }
422  }
423 
424  if (FoundPCH || FoundPTH) {
425  if (IsFirstImplicitInclude) {
426  A->claim();
427  if (UsePCH)
428  CmdArgs.push_back("-include-pch");
429  else
430  CmdArgs.push_back("-include-pth");
431  CmdArgs.push_back(Args.MakeArgString(P));
432  continue;
433  } else {
434  // Ignore the PCH if not first on command line and emit warning.
435  D.Diag(diag::warn_drv_pch_not_first_include) << P
436  << A->getAsString(Args);
437  }
438  }
439  }
440 
441  // Not translated, render as usual.
442  A->claim();
443  A->render(Args, CmdArgs);
444  }
445 
446  Args.AddAllArgs(CmdArgs,
447  {options::OPT_D, options::OPT_U, options::OPT_I_Group,
448  options::OPT_F, options::OPT_index_header_map});
449 
450  // Add -Wp, and -Xpreprocessor if using the preprocessor.
451 
452  // FIXME: There is a very unfortunate problem here, some troubled
453  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
454  // really support that we would have to parse and then translate
455  // those options. :(
456  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
457  options::OPT_Xpreprocessor);
458 
459  // -I- is a deprecated GCC feature, reject it.
460  if (Arg *A = Args.getLastArg(options::OPT_I_))
461  D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
462 
463  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
464  // -isysroot to the CC1 invocation.
465  StringRef sysroot = C.getSysRoot();
466  if (sysroot != "") {
467  if (!Args.hasArg(options::OPT_isysroot)) {
468  CmdArgs.push_back("-isysroot");
469  CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
470  }
471  }
472 
473  // Parse additional include paths from environment variables.
474  // FIXME: We should probably sink the logic for handling these from the
475  // frontend into the driver. It will allow deleting 4 otherwise unused flags.
476  // CPATH - included following the user specified includes (but prior to
477  // builtin and standard includes).
478  addDirectoryList(Args, CmdArgs, "-I", "CPATH");
479  // C_INCLUDE_PATH - system includes enabled when compiling C.
480  addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
481  // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
482  addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
483  // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
484  addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
485  // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
486  addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
487 
488  // Optional AuxToolChain indicates that we need to include headers
489  // for more than one target. If that's the case, add include paths
490  // from AuxToolChain right after include paths of the same kind for
491  // the current target.
492 
493  // Add C++ include arguments, if needed.
494  if (types::isCXX(Inputs[0].getType())) {
495  getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
496  if (AuxToolChain)
497  AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
498  }
499 
500  // Add system include arguments.
501  getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
502  if (AuxToolChain)
503  AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
504 
505  // Add CUDA include arguments, if needed.
506  if (types::isCuda(Inputs[0].getType()))
507  getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
508 }
509 
510 // FIXME: Move to target hook.
511 static bool isSignedCharDefault(const llvm::Triple &Triple) {
512  switch (Triple.getArch()) {
513  default:
514  return true;
515 
516  case llvm::Triple::aarch64:
517  case llvm::Triple::aarch64_be:
518  case llvm::Triple::arm:
519  case llvm::Triple::armeb:
520  case llvm::Triple::thumb:
521  case llvm::Triple::thumbeb:
522  if (Triple.isOSDarwin() || Triple.isOSWindows())
523  return true;
524  return false;
525 
526  case llvm::Triple::ppc:
527  case llvm::Triple::ppc64:
528  if (Triple.isOSDarwin())
529  return true;
530  return false;
531 
532  case llvm::Triple::hexagon:
533  case llvm::Triple::ppc64le:
534  case llvm::Triple::systemz:
535  case llvm::Triple::xcore:
536  return false;
537  }
538 }
539 
540 static bool isNoCommonDefault(const llvm::Triple &Triple) {
541  switch (Triple.getArch()) {
542  default:
543  return false;
544 
545  case llvm::Triple::xcore:
546  case llvm::Triple::wasm32:
547  case llvm::Triple::wasm64:
548  return true;
549  }
550 }
551 
552 // ARM tools start.
553 
554 // Get SubArch (vN).
555 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
556  llvm::StringRef Arch = Triple.getArchName();
557  return llvm::ARM::parseArchVersion(Arch);
558 }
559 
560 // True if M-profile.
561 static bool isARMMProfile(const llvm::Triple &Triple) {
562  llvm::StringRef Arch = Triple.getArchName();
563  unsigned Profile = llvm::ARM::parseArchProfile(Arch);
564  return Profile == llvm::ARM::PK_M;
565 }
566 
567 // Get Arch/CPU from args.
568 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
569  llvm::StringRef &CPU, bool FromAs = false) {
570  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
571  CPU = A->getValue();
572  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
573  Arch = A->getValue();
574  if (!FromAs)
575  return;
576 
577  for (const Arg *A :
578  Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
579  StringRef Value = A->getValue();
580  if (Value.startswith("-mcpu="))
581  CPU = Value.substr(6);
582  if (Value.startswith("-march="))
583  Arch = Value.substr(7);
584  }
585 }
586 
587 // Handle -mhwdiv=.
588 // FIXME: Use ARMTargetParser.
589 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
590  const ArgList &Args, StringRef HWDiv,
591  std::vector<const char *> &Features) {
592  unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
593  if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
594  D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
595 }
596 
597 // Handle -mfpu=.
598 static void getARMFPUFeatures(const Driver &D, const Arg *A,
599  const ArgList &Args, StringRef FPU,
600  std::vector<const char *> &Features) {
601  unsigned FPUID = llvm::ARM::parseFPU(FPU);
602  if (!llvm::ARM::getFPUFeatures(FPUID, Features))
603  D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
604 }
605 
606 // Decode ARM features from string like +[no]featureA+[no]featureB+...
607 static bool DecodeARMFeatures(const Driver &D, StringRef text,
608  std::vector<const char *> &Features) {
610  text.split(Split, StringRef("+"), -1, false);
611 
612  for (StringRef Feature : Split) {
613  const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
614  if (FeatureName)
615  Features.push_back(FeatureName);
616  else
617  return false;
618  }
619  return true;
620 }
621 
622 // Check if -march is valid by checking if it can be canonicalised and parsed.
623 // getARMArch is used here instead of just checking the -march value in order
624 // to handle -march=native correctly.
625 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
626  llvm::StringRef ArchName,
627  std::vector<const char *> &Features,
628  const llvm::Triple &Triple) {
629  std::pair<StringRef, StringRef> Split = ArchName.split("+");
630 
631  std::string MArch = arm::getARMArch(ArchName, Triple);
632  if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
633  (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
634  D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
635 }
636 
637 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
638 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
639  llvm::StringRef CPUName, llvm::StringRef ArchName,
640  std::vector<const char *> &Features,
641  const llvm::Triple &Triple) {
642  std::pair<StringRef, StringRef> Split = CPUName.split("+");
643 
644  std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
645  if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
646  (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
647  D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
648 }
649 
650 static bool useAAPCSForMachO(const llvm::Triple &T) {
651  // The backend is hardwired to assume AAPCS for M-class processors, ensure
652  // the frontend matches that.
653  return T.getEnvironment() == llvm::Triple::EABI ||
654  T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
655 }
656 
657 // Select the float ABI as determined by -msoft-float, -mhard-float, and
658 // -mfloat-abi=.
659 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
660  const Driver &D = TC.getDriver();
661  const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
662  auto SubArch = getARMSubArchVersionNumber(Triple);
663  arm::FloatABI ABI = FloatABI::Invalid;
664  if (Arg *A =
665  Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
666  options::OPT_mfloat_abi_EQ)) {
667  if (A->getOption().matches(options::OPT_msoft_float)) {
668  ABI = FloatABI::Soft;
669  } else if (A->getOption().matches(options::OPT_mhard_float)) {
670  ABI = FloatABI::Hard;
671  } else {
672  ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
673  .Case("soft", FloatABI::Soft)
674  .Case("softfp", FloatABI::SoftFP)
675  .Case("hard", FloatABI::Hard)
676  .Default(FloatABI::Invalid);
677  if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
678  D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
679  ABI = FloatABI::Soft;
680  }
681  }
682 
683  // It is incorrect to select hard float ABI on MachO platforms if the ABI is
684  // "apcs-gnu".
685  if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
686  ABI == FloatABI::Hard) {
687  D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
688  << Triple.getArchName();
689  }
690  }
691 
692  // If unspecified, choose the default based on the platform.
693  if (ABI == FloatABI::Invalid) {
694  switch (Triple.getOS()) {
695  case llvm::Triple::Darwin:
696  case llvm::Triple::MacOSX:
697  case llvm::Triple::IOS:
698  case llvm::Triple::TvOS: {
699  // Darwin defaults to "softfp" for v6 and v7.
700  ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
701  break;
702  }
703  case llvm::Triple::WatchOS:
704  ABI = FloatABI::Hard;
705  break;
706 
707  // FIXME: this is invalid for WindowsCE
708  case llvm::Triple::Win32:
709  ABI = FloatABI::Hard;
710  break;
711 
712  case llvm::Triple::FreeBSD:
713  switch (Triple.getEnvironment()) {
714  case llvm::Triple::GNUEABIHF:
715  ABI = FloatABI::Hard;
716  break;
717  default:
718  // FreeBSD defaults to soft float
719  ABI = FloatABI::Soft;
720  break;
721  }
722  break;
723 
724  default:
725  switch (Triple.getEnvironment()) {
726  case llvm::Triple::GNUEABIHF:
727  case llvm::Triple::EABIHF:
728  ABI = FloatABI::Hard;
729  break;
730  case llvm::Triple::GNUEABI:
731  case llvm::Triple::EABI:
732  // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
733  ABI = FloatABI::SoftFP;
734  break;
735  case llvm::Triple::Android:
736  ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
737  break;
738  default:
739  // Assume "soft", but warn the user we are guessing.
740  ABI = FloatABI::Soft;
741  if (Triple.getOS() != llvm::Triple::UnknownOS ||
742  !Triple.isOSBinFormatMachO())
743  D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
744  break;
745  }
746  }
747  }
748 
749  assert(ABI != FloatABI::Invalid && "must select an ABI");
750  return ABI;
751 }
752 
753 static void getARMTargetFeatures(const ToolChain &TC,
754  const llvm::Triple &Triple,
755  const ArgList &Args,
756  std::vector<const char *> &Features,
757  bool ForAS) {
758  const Driver &D = TC.getDriver();
759 
760  bool KernelOrKext =
761  Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
762  arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
763  const Arg *WaCPU = nullptr, *WaFPU = nullptr;
764  const Arg *WaHDiv = nullptr, *WaArch = nullptr;
765 
766  if (!ForAS) {
767  // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
768  // yet (it uses the -mfloat-abi and -msoft-float options), and it is
769  // stripped out by the ARM target. We should probably pass this a new
770  // -target-option, which is handled by the -cc1/-cc1as invocation.
771  //
772  // FIXME2: For consistency, it would be ideal if we set up the target
773  // machine state the same when using the frontend or the assembler. We don't
774  // currently do that for the assembler, we pass the options directly to the
775  // backend and never even instantiate the frontend TargetInfo. If we did,
776  // and used its handleTargetFeatures hook, then we could ensure the
777  // assembler and the frontend behave the same.
778 
779  // Use software floating point operations?
780  if (ABI == arm::FloatABI::Soft)
781  Features.push_back("+soft-float");
782 
783  // Use software floating point argument passing?
784  if (ABI != arm::FloatABI::Hard)
785  Features.push_back("+soft-float-abi");
786  } else {
787  // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
788  // to the assembler correctly.
789  for (const Arg *A :
790  Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
791  StringRef Value = A->getValue();
792  if (Value.startswith("-mfpu=")) {
793  WaFPU = A;
794  } else if (Value.startswith("-mcpu=")) {
795  WaCPU = A;
796  } else if (Value.startswith("-mhwdiv=")) {
797  WaHDiv = A;
798  } else if (Value.startswith("-march=")) {
799  WaArch = A;
800  }
801  }
802  }
803 
804  // Check -march. ClangAs gives preference to -Wa,-march=.
805  const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
806  StringRef ArchName;
807  if (WaArch) {
808  if (ArchArg)
809  D.Diag(clang::diag::warn_drv_unused_argument)
810  << ArchArg->getAsString(Args);
811  ArchName = StringRef(WaArch->getValue()).substr(7);
812  checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
813  // FIXME: Set Arch.
814  D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
815  } else if (ArchArg) {
816  ArchName = ArchArg->getValue();
817  checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
818  }
819 
820  // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
821  const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
822  StringRef CPUName;
823  if (WaCPU) {
824  if (CPUArg)
825  D.Diag(clang::diag::warn_drv_unused_argument)
826  << CPUArg->getAsString(Args);
827  CPUName = StringRef(WaCPU->getValue()).substr(6);
828  checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
829  } else if (CPUArg) {
830  CPUName = CPUArg->getValue();
831  checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
832  }
833 
834  // Add CPU features for generic CPUs
835  if (CPUName == "native") {
836  llvm::StringMap<bool> HostFeatures;
837  if (llvm::sys::getHostCPUFeatures(HostFeatures))
838  for (auto &F : HostFeatures)
839  Features.push_back(
840  Args.MakeArgString((F.second ? "+" : "-") + F.first()));
841  }
842 
843  // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
844  const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
845  if (WaFPU) {
846  if (FPUArg)
847  D.Diag(clang::diag::warn_drv_unused_argument)
848  << FPUArg->getAsString(Args);
849  getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
850  Features);
851  } else if (FPUArg) {
852  getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
853  }
854 
855  // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
856  const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
857  if (WaHDiv) {
858  if (HDivArg)
859  D.Diag(clang::diag::warn_drv_unused_argument)
860  << HDivArg->getAsString(Args);
861  getARMHWDivFeatures(D, WaHDiv, Args,
862  StringRef(WaHDiv->getValue()).substr(8), Features);
863  } else if (HDivArg)
864  getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
865 
866  // Setting -msoft-float effectively disables NEON because of the GCC
867  // implementation, although the same isn't true of VFP or VFP3.
868  if (ABI == arm::FloatABI::Soft) {
869  Features.push_back("-neon");
870  // Also need to explicitly disable features which imply NEON.
871  Features.push_back("-crypto");
872  }
873 
874  // En/disable crc code generation.
875  if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
876  if (A->getOption().matches(options::OPT_mcrc))
877  Features.push_back("+crc");
878  else
879  Features.push_back("-crc");
880  }
881 
882  if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
883  Features.insert(Features.begin(), "+v8.1a");
884  }
885 
886  // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
887  // neither options are specified, see if we are compiling for kernel/kext and
888  // decide whether to pass "+long-calls" based on the OS and its version.
889  if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
890  options::OPT_mno_long_calls)) {
891  if (A->getOption().matches(options::OPT_mlong_calls))
892  Features.push_back("+long-calls");
893  } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
894  !Triple.isWatchOS()) {
895  Features.push_back("+long-calls");
896  }
897 
898  // Kernel code has more strict alignment requirements.
899  if (KernelOrKext)
900  Features.push_back("+strict-align");
901  else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
902  options::OPT_munaligned_access)) {
903  if (A->getOption().matches(options::OPT_munaligned_access)) {
904  // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
905  if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
906  D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
907  } else
908  Features.push_back("+strict-align");
909  } else {
910  // Assume pre-ARMv6 doesn't support unaligned accesses.
911  //
912  // ARMv6 may or may not support unaligned accesses depending on the
913  // SCTLR.U bit, which is architecture-specific. We assume ARMv6
914  // Darwin and NetBSD targets support unaligned accesses, and others don't.
915  //
916  // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
917  // which raises an alignment fault on unaligned accesses. Linux
918  // defaults this bit to 0 and handles it as a system-wide (not
919  // per-process) setting. It is therefore safe to assume that ARMv7+
920  // Linux targets support unaligned accesses. The same goes for NaCl.
921  //
922  // The above behavior is consistent with GCC.
923  int VersionNum = getARMSubArchVersionNumber(Triple);
924  if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
925  if (VersionNum < 6 ||
926  Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
927  Features.push_back("+strict-align");
928  } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
929  if (VersionNum < 7)
930  Features.push_back("+strict-align");
931  } else
932  Features.push_back("+strict-align");
933  }
934 
935  // llvm does not support reserving registers in general. There is support
936  // for reserving r9 on ARM though (defined as a platform-specific register
937  // in ARM EABI).
938  if (Args.hasArg(options::OPT_ffixed_r9))
939  Features.push_back("+reserve-r9");
940 
941  // The kext linker doesn't know how to deal with movw/movt.
942  if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
943  Features.push_back("+no-movt");
944 }
945 
946 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
947  ArgStringList &CmdArgs, bool KernelOrKext) const {
948  // Select the ABI to use.
949  // FIXME: Support -meabi.
950  // FIXME: Parts of this are duplicated in the backend, unify this somehow.
951  const char *ABIName = nullptr;
952  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
953  ABIName = A->getValue();
954  } else if (Triple.isOSBinFormatMachO()) {
955  if (useAAPCSForMachO(Triple)) {
956  ABIName = "aapcs";
957  } else if (Triple.isWatchOS()) {
958  ABIName = "aapcs16";
959  } else {
960  ABIName = "apcs-gnu";
961  }
962  } else if (Triple.isOSWindows()) {
963  // FIXME: this is invalid for WindowsCE
964  ABIName = "aapcs";
965  } else {
966  // Select the default based on the platform.
967  switch (Triple.getEnvironment()) {
968  case llvm::Triple::Android:
969  case llvm::Triple::GNUEABI:
970  case llvm::Triple::GNUEABIHF:
971  ABIName = "aapcs-linux";
972  break;
973  case llvm::Triple::EABIHF:
974  case llvm::Triple::EABI:
975  ABIName = "aapcs";
976  break;
977  default:
978  if (Triple.getOS() == llvm::Triple::NetBSD)
979  ABIName = "apcs-gnu";
980  else
981  ABIName = "aapcs";
982  break;
983  }
984  }
985  CmdArgs.push_back("-target-abi");
986  CmdArgs.push_back(ABIName);
987 
988  // Determine floating point ABI from the options & target defaults.
989  arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
990  if (ABI == arm::FloatABI::Soft) {
991  // Floating point operations and argument passing are soft.
992  // FIXME: This changes CPP defines, we need -target-soft-float.
993  CmdArgs.push_back("-msoft-float");
994  CmdArgs.push_back("-mfloat-abi");
995  CmdArgs.push_back("soft");
996  } else if (ABI == arm::FloatABI::SoftFP) {
997  // Floating point operations are hard, but argument passing is soft.
998  CmdArgs.push_back("-mfloat-abi");
999  CmdArgs.push_back("soft");
1000  } else {
1001  // Floating point operations and argument passing are hard.
1002  assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1003  CmdArgs.push_back("-mfloat-abi");
1004  CmdArgs.push_back("hard");
1005  }
1006 
1007  // Forward the -mglobal-merge option for explicit control over the pass.
1008  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1009  options::OPT_mno_global_merge)) {
1010  CmdArgs.push_back("-backend-option");
1011  if (A->getOption().matches(options::OPT_mno_global_merge))
1012  CmdArgs.push_back("-arm-global-merge=false");
1013  else
1014  CmdArgs.push_back("-arm-global-merge=true");
1015  }
1016 
1017  if (!Args.hasFlag(options::OPT_mimplicit_float,
1018  options::OPT_mno_implicit_float, true))
1019  CmdArgs.push_back("-no-implicit-float");
1020 }
1021 // ARM tools end.
1022 
1023 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1024 /// targeting.
1025 static std::string getAArch64TargetCPU(const ArgList &Args) {
1026  Arg *A;
1027  std::string CPU;
1028  // If we have -mtune or -mcpu, use that.
1029  if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1030  CPU = StringRef(A->getValue()).lower();
1031  } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1032  StringRef Mcpu = A->getValue();
1033  CPU = Mcpu.split("+").first.lower();
1034  }
1035 
1036  // Handle CPU name is 'native'.
1037  if (CPU == "native")
1038  return llvm::sys::getHostCPUName();
1039  else if (CPU.size())
1040  return CPU;
1041 
1042  // Make sure we pick "cyclone" if -arch is used.
1043  // FIXME: Should this be picked by checking the target triple instead?
1044  if (Args.getLastArg(options::OPT_arch))
1045  return "cyclone";
1046 
1047  return "generic";
1048 }
1049 
1050 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1051  ArgStringList &CmdArgs) const {
1052  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1053  llvm::Triple Triple(TripleStr);
1054 
1055  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1056  Args.hasArg(options::OPT_mkernel) ||
1057  Args.hasArg(options::OPT_fapple_kext))
1058  CmdArgs.push_back("-disable-red-zone");
1059 
1060  if (!Args.hasFlag(options::OPT_mimplicit_float,
1061  options::OPT_mno_implicit_float, true))
1062  CmdArgs.push_back("-no-implicit-float");
1063 
1064  const char *ABIName = nullptr;
1065  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1066  ABIName = A->getValue();
1067  else if (Triple.isOSDarwin())
1068  ABIName = "darwinpcs";
1069  else
1070  ABIName = "aapcs";
1071 
1072  CmdArgs.push_back("-target-abi");
1073  CmdArgs.push_back(ABIName);
1074 
1075  if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1076  options::OPT_mno_fix_cortex_a53_835769)) {
1077  CmdArgs.push_back("-backend-option");
1078  if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1079  CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1080  else
1081  CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1082  } else if (Triple.isAndroid()) {
1083  // Enabled A53 errata (835769) workaround by default on android
1084  CmdArgs.push_back("-backend-option");
1085  CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1086  }
1087 
1088  // Forward the -mglobal-merge option for explicit control over the pass.
1089  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1090  options::OPT_mno_global_merge)) {
1091  CmdArgs.push_back("-backend-option");
1092  if (A->getOption().matches(options::OPT_mno_global_merge))
1093  CmdArgs.push_back("-aarch64-global-merge=false");
1094  else
1095  CmdArgs.push_back("-aarch64-global-merge=true");
1096  }
1097 }
1098 
1099 // Get CPU and ABI names. They are not independent
1100 // so we have to calculate them together.
1101 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1102  StringRef &CPUName, StringRef &ABIName) {
1103  const char *DefMips32CPU = "mips32r2";
1104  const char *DefMips64CPU = "mips64r2";
1105 
1106  // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1107  // default for mips64(el)?-img-linux-gnu.
1108  if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1109  Triple.getEnvironment() == llvm::Triple::GNU) {
1110  DefMips32CPU = "mips32r6";
1111  DefMips64CPU = "mips64r6";
1112  }
1113 
1114  // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1115  if (Triple.isAndroid())
1116  DefMips64CPU = "mips64r6";
1117 
1118  // MIPS3 is the default for mips64*-unknown-openbsd.
1119  if (Triple.getOS() == llvm::Triple::OpenBSD)
1120  DefMips64CPU = "mips3";
1121 
1122  if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1123  CPUName = A->getValue();
1124 
1125  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1126  ABIName = A->getValue();
1127  // Convert a GNU style Mips ABI name to the name
1128  // accepted by LLVM Mips backend.
1129  ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1130  .Case("32", "o32")
1131  .Case("64", "n64")
1132  .Default(ABIName);
1133  }
1134 
1135  // Setup default CPU and ABI names.
1136  if (CPUName.empty() && ABIName.empty()) {
1137  switch (Triple.getArch()) {
1138  default:
1139  llvm_unreachable("Unexpected triple arch name");
1140  case llvm::Triple::mips:
1141  case llvm::Triple::mipsel:
1142  CPUName = DefMips32CPU;
1143  break;
1144  case llvm::Triple::mips64:
1145  case llvm::Triple::mips64el:
1146  CPUName = DefMips64CPU;
1147  break;
1148  }
1149  }
1150 
1151  if (ABIName.empty()) {
1152  // Deduce ABI name from the target triple.
1153  if (Triple.getArch() == llvm::Triple::mips ||
1154  Triple.getArch() == llvm::Triple::mipsel)
1155  ABIName = "o32";
1156  else
1157  ABIName = "n64";
1158  }
1159 
1160  if (CPUName.empty()) {
1161  // Deduce CPU name from ABI name.
1162  CPUName = llvm::StringSwitch<const char *>(ABIName)
1163  .Cases("o32", "eabi", DefMips32CPU)
1164  .Cases("n32", "n64", DefMips64CPU)
1165  .Default("");
1166  }
1167 
1168  // FIXME: Warn on inconsistent use of -march and -mabi.
1169 }
1170 
1171 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1172  const llvm::Triple &Triple) {
1173  StringRef CPUName, ABIName;
1174  tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1175  return llvm::StringSwitch<std::string>(ABIName)
1176  .Case("o32", "")
1177  .Case("n32", "32")
1178  .Case("n64", "64");
1179 }
1180 
1181 // Convert ABI name to the GNU tools acceptable variant.
1182 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1183  return llvm::StringSwitch<llvm::StringRef>(ABI)
1184  .Case("o32", "32")
1185  .Case("n64", "64")
1186  .Default(ABI);
1187 }
1188 
1189 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1190 // and -mfloat-abi=.
1191 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1193  if (Arg *A =
1194  Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1195  options::OPT_mfloat_abi_EQ)) {
1196  if (A->getOption().matches(options::OPT_msoft_float))
1197  ABI = mips::FloatABI::Soft;
1198  else if (A->getOption().matches(options::OPT_mhard_float))
1199  ABI = mips::FloatABI::Hard;
1200  else {
1201  ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1202  .Case("soft", mips::FloatABI::Soft)
1203  .Case("hard", mips::FloatABI::Hard)
1204  .Default(mips::FloatABI::Invalid);
1205  if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1206  D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1207  ABI = mips::FloatABI::Hard;
1208  }
1209  }
1210  }
1211 
1212  // If unspecified, choose the default based on the platform.
1213  if (ABI == mips::FloatABI::Invalid) {
1214  // Assume "hard", because it's a default value used by gcc.
1215  // When we start to recognize specific target MIPS processors,
1216  // we will be able to select the default more correctly.
1217  ABI = mips::FloatABI::Hard;
1218  }
1219 
1220  assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1221  return ABI;
1222 }
1223 
1224 static void AddTargetFeature(const ArgList &Args,
1225  std::vector<const char *> &Features,
1226  OptSpecifier OnOpt, OptSpecifier OffOpt,
1227  StringRef FeatureName) {
1228  if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1229  if (A->getOption().matches(OnOpt))
1230  Features.push_back(Args.MakeArgString("+" + FeatureName));
1231  else
1232  Features.push_back(Args.MakeArgString("-" + FeatureName));
1233  }
1234 }
1235 
1236 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1237  const ArgList &Args,
1238  std::vector<const char *> &Features) {
1239  StringRef CPUName;
1240  StringRef ABIName;
1241  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1242  ABIName = getGnuCompatibleMipsABIName(ABIName);
1243 
1244  AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1245  options::OPT_mabicalls, "noabicalls");
1246 
1248  if (FloatABI == mips::FloatABI::Soft) {
1249  // FIXME: Note, this is a hack. We need to pass the selected float
1250  // mode to the MipsTargetInfoBase to define appropriate macros there.
1251  // Now it is the only method.
1252  Features.push_back("+soft-float");
1253  }
1254 
1255  if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1256  StringRef Val = StringRef(A->getValue());
1257  if (Val == "2008") {
1259  Features.push_back("+nan2008");
1260  else {
1261  Features.push_back("-nan2008");
1262  D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1263  }
1264  } else if (Val == "legacy") {
1266  Features.push_back("-nan2008");
1267  else {
1268  Features.push_back("+nan2008");
1269  D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1270  }
1271  } else
1272  D.Diag(diag::err_drv_unsupported_option_argument)
1273  << A->getOption().getName() << Val;
1274  }
1275 
1276  AddTargetFeature(Args, Features, options::OPT_msingle_float,
1277  options::OPT_mdouble_float, "single-float");
1278  AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1279  "mips16");
1280  AddTargetFeature(Args, Features, options::OPT_mmicromips,
1281  options::OPT_mno_micromips, "micromips");
1282  AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1283  "dsp");
1284  AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1285  "dspr2");
1286  AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1287  "msa");
1288 
1289  // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1290  // pass -mfpxx
1291  if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1292  options::OPT_mfp64)) {
1293  if (A->getOption().matches(options::OPT_mfp32))
1294  Features.push_back(Args.MakeArgString("-fp64"));
1295  else if (A->getOption().matches(options::OPT_mfpxx)) {
1296  Features.push_back(Args.MakeArgString("+fpxx"));
1297  Features.push_back(Args.MakeArgString("+nooddspreg"));
1298  } else
1299  Features.push_back(Args.MakeArgString("+fp64"));
1300  } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1301  Features.push_back(Args.MakeArgString("+fpxx"));
1302  Features.push_back(Args.MakeArgString("+nooddspreg"));
1303  }
1304 
1305  AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1306  options::OPT_modd_spreg, "nooddspreg");
1307 }
1308 
1309 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1310  ArgStringList &CmdArgs) const {
1311  const Driver &D = getToolChain().getDriver();
1312  StringRef CPUName;
1313  StringRef ABIName;
1314  const llvm::Triple &Triple = getToolChain().getTriple();
1315  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1316 
1317  CmdArgs.push_back("-target-abi");
1318  CmdArgs.push_back(ABIName.data());
1319 
1320  mips::FloatABI ABI = getMipsFloatABI(D, Args);
1321  if (ABI == mips::FloatABI::Soft) {
1322  // Floating point operations and argument passing are soft.
1323  CmdArgs.push_back("-msoft-float");
1324  CmdArgs.push_back("-mfloat-abi");
1325  CmdArgs.push_back("soft");
1326  } else {
1327  // Floating point operations and argument passing are hard.
1328  assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1329  CmdArgs.push_back("-mfloat-abi");
1330  CmdArgs.push_back("hard");
1331  }
1332 
1333  if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1334  if (A->getOption().matches(options::OPT_mxgot)) {
1335  CmdArgs.push_back("-mllvm");
1336  CmdArgs.push_back("-mxgot");
1337  }
1338  }
1339 
1340  if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1341  options::OPT_mno_ldc1_sdc1)) {
1342  if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1343  CmdArgs.push_back("-mllvm");
1344  CmdArgs.push_back("-mno-ldc1-sdc1");
1345  }
1346  }
1347 
1348  if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1349  options::OPT_mno_check_zero_division)) {
1350  if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1351  CmdArgs.push_back("-mllvm");
1352  CmdArgs.push_back("-mno-check-zero-division");
1353  }
1354  }
1355 
1356  if (Arg *A = Args.getLastArg(options::OPT_G)) {
1357  StringRef v = A->getValue();
1358  CmdArgs.push_back("-mllvm");
1359  CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1360  A->claim();
1361  }
1362 }
1363 
1364 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1365 static std::string getPPCTargetCPU(const ArgList &Args) {
1366  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1367  StringRef CPUName = A->getValue();
1368 
1369  if (CPUName == "native") {
1370  std::string CPU = llvm::sys::getHostCPUName();
1371  if (!CPU.empty() && CPU != "generic")
1372  return CPU;
1373  else
1374  return "";
1375  }
1376 
1377  return llvm::StringSwitch<const char *>(CPUName)
1378  .Case("common", "generic")
1379  .Case("440", "440")
1380  .Case("440fp", "440")
1381  .Case("450", "450")
1382  .Case("601", "601")
1383  .Case("602", "602")
1384  .Case("603", "603")
1385  .Case("603e", "603e")
1386  .Case("603ev", "603ev")
1387  .Case("604", "604")
1388  .Case("604e", "604e")
1389  .Case("620", "620")
1390  .Case("630", "pwr3")
1391  .Case("G3", "g3")
1392  .Case("7400", "7400")
1393  .Case("G4", "g4")
1394  .Case("7450", "7450")
1395  .Case("G4+", "g4+")
1396  .Case("750", "750")
1397  .Case("970", "970")
1398  .Case("G5", "g5")
1399  .Case("a2", "a2")
1400  .Case("a2q", "a2q")
1401  .Case("e500mc", "e500mc")
1402  .Case("e5500", "e5500")
1403  .Case("power3", "pwr3")
1404  .Case("power4", "pwr4")
1405  .Case("power5", "pwr5")
1406  .Case("power5x", "pwr5x")
1407  .Case("power6", "pwr6")
1408  .Case("power6x", "pwr6x")
1409  .Case("power7", "pwr7")
1410  .Case("power8", "pwr8")
1411  .Case("pwr3", "pwr3")
1412  .Case("pwr4", "pwr4")
1413  .Case("pwr5", "pwr5")
1414  .Case("pwr5x", "pwr5x")
1415  .Case("pwr6", "pwr6")
1416  .Case("pwr6x", "pwr6x")
1417  .Case("pwr7", "pwr7")
1418  .Case("pwr8", "pwr8")
1419  .Case("powerpc", "ppc")
1420  .Case("powerpc64", "ppc64")
1421  .Case("powerpc64le", "ppc64le")
1422  .Default("");
1423  }
1424 
1425  return "";
1426 }
1427 
1428 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1429  const ArgList &Args,
1430  std::vector<const char *> &Features) {
1431  handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
1432 
1434  if (FloatABI == ppc::FloatABI::Soft &&
1435  !(Triple.getArch() == llvm::Triple::ppc64 ||
1436  Triple.getArch() == llvm::Triple::ppc64le))
1437  Features.push_back("+soft-float");
1438  else if (FloatABI == ppc::FloatABI::Soft &&
1439  (Triple.getArch() == llvm::Triple::ppc64 ||
1440  Triple.getArch() == llvm::Triple::ppc64le))
1441  D.Diag(diag::err_drv_invalid_mfloat_abi)
1442  << "soft float is not supported for ppc64";
1443 
1444  // Altivec is a bit weird, allow overriding of the Altivec feature here.
1445  AddTargetFeature(Args, Features, options::OPT_faltivec,
1446  options::OPT_fno_altivec, "altivec");
1447 }
1448 
1449 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1451  if (Arg *A =
1452  Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1453  options::OPT_mfloat_abi_EQ)) {
1454  if (A->getOption().matches(options::OPT_msoft_float))
1455  ABI = ppc::FloatABI::Soft;
1456  else if (A->getOption().matches(options::OPT_mhard_float))
1457  ABI = ppc::FloatABI::Hard;
1458  else {
1459  ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1460  .Case("soft", ppc::FloatABI::Soft)
1461  .Case("hard", ppc::FloatABI::Hard)
1462  .Default(ppc::FloatABI::Invalid);
1463  if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1464  D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1465  ABI = ppc::FloatABI::Hard;
1466  }
1467  }
1468  }
1469 
1470  // If unspecified, choose the default based on the platform.
1471  if (ABI == ppc::FloatABI::Invalid) {
1472  ABI = ppc::FloatABI::Hard;
1473  }
1474 
1475  return ABI;
1476 }
1477 
1478 void Clang::AddPPCTargetArgs(const ArgList &Args,
1479  ArgStringList &CmdArgs) const {
1480  // Select the ABI to use.
1481  const char *ABIName = nullptr;
1482  if (getToolChain().getTriple().isOSLinux())
1483  switch (getToolChain().getArch()) {
1484  case llvm::Triple::ppc64: {
1485  // When targeting a processor that supports QPX, or if QPX is
1486  // specifically enabled, default to using the ABI that supports QPX (so
1487  // long as it is not specifically disabled).
1488  bool HasQPX = false;
1489  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1490  HasQPX = A->getValue() == StringRef("a2q");
1491  HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1492  if (HasQPX) {
1493  ABIName = "elfv1-qpx";
1494  break;
1495  }
1496 
1497  ABIName = "elfv1";
1498  break;
1499  }
1500  case llvm::Triple::ppc64le:
1501  ABIName = "elfv2";
1502  break;
1503  default:
1504  break;
1505  }
1506 
1507  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1508  // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1509  // the option if given as we don't have backend support for any targets
1510  // that don't use the altivec abi.
1511  if (StringRef(A->getValue()) != "altivec")
1512  ABIName = A->getValue();
1513 
1515  ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1516 
1517  if (FloatABI == ppc::FloatABI::Soft) {
1518  // Floating point operations and argument passing are soft.
1519  CmdArgs.push_back("-msoft-float");
1520  CmdArgs.push_back("-mfloat-abi");
1521  CmdArgs.push_back("soft");
1522  } else {
1523  // Floating point operations and argument passing are hard.
1524  assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1525  CmdArgs.push_back("-mfloat-abi");
1526  CmdArgs.push_back("hard");
1527  }
1528 
1529  if (ABIName) {
1530  CmdArgs.push_back("-target-abi");
1531  CmdArgs.push_back(ABIName);
1532  }
1533 }
1534 
1535 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1536  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1537  return A && (A->getValue() == StringRef(Value));
1538 }
1539 
1540 /// Get the (LLVM) name of the R600 gpu we are targeting.
1541 static std::string getR600TargetGPU(const ArgList &Args) {
1542  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1543  const char *GPUName = A->getValue();
1544  return llvm::StringSwitch<const char *>(GPUName)
1545  .Cases("rv630", "rv635", "r600")
1546  .Cases("rv610", "rv620", "rs780", "rs880")
1547  .Case("rv740", "rv770")
1548  .Case("palm", "cedar")
1549  .Cases("sumo", "sumo2", "sumo")
1550  .Case("hemlock", "cypress")
1551  .Case("aruba", "cayman")
1552  .Default(GPUName);
1553  }
1554  return "";
1555 }
1556 
1557 void Clang::AddSparcTargetArgs(const ArgList &Args,
1558  ArgStringList &CmdArgs) const {
1559  const Driver &D = getToolChain().getDriver();
1560  std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1561 
1562  bool SoftFloatABI = false;
1563  if (Arg *A =
1564  Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1565  if (A->getOption().matches(options::OPT_msoft_float))
1566  SoftFloatABI = true;
1567  }
1568 
1569  // Only the hard-float ABI on Sparc is standardized, and it is the
1570  // default. GCC also supports a nonstandard soft-float ABI mode, and
1571  // perhaps LLVM should implement that, too. However, since llvm
1572  // currently does not support Sparc soft-float, at all, display an
1573  // error if it's requested.
1574  if (SoftFloatABI) {
1575  D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1576  << Triple;
1577  }
1578 }
1579 
1580 static const char *getSystemZTargetCPU(const ArgList &Args) {
1581  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1582  return A->getValue();
1583  return "z10";
1584 }
1585 
1586 static void getSystemZTargetFeatures(const ArgList &Args,
1587  std::vector<const char *> &Features) {
1588  // -m(no-)htm overrides use of the transactional-execution facility.
1589  if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1590  if (A->getOption().matches(options::OPT_mhtm))
1591  Features.push_back("+transactional-execution");
1592  else
1593  Features.push_back("-transactional-execution");
1594  }
1595  // -m(no-)vx overrides use of the vector facility.
1596  if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1597  if (A->getOption().matches(options::OPT_mvx))
1598  Features.push_back("+vector");
1599  else
1600  Features.push_back("-vector");
1601  }
1602 }
1603 
1604 static const char *getX86TargetCPU(const ArgList &Args,
1605  const llvm::Triple &Triple) {
1606  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1607  if (StringRef(A->getValue()) != "native") {
1608  if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1609  return "core-avx2";
1610 
1611  return A->getValue();
1612  }
1613 
1614  // FIXME: Reject attempts to use -march=native unless the target matches
1615  // the host.
1616  //
1617  // FIXME: We should also incorporate the detected target features for use
1618  // with -native.
1619  std::string CPU = llvm::sys::getHostCPUName();
1620  if (!CPU.empty() && CPU != "generic")
1621  return Args.MakeArgString(CPU);
1622  }
1623 
1624  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1625  // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1626  StringRef Arch = A->getValue();
1627  const char *CPU;
1628  if (Triple.getArch() == llvm::Triple::x86) {
1629  CPU = llvm::StringSwitch<const char *>(Arch)
1630  .Case("IA32", "i386")
1631  .Case("SSE", "pentium3")
1632  .Case("SSE2", "pentium4")
1633  .Case("AVX", "sandybridge")
1634  .Case("AVX2", "haswell")
1635  .Default(nullptr);
1636  } else {
1637  CPU = llvm::StringSwitch<const char *>(Arch)
1638  .Case("AVX", "sandybridge")
1639  .Case("AVX2", "haswell")
1640  .Default(nullptr);
1641  }
1642  if (CPU)
1643  return CPU;
1644  }
1645 
1646  // Select the default CPU if none was given (or detection failed).
1647 
1648  if (Triple.getArch() != llvm::Triple::x86_64 &&
1649  Triple.getArch() != llvm::Triple::x86)
1650  return nullptr; // This routine is only handling x86 targets.
1651 
1652  bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1653 
1654  // FIXME: Need target hooks.
1655  if (Triple.isOSDarwin()) {
1656  if (Triple.getArchName() == "x86_64h")
1657  return "core-avx2";
1658  return Is64Bit ? "core2" : "yonah";
1659  }
1660 
1661  // Set up default CPU name for PS4 compilers.
1662  if (Triple.isPS4CPU())
1663  return "btver2";
1664 
1665  // On Android use targets compatible with gcc
1666  if (Triple.isAndroid())
1667  return Is64Bit ? "x86-64" : "i686";
1668 
1669  // Everything else goes to x86-64 in 64-bit mode.
1670  if (Is64Bit)
1671  return "x86-64";
1672 
1673  switch (Triple.getOS()) {
1674  case llvm::Triple::FreeBSD:
1675  case llvm::Triple::NetBSD:
1676  case llvm::Triple::OpenBSD:
1677  return "i486";
1678  case llvm::Triple::Haiku:
1679  return "i586";
1680  case llvm::Triple::Bitrig:
1681  return "i686";
1682  default:
1683  // Fallback to p4.
1684  return "pentium4";
1685  }
1686 }
1687 
1688 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
1689 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1690  // If we have -mcpu=, use that.
1691  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1692  StringRef CPU = A->getValue();
1693 
1694 #ifdef __wasm__
1695  // Handle "native" by examining the host. "native" isn't meaningful when
1696  // cross compiling, so only support this when the host is also WebAssembly.
1697  if (CPU == "native")
1698  return llvm::sys::getHostCPUName();
1699 #endif
1700 
1701  return CPU;
1702  }
1703 
1704  return "generic";
1705 }
1706 
1707 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1708  bool FromAs = false) {
1709  switch (T.getArch()) {
1710  default:
1711  return "";
1712 
1713  case llvm::Triple::aarch64:
1714  case llvm::Triple::aarch64_be:
1715  return getAArch64TargetCPU(Args);
1716 
1717  case llvm::Triple::arm:
1718  case llvm::Triple::armeb:
1719  case llvm::Triple::thumb:
1720  case llvm::Triple::thumbeb: {
1721  StringRef MArch, MCPU;
1722  getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1723  return arm::getARMTargetCPU(MCPU, MArch, T);
1724  }
1725  case llvm::Triple::mips:
1726  case llvm::Triple::mipsel:
1727  case llvm::Triple::mips64:
1728  case llvm::Triple::mips64el: {
1729  StringRef CPUName;
1730  StringRef ABIName;
1731  mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1732  return CPUName;
1733  }
1734 
1735  case llvm::Triple::nvptx:
1736  case llvm::Triple::nvptx64:
1737  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1738  return A->getValue();
1739  return "";
1740 
1741  case llvm::Triple::ppc:
1742  case llvm::Triple::ppc64:
1743  case llvm::Triple::ppc64le: {
1744  std::string TargetCPUName = getPPCTargetCPU(Args);
1745  // LLVM may default to generating code for the native CPU,
1746  // but, like gcc, we default to a more generic option for
1747  // each architecture. (except on Darwin)
1748  if (TargetCPUName.empty() && !T.isOSDarwin()) {
1749  if (T.getArch() == llvm::Triple::ppc64)
1750  TargetCPUName = "ppc64";
1751  else if (T.getArch() == llvm::Triple::ppc64le)
1752  TargetCPUName = "ppc64le";
1753  else
1754  TargetCPUName = "ppc";
1755  }
1756  return TargetCPUName;
1757  }
1758 
1759  case llvm::Triple::sparc:
1760  case llvm::Triple::sparcel:
1761  case llvm::Triple::sparcv9:
1762  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1763  return A->getValue();
1764  return "";
1765 
1766  case llvm::Triple::x86:
1767  case llvm::Triple::x86_64:
1768  return getX86TargetCPU(Args, T);
1769 
1770  case llvm::Triple::hexagon:
1771  return "hexagon" +
1773 
1774  case llvm::Triple::systemz:
1775  return getSystemZTargetCPU(Args);
1776 
1777  case llvm::Triple::r600:
1778  case llvm::Triple::amdgcn:
1779  return getR600TargetGPU(Args);
1780 
1781  case llvm::Triple::wasm32:
1782  case llvm::Triple::wasm64:
1783  return getWebAssemblyTargetCPU(Args);
1784  }
1785 }
1786 
1787 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1788  ArgStringList &CmdArgs, bool IsThinLTO) {
1789  // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1790  // as gold requires -plugin to come before any -plugin-opt that -Wl might
1791  // forward.
1792  CmdArgs.push_back("-plugin");
1793  std::string Plugin =
1794  ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1795  CmdArgs.push_back(Args.MakeArgString(Plugin));
1796 
1797  // Try to pass driver level flags relevant to LTO code generation down to
1798  // the plugin.
1799 
1800  // Handle flags for selecting CPU variants.
1801  std::string CPU = getCPUName(Args, ToolChain.getTriple());
1802  if (!CPU.empty())
1803  CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1804 
1805  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1806  StringRef OOpt;
1807  if (A->getOption().matches(options::OPT_O4) ||
1808  A->getOption().matches(options::OPT_Ofast))
1809  OOpt = "3";
1810  else if (A->getOption().matches(options::OPT_O))
1811  OOpt = A->getValue();
1812  else if (A->getOption().matches(options::OPT_O0))
1813  OOpt = "0";
1814  if (!OOpt.empty())
1815  CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
1816  }
1817 
1818  if (IsThinLTO)
1819  CmdArgs.push_back("-plugin-opt=thinlto");
1820 }
1821 
1822 /// This is a helper function for validating the optional refinement step
1823 /// parameter in reciprocal argument strings. Return false if there is an error
1824 /// parsing the refinement step. Otherwise, return true and set the Position
1825 /// of the refinement step in the input string.
1826 static bool getRefinementStep(StringRef In, const Driver &D,
1827  const Arg &A, size_t &Position) {
1828  const char RefinementStepToken = ':';
1829  Position = In.find(RefinementStepToken);
1830  if (Position != StringRef::npos) {
1831  StringRef Option = A.getOption().getName();
1832  StringRef RefStep = In.substr(Position + 1);
1833  // Allow exactly one numeric character for the additional refinement
1834  // step parameter. This is reasonable for all currently-supported
1835  // operations and architectures because we would expect that a larger value
1836  // of refinement steps would cause the estimate "optimization" to
1837  // under-perform the native operation. Also, if the estimate does not
1838  // converge quickly, it probably will not ever converge, so further
1839  // refinement steps will not produce a better answer.
1840  if (RefStep.size() != 1) {
1841  D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1842  return false;
1843  }
1844  char RefStepChar = RefStep[0];
1845  if (RefStepChar < '0' || RefStepChar > '9') {
1846  D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1847  return false;
1848  }
1849  }
1850  return true;
1851 }
1852 
1853 /// The -mrecip flag requires processing of many optional parameters.
1854 static void ParseMRecip(const Driver &D, const ArgList &Args,
1855  ArgStringList &OutStrings) {
1856  StringRef DisabledPrefixIn = "!";
1857  StringRef DisabledPrefixOut = "!";
1858  StringRef EnabledPrefixOut = "";
1859  StringRef Out = "-mrecip=";
1860 
1861  Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1862  if (!A)
1863  return;
1864 
1865  unsigned NumOptions = A->getNumValues();
1866  if (NumOptions == 0) {
1867  // No option is the same as "all".
1868  OutStrings.push_back(Args.MakeArgString(Out + "all"));
1869  return;
1870  }
1871 
1872  // Pass through "all", "none", or "default" with an optional refinement step.
1873  if (NumOptions == 1) {
1874  StringRef Val = A->getValue(0);
1875  size_t RefStepLoc;
1876  if (!getRefinementStep(Val, D, *A, RefStepLoc))
1877  return;
1878  StringRef ValBase = Val.slice(0, RefStepLoc);
1879  if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1880  OutStrings.push_back(Args.MakeArgString(Out + Val));
1881  return;
1882  }
1883  }
1884 
1885  // Each reciprocal type may be enabled or disabled individually.
1886  // Check each input value for validity, concatenate them all back together,
1887  // and pass through.
1888 
1889  llvm::StringMap<bool> OptionStrings;
1890  OptionStrings.insert(std::make_pair("divd", false));
1891  OptionStrings.insert(std::make_pair("divf", false));
1892  OptionStrings.insert(std::make_pair("vec-divd", false));
1893  OptionStrings.insert(std::make_pair("vec-divf", false));
1894  OptionStrings.insert(std::make_pair("sqrtd", false));
1895  OptionStrings.insert(std::make_pair("sqrtf", false));
1896  OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1897  OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1898 
1899  for (unsigned i = 0; i != NumOptions; ++i) {
1900  StringRef Val = A->getValue(i);
1901 
1902  bool IsDisabled = Val.startswith(DisabledPrefixIn);
1903  // Ignore the disablement token for string matching.
1904  if (IsDisabled)
1905  Val = Val.substr(1);
1906 
1907  size_t RefStep;
1908  if (!getRefinementStep(Val, D, *A, RefStep))
1909  return;
1910 
1911  StringRef ValBase = Val.slice(0, RefStep);
1912  llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1913  if (OptionIter == OptionStrings.end()) {
1914  // Try again specifying float suffix.
1915  OptionIter = OptionStrings.find(ValBase.str() + 'f');
1916  if (OptionIter == OptionStrings.end()) {
1917  // The input name did not match any known option string.
1918  D.Diag(diag::err_drv_unknown_argument) << Val;
1919  return;
1920  }
1921  // The option was specified without a float or double suffix.
1922  // Make sure that the double entry was not already specified.
1923  // The float entry will be checked below.
1924  if (OptionStrings[ValBase.str() + 'd']) {
1925  D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1926  return;
1927  }
1928  }
1929 
1930  if (OptionIter->second == true) {
1931  // Duplicate option specified.
1932  D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1933  return;
1934  }
1935 
1936  // Mark the matched option as found. Do not allow duplicate specifiers.
1937  OptionIter->second = true;
1938 
1939  // If the precision was not specified, also mark the double entry as found.
1940  if (ValBase.back() != 'f' && ValBase.back() != 'd')
1941  OptionStrings[ValBase.str() + 'd'] = true;
1942 
1943  // Build the output string.
1944  StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1945  Out = Args.MakeArgString(Out + Prefix + Val);
1946  if (i != NumOptions - 1)
1947  Out = Args.MakeArgString(Out + ",");
1948  }
1949 
1950  OutStrings.push_back(Args.MakeArgString(Out));
1951 }
1952 
1953 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1954  const ArgList &Args,
1955  std::vector<const char *> &Features) {
1956  // If -march=native, autodetect the feature list.
1957  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1958  if (StringRef(A->getValue()) == "native") {
1959  llvm::StringMap<bool> HostFeatures;
1960  if (llvm::sys::getHostCPUFeatures(HostFeatures))
1961  for (auto &F : HostFeatures)
1962  Features.push_back(
1963  Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1964  }
1965  }
1966 
1967  if (Triple.getArchName() == "x86_64h") {
1968  // x86_64h implies quite a few of the more modern subtarget features
1969  // for Haswell class CPUs, but not all of them. Opt-out of a few.
1970  Features.push_back("-rdrnd");
1971  Features.push_back("-aes");
1972  Features.push_back("-pclmul");
1973  Features.push_back("-rtm");
1974  Features.push_back("-hle");
1975  Features.push_back("-fsgsbase");
1976  }
1977 
1978  const llvm::Triple::ArchType ArchType = Triple.getArch();
1979  // Add features to be compatible with gcc for Android.
1980  if (Triple.isAndroid()) {
1981  if (ArchType == llvm::Triple::x86_64) {
1982  Features.push_back("+sse4.2");
1983  Features.push_back("+popcnt");
1984  } else
1985  Features.push_back("+ssse3");
1986  }
1987 
1988  // Set features according to the -arch flag on MSVC.
1989  if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1990  StringRef Arch = A->getValue();
1991  bool ArchUsed = false;
1992  // First, look for flags that are shared in x86 and x86-64.
1993  if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1994  if (Arch == "AVX" || Arch == "AVX2") {
1995  ArchUsed = true;
1996  Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1997  }
1998  }
1999  // Then, look for x86-specific flags.
2000  if (ArchType == llvm::Triple::x86) {
2001  if (Arch == "IA32") {
2002  ArchUsed = true;
2003  } else if (Arch == "SSE" || Arch == "SSE2") {
2004  ArchUsed = true;
2005  Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2006  }
2007  }
2008  if (!ArchUsed)
2009  D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2010  }
2011 
2012  // Now add any that the user explicitly requested on the command line,
2013  // which may override the defaults.
2014  handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2015 }
2016 
2017 void Clang::AddX86TargetArgs(const ArgList &Args,
2018  ArgStringList &CmdArgs) const {
2019  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2020  Args.hasArg(options::OPT_mkernel) ||
2021  Args.hasArg(options::OPT_fapple_kext))
2022  CmdArgs.push_back("-disable-red-zone");
2023 
2024  // Default to avoid implicit floating-point for kernel/kext code, but allow
2025  // that to be overridden with -mno-soft-float.
2026  bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2027  Args.hasArg(options::OPT_fapple_kext));
2028  if (Arg *A = Args.getLastArg(
2029  options::OPT_msoft_float, options::OPT_mno_soft_float,
2030  options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2031  const Option &O = A->getOption();
2032  NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2033  O.matches(options::OPT_msoft_float));
2034  }
2035  if (NoImplicitFloat)
2036  CmdArgs.push_back("-no-implicit-float");
2037 
2038  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2039  StringRef Value = A->getValue();
2040  if (Value == "intel" || Value == "att") {
2041  CmdArgs.push_back("-mllvm");
2042  CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2043  } else {
2044  getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2045  << A->getOption().getName() << Value;
2046  }
2047  }
2048 }
2049 
2050 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2051  ArgStringList &CmdArgs) const {
2052  CmdArgs.push_back("-mqdsp6-compat");
2053  CmdArgs.push_back("-Wreturn-type");
2054 
2056  std::string N = llvm::utostr(G.getValue());
2057  std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2058  CmdArgs.push_back("-mllvm");
2059  CmdArgs.push_back(Args.MakeArgString(Opt));
2060  }
2061 
2062  if (!Args.hasArg(options::OPT_fno_short_enums))
2063  CmdArgs.push_back("-fshort-enums");
2064  if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2065  CmdArgs.push_back("-mllvm");
2066  CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2067  }
2068  CmdArgs.push_back("-mllvm");
2069  CmdArgs.push_back("-machine-sink-split=0");
2070 }
2071 
2072 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2073  ArgStringList &CmdArgs) const {
2074  // Default to "hidden" visibility.
2075  if (!Args.hasArg(options::OPT_fvisibility_EQ,
2076  options::OPT_fvisibility_ms_compat)) {
2077  CmdArgs.push_back("-fvisibility");
2078  CmdArgs.push_back("hidden");
2079  }
2080 }
2081 
2082 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2083 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2084  std::vector<const char *> &Features) {
2086  text.split(Split, StringRef("+"), -1, false);
2087 
2088  for (StringRef Feature : Split) {
2089  const char *result = llvm::StringSwitch<const char *>(Feature)
2090  .Case("fp", "+fp-armv8")
2091  .Case("simd", "+neon")
2092  .Case("crc", "+crc")
2093  .Case("crypto", "+crypto")
2094  .Case("fp16", "+fullfp16")
2095  .Case("profile", "+spe")
2096  .Case("nofp", "-fp-armv8")
2097  .Case("nosimd", "-neon")
2098  .Case("nocrc", "-crc")
2099  .Case("nocrypto", "-crypto")
2100  .Case("nofp16", "-fullfp16")
2101  .Case("noprofile", "-spe")
2102  .Default(nullptr);
2103  if (result)
2104  Features.push_back(result);
2105  else if (Feature == "neon" || Feature == "noneon")
2106  D.Diag(diag::err_drv_no_neon_modifier);
2107  else
2108  return false;
2109  }
2110  return true;
2111 }
2112 
2113 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2114 // decode CPU and feature.
2115 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2116  std::vector<const char *> &Features) {
2117  std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2118  CPU = Split.first;
2119  if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
2120  CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1") {
2121  Features.push_back("+neon");
2122  Features.push_back("+crc");
2123  Features.push_back("+crypto");
2124  } else if (CPU == "generic") {
2125  Features.push_back("+neon");
2126  } else {
2127  return false;
2128  }
2129 
2130  if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2131  return false;
2132 
2133  return true;
2134 }
2135 
2136 static bool
2137 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2138  const ArgList &Args,
2139  std::vector<const char *> &Features) {
2140  std::string MarchLowerCase = March.lower();
2141  std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2142 
2143  if (Split.first == "armv8-a" || Split.first == "armv8a") {
2144  // ok, no additional features.
2145  } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2146  Features.push_back("+v8.1a");
2147  } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2148  Features.push_back("+v8.2a");
2149  } else {
2150  return false;
2151  }
2152 
2153  if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2154  return false;
2155 
2156  return true;
2157 }
2158 
2159 static bool
2160 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2161  const ArgList &Args,
2162  std::vector<const char *> &Features) {
2163  StringRef CPU;
2164  std::string McpuLowerCase = Mcpu.lower();
2165  if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2166  return false;
2167 
2168  return true;
2169 }
2170 
2171 static bool
2173  const ArgList &Args,
2174  std::vector<const char *> &Features) {
2175  std::string MtuneLowerCase = Mtune.lower();
2176  // Handle CPU name is 'native'.
2177  if (MtuneLowerCase == "native")
2178  MtuneLowerCase = llvm::sys::getHostCPUName();
2179  if (MtuneLowerCase == "cyclone") {
2180  Features.push_back("+zcm");
2181  Features.push_back("+zcz");
2182  }
2183  return true;
2184 }
2185 
2186 static bool
2188  const ArgList &Args,
2189  std::vector<const char *> &Features) {
2190  StringRef CPU;
2191  std::vector<const char *> DecodedFeature;
2192  std::string McpuLowerCase = Mcpu.lower();
2193  if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2194  return false;
2195 
2196  return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2197 }
2198 
2199 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2200  std::vector<const char *> &Features) {
2201  Arg *A;
2202  bool success = true;
2203  // Enable NEON by default.
2204  Features.push_back("+neon");
2205  if ((A = Args.getLastArg(options::OPT_march_EQ)))
2206  success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2207  else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2208  success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2209  else if (Args.hasArg(options::OPT_arch))
2210  success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2211  Features);
2212 
2213  if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2214  success =
2215  getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2216  else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2217  success =
2218  getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2219  else if (Args.hasArg(options::OPT_arch))
2221  Args, Features);
2222 
2223  if (!success)
2224  D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2225 
2226  if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2227  Features.push_back("-fp-armv8");
2228  Features.push_back("-crypto");
2229  Features.push_back("-neon");
2230  }
2231 
2232  // En/disable crc
2233  if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2234  if (A->getOption().matches(options::OPT_mcrc))
2235  Features.push_back("+crc");
2236  else
2237  Features.push_back("-crc");
2238  }
2239 
2240  if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2241  options::OPT_munaligned_access))
2242  if (A->getOption().matches(options::OPT_mno_unaligned_access))
2243  Features.push_back("+strict-align");
2244 
2245  if (Args.hasArg(options::OPT_ffixed_x18))
2246  Features.push_back("+reserve-x18");
2247 }
2248 
2249 static void getHexagonTargetFeatures(const ArgList &Args,
2250  std::vector<const char *> &Features) {
2251  bool HasHVX = false, HasHVXD = false;
2252 
2253  // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2254  // doing dependent option handling here rather than in initFeatureMap or a
2255  // similar handler.
2256  for (auto &A : Args) {
2257  auto &Opt = A->getOption();
2258  if (Opt.matches(options::OPT_mhexagon_hvx))
2259  HasHVX = true;
2260  else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2261  HasHVXD = HasHVX = false;
2262  else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2263  HasHVXD = HasHVX = true;
2264  else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2265  HasHVXD = false;
2266  else
2267  continue;
2268  A->claim();
2269  }
2270 
2271  Features.push_back(HasHVX ? "+hvx" : "-hvx");
2272  Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2273 }
2274 
2275 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2276  std::vector<const char *> &Features) {
2277  handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2278 }
2279 
2280 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2281  const ArgList &Args, ArgStringList &CmdArgs,
2282  bool ForAS) {
2283  const Driver &D = TC.getDriver();
2284  std::vector<const char *> Features;
2285  switch (Triple.getArch()) {
2286  default:
2287  break;
2288  case llvm::Triple::mips:
2289  case llvm::Triple::mipsel:
2290  case llvm::Triple::mips64:
2291  case llvm::Triple::mips64el:
2292  getMIPSTargetFeatures(D, Triple, Args, Features);
2293  break;
2294 
2295  case llvm::Triple::arm:
2296  case llvm::Triple::armeb:
2297  case llvm::Triple::thumb:
2298  case llvm::Triple::thumbeb:
2299  getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2300  break;
2301 
2302  case llvm::Triple::ppc:
2303  case llvm::Triple::ppc64:
2304  case llvm::Triple::ppc64le:
2305  getPPCTargetFeatures(D, Triple, Args, Features);
2306  break;
2307  case llvm::Triple::systemz:
2308  getSystemZTargetFeatures(Args, Features);
2309  break;
2310  case llvm::Triple::aarch64:
2311  case llvm::Triple::aarch64_be:
2312  getAArch64TargetFeatures(D, Args, Features);
2313  break;
2314  case llvm::Triple::x86:
2315  case llvm::Triple::x86_64:
2316  getX86TargetFeatures(D, Triple, Args, Features);
2317  break;
2318  case llvm::Triple::hexagon:
2319  getHexagonTargetFeatures(Args, Features);
2320  break;
2321  case llvm::Triple::wasm32:
2322  case llvm::Triple::wasm64:
2323  getWebAssemblyTargetFeatures(Args, Features);
2324  break;
2325  }
2326 
2327  // Find the last of each feature.
2328  llvm::StringMap<unsigned> LastOpt;
2329  for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2330  const char *Name = Features[I];
2331  assert(Name[0] == '-' || Name[0] == '+');
2332  LastOpt[Name + 1] = I;
2333  }
2334 
2335  for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2336  // If this feature was overridden, ignore it.
2337  const char *Name = Features[I];
2338  llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2339  assert(LastI != LastOpt.end());
2340  unsigned Last = LastI->second;
2341  if (Last != I)
2342  continue;
2343 
2344  CmdArgs.push_back("-target-feature");
2345  CmdArgs.push_back(Name);
2346  }
2347 }
2348 
2349 static bool
2351  const llvm::Triple &Triple) {
2352  // We use the zero-cost exception tables for Objective-C if the non-fragile
2353  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2354  // later.
2355  if (runtime.isNonFragile())
2356  return true;
2357 
2358  if (!Triple.isMacOSX())
2359  return false;
2360 
2361  return (!Triple.isMacOSXVersionLT(10, 5) &&
2362  (Triple.getArch() == llvm::Triple::x86_64 ||
2363  Triple.getArch() == llvm::Triple::arm));
2364 }
2365 
2366 /// Adds exception related arguments to the driver command arguments. There's a
2367 /// master flag, -fexceptions and also language specific flags to enable/disable
2368 /// C++ and Objective-C exceptions. This makes it possible to for example
2369 /// disable C++ exceptions but enable Objective-C exceptions.
2370 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2371  const ToolChain &TC, bool KernelOrKext,
2372  const ObjCRuntime &objcRuntime,
2373  ArgStringList &CmdArgs) {
2374  const Driver &D = TC.getDriver();
2375  const llvm::Triple &Triple = TC.getTriple();
2376 
2377  if (KernelOrKext) {
2378  // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2379  // arguments now to avoid warnings about unused arguments.
2380  Args.ClaimAllArgs(options::OPT_fexceptions);
2381  Args.ClaimAllArgs(options::OPT_fno_exceptions);
2382  Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2383  Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2384  Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2385  Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2386  return;
2387  }
2388 
2389  // See if the user explicitly enabled exceptions.
2390  bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2391  false);
2392 
2393  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2394  // is not necessarily sensible, but follows GCC.
2395  if (types::isObjC(InputType) &&
2396  Args.hasFlag(options::OPT_fobjc_exceptions,
2397  options::OPT_fno_objc_exceptions, true)) {
2398  CmdArgs.push_back("-fobjc-exceptions");
2399 
2400  EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2401  }
2402 
2403  if (types::isCXX(InputType)) {
2404  // Disable C++ EH by default on XCore, PS4, and MSVC.
2405  // FIXME: Remove MSVC from this list once things work.
2406  bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2407  !Triple.isPS4CPU() &&
2408  !Triple.isWindowsMSVCEnvironment();
2409  Arg *ExceptionArg = Args.getLastArg(
2410  options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2411  options::OPT_fexceptions, options::OPT_fno_exceptions);
2412  if (ExceptionArg)
2413  CXXExceptionsEnabled =
2414  ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2415  ExceptionArg->getOption().matches(options::OPT_fexceptions);
2416 
2417  if (CXXExceptionsEnabled) {
2418  if (Triple.isPS4CPU()) {
2419  ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2420  assert(ExceptionArg &&
2421  "On the PS4 exceptions should only be enabled if passing "
2422  "an argument");
2423  if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2424  const Arg *RTTIArg = TC.getRTTIArg();
2425  assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2426  D.Diag(diag::err_drv_argument_not_allowed_with)
2427  << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2428  } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2429  D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2430  } else
2432 
2433  CmdArgs.push_back("-fcxx-exceptions");
2434 
2435  EH = true;
2436  }
2437  }
2438 
2439  if (EH)
2440  CmdArgs.push_back("-fexceptions");
2441 }
2442 
2443 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2444  bool Default = true;
2445  if (TC.getTriple().isOSDarwin()) {
2446  // The native darwin assembler doesn't support the linker_option directives,
2447  // so we disable them if we think the .s file will be passed to it.
2448  Default = TC.useIntegratedAs();
2449  }
2450  return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2451  Default);
2452 }
2453 
2454 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2455  const ToolChain &TC) {
2456  bool UseDwarfDirectory =
2457  Args.hasFlag(options::OPT_fdwarf_directory_asm,
2458  options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2459  return !UseDwarfDirectory;
2460 }
2461 
2462 /// \brief Check whether the given input tree contains any compilation actions.
2463 static bool ContainsCompileAction(const Action *A) {
2464  if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2465  return true;
2466 
2467  for (const auto &Act : *A)
2468  if (ContainsCompileAction(Act))
2469  return true;
2470 
2471  return false;
2472 }
2473 
2474 /// \brief Check if -relax-all should be passed to the internal assembler.
2475 /// This is done by default when compiling non-assembler source with -O0.
2476 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2477  bool RelaxDefault = true;
2478 
2479  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2480  RelaxDefault = A->getOption().matches(options::OPT_O0);
2481 
2482  if (RelaxDefault) {
2483  RelaxDefault = false;
2484  for (const auto &Act : C.getActions()) {
2485  if (ContainsCompileAction(Act)) {
2486  RelaxDefault = true;
2487  break;
2488  }
2489  }
2490  }
2491 
2492  return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2493  RelaxDefault);
2494 }
2495 
2496 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2497 // to the corresponding DebugInfoKind.
2499  assert(A.getOption().matches(options::OPT_gN_Group) &&
2500  "Not a -g option that specifies a debug-info level");
2501  if (A.getOption().matches(options::OPT_g0) ||
2502  A.getOption().matches(options::OPT_ggdb0))
2504  if (A.getOption().matches(options::OPT_gline_tables_only) ||
2505  A.getOption().matches(options::OPT_ggdb1))
2508 }
2509 
2510 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2511 // on mismatch. The StringRef input (rather than an Arg) allows
2512 // for use by the "-Xassembler" option parser.
2513 static unsigned DwarfVersionNum(StringRef ArgValue) {
2514  return llvm::StringSwitch<unsigned>(ArgValue)
2515  .Case("-gdwarf-2", 2)
2516  .Case("-gdwarf-3", 3)
2517  .Case("-gdwarf-4", 4)
2518  .Case("-gdwarf-5", 5)
2519  .Default(0);
2520 }
2521 
2522 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2523  CodeGenOptions::DebugInfoKind DebugInfoKind,
2524  unsigned DwarfVersion,
2525  llvm::DebuggerKind DebuggerTuning) {
2526  switch (DebugInfoKind) {
2528  CmdArgs.push_back("-debug-info-kind=line-tables-only");
2529  break;
2531  CmdArgs.push_back("-debug-info-kind=limited");
2532  break;
2534  CmdArgs.push_back("-debug-info-kind=standalone");
2535  break;
2536  default:
2537  break;
2538  }
2539  if (DwarfVersion > 0)
2540  CmdArgs.push_back(
2541  Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2542  switch (DebuggerTuning) {
2543  case llvm::DebuggerKind::GDB:
2544  CmdArgs.push_back("-debugger-tuning=gdb");
2545  break;
2546  case llvm::DebuggerKind::LLDB:
2547  CmdArgs.push_back("-debugger-tuning=lldb");
2548  break;
2549  case llvm::DebuggerKind::SCE:
2550  CmdArgs.push_back("-debugger-tuning=sce");
2551  break;
2552  default:
2553  break;
2554  }
2555 }
2556 
2558  const ArgList &Args,
2559  ArgStringList &CmdArgs,
2560  const Driver &D) {
2561  if (UseRelaxAll(C, Args))
2562  CmdArgs.push_back("-mrelax-all");
2563 
2564  // Only default to -mincremental-linker-compatible if we think we are
2565  // targeting the MSVC linker.
2566  bool DefaultIncrementalLinkerCompatible =
2567  C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2568  if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2569  options::OPT_mno_incremental_linker_compatible,
2570  DefaultIncrementalLinkerCompatible))
2571  CmdArgs.push_back("-mincremental-linker-compatible");
2572 
2573  // When passing -I arguments to the assembler we sometimes need to
2574  // unconditionally take the next argument. For example, when parsing
2575  // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2576  // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2577  // arg after parsing the '-I' arg.
2578  bool TakeNextArg = false;
2579 
2580  // When using an integrated assembler, translate -Wa, and -Xassembler
2581  // options.
2582  bool CompressDebugSections = false;
2583  for (const Arg *A :
2584  Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2585  A->claim();
2586 
2587  for (StringRef Value : A->getValues()) {
2588  if (TakeNextArg) {
2589  CmdArgs.push_back(Value.data());
2590  TakeNextArg = false;
2591  continue;
2592  }
2593 
2594  switch (C.getDefaultToolChain().getArch()) {
2595  default:
2596  break;
2597  case llvm::Triple::mips:
2598  case llvm::Triple::mipsel:
2599  case llvm::Triple::mips64:
2600  case llvm::Triple::mips64el:
2601  if (Value == "--trap") {
2602  CmdArgs.push_back("-target-feature");
2603  CmdArgs.push_back("+use-tcc-in-div");
2604  continue;
2605  }
2606  if (Value == "--break") {
2607  CmdArgs.push_back("-target-feature");
2608  CmdArgs.push_back("-use-tcc-in-div");
2609  continue;
2610  }
2611  if (Value.startswith("-msoft-float")) {
2612  CmdArgs.push_back("-target-feature");
2613  CmdArgs.push_back("+soft-float");
2614  continue;
2615  }
2616  if (Value.startswith("-mhard-float")) {
2617  CmdArgs.push_back("-target-feature");
2618  CmdArgs.push_back("-soft-float");
2619  continue;
2620  }
2621  break;
2622  }
2623 
2624  if (Value == "-force_cpusubtype_ALL") {
2625  // Do nothing, this is the default and we don't support anything else.
2626  } else if (Value == "-L") {
2627  CmdArgs.push_back("-msave-temp-labels");
2628  } else if (Value == "--fatal-warnings") {
2629  CmdArgs.push_back("-massembler-fatal-warnings");
2630  } else if (Value == "--noexecstack") {
2631  CmdArgs.push_back("-mnoexecstack");
2632  } else if (Value == "-compress-debug-sections" ||
2633  Value == "--compress-debug-sections") {
2634  CompressDebugSections = true;
2635  } else if (Value == "-nocompress-debug-sections" ||
2636  Value == "--nocompress-debug-sections") {
2637  CompressDebugSections = false;
2638  } else if (Value.startswith("-I")) {
2639  CmdArgs.push_back(Value.data());
2640  // We need to consume the next argument if the current arg is a plain
2641  // -I. The next arg will be the include directory.
2642  if (Value == "-I")
2643  TakeNextArg = true;
2644  } else if (Value.startswith("-gdwarf-")) {
2645  // "-gdwarf-N" options are not cc1as options.
2646  unsigned DwarfVersion = DwarfVersionNum(Value);
2647  if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2648  CmdArgs.push_back(Value.data());
2649  } else {
2651  Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion,
2652  llvm::DebuggerKind::Default);
2653  }
2654  } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2655  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2656  // Do nothing, we'll validate it later.
2657  } else {
2658  D.Diag(diag::err_drv_unsupported_option_argument)
2659  << A->getOption().getName() << Value;
2660  }
2661  }
2662  }
2663  if (CompressDebugSections) {
2664  if (llvm::zlib::isAvailable())
2665  CmdArgs.push_back("-compress-debug-sections");
2666  else
2667  D.Diag(diag::warn_debug_compression_unavailable);
2668  }
2669 }
2670 
2671 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2672 // FIXME: Make sure we can also emit shared objects if they're requested
2673 // and available, check for possible errors, etc.
2674 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2675  ArgStringList &CmdArgs) {
2676  CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2677 }
2678 
2679 namespace {
2681  /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2682  /// without knowing what runtime to target.
2683  OMPRT_Unknown,
2684 
2685  /// The LLVM OpenMP runtime. When completed and integrated, this will become
2686  /// the default for Clang.
2687  OMPRT_OMP,
2688 
2689  /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2690  /// this runtime but can swallow the pragmas, and find and link against the
2691  /// runtime library itself.
2692  OMPRT_GOMP,
2693 
2694  /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2695  /// OpenMP runtime. We support this mode for users with existing dependencies
2696  /// on this runtime library name.
2697  OMPRT_IOMP5
2698 };
2699 }
2700 
2701 /// Compute the desired OpenMP runtime from the flag provided.
2703  const ArgList &Args) {
2704  StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2705 
2706  const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2707  if (A)
2708  RuntimeName = A->getValue();
2709 
2710  auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2711  .Case("libomp", OMPRT_OMP)
2712  .Case("libgomp", OMPRT_GOMP)
2713  .Case("libiomp5", OMPRT_IOMP5)
2714  .Default(OMPRT_Unknown);
2715 
2716  if (RT == OMPRT_Unknown) {
2717  if (A)
2718  TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2719  << A->getOption().getName() << A->getValue();
2720  else
2721  // FIXME: We could use a nicer diagnostic here.
2722  TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2723  }
2724 
2725  return RT;
2726 }
2727 
2728 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
2729  const ArgList &Args) {
2730  if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
2731  options::OPT_fno_openmp, false))
2732  return;
2733 
2734  switch (getOpenMPRuntime(TC, Args)) {
2735  case OMPRT_OMP:
2736  CmdArgs.push_back("-lomp");
2737  break;
2738  case OMPRT_GOMP:
2739  CmdArgs.push_back("-lgomp");
2740  break;
2741  case OMPRT_IOMP5:
2742  CmdArgs.push_back("-liomp5");
2743  break;
2744  case OMPRT_Unknown:
2745  // Already diagnosed.
2746  break;
2747  }
2748 }
2749 
2750 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2751  ArgStringList &CmdArgs, StringRef Sanitizer,
2752  bool IsShared) {
2753  // Static runtimes must be forced into executable, so we wrap them in
2754  // whole-archive.
2755  if (!IsShared) CmdArgs.push_back("-whole-archive");
2756  CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
2757  if (!IsShared) CmdArgs.push_back("-no-whole-archive");
2758 }
2759 
2760 // Tries to use a file with the list of dynamic symbols that need to be exported
2761 // from the runtime library. Returns true if the file was found.
2762 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2763  ArgStringList &CmdArgs,
2764  StringRef Sanitizer) {
2765  SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
2766  if (llvm::sys::fs::exists(SanRT + ".syms")) {
2767  CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2768  return true;
2769  }
2770  return false;
2771 }
2772 
2773 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2774  ArgStringList &CmdArgs) {
2775  // Force linking against the system libraries sanitizers depends on
2776  // (see PR15823 why this is necessary).
2777  CmdArgs.push_back("--no-as-needed");
2778  CmdArgs.push_back("-lpthread");
2779  CmdArgs.push_back("-lrt");
2780  CmdArgs.push_back("-lm");
2781  // There's no libdl on FreeBSD.
2782  if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2783  CmdArgs.push_back("-ldl");
2784 }
2785 
2786 static void
2787 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2788  SmallVectorImpl<StringRef> &SharedRuntimes,
2789  SmallVectorImpl<StringRef> &StaticRuntimes,
2790  SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2791  const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2792  // Collect shared runtimes.
2793  if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2794  SharedRuntimes.push_back("asan");
2795  }
2796 
2797  // Collect static runtimes.
2798  if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
2799  // Don't link static runtimes into DSOs or if compiling for Android.
2800  return;
2801  }
2802  if (SanArgs.needsAsanRt()) {
2803  if (SanArgs.needsSharedAsanRt()) {
2804  HelperStaticRuntimes.push_back("asan-preinit");
2805  } else {
2806  StaticRuntimes.push_back("asan");
2807  if (SanArgs.linkCXXRuntimes())
2808  StaticRuntimes.push_back("asan_cxx");
2809  }
2810  }
2811  if (SanArgs.needsDfsanRt())
2812  StaticRuntimes.push_back("dfsan");
2813  if (SanArgs.needsLsanRt())
2814  StaticRuntimes.push_back("lsan");
2815  if (SanArgs.needsMsanRt()) {
2816  StaticRuntimes.push_back("msan");
2817  if (SanArgs.linkCXXRuntimes())
2818  StaticRuntimes.push_back("msan_cxx");
2819  }
2820  if (SanArgs.needsTsanRt()) {
2821  StaticRuntimes.push_back("tsan");
2822  if (SanArgs.linkCXXRuntimes())
2823  StaticRuntimes.push_back("tsan_cxx");
2824  }
2825  if (SanArgs.needsUbsanRt()) {
2826  StaticRuntimes.push_back("ubsan_standalone");
2827  if (SanArgs.linkCXXRuntimes())
2828  StaticRuntimes.push_back("ubsan_standalone_cxx");
2829  }
2830  if (SanArgs.needsSafeStackRt())
2831  StaticRuntimes.push_back("safestack");
2832  if (SanArgs.needsCfiRt())
2833  StaticRuntimes.push_back("cfi");
2834  if (SanArgs.needsCfiDiagRt())
2835  StaticRuntimes.push_back("cfi_diag");
2836 }
2837 
2838 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2839 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2840 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2841  ArgStringList &CmdArgs) {
2842  SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2843  HelperStaticRuntimes;
2844  collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2845  HelperStaticRuntimes);
2846  for (auto RT : SharedRuntimes)
2847  addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2848  for (auto RT : HelperStaticRuntimes)
2849  addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2850  bool AddExportDynamic = false;
2851  for (auto RT : StaticRuntimes) {
2852  addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2853  AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2854  }
2855  // If there is a static runtime with no dynamic list, force all the symbols
2856  // to be dynamic to be sure we export sanitizer interface functions.
2857  if (AddExportDynamic)
2858  CmdArgs.push_back("-export-dynamic");
2859  return !StaticRuntimes.empty();
2860 }
2861 
2862 static bool areOptimizationsEnabled(const ArgList &Args) {
2863  // Find the last -O arg and see if it is non-zero.
2864  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2865  return !A->getOption().matches(options::OPT_O0);
2866  // Defaults to -O0.
2867  return false;
2868 }
2869 
2870 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2871  const llvm::Triple &Triple) {
2872  switch (Triple.getArch()) {
2873  case llvm::Triple::xcore:
2874  case llvm::Triple::wasm32:
2875  case llvm::Triple::wasm64:
2876  // XCore never wants frame pointers, regardless of OS.
2877  // WebAssembly never wants frame pointers.
2878  return false;
2879  default:
2880  break;
2881  }
2882 
2883  if (Triple.isOSLinux()) {
2884  switch (Triple.getArch()) {
2885  // Don't use a frame pointer on linux if optimizing for certain targets.
2886  case llvm::Triple::mips64:
2887  case llvm::Triple::mips64el:
2888  case llvm::Triple::mips:
2889  case llvm::Triple::mipsel:
2890  case llvm::Triple::systemz:
2891  case llvm::Triple::x86:
2892  case llvm::Triple::x86_64:
2893  return !areOptimizationsEnabled(Args);
2894  default:
2895  return true;
2896  }
2897  }
2898 
2899  if (Triple.isOSWindows()) {
2900  switch (Triple.getArch()) {
2901  case llvm::Triple::x86:
2902  return !areOptimizationsEnabled(Args);
2903  case llvm::Triple::arm:
2904  case llvm::Triple::thumb:
2905  // Windows on ARM builds with FPO disabled to aid fast stack walking
2906  return true;
2907  default:
2908  // All other supported Windows ISAs use xdata unwind information, so frame
2909  // pointers are not generally useful.
2910  return false;
2911  }
2912  }
2913 
2914  return true;
2915 }
2916 
2917 static bool shouldUseFramePointer(const ArgList &Args,
2918  const llvm::Triple &Triple) {
2919  if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2920  options::OPT_fomit_frame_pointer))
2921  return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2922  if (Args.hasArg(options::OPT_pg))
2923  return true;
2924 
2925  return shouldUseFramePointerForTarget(Args, Triple);
2926 }
2927 
2928 static bool shouldUseLeafFramePointer(const ArgList &Args,
2929  const llvm::Triple &Triple) {
2930  if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2931  options::OPT_momit_leaf_frame_pointer))
2932  return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2933  if (Args.hasArg(options::OPT_pg))
2934  return true;
2935 
2936  if (Triple.isPS4CPU())
2937  return false;
2938 
2939  return shouldUseFramePointerForTarget(Args, Triple);
2940 }
2941 
2942 /// Add a CC1 option to specify the debug compilation directory.
2943 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2944  SmallString<128> cwd;
2945  if (!llvm::sys::fs::current_path(cwd)) {
2946  CmdArgs.push_back("-fdebug-compilation-dir");
2947  CmdArgs.push_back(Args.MakeArgString(cwd));
2948  }
2949 }
2950 
2951 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2952  Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2953  if (FinalOutput && Args.hasArg(options::OPT_c)) {
2954  SmallString<128> T(FinalOutput->getValue());
2955  llvm::sys::path::replace_extension(T, "dwo");
2956  return Args.MakeArgString(T);
2957  } else {
2958  // Use the compilation dir.
2959  SmallString<128> T(
2960  Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2961  SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2962  llvm::sys::path::replace_extension(F, "dwo");
2963  T += F;
2964  return Args.MakeArgString(F);
2965  }
2966 }
2967 
2968 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2969  const JobAction &JA, const ArgList &Args,
2970  const InputInfo &Output, const char *OutFile) {
2971  ArgStringList ExtractArgs;
2972  ExtractArgs.push_back("--extract-dwo");
2973 
2974  ArgStringList StripArgs;
2975  StripArgs.push_back("--strip-dwo");
2976 
2977  // Grabbing the output of the earlier compile step.
2978  StripArgs.push_back(Output.getFilename());
2979  ExtractArgs.push_back(Output.getFilename());
2980  ExtractArgs.push_back(OutFile);
2981 
2982  const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2983  InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
2984 
2985  // First extract the dwo sections.
2986  C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
2987 
2988  // Then remove them from the original .o file.
2989  C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
2990 }
2991 
2992 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2993 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2994 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2995  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2996  if (A->getOption().matches(options::OPT_O4) ||
2997  A->getOption().matches(options::OPT_Ofast))
2998  return true;
2999 
3000  if (A->getOption().matches(options::OPT_O0))
3001  return false;
3002 
3003  assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3004 
3005  // Vectorize -Os.
3006  StringRef S(A->getValue());
3007  if (S == "s")
3008  return true;
3009 
3010  // Don't vectorize -Oz, unless it's the slp vectorizer.
3011  if (S == "z")
3012  return isSlpVec;
3013 
3014  unsigned OptLevel = 0;
3015  if (S.getAsInteger(10, OptLevel))
3016  return false;
3017 
3018  return OptLevel > 1;
3019  }
3020 
3021  return false;
3022 }
3023 
3024 /// Add -x lang to \p CmdArgs for \p Input.
3025 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3026  ArgStringList &CmdArgs) {
3027  // When using -verify-pch, we don't want to provide the type
3028  // 'precompiled-header' if it was inferred from the file extension
3029  if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3030  return;
3031 
3032  CmdArgs.push_back("-x");
3033  if (Args.hasArg(options::OPT_rewrite_objc))
3034  CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3035  else
3036  CmdArgs.push_back(types::getTypeName(Input.getType()));
3037 }
3038 
3039 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3040  if (Version < 100)
3041  return VersionTuple(Version);
3042 
3043  if (Version < 10000)
3044  return VersionTuple(Version / 100, Version % 100);
3045 
3046  unsigned Build = 0, Factor = 1;
3047  for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3048  Build = Build + (Version % 10) * Factor;
3049  return VersionTuple(Version / 100, Version % 100, Build);
3050 }
3051 
3052 // Claim options we don't want to warn if they are unused. We do this for
3053 // options that build systems might add but are unused when assembling or only
3054 // running the preprocessor for example.
3055 static void claimNoWarnArgs(const ArgList &Args) {
3056  // Don't warn about unused -f(no-)?lto. This can happen when we're
3057  // preprocessing, precompiling or assembling.
3058  Args.ClaimAllArgs(options::OPT_flto_EQ);
3059  Args.ClaimAllArgs(options::OPT_flto);
3060  Args.ClaimAllArgs(options::OPT_fno_lto);
3061 }
3062 
3064 #ifdef LLVM_ON_UNIX
3065  const char *Username = getenv("LOGNAME");
3066 #else
3067  const char *Username = getenv("USERNAME");
3068 #endif
3069  if (Username) {
3070  // Validate that LoginName can be used in a path, and get its length.
3071  size_t Len = 0;
3072  for (const char *P = Username; *P; ++P, ++Len) {
3073  if (!isAlphanumeric(*P) && *P != '_') {
3074  Username = nullptr;
3075  break;
3076  }
3077  }
3078 
3079  if (Username && Len > 0) {
3080  Result.append(Username, Username + Len);
3081  return;
3082  }
3083  }
3084 
3085 // Fallback to user id.
3086 #ifdef LLVM_ON_UNIX
3087  std::string UID = llvm::utostr(getuid());
3088 #else
3089  // FIXME: Windows seems to have an 'SID' that might work.
3090  std::string UID = "9999";
3091 #endif
3092  Result.append(UID.begin(), UID.end());
3093 }
3094 
3096  const llvm::Triple &Triple,
3097  const llvm::opt::ArgList &Args,
3098  bool IsWindowsMSVC) {
3099  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3100  IsWindowsMSVC) ||
3101  Args.hasArg(options::OPT_fmsc_version) ||
3102  Args.hasArg(options::OPT_fms_compatibility_version)) {
3103  const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3104  const Arg *MSCompatibilityVersion =
3105  Args.getLastArg(options::OPT_fms_compatibility_version);
3106 
3107  if (MSCVersion && MSCompatibilityVersion) {
3108  if (D)
3109  D->Diag(diag::err_drv_argument_not_allowed_with)
3110  << MSCVersion->getAsString(Args)
3111  << MSCompatibilityVersion->getAsString(Args);
3112  return VersionTuple();
3113  }
3114 
3115  if (MSCompatibilityVersion) {
3116  VersionTuple MSVT;
3117  if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3118  D->Diag(diag::err_drv_invalid_value)
3119  << MSCompatibilityVersion->getAsString(Args)
3120  << MSCompatibilityVersion->getValue();
3121  return MSVT;
3122  }
3123 
3124  if (MSCVersion) {
3125  unsigned Version = 0;
3126  if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3127  D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3128  << MSCVersion->getValue();
3129  return getMSCompatibilityVersion(Version);
3130  }
3131 
3132  unsigned Major, Minor, Micro;
3133  Triple.getEnvironmentVersion(Major, Minor, Micro);
3134  if (Major || Minor || Micro)
3135  return VersionTuple(Major, Minor, Micro);
3136 
3137  return VersionTuple(18);
3138  }
3139  return VersionTuple();
3140 }
3141 
3142 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3143  const InputInfo &Output, const ArgList &Args,
3144  ArgStringList &CmdArgs) {
3145  auto *ProfileGenerateArg = Args.getLastArg(
3146  options::OPT_fprofile_instr_generate,
3147  options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
3148  options::OPT_fprofile_generate_EQ,
3149  options::OPT_fno_profile_instr_generate);
3150  if (ProfileGenerateArg &&
3151  ProfileGenerateArg->getOption().matches(
3152  options::OPT_fno_profile_instr_generate))
3153  ProfileGenerateArg = nullptr;
3154 
3155  auto *ProfileUseArg = Args.getLastArg(
3156  options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3157  options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3158  options::OPT_fno_profile_instr_use);
3159  if (ProfileUseArg &&
3160  ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3161  ProfileUseArg = nullptr;
3162 
3163  if (ProfileGenerateArg && ProfileUseArg)
3164  D.Diag(diag::err_drv_argument_not_allowed_with)
3165  << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3166 
3167  if (ProfileGenerateArg) {
3168  if (ProfileGenerateArg->getOption().matches(
3169  options::OPT_fprofile_instr_generate_EQ))
3170  ProfileGenerateArg->render(Args, CmdArgs);
3171  else if (ProfileGenerateArg->getOption().matches(
3172  options::OPT_fprofile_generate_EQ)) {
3173  SmallString<128> Path(ProfileGenerateArg->getValue());
3174  llvm::sys::path::append(Path, "default.profraw");
3175  CmdArgs.push_back(
3176  Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
3177  } else
3178  Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3179  }
3180 
3181  if (ProfileUseArg) {
3182  if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3183  ProfileUseArg->render(Args, CmdArgs);
3184  else if ((ProfileUseArg->getOption().matches(
3185  options::OPT_fprofile_use_EQ) ||
3186  ProfileUseArg->getOption().matches(
3187  options::OPT_fprofile_instr_use))) {
3188  SmallString<128> Path(
3189  ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3190  if (Path.empty() || llvm::sys::fs::is_directory(Path))
3191  llvm::sys::path::append(Path, "default.profdata");
3192  CmdArgs.push_back(
3193  Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
3194  }
3195  }
3196 
3197  if (Args.hasArg(options::OPT_ftest_coverage) ||
3198  Args.hasArg(options::OPT_coverage))
3199  CmdArgs.push_back("-femit-coverage-notes");
3200  if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3201  false) ||
3202  Args.hasArg(options::OPT_coverage))
3203  CmdArgs.push_back("-femit-coverage-data");
3204 
3205  if (Args.hasFlag(options::OPT_fcoverage_mapping,
3206  options::OPT_fno_coverage_mapping, false) &&
3207  !ProfileGenerateArg)
3208  D.Diag(diag::err_drv_argument_only_allowed_with)
3209  << "-fcoverage-mapping"
3210  << "-fprofile-instr-generate";
3211 
3212  if (Args.hasFlag(options::OPT_fcoverage_mapping,
3213  options::OPT_fno_coverage_mapping, false))
3214  CmdArgs.push_back("-fcoverage-mapping");
3215 
3216  if (C.getArgs().hasArg(options::OPT_c) ||
3217  C.getArgs().hasArg(options::OPT_S)) {
3218  if (Output.isFilename()) {
3219  CmdArgs.push_back("-coverage-file");
3220  SmallString<128> CoverageFilename;
3221  if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3222  CoverageFilename = FinalOutput->getValue();
3223  } else {
3224  CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3225  }
3226  if (llvm::sys::path::is_relative(CoverageFilename)) {
3227  SmallString<128> Pwd;
3228  if (!llvm::sys::fs::current_path(Pwd)) {
3229  llvm::sys::path::append(Pwd, CoverageFilename);
3230  CoverageFilename.swap(Pwd);
3231  }
3232  }
3233  CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3234  }
3235  }
3236 }
3237 
3238 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3239  ArgStringList &CmdArgs) {
3240  if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3241  false) ||
3242  Args.hasFlag(options::OPT_fprofile_generate,
3243  options::OPT_fno_profile_instr_generate, false) ||
3244  Args.hasFlag(options::OPT_fprofile_generate_EQ,
3245  options::OPT_fno_profile_instr_generate, false) ||
3246  Args.hasFlag(options::OPT_fprofile_instr_generate,
3247  options::OPT_fno_profile_instr_generate, false) ||
3248  Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3249  options::OPT_fno_profile_instr_generate, false) ||
3250  Args.hasArg(options::OPT_fcreate_profile) ||
3251  Args.hasArg(options::OPT_coverage)))
3252  CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3253 }
3254 
3255 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
3256 /// smooshes them together with platform defaults, to decide whether
3257 /// this compile should be using PIC mode or not. Returns a tuple of
3258 /// (RelocationModel, PICLevel, IsPIE).
3259 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3260 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3261  const ArgList &Args) {
3262  // FIXME: why does this code...and so much everywhere else, use both
3263  // ToolChain.getTriple() and Triple?
3264  bool PIE = ToolChain.isPIEDefault();
3265  bool PIC = PIE || ToolChain.isPICDefault();
3266  // The Darwin/MachO default to use PIC does not apply when using -static.
3267  if (ToolChain.getTriple().isOSBinFormatMachO() &&
3268  Args.hasArg(options::OPT_static))
3269  PIE = PIC = false;
3270  bool IsPICLevelTwo = PIC;
3271 
3272  bool KernelOrKext =
3273  Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3274 
3275  // Android-specific defaults for PIC/PIE
3276  if (ToolChain.getTriple().isAndroid()) {
3277  switch (ToolChain.getArch()) {
3278  case llvm::Triple::arm:
3279  case llvm::Triple::armeb:
3280  case llvm::Triple::thumb:
3281  case llvm::Triple::thumbeb:
3282  case llvm::Triple::aarch64:
3283  case llvm::Triple::mips:
3284  case llvm::Triple::mipsel:
3285  case llvm::Triple::mips64:
3286  case llvm::Triple::mips64el:
3287  PIC = true; // "-fpic"
3288  break;
3289 
3290  case llvm::Triple::x86:
3291  case llvm::Triple::x86_64:
3292  PIC = true; // "-fPIC"
3293  IsPICLevelTwo = true;
3294  break;
3295 
3296  default:
3297  break;
3298  }
3299  }
3300 
3301  // OpenBSD-specific defaults for PIE
3302  if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3303  switch (ToolChain.getArch()) {
3304  case llvm::Triple::mips64:
3305  case llvm::Triple::mips64el:
3306  case llvm::Triple::sparcel:
3307  case llvm::Triple::x86:
3308  case llvm::Triple::x86_64:
3309  IsPICLevelTwo = false; // "-fpie"
3310  break;
3311 
3312  case llvm::Triple::ppc:
3313  case llvm::Triple::sparc:
3314  case llvm::Triple::sparcv9:
3315  IsPICLevelTwo = true; // "-fPIE"
3316  break;
3317 
3318  default:
3319  break;
3320  }
3321  }
3322 
3323  // The last argument relating to either PIC or PIE wins, and no
3324  // other argument is used. If the last argument is any flavor of the
3325  // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3326  // option implicitly enables PIC at the same level.
3327  Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3328  options::OPT_fpic, options::OPT_fno_pic,
3329  options::OPT_fPIE, options::OPT_fno_PIE,
3330  options::OPT_fpie, options::OPT_fno_pie);
3331  // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3332  // is forced, then neither PIC nor PIE flags will have no effect.
3333  if (!ToolChain.isPICDefaultForced()) {
3334  if (LastPICArg) {
3335  Option O = LastPICArg->getOption();
3336  if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3337  O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3338  PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3339  PIC =
3340  PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3341  IsPICLevelTwo =
3342  O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3343  } else {
3344  PIE = PIC = false;
3345  if (Triple.isPS4CPU()) {
3346  Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3347  StringRef Model = ModelArg ? ModelArg->getValue() : "";
3348  if (Model != "kernel") {
3349  PIC = true;
3350  ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3351  << LastPICArg->getSpelling();
3352  }
3353  }
3354  }
3355  }
3356  }
3357 
3358  // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3359  // PIC level would've been set to level 1, force it back to level 2 PIC
3360  // instead.
3361  if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3362  IsPICLevelTwo |= ToolChain.isPICDefault();
3363 
3364  // This kernel flags are a trump-card: they will disable PIC/PIE
3365  // generation, independent of the argument order.
3366  if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3367  !Triple.isWatchOS()))
3368  PIC = PIE = false;
3369 
3370  if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3371  // This is a very special mode. It trumps the other modes, almost no one
3372  // uses it, and it isn't even valid on any OS but Darwin.
3373  if (!ToolChain.getTriple().isOSDarwin())
3374  ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3375  << A->getSpelling() << ToolChain.getTriple().str();
3376 
3377  // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3378 
3379  // Only a forced PIC mode can cause the actual compile to have PIC defines
3380  // etc., no flags are sufficient. This behavior was selected to closely
3381  // match that of llvm-gcc and Apple GCC before that.
3382  PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3383 
3384  return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3385  }
3386 
3387  if (PIC)
3388  return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3389 
3390  return std::make_tuple(llvm::Reloc::Static, 0, false);
3391 }
3392 
3393 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3394  switch (Model) {
3395  case llvm::Reloc::Default:
3396  return nullptr;
3397  case llvm::Reloc::Static:
3398  return "static";
3399  case llvm::Reloc::PIC_:
3400  return "pic";
3401  case llvm::Reloc::DynamicNoPIC:
3402  return "dynamic-no-pic";
3403  }
3404  llvm_unreachable("Unknown Reloc::Model kind");
3405 }
3406 
3407 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3408  ArgStringList &CmdArgs) {
3409  llvm::Reloc::Model RelocationModel;
3410  unsigned PICLevel;
3411  bool IsPIE;
3412  std::tie(RelocationModel, PICLevel, IsPIE) =
3413  ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3414 
3415  if (RelocationModel != llvm::Reloc::Static)
3416  CmdArgs.push_back("-KPIC");
3417 }
3418 
3420  const InputInfo &Output, const InputInfoList &Inputs,
3421  const ArgList &Args, const char *LinkingOutput) const {
3422  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3423  const llvm::Triple Triple(TripleStr);
3424 
3425  bool KernelOrKext =
3426  Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3427  const Driver &D = getToolChain().getDriver();
3428  ArgStringList CmdArgs;
3429 
3430  bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3431  bool IsWindowsCygnus =
3432  getToolChain().getTriple().isWindowsCygwinEnvironment();
3433  bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3434  bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3435 
3436  // Check number of inputs for sanity. We need at least one input.
3437  assert(Inputs.size() >= 1 && "Must have at least one input.");
3438  const InputInfo &Input = Inputs[0];
3439  // CUDA compilation may have multiple inputs (source file + results of
3440  // device-side compilations). All other jobs are expected to have exactly one
3441  // input.
3442  bool IsCuda = types::isCuda(Input.getType());
3443  assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3444 
3445  // Invoke ourselves in -cc1 mode.
3446  //
3447  // FIXME: Implement custom jobs for internal actions.
3448  CmdArgs.push_back("-cc1");
3449 
3450  // Add the "effective" target triple.
3451  CmdArgs.push_back("-triple");
3452  CmdArgs.push_back(Args.MakeArgString(TripleStr));
3453 
3454  const ToolChain *AuxToolChain = nullptr;
3455  if (IsCuda) {
3456  // FIXME: We need a (better) way to pass information about
3457  // particular compilation pass we're constructing here. For now we
3458  // can check which toolchain we're using and pick the other one to
3459  // extract the triple.
3460  if (&getToolChain() == C.getCudaDeviceToolChain())
3461  AuxToolChain = C.getCudaHostToolChain();
3462  else if (&getToolChain() == C.getCudaHostToolChain())
3463  AuxToolChain = C.getCudaDeviceToolChain();
3464  else
3465  llvm_unreachable("Can't figure out CUDA compilation mode.");
3466  assert(AuxToolChain != nullptr && "No aux toolchain.");
3467  CmdArgs.push_back("-aux-triple");
3468  CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
3469  CmdArgs.push_back("-fcuda-target-overloads");
3470  CmdArgs.push_back("-fcuda-disable-target-call-checks");
3471  }
3472 
3473  if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3474  Triple.getArch() == llvm::Triple::thumb)) {
3475  unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3476  unsigned Version;
3477  Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3478  if (Version < 7)
3479  D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3480  << TripleStr;
3481  }
3482 
3483  // Push all default warning arguments that are specific to
3484  // the given target. These come before user provided warning options
3485  // are provided.
3486  getToolChain().addClangWarningOptions(CmdArgs);
3487 
3488  // Select the appropriate action.
3489  RewriteKind rewriteKind = RK_None;
3490 
3491  if (isa<AnalyzeJobAction>(JA)) {
3492  assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3493  CmdArgs.push_back("-analyze");
3494  } else if (isa<MigrateJobAction>(JA)) {
3495  CmdArgs.push_back("-migrate");
3496  } else if (isa<PreprocessJobAction>(JA)) {
3497  if (Output.getType() == types::TY_Dependencies)
3498  CmdArgs.push_back("-Eonly");
3499  else {
3500  CmdArgs.push_back("-E");
3501  if (Args.hasArg(options::OPT_rewrite_objc) &&
3502  !Args.hasArg(options::OPT_g_Group))
3503  CmdArgs.push_back("-P");
3504  }
3505  } else if (isa<AssembleJobAction>(JA)) {
3506  CmdArgs.push_back("-emit-obj");
3507 
3508  CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3509 
3510  // Also ignore explicit -force_cpusubtype_ALL option.
3511  (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3512  } else if (isa<PrecompileJobAction>(JA)) {
3513  // Use PCH if the user requested it.
3514  bool UsePCH = D.CCCUsePCH;
3515 
3516  if (JA.getType() == types::TY_Nothing)
3517  CmdArgs.push_back("-fsyntax-only");
3518  else if (UsePCH)
3519  CmdArgs.push_back("-emit-pch");
3520  else
3521  CmdArgs.push_back("-emit-pth");
3522  } else if (isa<VerifyPCHJobAction>(JA)) {
3523  CmdArgs.push_back("-verify-pch");
3524  } else {
3525  assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3526  "Invalid action for clang tool.");
3527  if (JA.getType() == types::TY_Nothing) {
3528  CmdArgs.push_back("-fsyntax-only");
3529  } else if (JA.getType() == types::TY_LLVM_IR ||
3530  JA.getType() == types::TY_LTO_IR) {
3531  CmdArgs.push_back("-emit-llvm");
3532  } else if (JA.getType() == types::TY_LLVM_BC ||
3533  JA.getType() == types::TY_LTO_BC) {
3534  CmdArgs.push_back("-emit-llvm-bc");
3535  } else if (JA.getType() == types::TY_PP_Asm) {
3536  CmdArgs.push_back("-S");
3537  } else if (JA.getType() == types::TY_AST) {
3538  CmdArgs.push_back("-emit-pch");
3539  } else if (JA.getType() == types::TY_ModuleFile) {
3540  CmdArgs.push_back("-module-file-info");
3541  } else if (JA.getType() == types::TY_RewrittenObjC) {
3542  CmdArgs.push_back("-rewrite-objc");
3543  rewriteKind = RK_NonFragile;
3544  } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3545  CmdArgs.push_back("-rewrite-objc");
3546  rewriteKind = RK_Fragile;
3547  } else {
3548  assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3549  }
3550 
3551  // Preserve use-list order by default when emitting bitcode, so that
3552  // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3553  // same result as running passes here. For LTO, we don't need to preserve
3554  // the use-list order, since serialization to bitcode is part of the flow.
3555  if (JA.getType() == types::TY_LLVM_BC)
3556  CmdArgs.push_back("-emit-llvm-uselists");
3557 
3558  if (D.isUsingLTO())
3559  Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3560  }
3561 
3562  if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3563  if (!types::isLLVMIR(Input.getType()))
3564  D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3565  << "-x ir";
3566  Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3567  }
3568 
3569  // We normally speed up the clang process a bit by skipping destructors at
3570  // exit, but when we're generating diagnostics we can rely on some of the
3571  // cleanup.
3572  if (!C.isForDiagnostics())
3573  CmdArgs.push_back("-disable-free");
3574 
3575 // Disable the verification pass in -asserts builds.
3576 #ifdef NDEBUG
3577  CmdArgs.push_back("-disable-llvm-verifier");
3578 #endif
3579 
3580  // Set the main file name, so that debug info works even with
3581  // -save-temps.
3582  CmdArgs.push_back("-main-file-name");
3583  CmdArgs.push_back(getBaseInputName(Args, Input));
3584 
3585  // Some flags which affect the language (via preprocessor
3586  // defines).
3587  if (Args.hasArg(options::OPT_static))
3588  CmdArgs.push_back("-static-define");
3589 
3590  if (isa<AnalyzeJobAction>(JA)) {
3591  // Enable region store model by default.
3592  CmdArgs.push_back("-analyzer-store=region");
3593 
3594  // Treat blocks as analysis entry points.
3595  CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3596 
3597  CmdArgs.push_back("-analyzer-eagerly-assume");
3598 
3599  // Add default argument set.
3600  if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3601  CmdArgs.push_back("-analyzer-checker=core");
3602 
3603  if (!IsWindowsMSVC)
3604  CmdArgs.push_back("-analyzer-checker=unix");
3605 
3606  // Disable some unix checkers for PS4.
3607  if (IsPS4CPU) {
3608  CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3609  CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3610  }
3611 
3612  if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3613  CmdArgs.push_back("-analyzer-checker=osx");
3614 
3615  CmdArgs.push_back("-analyzer-checker=deadcode");
3616 
3617  if (types::isCXX(Input.getType()))
3618  CmdArgs.push_back("-analyzer-checker=cplusplus");
3619 
3620  if (!IsPS4CPU) {
3621  CmdArgs.push_back(
3622  "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3623  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3624  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3625  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3626  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3627  CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3628  }
3629 
3630  // Default nullability checks.
3631  CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3632  CmdArgs.push_back(
3633  "-analyzer-checker=nullability.NullReturnedFromNonnull");
3634  }
3635 
3636  // Set the output format. The default is plist, for (lame) historical
3637  // reasons.
3638  CmdArgs.push_back("-analyzer-output");
3639  if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3640  CmdArgs.push_back(A->getValue());
3641  else
3642  CmdArgs.push_back("plist");
3643 
3644  // Disable the presentation of standard compiler warnings when
3645  // using --analyze. We only want to show static analyzer diagnostics
3646  // or frontend errors.
3647  CmdArgs.push_back("-w");
3648 
3649  // Add -Xanalyzer arguments when running as analyzer.
3650  Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3651  }
3652 
3653  CheckCodeGenerationOptions(D, Args);
3654 
3655  llvm::Reloc::Model RelocationModel;
3656  unsigned PICLevel;
3657  bool IsPIE;
3658  std::tie(RelocationModel, PICLevel, IsPIE) =
3659  ParsePICArgs(getToolChain(), Triple, Args);
3660 
3661  const char *RMName = RelocationModelName(RelocationModel);
3662  if (RMName) {
3663  CmdArgs.push_back("-mrelocation-model");
3664  CmdArgs.push_back(RMName);
3665  }
3666  if (PICLevel > 0) {
3667  CmdArgs.push_back("-pic-level");
3668  CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3669  if (IsPIE) {
3670  CmdArgs.push_back("-pie-level");
3671  CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3672  }
3673  }
3674 
3675  if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3676  CmdArgs.push_back("-meabi");
3677  CmdArgs.push_back(A->getValue());
3678  }
3679 
3680  CmdArgs.push_back("-mthread-model");
3681  if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3682  CmdArgs.push_back(A->getValue());
3683  else
3684  CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3685 
3686  Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3687 
3688  if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3689  options::OPT_fno_merge_all_constants))
3690  CmdArgs.push_back("-fno-merge-all-constants");
3691 
3692  // LLVM Code Generator Options.
3693 
3694  if (Args.hasArg(options::OPT_frewrite_map_file) ||
3695  Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3696  for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3697  options::OPT_frewrite_map_file_EQ)) {
3698  CmdArgs.push_back("-frewrite-map-file");
3699  CmdArgs.push_back(A->getValue());
3700  A->claim();
3701  }
3702  }
3703 
3704  if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3705  StringRef v = A->getValue();
3706  CmdArgs.push_back("-mllvm");
3707  CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3708  A->claim();
3709  }
3710 
3711  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3712  CmdArgs.push_back("-mregparm");
3713  CmdArgs.push_back(A->getValue());
3714  }
3715 
3716  if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3717  options::OPT_freg_struct_return)) {
3718  if (getToolChain().getArch() != llvm::Triple::x86) {
3719  D.Diag(diag::err_drv_unsupported_opt_for_target)
3720  << A->getSpelling() << getToolChain().getTriple().str();
3721  } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3722  CmdArgs.push_back("-fpcc-struct-return");
3723  } else {
3724  assert(A->getOption().matches(options::OPT_freg_struct_return));
3725  CmdArgs.push_back("-freg-struct-return");
3726  }
3727  }
3728 
3729  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3730  CmdArgs.push_back("-mrtd");
3731 
3732  if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3733  CmdArgs.push_back("-mdisable-fp-elim");
3734  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3735  options::OPT_fno_zero_initialized_in_bss))
3736  CmdArgs.push_back("-mno-zero-initialized-in-bss");
3737 
3738  bool OFastEnabled = isOptimizationLevelFast(Args);
3739  // If -Ofast is the optimization level, then -fstrict-aliasing should be
3740  // enabled. This alias option is being used to simplify the hasFlag logic.
3741  OptSpecifier StrictAliasingAliasOption =
3742  OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3743  // We turn strict aliasing off by default if we're in CL mode, since MSVC
3744  // doesn't do any TBAA.
3745  bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3746  if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3747  options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3748  CmdArgs.push_back("-relaxed-aliasing");
3749  if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3750  options::OPT_fno_struct_path_tbaa))
3751  CmdArgs.push_back("-no-struct-path-tbaa");
3752  if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3753  false))
3754  CmdArgs.push_back("-fstrict-enums");
3755  if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3756  options::OPT_fno_strict_vtable_pointers,
3757  false))
3758  CmdArgs.push_back("-fstrict-vtable-pointers");
3759  if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3760  options::OPT_fno_optimize_sibling_calls))
3761  CmdArgs.push_back("-mdisable-tail-calls");
3762 
3763  // Handle segmented stacks.
3764  if (Args.hasArg(options::OPT_fsplit_stack))
3765  CmdArgs.push_back("-split-stacks");
3766 
3767  // If -Ofast is the optimization level, then -ffast-math should be enabled.
3768  // This alias option is being used to simplify the getLastArg logic.
3769  OptSpecifier FastMathAliasOption =
3770  OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3771 
3772  // Handle various floating point optimization flags, mapping them to the
3773  // appropriate LLVM code generation flags. The pattern for all of these is to
3774  // default off the codegen optimizations, and if any flag enables them and no
3775  // flag disables them after the flag enabling them, enable the codegen
3776  // optimization. This is complicated by several "umbrella" flags.
3777  if (Arg *A = Args.getLastArg(
3778  options::OPT_ffast_math, FastMathAliasOption,
3779  options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3780  options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3781  options::OPT_fno_honor_infinities))
3782  if (A->getOption().getID() != options::OPT_fno_fast_math &&
3783  A->getOption().getID() != options::OPT_fno_finite_math_only &&
3784  A->getOption().getID() != options::OPT_fhonor_infinities)
3785  CmdArgs.push_back("-menable-no-infs");
3786  if (Arg *A = Args.getLastArg(
3787  options::OPT_ffast_math, FastMathAliasOption,
3788  options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3789  options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3790  options::OPT_fno_honor_nans))
3791  if (A->getOption().getID() != options::OPT_fno_fast_math &&
3792  A->getOption().getID() != options::OPT_fno_finite_math_only &&
3793  A->getOption().getID() != options::OPT_fhonor_nans)
3794  CmdArgs.push_back("-menable-no-nans");
3795 
3796  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3797  bool MathErrno = getToolChain().IsMathErrnoDefault();
3798  if (Arg *A =
3799  Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3800  options::OPT_fno_fast_math, options::OPT_fmath_errno,
3801  options::OPT_fno_math_errno)) {
3802  // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3803  // However, turning *off* -ffast_math merely restores the toolchain default
3804  // (which may be false).
3805  if (A->getOption().getID() == options::OPT_fno_math_errno ||
3806  A->getOption().getID() == options::OPT_ffast_math ||
3807  A->getOption().getID() == options::OPT_Ofast)
3808  MathErrno = false;
3809  else if (A->getOption().getID() == options::OPT_fmath_errno)
3810  MathErrno = true;
3811  }
3812  if (MathErrno)
3813  CmdArgs.push_back("-fmath-errno");
3814 
3815  // There are several flags which require disabling very specific
3816  // optimizations. Any of these being disabled forces us to turn off the
3817  // entire set of LLVM optimizations, so collect them through all the flag
3818  // madness.
3819  bool AssociativeMath = false;
3820  if (Arg *A = Args.getLastArg(
3821  options::OPT_ffast_math, FastMathAliasOption,
3822  options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3823  options::OPT_fno_unsafe_math_optimizations,
3824  options::OPT_fassociative_math, options::OPT_fno_associative_math))
3825  if (A->getOption().getID() != options::OPT_fno_fast_math &&
3826  A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3827  A->getOption().getID() != options::OPT_fno_associative_math)
3828  AssociativeMath = true;
3829  bool ReciprocalMath = false;
3830  if (Arg *A = Args.getLastArg(
3831  options::OPT_ffast_math, FastMathAliasOption,
3832  options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3833  options::OPT_fno_unsafe_math_optimizations,
3834  options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3835  if (A->getOption().getID() != options::OPT_fno_fast_math &&
3836  A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3837  A->getOption().getID() != options::OPT_fno_reciprocal_math)
3838  ReciprocalMath = true;
3839  bool SignedZeros = true;
3840  if (Arg *A = Args.getLastArg(
3841  options::OPT_ffast_math, FastMathAliasOption,
3842  options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3843  options::OPT_fno_unsafe_math_optimizations,
3844  options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3845  if (A->getOption().getID() != options::OPT_fno_fast_math &&
3846  A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3847  A->getOption().getID() != options::OPT_fsigned_zeros)
3848  SignedZeros = false;
3849  bool TrappingMath = true;
3850  if (Arg *A = Args.getLastArg(
3851  options::OPT_ffast_math, FastMathAliasOption,
3852  options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3853  options::OPT_fno_unsafe_math_optimizations,
3854  options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3855  if (A->getOption().getID() != options::OPT_fno_fast_math &&
3856  A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3857  A->getOption().getID() != options::OPT_ftrapping_math)
3858  TrappingMath = false;
3859  if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3860  !TrappingMath)
3861  CmdArgs.push_back("-menable-unsafe-fp-math");
3862 
3863  if (!SignedZeros)
3864  CmdArgs.push_back("-fno-signed-zeros");
3865 
3866  if (ReciprocalMath)
3867  CmdArgs.push_back("-freciprocal-math");
3868 
3869  // Validate and pass through -fp-contract option.
3870  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3871  options::OPT_fno_fast_math,
3872  options::OPT_ffp_contract)) {
3873  if (A->getOption().getID() == options::OPT_ffp_contract) {
3874  StringRef Val = A->getValue();
3875  if (Val == "fast" || Val == "on" || Val == "off") {
3876  CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3877  } else {
3878  D.Diag(diag::err_drv_unsupported_option_argument)
3879  << A->getOption().getName() << Val;
3880  }
3881  } else if (A->getOption().matches(options::OPT_ffast_math) ||
3882  (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3883  // If fast-math is set then set the fp-contract mode to fast.
3884  CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3885  }
3886  }
3887 
3888  ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3889 
3890  // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3891  // and if we find them, tell the frontend to provide the appropriate
3892  // preprocessor macros. This is distinct from enabling any optimizations as
3893  // these options induce language changes which must survive serialization
3894  // and deserialization, etc.
3895  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3896  options::OPT_fno_fast_math))
3897  if (!A->getOption().matches(options::OPT_fno_fast_math))
3898  CmdArgs.push_back("-ffast-math");
3899  if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3900  options::OPT_fno_fast_math))
3901  if (A->getOption().matches(options::OPT_ffinite_math_only))
3902  CmdArgs.push_back("-ffinite-math-only");
3903 
3904  // Decide whether to use verbose asm. Verbose assembly is the default on
3905  // toolchains which have the integrated assembler on by default.
3906  bool IsIntegratedAssemblerDefault =
3907  getToolChain().IsIntegratedAssemblerDefault();
3908  if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3909  IsIntegratedAssemblerDefault) ||
3910  Args.hasArg(options::OPT_dA))
3911  CmdArgs.push_back("-masm-verbose");
3912 
3913  if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3914  IsIntegratedAssemblerDefault))
3915  CmdArgs.push_back("-no-integrated-as");
3916 
3917  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3918  CmdArgs.push_back("-mdebug-pass");
3919  CmdArgs.push_back("Structure");
3920  }
3921  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3922  CmdArgs.push_back("-mdebug-pass");
3923  CmdArgs.push_back("Arguments");
3924  }
3925 
3926  // Enable -mconstructor-aliases except on darwin, where we have to
3927  // work around a linker bug; see <rdar://problem/7651567>.
3928  if (!getToolChain().getTriple().isOSDarwin())
3929  CmdArgs.push_back("-mconstructor-aliases");
3930 
3931  // Darwin's kernel doesn't support guard variables; just die if we
3932  // try to use them.
3933  if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3934  CmdArgs.push_back("-fforbid-guard-variables");
3935 
3936  if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3937  false)) {
3938  CmdArgs.push_back("-mms-bitfields");
3939  }
3940 
3941  // This is a coarse approximation of what llvm-gcc actually does, both
3942  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3943  // complicated ways.
3944  bool AsynchronousUnwindTables =
3945  Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3946  options::OPT_fno_asynchronous_unwind_tables,
3947  (getToolChain().IsUnwindTablesDefault() ||
3948  getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3949  !KernelOrKext);
3950  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3951  AsynchronousUnwindTables))
3952  CmdArgs.push_back("-munwind-tables");
3953 
3954  getToolChain().addClangTargetOptions(Args, CmdArgs);
3955 
3956  if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3957  CmdArgs.push_back("-mlimit-float-precision");
3958  CmdArgs.push_back(A->getValue());
3959  }
3960 
3961  // FIXME: Handle -mtune=.
3962  (void)Args.hasArg(options::OPT_mtune_EQ);
3963 
3964  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3965  CmdArgs.push_back("-mcode-model");
3966  CmdArgs.push_back(A->getValue());
3967  }
3968 
3969  // Add the target cpu
3970  std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3971  if (!CPU.empty()) {
3972  CmdArgs.push_back("-target-cpu");
3973  CmdArgs.push_back(Args.MakeArgString(CPU));
3974  }
3975 
3976  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3977  CmdArgs.push_back("-mfpmath");
3978  CmdArgs.push_back(A->getValue());
3979  }
3980 
3981  // Add the target features
3982  getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
3983 
3984  // Add target specific flags.
3985  switch (getToolChain().getArch()) {
3986  default:
3987  break;
3988 
3989  case llvm::Triple::arm:
3990  case llvm::Triple::armeb:
3991  case llvm::Triple::thumb:
3992  case llvm::Triple::thumbeb:
3993  // Use the effective triple, which takes into account the deployment target.
3994  AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
3995  break;
3996 
3997  case llvm::Triple::aarch64:
3998  case llvm::Triple::aarch64_be:
3999  AddAArch64TargetArgs(Args, CmdArgs);
4000  break;
4001 
4002  case llvm::Triple::mips:
4003  case llvm::Triple::mipsel:
4004  case llvm::Triple::mips64:
4005  case llvm::Triple::mips64el:
4006  AddMIPSTargetArgs(Args, CmdArgs);
4007  break;
4008 
4009  case llvm::Triple::ppc:
4010  case llvm::Triple::ppc64:
4011  case llvm::Triple::ppc64le:
4012  AddPPCTargetArgs(Args, CmdArgs);
4013  break;
4014 
4015  case llvm::Triple::sparc:
4016  case llvm::Triple::sparcel:
4017  case llvm::Triple::sparcv9:
4018  AddSparcTargetArgs(Args, CmdArgs);
4019  break;
4020 
4021  case llvm::Triple::x86:
4022  case llvm::Triple::x86_64:
4023  AddX86TargetArgs(Args, CmdArgs);
4024  break;
4025 
4026  case llvm::Triple::hexagon:
4027  AddHexagonTargetArgs(Args, CmdArgs);
4028  break;
4029 
4030  case llvm::Triple::wasm32:
4031  case llvm::Triple::wasm64:
4032  AddWebAssemblyTargetArgs(Args, CmdArgs);
4033  break;
4034  }
4035 
4036  // The 'g' groups options involve a somewhat intricate sequence of decisions
4037  // about what to pass from the driver to the frontend, but by the time they
4038  // reach cc1 they've been factored into three well-defined orthogonal choices:
4039  // * what level of debug info to generate
4040  // * what dwarf version to write
4041  // * what debugger tuning to use
4042  // This avoids having to monkey around further in cc1 other than to disable
4043  // codeview if not running in a Windows environment. Perhaps even that
4044  // decision should be made in the driver as well though.
4045  unsigned DwarfVersion = 0;
4046  llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4047  // These two are potentially updated by AddClangCLArgs.
4048  enum CodeGenOptions::DebugInfoKind DebugInfoKind =
4050  bool EmitCodeView = false;
4051 
4052  // Add clang-cl arguments.
4053  if (getToolChain().getDriver().IsCLMode())
4054  AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
4055 
4056  // Pass the linker version in use.
4057  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4058  CmdArgs.push_back("-target-linker-version");
4059  CmdArgs.push_back(A->getValue());
4060  }
4061 
4062  if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4063  CmdArgs.push_back("-momit-leaf-frame-pointer");
4064 
4065  // Explicitly error on some things we know we don't support and can't just
4066  // ignore.
4067  types::ID InputType = Input.getType();
4068  if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4069  Arg *Unsupported;
4070  if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4071  getToolChain().getArch() == llvm::Triple::x86) {
4072  if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4073  (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4074  D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4075  << Unsupported->getOption().getName();
4076  }
4077  }
4078 
4079  Args.AddAllArgs(CmdArgs, options::OPT_v);
4080  Args.AddLastArg(CmdArgs, options::OPT_H);
4081  if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4082  CmdArgs.push_back("-header-include-file");
4083  CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4084  : "-");
4085  }
4086  Args.AddLastArg(CmdArgs, options::OPT_P);
4087  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4088 
4089  if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4090  CmdArgs.push_back("-diagnostic-log-file");
4091  CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4092  : "-");
4093  }
4094 
4095  Args.ClaimAllArgs(options::OPT_g_Group);
4096  Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4097  if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4098  // If the last option explicitly specified a debug-info level, use it.
4099  if (A->getOption().matches(options::OPT_gN_Group)) {
4100  DebugInfoKind = DebugLevelToInfoKind(*A);
4101  // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4102  // But -gsplit-dwarf is not a g_group option, hence we have to check the
4103  // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4104  if (SplitDwarfArg && DebugInfoKind < CodeGenOptions::LimitedDebugInfo &&
4105  A->getIndex() > SplitDwarfArg->getIndex())
4106  SplitDwarfArg = nullptr;
4107  } else
4108  // For any other 'g' option, use Limited.
4109  DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4110  }
4111 
4112  // If a debugger tuning argument appeared, remember it.
4113  if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4114  options::OPT_ggdbN_Group)) {
4115  if (A->getOption().matches(options::OPT_glldb))
4116  DebuggerTuning = llvm::DebuggerKind::LLDB;
4117  else if (A->getOption().matches(options::OPT_gsce))
4118  DebuggerTuning = llvm::DebuggerKind::SCE;
4119  else
4120  DebuggerTuning = llvm::DebuggerKind::GDB;
4121  }
4122 
4123  // If a -gdwarf argument appeared, remember it.
4124  if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4125  options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4126  DwarfVersion = DwarfVersionNum(A->getSpelling());
4127 
4128  // Forward -gcodeview.
4129  // 'EmitCodeView might have been set by CL-compatibility argument parsing.
4130  if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4131  // DwarfVersion remains at 0 if no explicit choice was made.
4132  CmdArgs.push_back("-gcodeview");
4133  } else if (DwarfVersion == 0 &&
4134  DebugInfoKind != CodeGenOptions::NoDebugInfo) {
4135  DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4136  }
4137 
4138  // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4139  Args.ClaimAllArgs(options::OPT_g_flags_Group);
4140 
4141  // PS4 defaults to no column info
4142  if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4143  /*Default=*/ !IsPS4CPU))
4144  CmdArgs.push_back("-dwarf-column-info");
4145 
4146  // FIXME: Move backend command line options to the module.
4147  if (Args.hasArg(options::OPT_gmodules)) {
4148  DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4149  CmdArgs.push_back("-dwarf-ext-refs");
4150  CmdArgs.push_back("-fmodule-format=obj");
4151  }
4152 
4153  // -gsplit-dwarf should turn on -g and enable the backend dwarf
4154  // splitting and extraction.
4155  // FIXME: Currently only works on Linux.
4156  if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4157  DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4158  CmdArgs.push_back("-backend-option");
4159  CmdArgs.push_back("-split-dwarf=Enable");
4160  }
4161 
4162  // After we've dealt with all combinations of things that could
4163  // make DebugInfoKind be other than None or DebugLineTablesOnly,
4164  // figure out if we need to "upgrade" it to standalone debug info.
4165  // We parse these two '-f' options whether or not they will be used,
4166  // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4167  bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4168  options::OPT_fno_standalone_debug,
4169  getToolChain().GetDefaultStandaloneDebug());
4170  if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
4171  DebugInfoKind = CodeGenOptions::FullDebugInfo;
4172  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4173  DebuggerTuning);
4174 
4175  // -ggnu-pubnames turns on gnu style pubnames in the backend.
4176  if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4177  CmdArgs.push_back("-backend-option");
4178  CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4179  }
4180 
4181  // -gdwarf-aranges turns on the emission of the aranges section in the
4182  // backend.
4183  // Always enabled on the PS4.
4184  if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4185  CmdArgs.push_back("-backend-option");
4186  CmdArgs.push_back("-generate-arange-section");
4187  }
4188 
4189  if (Args.hasFlag(options::OPT_fdebug_types_section,
4190  options::OPT_fno_debug_types_section, false)) {
4191  CmdArgs.push_back("-backend-option");
4192  CmdArgs.push_back("-generate-type-units");
4193  }
4194 
4195  // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
4196  // default.
4197  bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
4198  Triple.getArch() == llvm::Triple::wasm32 ||
4199  Triple.getArch() == llvm::Triple::wasm64;
4200 
4201  if (Args.hasFlag(options::OPT_ffunction_sections,
4202  options::OPT_fno_function_sections, UseSeparateSections)) {
4203  CmdArgs.push_back("-ffunction-sections");
4204  }
4205 
4206  if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4207  UseSeparateSections)) {
4208  CmdArgs.push_back("-fdata-sections");
4209  }
4210 
4211  if (!Args.hasFlag(options::OPT_funique_section_names,
4212  options::OPT_fno_unique_section_names, true))
4213  CmdArgs.push_back("-fno-unique-section-names");
4214 
4215  Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4216 
4217  addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4218 
4219  // Add runtime flag for PS4 when PGO or Coverage are enabled.
4220  if (getToolChain().getTriple().isPS4CPU())
4221  addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4222 
4223  // Pass options for controlling the default header search paths.
4224  if (Args.hasArg(options::OPT_nostdinc)) {
4225  CmdArgs.push_back("-nostdsysteminc");
4226  CmdArgs.push_back("-nobuiltininc");
4227  } else {
4228  if (Args.hasArg(options::OPT_nostdlibinc))
4229  CmdArgs.push_back("-nostdsysteminc");
4230  Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4231  Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4232  }
4233 
4234  // Pass the path to compiler resource files.
4235  CmdArgs.push_back("-resource-dir");
4236  CmdArgs.push_back(D.ResourceDir.c_str());
4237 
4238  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4239 
4240  bool ARCMTEnabled = false;
4241  if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4242  if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4243  options::OPT_ccc_arcmt_modify,
4244  options::OPT_ccc_arcmt_migrate)) {
4245  ARCMTEnabled = true;
4246  switch (A->getOption().getID()) {
4247  default:
4248  llvm_unreachable("missed a case");
4249  case options::OPT_ccc_arcmt_check:
4250  CmdArgs.push_back("-arcmt-check");
4251  break;
4252  case options::OPT_ccc_arcmt_modify:
4253  CmdArgs.push_back("-arcmt-modify");
4254  break;
4255  case options::OPT_ccc_arcmt_migrate:
4256  CmdArgs.push_back("-arcmt-migrate");
4257  CmdArgs.push_back("-mt-migrate-directory");
4258  CmdArgs.push_back(A->getValue());
4259 
4260  Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4261  Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4262  break;
4263  }
4264  }
4265  } else {
4266  Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4267  Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4268  Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4269  }
4270 
4271  if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4272  if (ARCMTEnabled) {
4273  D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4274  << "-ccc-arcmt-migrate";
4275  }
4276  CmdArgs.push_back("-mt-migrate-directory");
4277  CmdArgs.push_back(A->getValue());
4278 
4279  if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4280  options::OPT_objcmt_migrate_subscripting,
4281  options::OPT_objcmt_migrate_property)) {
4282  // None specified, means enable them all.
4283  CmdArgs.push_back("-objcmt-migrate-literals");
4284  CmdArgs.push_back("-objcmt-migrate-subscripting");
4285  CmdArgs.push_back("-objcmt-migrate-property");
4286  } else {
4287  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4288  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4289  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4290  }
4291  } else {
4292  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4293  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4294  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4295  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4296  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4297  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4298  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4299  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4300  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4301  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4302  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4303  Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4304  Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4305  Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4306  Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4307  Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4308  }
4309 
4310  // Add preprocessing options like -I, -D, etc. if we are using the
4311  // preprocessor.
4312  //
4313  // FIXME: Support -fpreprocessed
4315  AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
4316  AuxToolChain);
4317 
4318  // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4319  // that "The compiler can only warn and ignore the option if not recognized".
4320  // When building with ccache, it will pass -D options to clang even on
4321  // preprocessed inputs and configure concludes that -fPIC is not supported.
4322  Args.ClaimAllArgs(options::OPT_D);
4323 
4324  // Manually translate -O4 to -O3; let clang reject others.
4325  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4326  if (A->getOption().matches(options::OPT_O4)) {
4327  CmdArgs.push_back("-O3");
4328  D.Diag(diag::warn_O4_is_O3);
4329  } else {
4330  A->render(Args, CmdArgs);
4331  }
4332  }
4333 
4334  // Warn about ignored options to clang.
4335  for (const Arg *A :
4336  Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4337  D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4338  A->claim();
4339  }
4340 
4341  claimNoWarnArgs(Args);
4342 
4343  Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4344  Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4345  if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4346  CmdArgs.push_back("-pedantic");
4347  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4348  Args.AddLastArg(CmdArgs, options::OPT_w);
4349 
4350  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4351  // (-ansi is equivalent to -std=c89 or -std=c++98).
4352  //
4353  // If a std is supplied, only add -trigraphs if it follows the
4354  // option.
4355  bool ImplyVCPPCXXVer = false;
4356  if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4357  if (Std->getOption().matches(options::OPT_ansi))
4358  if (types::isCXX(InputType))
4359  CmdArgs.push_back("-std=c++98");
4360  else
4361  CmdArgs.push_back("-std=c89");
4362  else
4363  Std->render(Args, CmdArgs);
4364 
4365  // If -f(no-)trigraphs appears after the language standard flag, honor it.
4366  if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4367  options::OPT_ftrigraphs,
4368  options::OPT_fno_trigraphs))
4369  if (A != Std)
4370  A->render(Args, CmdArgs);
4371  } else {
4372  // Honor -std-default.
4373  //
4374  // FIXME: Clang doesn't correctly handle -std= when the input language
4375  // doesn't match. For the time being just ignore this for C++ inputs;
4376  // eventually we want to do all the standard defaulting here instead of
4377  // splitting it between the driver and clang -cc1.
4378  if (!types::isCXX(InputType))
4379  Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4380  /*Joined=*/true);
4381  else if (IsWindowsMSVC)
4382  ImplyVCPPCXXVer = true;
4383 
4384  Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4385  options::OPT_fno_trigraphs);
4386  }
4387 
4388  // GCC's behavior for -Wwrite-strings is a bit strange:
4389  // * In C, this "warning flag" changes the types of string literals from
4390  // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4391  // for the discarded qualifier.
4392  // * In C++, this is just a normal warning flag.
4393  //
4394  // Implementing this warning correctly in C is hard, so we follow GCC's
4395  // behavior for now. FIXME: Directly diagnose uses of a string literal as
4396  // a non-const char* in C, rather than using this crude hack.
4397  if (!types::isCXX(InputType)) {
4398  // FIXME: This should behave just like a warning flag, and thus should also
4399  // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4400  Arg *WriteStrings =
4401  Args.getLastArg(options::OPT_Wwrite_strings,
4402  options::OPT_Wno_write_strings, options::OPT_w);
4403  if (WriteStrings &&
4404  WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4405  CmdArgs.push_back("-fconst-strings");
4406  }
4407 
4408  // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4409  // during C++ compilation, which it is by default. GCC keeps this define even
4410  // in the presence of '-w', match this behavior bug-for-bug.
4411  if (types::isCXX(InputType) &&
4412  Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4413  true)) {
4414  CmdArgs.push_back("-fdeprecated-macro");
4415  }
4416 
4417  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4418  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4419  if (Asm->getOption().matches(options::OPT_fasm))
4420  CmdArgs.push_back("-fgnu-keywords");
4421  else
4422  CmdArgs.push_back("-fno-gnu-keywords");
4423  }
4424 
4425  if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4426  CmdArgs.push_back("-fno-dwarf-directory-asm");
4427 
4428  if (ShouldDisableAutolink(Args, getToolChain()))
4429  CmdArgs.push_back("-fno-autolink");
4430 
4431  // Add in -fdebug-compilation-dir if necessary.
4432  addDebugCompDirArg(Args, CmdArgs);
4433 
4434  for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4435  StringRef Map = A->getValue();
4436  if (Map.find('=') == StringRef::npos)
4437  D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4438  else
4439  CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4440  A->claim();
4441  }
4442 
4443  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4444  options::OPT_ftemplate_depth_EQ)) {
4445  CmdArgs.push_back("-ftemplate-depth");
4446  CmdArgs.push_back(A->getValue());
4447  }
4448 
4449  if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4450  CmdArgs.push_back("-foperator-arrow-depth");
4451  CmdArgs.push_back(A->getValue());
4452  }
4453 
4454  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4455  CmdArgs.push_back("-fconstexpr-depth");
4456  CmdArgs.push_back(A->getValue());
4457  }
4458 
4459  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4460  CmdArgs.push_back("-fconstexpr-steps");
4461  CmdArgs.push_back(A->getValue());
4462  }
4463 
4464  if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4465  CmdArgs.push_back("-fbracket-depth");
4466  CmdArgs.push_back(A->getValue());
4467  }
4468 
4469  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4470  options::OPT_Wlarge_by_value_copy_def)) {
4471  if (A->getNumValues()) {
4472  StringRef bytes = A->getValue();
4473  CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4474  } else
4475  CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4476  }
4477 
4478  if (Args.hasArg(options::OPT_relocatable_pch))
4479  CmdArgs.push_back("-relocatable-pch");
4480 
4481  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4482  CmdArgs.push_back("-fconstant-string-class");
4483  CmdArgs.push_back(A->getValue());
4484  }
4485 
4486  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4487  CmdArgs.push_back("-ftabstop");
4488  CmdArgs.push_back(A->getValue());
4489  }
4490 
4491  CmdArgs.push_back("-ferror-limit");
4492  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4493  CmdArgs.push_back(A->getValue());
4494  else
4495  CmdArgs.push_back("19");
4496 
4497  if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4498  CmdArgs.push_back("-fmacro-backtrace-limit");
4499  CmdArgs.push_back(A->getValue());
4500  }
4501 
4502  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4503  CmdArgs.push_back("-ftemplate-backtrace-limit");
4504  CmdArgs.push_back(A->getValue());
4505  }
4506 
4507  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4508  CmdArgs.push_back("-fconstexpr-backtrace-limit");
4509  CmdArgs.push_back(A->getValue());
4510  }
4511 
4512  if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4513  CmdArgs.push_back("-fspell-checking-limit");
4514  CmdArgs.push_back(A->getValue());
4515  }
4516 
4517  // Pass -fmessage-length=.
4518  CmdArgs.push_back("-fmessage-length");
4519  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4520  CmdArgs.push_back(A->getValue());
4521  } else {
4522  // If -fmessage-length=N was not specified, determine whether this is a
4523  // terminal and, if so, implicitly define -fmessage-length appropriately.
4524  unsigned N = llvm::sys::Process::StandardErrColumns();
4525  CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4526  }
4527 
4528  // -fvisibility= and -fvisibility-ms-compat are of a piece.
4529  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4530  options::OPT_fvisibility_ms_compat)) {
4531  if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4532  CmdArgs.push_back("-fvisibility");
4533  CmdArgs.push_back(A->getValue());
4534  } else {
4535  assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4536  CmdArgs.push_back("-fvisibility");
4537  CmdArgs.push_back("hidden");
4538  CmdArgs.push_back("-ftype-visibility");
4539  CmdArgs.push_back("default");
4540  }
4541  }
4542 
4543  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4544 
4545  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4546 
4547  // -fhosted is default.
4548  if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4549  KernelOrKext)
4550  CmdArgs.push_back("-ffreestanding");
4551 
4552  // Forward -f (flag) options which we can pass directly.
4553  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4554  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4555  Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4556  // Emulated TLS is enabled by default on Android, and can be enabled manually
4557  // with -femulated-tls.
4558  bool EmulatedTLSDefault = Triple.isAndroid();
4559  if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
4560  EmulatedTLSDefault))
4561  CmdArgs.push_back("-femulated-tls");
4562  // AltiVec-like language extensions aren't relevant for assembling.
4563  if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4564  Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4565  Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4566  }
4567  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4568  Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4569 
4570  // Forward flags for OpenMP
4571  if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4572  options::OPT_fno_openmp, false))
4573  switch (getOpenMPRuntime(getToolChain(), Args)) {
4574  case OMPRT_OMP:
4575  case OMPRT_IOMP5:
4576  // Clang can generate useful OpenMP code for these two runtime libraries.
4577  CmdArgs.push_back("-fopenmp");
4578 
4579  // If no option regarding the use of TLS in OpenMP codegeneration is
4580  // given, decide a default based on the target. Otherwise rely on the
4581  // options and pass the right information to the frontend.
4582  if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4583  options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4584  CmdArgs.push_back("-fnoopenmp-use-tls");
4585  break;
4586  default:
4587  // By default, if Clang doesn't know how to generate useful OpenMP code
4588  // for a specific runtime library, we just don't pass the '-fopenmp' flag
4589  // down to the actual compilation.
4590  // FIXME: It would be better to have a mode which *only* omits IR
4591  // generation based on the OpenMP support so that we get consistent
4592  // semantic analysis, etc.
4593  break;
4594  }
4595 
4596  const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4597  Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4598 
4599  // Report an error for -faltivec on anything other than PowerPC.
4600  if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4601  const llvm::Triple::ArchType Arch = getToolChain().getArch();
4602  if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4603  Arch == llvm::Triple::ppc64le))
4604  D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4605  << "ppc/ppc64/ppc64le";
4606  }
4607 
4608  // -fzvector is incompatible with -faltivec.
4609  if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4610  if (Args.hasArg(options::OPT_faltivec))
4611  D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4612  << "-faltivec";
4613 
4614  if (getToolChain().SupportsProfiling())
4615  Args.AddLastArg(CmdArgs, options::OPT_pg);
4616 
4617  // -flax-vector-conversions is default.
4618  if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4619  options::OPT_fno_lax_vector_conversions))
4620  CmdArgs.push_back("-fno-lax-vector-conversions");
4621 
4622  if (Args.getLastArg(options::OPT_fapple_kext) ||
4623  (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4624  CmdArgs.push_back("-fapple-kext");
4625 
4626  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4627  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4628  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4629  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4630  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4631 
4632  if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4633  CmdArgs.push_back("-ftrapv-handler");
4634  CmdArgs.push_back(A->getValue());
4635  }
4636 
4637  Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4638 
4639  // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4640  // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4641  if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4642  if (A->getOption().matches(options::OPT_fwrapv))
4643  CmdArgs.push_back("-fwrapv");
4644  } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4645  options::OPT_fno_strict_overflow)) {
4646  if (A->getOption().matches(options::OPT_fno_strict_overflow))
4647  CmdArgs.push_back("-fwrapv");
4648  }
4649 
4650  if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4651  options::OPT_fno_reroll_loops))
4652  if (A->getOption().matches(options::OPT_freroll_loops))
4653  CmdArgs.push_back("-freroll-loops");
4654 
4655  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4656  Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4657  options::OPT_fno_unroll_loops);
4658 
4659  Args.AddLastArg(CmdArgs, options::OPT_pthread);
4660 
4661  // -stack-protector=0 is default.
4662  unsigned StackProtectorLevel = 0;
4663  if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4664  Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4665  Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4666  Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4667  Args.ClaimAllArgs(options::OPT_fstack_protector);
4668  } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4669  options::OPT_fstack_protector_all,
4670  options::OPT_fstack_protector_strong,
4671  options::OPT_fstack_protector)) {
4672  if (A->getOption().matches(options::OPT_fstack_protector)) {
4673  StackProtectorLevel = std::max<unsigned>(
4675  getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4676  } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4677  StackProtectorLevel = LangOptions::SSPStrong;
4678  else if (A->getOption().matches(options::OPT_fstack_protector_all))
4679  StackProtectorLevel = LangOptions::SSPReq;
4680  } else {
4681  StackProtectorLevel =
4682  getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4683  }
4684  if (StackProtectorLevel) {
4685  CmdArgs.push_back("-stack-protector");
4686  CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4687  }
4688 
4689  // --param ssp-buffer-size=
4690  for (const Arg *A : Args.filtered(options::OPT__param)) {
4691  StringRef Str(A->getValue());
4692  if (Str.startswith("ssp-buffer-size=")) {
4693  if (StackProtectorLevel) {
4694  CmdArgs.push_back("-stack-protector-buffer-size");
4695  // FIXME: Verify the argument is a valid integer.
4696  CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4697  }
4698  A->claim();
4699  }
4700  }
4701 
4702  // Translate -mstackrealign
4703  if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4704  false))
4705  CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4706 
4707  if (Args.hasArg(options::OPT_mstack_alignment)) {
4708  StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4709  CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4710  }
4711 
4712  if (Args.hasArg(options::OPT_mstack_probe_size)) {
4713  StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4714 
4715  if (!Size.empty())
4716  CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4717  else
4718  CmdArgs.push_back("-mstack-probe-size=0");
4719  }
4720 
4721  switch (getToolChain().getArch()) {
4722  case llvm::Triple::aarch64:
4723  case llvm::Triple::aarch64_be:
4724  case llvm::Triple::arm:
4725  case llvm::Triple::armeb:
4726  case llvm::Triple::thumb:
4727  case llvm::Triple::thumbeb:
4728  CmdArgs.push_back("-fallow-half-arguments-and-returns");
4729  break;
4730 
4731  default:
4732  break;
4733  }
4734 
4735  if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4736  options::OPT_mno_restrict_it)) {
4737  if (A->getOption().matches(options::OPT_mrestrict_it)) {
4738  CmdArgs.push_back("-backend-option");
4739  CmdArgs.push_back("-arm-restrict-it");
4740  } else {
4741  CmdArgs.push_back("-backend-option");
4742  CmdArgs.push_back("-arm-no-restrict-it");
4743  }
4744  } else if (Triple.isOSWindows() &&
4745  (Triple.getArch() == llvm::Triple::arm ||
4746  Triple.getArch() == llvm::Triple::thumb)) {
4747  // Windows on ARM expects restricted IT blocks
4748  CmdArgs.push_back("-backend-option");
4749  CmdArgs.push_back("-arm-restrict-it");
4750  }
4751 
4752  // Forward -f options with positive and negative forms; we translate
4753  // these by hand.
4754  if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4755  StringRef fname = A->getValue();
4756  if (!llvm::sys::fs::exists(fname))
4757  D.Diag(diag::err_drv_no_such_file) << fname;
4758  else
4759  A->render(Args, CmdArgs);
4760  }
4761 
4762  // -fbuiltin is default unless -mkernel is used.
4763  bool UseBuiltins =
4764  Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4765  !Args.hasArg(options::OPT_mkernel));
4766  if (!UseBuiltins)
4767  CmdArgs.push_back("-fno-builtin");
4768 
4769  // -ffreestanding implies -fno-builtin.
4770  if (Args.hasArg(options::OPT_ffreestanding))
4771  UseBuiltins = false;
4772 
4773  // Process the -fno-builtin-* options.
4774  for (const auto &Arg : Args) {
4775  const Option &O = Arg->getOption();
4776  if (!O.matches(options::OPT_fno_builtin_))
4777  continue;
4778 
4779  Arg->claim();
4780  // If -fno-builtin is specified, then there's no need to pass the option to
4781  // the frontend.
4782  if (!UseBuiltins)
4783  continue;
4784 
4785  StringRef FuncName = Arg->getValue();
4786  CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
4787  }
4788 
4789  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4790  options::OPT_fno_assume_sane_operator_new))
4791  CmdArgs.push_back("-fno-assume-sane-operator-new");
4792 
4793  // -fblocks=0 is default.
4794  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4795  getToolChain().IsBlocksDefault()) ||
4796  (Args.hasArg(options::OPT_fgnu_runtime) &&
4797  Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4798  !Args.hasArg(options::OPT_fno_blocks))) {
4799  CmdArgs.push_back("-fblocks");
4800 
4801  if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4802  !getToolChain().hasBlocksRuntime())
4803  CmdArgs.push_back("-fblocks-runtime-optional");
4804  }
4805 
4806  // -fmodules enables the use of precompiled modules (off by default).
4807  // Users can pass -fno-cxx-modules to turn off modules support for
4808  // C++/Objective-C++ programs.
4809  bool HaveModules = false;
4810  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4811  bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4812  options::OPT_fno_cxx_modules, true);
4813  if (AllowedInCXX || !types::isCXX(InputType)) {
4814  CmdArgs.push_back("-fmodules");
4815  HaveModules = true;
4816  }
4817  }
4818 
4819  // -fmodule-maps enables implicit reading of module map files. By default,
4820  // this is enabled if we are using precompiled modules.
4821  if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4822  options::OPT_fno_implicit_module_maps, HaveModules)) {
4823  CmdArgs.push_back("-fimplicit-module-maps");
4824  }
4825 
4826  // -fmodules-decluse checks that modules used are declared so (off by
4827  // default).
4828  if (Args.hasFlag(options::OPT_fmodules_decluse,
4829  options::OPT_fno_modules_decluse, false)) {
4830  CmdArgs.push_back("-fmodules-decluse");
4831  }
4832 
4833  // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4834  // all #included headers are part of modules.
4835  if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4836  options::OPT_fno_modules_strict_decluse, false)) {
4837  CmdArgs.push_back("-fmodules-strict-decluse");
4838  }
4839 
4840  // -fno-implicit-modules turns off implicitly compiling modules on demand.
4841  if (!Args.hasFlag(options::OPT_fimplicit_modules,
4842  options::OPT_fno_implicit_modules)) {
4843  CmdArgs.push_back("-fno-implicit-modules");
4844  }
4845 
4846  // -fmodule-name specifies the module that is currently being built (or
4847  // used for header checking by -fmodule-maps).
4848  Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4849 
4850  // -fmodule-map-file can be used to specify files containing module
4851  // definitions.
4852  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4853 
4854  // -fmodule-file can be used to specify files containing precompiled modules.
4855  if (HaveModules)
4856  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4857  else
4858  Args.ClaimAllArgs(options::OPT_fmodule_file);
4859 
4860  // -fmodule-cache-path specifies where our implicitly-built module files
4861  // should be written.
4862  SmallString<128> Path;
4863  if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4864  Path = A->getValue();
4865  if (HaveModules) {
4866  if (C.isForDiagnostics()) {
4867  // When generating crash reports, we want to emit the modules along with
4868  // the reproduction sources, so we ignore any provided module path.
4869  Path = Output.getFilename();
4870  llvm::sys::path::replace_extension(Path, ".cache");
4871  llvm::sys::path::append(Path, "modules");
4872  } else if (Path.empty()) {
4873  // No module path was provided: use the default.
4874  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4875  llvm::sys::path::append(Path, "org.llvm.clang.");
4876  appendUserToPath(Path);
4877  llvm::sys::path::append(Path, "ModuleCache");
4878  }
4879  const char Arg[] = "-fmodules-cache-path=";
4880  Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4881  CmdArgs.push_back(Args.MakeArgString(Path));
4882  }
4883 
4884  // When building modules and generating crashdumps, we need to dump a module
4885  // dependency VFS alongside the output.
4886  if (HaveModules && C.isForDiagnostics()) {
4887  SmallString<128> VFSDir(Output.getFilename());
4888  llvm::sys::path::replace_extension(VFSDir, ".cache");
4889  // Add the cache directory as a temp so the crash diagnostics pick it up.
4890  C.addTempFile(Args.MakeArgString(VFSDir));
4891 
4892  llvm::sys::path::append(VFSDir, "vfs");
4893  CmdArgs.push_back("-module-dependency-dir");
4894  CmdArgs.push_back(Args.MakeArgString(VFSDir));
4895  }
4896 
4897  if (HaveModules)
4898  Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4899 
4900  // Pass through all -fmodules-ignore-macro arguments.
4901  Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4902  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4903  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4904 
4905  Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4906 
4907  if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4908  if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4909  D.Diag(diag::err_drv_argument_not_allowed_with)
4910  << A->getAsString(Args) << "-fbuild-session-timestamp";
4911 
4912  llvm::sys::fs::file_status Status;
4913  if (llvm::sys::fs::status(A->getValue(), Status))
4914  D.Diag(diag::err_drv_no_such_file) << A->getValue();
4915  CmdArgs.push_back(Args.MakeArgString(
4916  "-fbuild-session-timestamp=" +
4917  Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4918  }
4919 
4920  if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4921  if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4922  options::OPT_fbuild_session_file))
4923  D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4924 
4925  Args.AddLastArg(CmdArgs,
4926  options::OPT_fmodules_validate_once_per_build_session);
4927  }
4928 
4929  Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4930 
4931  // -faccess-control is default.
4932  if (Args.hasFlag(options::OPT_fno_access_control,
4933  options::OPT_faccess_control, false))
4934  CmdArgs.push_back("-fno-access-control");
4935 
4936  // -felide-constructors is the default.
4937  if (Args.hasFlag(options::OPT_fno_elide_constructors,
4938  options::OPT_felide_constructors, false))
4939  CmdArgs.push_back("-fno-elide-constructors");
4940 
4941  ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4942 
4943  if (KernelOrKext || (types::isCXX(InputType) &&
4944  (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4945  RTTIMode == ToolChain::RM_DisabledImplicitly)))
4946  CmdArgs.push_back("-fno-rtti");
4947 
4948  // -fshort-enums=0 is default for all architectures except Hexagon.
4949  if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4950  getToolChain().getArch() == llvm::Triple::hexagon))
4951  CmdArgs.push_back("-fshort-enums");
4952 
4953  // -fsigned-char is default.
4954  if (Arg *A = Args.getLastArg(
4955  options::OPT_fsigned_char, options::OPT_fno_signed_char,
4956  options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4957  if (A->getOption().matches(options::OPT_funsigned_char) ||
4958  A->getOption().matches(options::OPT_fno_signed_char)) {
4959  CmdArgs.push_back("-fno-signed-char");
4960  }
4961  } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4962  CmdArgs.push_back("-fno-signed-char");
4963  }
4964 
4965  // -fuse-cxa-atexit is default.
4966  if (!Args.hasFlag(
4967  options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4968  !IsWindowsCygnus && !IsWindowsGNU &&
4969  getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
4970  getToolChain().getArch() != llvm::Triple::hexagon &&
4971  getToolChain().getArch() != llvm::Triple::xcore &&
4972  ((getToolChain().getTriple().getVendor() !=
4973  llvm::Triple::MipsTechnologies) ||
4974  getToolChain().getTriple().hasEnvironment())) ||
4975  KernelOrKext)
4976  CmdArgs.push_back("-fno-use-cxa-atexit");
4977 
4978  // -fms-extensions=0 is default.
4979  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4980  IsWindowsMSVC))
4981  CmdArgs.push_back("-fms-extensions");
4982 
4983  // -fno-use-line-directives is default.
4984  if (Args.hasFlag(options::OPT_fuse_line_directives,
4985  options::OPT_fno_use_line_directives, false))
4986  CmdArgs.push_back("-fuse-line-directives");
4987 
4988  // -fms-compatibility=0 is default.
4989  if (Args.hasFlag(options::OPT_fms_compatibility,
4990  options::OPT_fno_ms_compatibility,
4991  (IsWindowsMSVC &&
4992  Args.hasFlag(options::OPT_fms_extensions,
4993  options::OPT_fno_ms_extensions, true))))
4994  CmdArgs.push_back("-fms-compatibility");
4995 
4996  // -fms-compatibility-version=18.00 is default.
4998  &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4999  if (!MSVT.empty())
5000  CmdArgs.push_back(
5001  Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5002 
5003  bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5004  if (ImplyVCPPCXXVer) {
5005  if (IsMSVC2015Compatible)
5006  CmdArgs.push_back("-std=c++14");
5007  else
5008  CmdArgs.push_back("-std=c++11");
5009  }
5010 
5011  // -fno-borland-extensions is default.
5012  if (Args.hasFlag(options::OPT_fborland_extensions,
5013  options::OPT_fno_borland_extensions, false))
5014  CmdArgs.push_back("-fborland-extensions");
5015 
5016  // -fno-declspec is default, except for PS4.
5017  if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5018  getToolChain().getTriple().isPS4()))
5019  CmdArgs.push_back("-fdeclspec");
5020  else if (Args.hasArg(options::OPT_fno_declspec))
5021  CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5022 
5023  // -fthreadsafe-static is default, except for MSVC compatibility versions less
5024  // than 19.
5025  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5026  options::OPT_fno_threadsafe_statics,
5027  !IsWindowsMSVC || IsMSVC2015Compatible))
5028  CmdArgs.push_back("-fno-threadsafe-statics");
5029 
5030  // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5031  // needs it.
5032  if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5033  options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5034  CmdArgs.push_back("-fdelayed-template-parsing");
5035 
5036  // -fgnu-keywords default varies depending on language; only pass if
5037  // specified.
5038  if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5039  options::OPT_fno_gnu_keywords))
5040  A->render(Args, CmdArgs);
5041 
5042  if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5043  false))
5044  CmdArgs.push_back("-fgnu89-inline");
5045 
5046  if (Args.hasArg(options::OPT_fno_inline))
5047  CmdArgs.push_back("-fno-inline");
5048 
5049  if (Args.hasArg(options::OPT_fno_inline_functions))
5050  CmdArgs.push_back("-fno-inline-functions");
5051 
5052  ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5053 
5054  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5055  // legacy is the default. Except for deployment taget of 10.5,
5056  // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5057  // gets ignored silently.
5058  if (objcRuntime.isNonFragile()) {
5059  if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5060  options::OPT_fno_objc_legacy_dispatch,
5061  objcRuntime.isLegacyDispatchDefaultForArch(
5062  getToolChain().getArch()))) {
5063  if (getToolChain().UseObjCMixedDispatch())
5064  CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5065  else
5066  CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5067  }
5068  }
5069 
5070  // When ObjectiveC legacy runtime is in effect on MacOSX,
5071  // turn on the option to do Array/Dictionary subscripting
5072  // by default.
5073  if (getToolChain().getArch() == llvm::Triple::x86 &&
5074  getToolChain().getTriple().isMacOSX() &&
5075  !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5076  objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5077  objcRuntime.isNeXTFamily())
5078  CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5079 
5080  // -fencode-extended-block-signature=1 is default.
5081  if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5082  CmdArgs.push_back("-fencode-extended-block-signature");
5083  }
5084 
5085  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5086  // NOTE: This logic is duplicated in ToolChains.cpp.
5087  bool ARC = isObjCAutoRefCount(Args);
5088  if (ARC) {
5089  getToolChain().CheckObjCARC();
5090 
5091  CmdArgs.push_back("-fobjc-arc");
5092 
5093  // FIXME: It seems like this entire block, and several around it should be
5094  // wrapped in isObjC, but for now we just use it here as this is where it
5095  // was being used previously.
5096  if (types::isCXX(InputType) && types::isObjC(InputType)) {
5097  if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5098  CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5099  else
5100  CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5101  }
5102 
5103  // Allow the user to enable full exceptions code emission.
5104  // We define off for Objective-CC, on for Objective-C++.
5105  if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5106  options::OPT_fno_objc_arc_exceptions,
5107  /*default*/ types::isCXX(InputType)))
5108  CmdArgs.push_back("-fobjc-arc-exceptions");
5109 
5110  }
5111 
5112  // -fobjc-infer-related-result-type is the default, except in the Objective-C
5113  // rewriter.
5114  if (rewriteKind != RK_None)
5115  CmdArgs.push_back("-fno-objc-infer-related-result-type");
5116 
5117  // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5118  // takes precedence.
5119  const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5120  if (!GCArg)
5121  GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5122  if (GCArg) {
5123  if (ARC) {
5124  D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5125  } else if (getToolChain().SupportsObjCGC()) {
5126  GCArg->render(Args, CmdArgs);
5127  } else {
5128  // FIXME: We should move this to a hard error.
5129  D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5130  }
5131  }
5132 
5133  // Pass down -fobjc-weak or -fno-objc-weak if present.
5134  if (types::isObjC(InputType)) {
5135  auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5136  options::OPT_fno_objc_weak);
5137  if (!WeakArg) {
5138  // nothing to do
5139  } else if (GCArg) {
5140  if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5141  D.Diag(diag::err_objc_weak_with_gc);
5142  } else if (!objcRuntime.allowsWeak()) {
5143  if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5144  D.Diag(diag::err_objc_weak_unsupported);
5145  } else {
5146  WeakArg->render(Args, CmdArgs);
5147  }
5148  }
5149 
5150  if (Args.hasFlag(options::OPT_fapplication_extension,
5151  options::OPT_fno_application_extension, false))
5152  CmdArgs.push_back("-fapplication-extension");
5153 
5154  // Handle GCC-style exception args.
5155  if (!C.getDriver().IsCLMode())
5156  addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5157  CmdArgs);
5158 
5159  if (getToolChain().UseSjLjExceptions(Args))
5160  CmdArgs.push_back("-fsjlj-exceptions");
5161 
5162  // C++ "sane" operator new.
5163  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5164  options::OPT_fno_assume_sane_operator_new))
5165  CmdArgs.push_back("-fno-assume-sane-operator-new");
5166 
5167  // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5168  // most platforms.
5169  if (Args.hasFlag(options::OPT_fsized_deallocation,
5170  options::OPT_fno_sized_deallocation, false))
5171  CmdArgs.push_back("-fsized-deallocation");
5172 
5173  // -fconstant-cfstrings is default, and may be subject to argument translation
5174  // on Darwin.
5175  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5176  options::OPT_fno_constant_cfstrings) ||
5177  !Args.hasFlag(options::OPT_mconstant_cfstrings,
5178  options::OPT_mno_constant_cfstrings))
5179  CmdArgs.push_back("-fno-constant-cfstrings");
5180 
5181  // -fshort-wchar default varies depending on platform; only
5182  // pass if specified.
5183  if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5184  options::OPT_fno_short_wchar))
5185  A->render(Args, CmdArgs);
5186 
5187  // -fno-pascal-strings is default, only pass non-default.
5188  if (Args.hasFlag(options::OPT_fpascal_strings,
5189  options::OPT_fno_pascal_strings, false))
5190  CmdArgs.push_back("-fpascal-strings");
5191 
5192  // Honor -fpack-struct= and -fpack-struct, if given. Note that
5193  // -fno-pack-struct doesn't apply to -fpack-struct=.
5194  if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5195  std::string PackStructStr = "-fpack-struct=";
5196  PackStructStr += A->getValue();
5197  CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5198  } else if (Args.hasFlag(options::OPT_fpack_struct,
5199  options::OPT_fno_pack_struct, false)) {
5200  CmdArgs.push_back("-fpack-struct=1");
5201  }
5202 
5203  // Handle -fmax-type-align=N and -fno-type-align
5204  bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5205  if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5206  if (!SkipMaxTypeAlign) {
5207  std::string MaxTypeAlignStr = "-fmax-type-align=";
5208  MaxTypeAlignStr += A->getValue();
5209  CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5210  }
5211  } else if (getToolChain().getTriple().isOSDarwin()) {
5212  if (!SkipMaxTypeAlign) {
5213  std::string MaxTypeAlignStr = "-fmax-type-align=16";
5214  CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5215  }
5216  }
5217 
5218  // -fcommon is the default unless compiling kernel code or the target says so
5219  bool NoCommonDefault =
5220  KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5221  if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5222  !NoCommonDefault))
5223  CmdArgs.push_back("-fno-common");
5224 
5225  // -fsigned-bitfields is default, and clang doesn't yet support
5226  // -funsigned-bitfields.
5227  if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5228  options::OPT_funsigned_bitfields))
5229  D.Diag(diag::warn_drv_clang_unsupported)
5230  << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5231 
5232  // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5233  if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5234  D.Diag(diag::err_drv_clang_unsupported)
5235  << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5236 
5237  // -finput_charset=UTF-8 is default. Reject others
5238  if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5239  StringRef value = inputCharset->getValue();
5240  if (value != "UTF-8")
5241  D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5242  << value;
5243  }
5244 
5245  // -fexec_charset=UTF-8 is default. Reject others
5246  if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5247  StringRef value = execCharset->getValue();
5248  if (value != "UTF-8")
5249  D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5250  << value;
5251  }
5252 
5253  // -fcaret-diagnostics is default.
5254  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5255  options::OPT_fno_caret_diagnostics, true))
5256  CmdArgs.push_back("-fno-caret-diagnostics");
5257 
5258  // -fdiagnostics-fixit-info is default, only pass non-default.
5259  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5260  options::OPT_fno_diagnostics_fixit_info))
5261  CmdArgs.push_back("-fno-diagnostics-fixit-info");
5262 
5263  // Enable -fdiagnostics-show-option by default.
5264  if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5265  options::OPT_fno_diagnostics_show_option))
5266  CmdArgs.push_back("-fdiagnostics-show-option");
5267 
5268  if (const Arg *A =
5269  Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5270  CmdArgs.push_back("-fdiagnostics-show-category");
5271  CmdArgs.push_back(A->getValue());
5272  }
5273 
5274  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5275  CmdArgs.push_back("-fdiagnostics-format");
5276  CmdArgs.push_back(A->getValue());
5277  }
5278 
5279  if (Arg *A = Args.getLastArg(
5280  options::OPT_fdiagnostics_show_note_include_stack,
5281  options::OPT_fno_diagnostics_show_note_include_stack)) {
5282  if (A->getOption().matches(
5283  options::OPT_fdiagnostics_show_note_include_stack))
5284  CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5285  else
5286  CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5287  }
5288 
5289  // Color diagnostics are the default, unless the terminal doesn't support
5290  // them.
5291  // Support both clang's -f[no-]color-diagnostics and gcc's
5292  // -f[no-]diagnostics-colors[=never|always|auto].
5293  enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
5294  for (const auto &Arg : Args) {
5295  const Option &O = Arg->getOption();
5296  if (!O.matches(options::OPT_fcolor_diagnostics) &&
5297  !O.matches(options::OPT_fdiagnostics_color) &&
5298  !O.matches(options::OPT_fno_color_diagnostics) &&
5299  !O.matches(options::OPT_fno_diagnostics_color) &&
5300  !O.matches(options::OPT_fdiagnostics_color_EQ))
5301  continue;
5302 
5303  Arg->claim();
5304  if (O.matches(options::OPT_fcolor_diagnostics) ||
5305  O.matches(options::OPT_fdiagnostics_color)) {
5306  ShowColors = Colors_On;
5307  } else if (O.matches(options::OPT_fno_color_diagnostics) ||
5308  O.matches(options::OPT_fno_diagnostics_color)) {
5309  ShowColors = Colors_Off;
5310  } else {
5311  assert(O.matches(options::OPT_fdiagnostics_color_EQ));
5312  StringRef value(Arg->getValue());
5313  if (value == "always")
5314  ShowColors = Colors_On;
5315  else if (value == "never")
5316  ShowColors = Colors_Off;
5317  else if (value == "auto")
5318  ShowColors = Colors_Auto;
5319  else
5320  getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5321  << ("-fdiagnostics-color=" + value).str();
5322  }
5323  }
5324  if (ShowColors == Colors_On ||
5325  (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
5326  CmdArgs.push_back("-fcolor-diagnostics");
5327 
5328  if (Args.hasArg(options::OPT_fansi_escape_codes))
5329  CmdArgs.push_back("-fansi-escape-codes");
5330 
5331  if (!Args.hasFlag(options::OPT_fshow_source_location,
5332  options::OPT_fno_show_source_location))
5333  CmdArgs.push_back("-fno-show-source-location");
5334 
5335  if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5336  true))
5337  CmdArgs.push_back("-fno-show-column");
5338 
5339  if (!Args.hasFlag(options::OPT_fspell_checking,
5340  options::OPT_fno_spell_checking))
5341  CmdArgs.push_back("-fno-spell-checking");
5342 
5343  // -fno-asm-blocks is default.
5344  if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5345  false))
5346  CmdArgs.push_back("-fasm-blocks");
5347 
5348  // -fgnu-inline-asm is default.
5349  if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5350  options::OPT_fno_gnu_inline_asm, true))
5351  CmdArgs.push_back("-fno-gnu-inline-asm");
5352 
5353  // Enable vectorization per default according to the optimization level
5354  // selected. For optimization levels that want vectorization we use the alias
5355  // option to simplify the hasFlag logic.
5356  bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5357  OptSpecifier VectorizeAliasOption =
5358  EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5359  if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5360  options::OPT_fno_vectorize, EnableVec))
5361  CmdArgs.push_back("-vectorize-loops");
5362 
5363  // -fslp-vectorize is enabled based on the optimization level selected.
5364  bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5365  OptSpecifier SLPVectAliasOption =
5366  EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5367  if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5368  options::OPT_fno_slp_vectorize, EnableSLPVec))
5369  CmdArgs.push_back("-vectorize-slp");
5370 
5371  // -fno-slp-vectorize-aggressive is default.
5372  if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5373  options::OPT_fno_slp_vectorize_aggressive, false))
5374  CmdArgs.push_back("-vectorize-slp-aggressive");
5375 
5376  if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5377  A->render(Args, CmdArgs);
5378 
5379  // -fdollars-in-identifiers default varies depending on platform and
5380  // language; only pass if specified.
5381  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5382  options::OPT_fno_dollars_in_identifiers)) {
5383  if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5384  CmdArgs.push_back("-fdollars-in-identifiers");
5385  else
5386  CmdArgs.push_back("-fno-dollars-in-identifiers");
5387  }
5388 
5389  // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5390  // practical purposes.
5391  if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5392  options::OPT_fno_unit_at_a_time)) {
5393  if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5394  D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5395  }
5396 
5397  if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5398  options::OPT_fno_apple_pragma_pack, false))
5399  CmdArgs.push_back("-fapple-pragma-pack");
5400 
5401  // le32-specific flags:
5402  // -fno-math-builtin: clang should not convert math builtins to intrinsics
5403  // by default.
5404  if (getToolChain().getArch() == llvm::Triple::le32) {
5405  CmdArgs.push_back("-fno-math-builtin");
5406  }
5407 
5408 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5409 //
5410 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
5411 #if 0
5412  if (getToolChain().getTriple().isOSDarwin() &&
5413  (getToolChain().getArch() == llvm::Triple::arm ||
5414  getToolChain().getArch() == llvm::Triple::thumb)) {
5415  if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5416  CmdArgs.push_back("-fno-builtin-strcat");
5417  if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5418  CmdArgs.push_back("-fno-builtin-strcpy");
5419  }
5420 #endif
5421 
5422  // Enable rewrite includes if the user's asked for it or if we're generating
5423  // diagnostics.
5424  // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5425  // nice to enable this when doing a crashdump for modules as well.
5426  if (Args.hasFlag(options::OPT_frewrite_includes,
5427  options::OPT_fno_rewrite_includes, false) ||
5428  (C.isForDiagnostics() && !HaveModules))
5429  CmdArgs.push_back("-frewrite-includes");
5430 
5431  // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5432  if (Arg *A = Args.getLastArg(options::OPT_traditional,
5433  options::OPT_traditional_cpp)) {
5434  if (isa<PreprocessJobAction>(JA))
5435  CmdArgs.push_back("-traditional-cpp");
5436  else
5437  D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5438  }
5439 
5440  Args.AddLastArg(CmdArgs, options::OPT_dM);
5441  Args.AddLastArg(CmdArgs, options::OPT_dD);
5442 
5443  // Handle serialized diagnostics.
5444  if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5445  CmdArgs.push_back("-serialize-diagnostic-file");
5446  CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5447  }
5448 
5449  if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5450  CmdArgs.push_back("-fretain-comments-from-system-headers");
5451 
5452  // Forward -fcomment-block-commands to -cc1.
5453  Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5454  // Forward -fparse-all-comments to -cc1.
5455  Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5456 
5457  // Turn -fplugin=name.so into -load name.so
5458  for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5459  CmdArgs.push_back("-load");
5460  CmdArgs.push_back(A->getValue());
5461  A->claim();
5462  }
5463 
5464  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5465  // parser.
5466  Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5467  for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5468  A->claim();
5469 
5470  // We translate this by hand to the -cc1 argument, since nightly test uses
5471  // it and developers have been trained to spell it with -mllvm.
5472  if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5473  CmdArgs.push_back("-disable-llvm-optzns");
5474  } else
5475  A->render(Args, CmdArgs);
5476  }
5477 
5478  // With -save-temps, we want to save the unoptimized bitcode output from the
5479  // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5480  // by the frontend.
5481  if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
5482  CmdArgs.push_back("-disable-llvm-passes");
5483 
5484  if (Output.getType() == types::TY_Dependencies) {
5485  // Handled with other dependency code.
5486  } else if (Output.isFilename()) {
5487  CmdArgs.push_back("-o");
5488  CmdArgs.push_back(Output.getFilename());
5489  } else {
5490  assert(Output.isNothing() && "Invalid output.");
5491  }
5492 
5493  addDashXForInput(Args, Input, CmdArgs);
5494 
5495  if (Input.isFilename())
5496  CmdArgs.push_back(Input.getFilename());
5497  else
5498  Input.getInputArg().renderAsInput(Args, CmdArgs);
5499 
5500  Args.AddAllArgs(CmdArgs, options::OPT_undef);
5501 
5502  const char *Exec = getToolChain().getDriver().getClangProgramPath();
5503 
5504  // Optionally embed the -cc1 level arguments into the debug info, for build
5505  // analysis.
5506  if (getToolChain().UseDwarfDebugFlags()) {
5507  ArgStringList OriginalArgs;
5508  for (const auto &Arg : Args)
5509  Arg->render(Args, OriginalArgs);
5510 
5511  SmallString<256> Flags;
5512  Flags += Exec;
5513  for (const char *OriginalArg : OriginalArgs) {
5514  SmallString<128> EscapedArg;
5515  EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5516  Flags += " ";
5517  Flags += EscapedArg;
5518  }
5519  CmdArgs.push_back("-dwarf-debug-flags");
5520  CmdArgs.push_back(Args.MakeArgString(Flags));
5521  }
5522 
5523  // Add the split debug info name to the command lines here so we
5524  // can propagate it to the backend.
5525  bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
5526  (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5527  isa<BackendJobAction>(JA));
5528  const char *SplitDwarfOut;
5529  if (SplitDwarf) {
5530  CmdArgs.push_back("-split-dwarf-file");
5531  SplitDwarfOut = SplitDebugName(Args, Input);
5532  CmdArgs.push_back(SplitDwarfOut);
5533  }
5534 
5535  // Host-side cuda compilation receives device-side outputs as Inputs[1...].
5536  // Include them with -fcuda-include-gpubinary.
5537  if (IsCuda && Inputs.size() > 1)
5538  for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
5539  CmdArgs.push_back("-fcuda-include-gpubinary");
5540  CmdArgs.push_back(I->getFilename());
5541  }
5542 
5543  // Finally add the compile command to the compilation.
5544  if (Args.hasArg(options::OPT__SLASH_fallback) &&
5545  Output.getType() == types::TY_Object &&
5546  (InputType == types::TY_C || InputType == types::TY_CXX)) {
5547  auto CLCommand =
5548  getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5549  C.addCommand(llvm::make_unique<FallbackCommand>(
5550  JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5551  } else {
5552  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5553  }
5554 
5555  // Handle the debug info splitting at object creation time if we're
5556  // creating an object.
5557  // TODO: Currently only works on linux with newer objcopy.
5558  if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5559  SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5560 
5561  if (Arg *A = Args.getLastArg(options::OPT_pg))
5562  if (Args.hasArg(options::OPT_fomit_frame_pointer))
5563  D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5564  << A->getAsString(Args);
5565 
5566  // Claim some arguments which clang supports automatically.
5567 
5568  // -fpch-preprocess is used with gcc to add a special marker in the output to
5569  // include the PCH file. Clang's PTH solution is completely transparent, so we
5570  // do not need to deal with it at all.
5571  Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5572 
5573  // Claim some arguments which clang doesn't support, but we don't
5574  // care to warn the user about.
5575  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5576  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5577 
5578  // Disable warnings for clang -E -emit-llvm foo.c
5579  Args.ClaimAllArgs(options::OPT_emit_llvm);
5580 }
5581 
5582 /// Add options related to the Objective-C runtime/ABI.
5583 ///
5584 /// Returns true if the runtime is non-fragile.
5585 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5586  ArgStringList &cmdArgs,
5587  RewriteKind rewriteKind) const {
5588  // Look for the controlling runtime option.
5589  Arg *runtimeArg =
5590  args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5591  options::OPT_fobjc_runtime_EQ);
5592 
5593  // Just forward -fobjc-runtime= to the frontend. This supercedes
5594  // options about fragility.
5595  if (runtimeArg &&
5596  runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5597  ObjCRuntime runtime;
5598  StringRef value = runtimeArg->getValue();
5599  if (runtime.tryParse(value)) {
5600  getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5601  << value;
5602  }
5603 
5604  runtimeArg->render(args, cmdArgs);
5605  return runtime;
5606  }
5607 
5608  // Otherwise, we'll need the ABI "version". Version numbers are
5609  // slightly confusing for historical reasons:
5610  // 1 - Traditional "fragile" ABI
5611  // 2 - Non-fragile ABI, version 1
5612  // 3 - Non-fragile ABI, version 2
5613  unsigned objcABIVersion = 1;
5614  // If -fobjc-abi-version= is present, use that to set the version.
5615  if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5616  StringRef value = abiArg->getValue();
5617  if (value == "1")
5618  objcABIVersion = 1;
5619  else if (value == "2")
5620  objcABIVersion = 2;
5621  else if (value == "3")
5622  objcABIVersion = 3;
5623  else
5624  getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5625  } else {
5626  // Otherwise, determine if we are using the non-fragile ABI.
5627  bool nonFragileABIIsDefault =
5628  (rewriteKind == RK_NonFragile ||
5629  (rewriteKind == RK_None &&
5630  getToolChain().IsObjCNonFragileABIDefault()));
5631  if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5632  options::OPT_fno_objc_nonfragile_abi,
5633  nonFragileABIIsDefault)) {
5634 // Determine the non-fragile ABI version to use.
5635 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5636  unsigned nonFragileABIVersion = 1;
5637 #else
5638  unsigned nonFragileABIVersion = 2;
5639 #endif
5640 
5641  if (Arg *abiArg =
5642  args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5643  StringRef value = abiArg->getValue();
5644  if (value == "1")
5645  nonFragileABIVersion = 1;
5646  else if (value == "2")
5647  nonFragileABIVersion = 2;
5648  else
5649  getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5650  << value;
5651  }
5652 
5653  objcABIVersion = 1 + nonFragileABIVersion;
5654  } else {
5655  objcABIVersion = 1;
5656  }
5657  }
5658 
5659  // We don't actually care about the ABI version other than whether
5660  // it's non-fragile.
5661  bool isNonFragile = objcABIVersion != 1;
5662 
5663  // If we have no runtime argument, ask the toolchain for its default runtime.
5664  // However, the rewriter only really supports the Mac runtime, so assume that.
5665  ObjCRuntime runtime;
5666  if (!runtimeArg) {
5667  switch (rewriteKind) {
5668  case RK_None:
5669  runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5670  break;
5671  case RK_Fragile:
5673  break;
5674  case RK_NonFragile:
5676  break;
5677  }
5678 
5679  // -fnext-runtime
5680  } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5681  // On Darwin, make this use the default behavior for the toolchain.
5682  if (getToolChain().getTriple().isOSDarwin()) {
5683  runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5684 
5685  // Otherwise, build for a generic macosx port.
5686  } else {
5688  }
5689 
5690  // -fgnu-runtime
5691  } else {
5692  assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5693  // Legacy behaviour is to target the gnustep runtime if we are in
5694  // non-fragile mode or the GCC runtime in fragile mode.
5695  if (isNonFragile)
5696  runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5697  else
5699  }
5700 
5701  cmdArgs.push_back(
5702  args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5703  return runtime;
5704 }
5705 
5706 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5707  bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5708  I += HaveDash;
5709  return !HaveDash;
5710 }
5711 
5712 namespace {
5713 struct EHFlags {
5714  EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5715  bool Synch;
5716  bool Asynch;
5717  bool NoExceptC;
5718 };
5719 } // end anonymous namespace
5720 
5721 /// /EH controls whether to run destructor cleanups when exceptions are
5722 /// thrown. There are three modifiers:
5723 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5724 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5725 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5726 /// - c: Assume that extern "C" functions are implicitly noexcept. This
5727 /// modifier is an optimization, so we ignore it for now.
5728 /// The default is /EHs-c-, meaning cleanups are disabled.
5729 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5730  EHFlags EH;
5731 
5732  std::vector<std::string> EHArgs =
5733  Args.getAllArgValues(options::OPT__SLASH_EH);
5734  for (auto EHVal : EHArgs) {
5735  for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5736  switch (EHVal[I]) {
5737  case 'a':
5738  EH.Asynch = maybeConsumeDash(EHVal, I);
5739  continue;
5740  case 'c':
5741  EH.NoExceptC = maybeConsumeDash(EHVal, I);
5742  continue;
5743  case 's':
5744  EH.Synch = maybeConsumeDash(EHVal, I);
5745  continue;
5746  default:
5747  break;
5748  }
5749  D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5750  break;
5751  }
5752  }
5753 
5754  return EH;
5755 }
5756 
5757 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
5758  enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
5759  bool *EmitCodeView) const {
5760  unsigned RTOptionID = options::OPT__SLASH_MT;
5761 
5762  if (Args.hasArg(options::OPT__SLASH_LDd))
5763  // The /LDd option implies /MTd. The dependent lib part can be overridden,
5764  // but defining _DEBUG is sticky.
5765  RTOptionID = options::OPT__SLASH_MTd;
5766 
5767  if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5768  RTOptionID = A->getOption().getID();
5769 
5770  StringRef FlagForCRT;
5771  switch (RTOptionID) {
5772  case options::OPT__SLASH_MD:
5773  if (Args.hasArg(options::OPT__SLASH_LDd))
5774  CmdArgs.push_back("-D_DEBUG");
5775  CmdArgs.push_back("-D_MT");
5776  CmdArgs.push_back("-D_DLL");
5777  FlagForCRT = "--dependent-lib=msvcrt";
5778  break;
5779  case options::OPT__SLASH_MDd:
5780  CmdArgs.push_back("-D_DEBUG");
5781  CmdArgs.push_back("-D_MT");
5782  CmdArgs.push_back("-D_DLL");
5783  FlagForCRT = "--dependent-lib=msvcrtd";
5784  break;
5785  case options::OPT__SLASH_MT:
5786  if (Args.hasArg(options::OPT__SLASH_LDd))
5787  CmdArgs.push_back("-D_DEBUG");
5788  CmdArgs.push_back("-D_MT");
5789  FlagForCRT = "--dependent-lib=libcmt";
5790  break;
5791  case options::OPT__SLASH_MTd:
5792  CmdArgs.push_back("-D_DEBUG");
5793  CmdArgs.push_back("-D_MT");
5794  FlagForCRT = "--dependent-lib=libcmtd";
5795  break;
5796  default:
5797  llvm_unreachable("Unexpected option ID.");
5798  }
5799 
5800  if (Args.hasArg(options::OPT__SLASH_Zl)) {
5801  CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5802  } else {
5803  CmdArgs.push_back(FlagForCRT.data());
5804 
5805  // This provides POSIX compatibility (maps 'open' to '_open'), which most
5806  // users want. The /Za flag to cl.exe turns this off, but it's not
5807  // implemented in clang.
5808  CmdArgs.push_back("--dependent-lib=oldnames");
5809  }
5810 
5811  // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5812  // would produce interleaved output, so ignore /showIncludes in such cases.
5813  if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5814  if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5815  A->render(Args, CmdArgs);
5816 
5817  // This controls whether or not we emit RTTI data for polymorphic types.
5818  if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5819  /*default=*/false))
5820  CmdArgs.push_back("-fno-rtti-data");
5821 
5822  // Emit CodeView if -Z7 is present.
5823  *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
5824  bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
5825  // If we are emitting CV but not DWARF, don't build information that LLVM
5826  // can't yet process.
5827  if (*EmitCodeView && !EmitDwarf)
5828  *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
5829  if (*EmitCodeView)
5830  CmdArgs.push_back("-gcodeview");
5831 
5832  const Driver &D = getToolChain().getDriver();
5833  EHFlags EH = parseClangCLEHFlags(D, Args);
5834  // FIXME: Do something with NoExceptC.
5835  if (EH.Synch || EH.Asynch) {
5836  CmdArgs.push_back("-fcxx-exceptions");
5837  CmdArgs.push_back("-fexceptions");
5838  }
5839 
5840  // /EP should expand to -E -P.
5841  if (Args.hasArg(options::OPT__SLASH_EP)) {
5842  CmdArgs.push_back("-E");
5843  CmdArgs.push_back("-P");
5844  }
5845 
5846  unsigned VolatileOptionID;
5847  if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5848  getToolChain().getArch() == llvm::Triple::x86)
5849  VolatileOptionID = options::OPT__SLASH_volatile_ms;
5850  else
5851  VolatileOptionID = options::OPT__SLASH_volatile_iso;
5852 
5853  if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5854  VolatileOptionID = A->getOption().getID();
5855 
5856  if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5857  CmdArgs.push_back("-fms-volatile");
5858 
5859  Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5860  Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5861  if (MostGeneralArg && BestCaseArg)
5862  D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5863  << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5864 
5865  if (MostGeneralArg) {
5866  Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5867  Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5868  Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5869 
5870  Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5871  Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5872  if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5873  D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5874  << FirstConflict->getAsString(Args)
5875  << SecondConflict->getAsString(Args);
5876 
5877  if (SingleArg)
5878  CmdArgs.push_back("-fms-memptr-rep=single");
5879  else if (MultipleArg)
5880  CmdArgs.push_back("-fms-memptr-rep=multiple");
5881  else
5882  CmdArgs.push_back("-fms-memptr-rep=virtual");
5883  }
5884 
5885  if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5886  A->render(Args, CmdArgs);
5887 
5888  if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5889  CmdArgs.push_back("-fdiagnostics-format");
5890  if (Args.hasArg(options::OPT__SLASH_fallback))
5891  CmdArgs.push_back("msvc-fallback");
5892  else
5893  CmdArgs.push_back("msvc");
5894  }
5895 }
5896 
5897 visualstudio::Compiler *Clang::getCLFallback() const {
5898  if (!CLFallback)
5899  CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5900  return CLFallback.get();
5901 }
5902 
5903 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5904  ArgStringList &CmdArgs) const {
5905  StringRef CPUName;
5906  StringRef ABIName;
5907  const llvm::Triple &Triple = getToolChain().getTriple();
5908  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5909 
5910  CmdArgs.push_back("-target-abi");
5911  CmdArgs.push_back(ABIName.data());
5912 }
5913 
5915  const InputInfo &Output, const InputInfoList &Inputs,
5916  const ArgList &Args,
5917  const char *LinkingOutput) const {
5918  ArgStringList CmdArgs;
5919 
5920  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5921  const InputInfo &Input = Inputs[0];
5922 
5923  std::string TripleStr =
5924  getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5925  const llvm::Triple Triple(TripleStr);
5926 
5927  // Don't warn about "clang -w -c foo.s"
5928  Args.ClaimAllArgs(options::OPT_w);
5929  // and "clang -emit-llvm -c foo.s"
5930  Args.ClaimAllArgs(options::OPT_emit_llvm);
5931 
5932  claimNoWarnArgs(Args);
5933 
5934  // Invoke ourselves in -cc1as mode.
5935  //
5936  // FIXME: Implement custom jobs for internal actions.
5937  CmdArgs.push_back("-cc1as");
5938 
5939  // Add the "effective" target triple.
5940  CmdArgs.push_back("-triple");
5941  CmdArgs.push_back(Args.MakeArgString(TripleStr));
5942 
5943  // Set the output mode, we currently only expect to be used as a real
5944  // assembler.
5945  CmdArgs.push_back("-filetype");
5946  CmdArgs.push_back("obj");
5947 
5948  // Set the main file name, so that debug info works even with
5949  // -save-temps or preprocessed assembly.
5950  CmdArgs.push_back("-main-file-name");
5951  CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5952 
5953  // Add the target cpu
5954  std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5955  if (!CPU.empty()) {
5956  CmdArgs.push_back("-target-cpu");
5957  CmdArgs.push_back(Args.MakeArgString(CPU));
5958  }
5959 
5960  // Add the target features
5961  getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5962 
5963  // Ignore explicit -force_cpusubtype_ALL option.
5964  (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5965 
5966  // Pass along any -I options so we get proper .include search paths.
5967  Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5968 
5969  // Determine the original source input.
5970  const Action *SourceAction = &JA;
5971  while (SourceAction->getKind() != Action::InputClass) {
5972  assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5973  SourceAction = SourceAction->getInputs()[0];
5974  }
5975 
5976  // Forward -g and handle debug info related flags, assuming we are dealing
5977  // with an actual assembly file.
5978  if (SourceAction->getType() == types::TY_Asm ||
5979  SourceAction->getType() == types::TY_PP_Asm) {
5980  bool WantDebug = false;
5981  unsigned DwarfVersion = 0;
5982  Args.ClaimAllArgs(options::OPT_g_Group);
5983  if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5984  WantDebug = !A->getOption().matches(options::OPT_g0) &&
5985  !A->getOption().matches(options::OPT_ggdb0);
5986  if (WantDebug)
5987  DwarfVersion = DwarfVersionNum(A->getSpelling());
5988  }
5989  if (DwarfVersion == 0)
5990  DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5991  RenderDebugEnablingArgs(Args, CmdArgs,
5994  DwarfVersion, llvm::DebuggerKind::Default);
5995 
5996  // Add the -fdebug-compilation-dir flag if needed.
5997  addDebugCompDirArg(Args, CmdArgs);
5998 
5999  // Set the AT_producer to the clang version when using the integrated
6000  // assembler on assembly source files.
6001  CmdArgs.push_back("-dwarf-debug-producer");
6002  CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6003 
6004  // And pass along -I options
6005  Args.AddAllArgs(CmdArgs, options::OPT_I);
6006  }
6007 
6008  // Handle -fPIC et al -- the relocation-model affects the assembler
6009  // for some targets.
6010  llvm::Reloc::Model RelocationModel;
6011  unsigned PICLevel;
6012  bool IsPIE;
6013  std::tie(RelocationModel, PICLevel, IsPIE) =
6014  ParsePICArgs(getToolChain(), Triple, Args);
6015 
6016  const char *RMName = RelocationModelName(RelocationModel);
6017  if (RMName) {
6018  CmdArgs.push_back("-mrelocation-model");
6019  CmdArgs.push_back(RMName);
6020  }
6021 
6022  // Optionally embed the -cc1as level arguments into the debug info, for build
6023  // analysis.
6024  if (getToolChain().UseDwarfDebugFlags()) {
6025  ArgStringList OriginalArgs;
6026  for (const auto &Arg : Args)
6027  Arg->render(Args, OriginalArgs);
6028 
6029  SmallString<256> Flags;
6030  const char *Exec = getToolChain().getDriver().getClangProgramPath();
6031  Flags += Exec;
6032  for (const char *OriginalArg : OriginalArgs) {
6033  SmallString<128> EscapedArg;
6034  EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6035  Flags += " ";
6036  Flags += EscapedArg;
6037  }
6038  CmdArgs.push_back("-dwarf-debug-flags");
6039  CmdArgs.push_back(Args.MakeArgString(Flags));
6040  }
6041 
6042  // FIXME: Add -static support, once we have it.
6043 
6044  // Add target specific flags.
6045  switch (getToolChain().getArch()) {
6046  default:
6047  break;
6048 
6049  case llvm::Triple::mips:
6050  case llvm::Triple::mipsel:
6051  case llvm::Triple::mips64:
6052  case llvm::Triple::mips64el:
6053  AddMIPSTargetArgs(Args, CmdArgs);
6054  break;
6055  }
6056 
6057  // Consume all the warning flags. Usually this would be handled more
6058  // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6059  // doesn't handle that so rather than warning about unused flags that are
6060  // actually used, we'll lie by omission instead.
6061  // FIXME: Stop lying and consume only the appropriate driver flags
6062  Args.ClaimAllArgs(options::OPT_W_Group);
6063 
6064  CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6065  getToolChain().getDriver());
6066 
6067  Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6068 
6069  assert(Output.isFilename() && "Unexpected lipo output.");
6070  CmdArgs.push_back("-o");
6071  CmdArgs.push_back(Output.getFilename());
6072 
6073  assert(Input.isFilename() && "Invalid input.");
6074  CmdArgs.push_back(Input.getFilename());
6075 
6076  const char *Exec = getToolChain().getDriver().getClangProgramPath();
6077  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6078 
6079  // Handle the debug info splitting at object creation time if we're
6080  // creating an object.
6081  // TODO: Currently only works on linux with newer objcopy.
6082  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6083  getToolChain().getTriple().isOSLinux())
6084  SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6085  SplitDebugName(Args, Input));
6086 }
6087 
6088 void GnuTool::anchor() {}
6089 
6091  const InputInfo &Output,
6092  const InputInfoList &Inputs, const ArgList &Args,
6093  const char *LinkingOutput) const {
6094  const Driver &D = getToolChain().getDriver();
6095  ArgStringList CmdArgs;
6096 
6097  for (const auto &A : Args) {
6098  if (forwardToGCC(A->getOption())) {
6099  // It is unfortunate that we have to claim here, as this means
6100  // we will basically never report anything interesting for
6101  // platforms using a generic gcc, even if we are just using gcc
6102  // to get to the assembler.
6103  A->claim();
6104 
6105  // Don't forward any -g arguments to assembly steps.
6106  if (isa<AssembleJobAction>(JA) &&
6107  A->getOption().matches(options::OPT_g_Group))
6108  continue;
6109 
6110  // Don't forward any -W arguments to assembly and link steps.
6111  if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6112  A->getOption().matches(options::OPT_W_Group))
6113  continue;
6114 
6115  A->render(Args, CmdArgs);
6116  }
6117  }
6118 
6119  RenderExtraToolArgs(JA, CmdArgs);
6120 
6121  // If using a driver driver, force the arch.
6122  if (getToolChain().getTriple().isOSDarwin()) {
6123  CmdArgs.push_back("-arch");
6124  CmdArgs.push_back(
6125  Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6126  }
6127 
6128  // Try to force gcc to match the tool chain we want, if we recognize
6129  // the arch.
6130  //
6131  // FIXME: The triple class should directly provide the information we want
6132  // here.
6133  switch (getToolChain().getArch()) {
6134  default:
6135  break;
6136  case llvm::Triple::x86:
6137  case llvm::Triple::ppc:
6138  CmdArgs.push_back("-m32");
6139  break;
6140  case llvm::Triple::x86_64:
6141  case llvm::Triple::ppc64:
6142  case llvm::Triple::ppc64le:
6143  CmdArgs.push_back("-m64");
6144  break;
6145  case llvm::Triple::sparcel:
6146  CmdArgs.push_back("-EL");
6147  break;
6148  }
6149 
6150  if (Output.isFilename()) {
6151  CmdArgs.push_back("-o");
6152  CmdArgs.push_back(Output.getFilename());
6153  } else {
6154  assert(Output.isNothing() && "Unexpected output");
6155  CmdArgs.push_back("-fsyntax-only");
6156  }
6157 
6158  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6159 
6160  // Only pass -x if gcc will understand it; otherwise hope gcc
6161  // understands the suffix correctly. The main use case this would go
6162  // wrong in is for linker inputs if they happened to have an odd
6163  // suffix; really the only way to get this to happen is a command
6164  // like '-x foobar a.c' which will treat a.c like a linker input.
6165  //
6166  // FIXME: For the linker case specifically, can we safely convert
6167  // inputs into '-Wl,' options?
6168  for (const auto &II : Inputs) {
6169  // Don't try to pass LLVM or AST inputs to a generic gcc.
6170  if (types::isLLVMIR(II.getType()))
6171  D.Diag(diag::err_drv_no_linker_llvm_support)
6172  << getToolChain().getTripleString();
6173  else if (II.getType() == types::TY_AST)
6174  D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6175  else if (II.getType() == types::TY_ModuleFile)
6176  D.Diag(diag::err_drv_no_module_support)
6177  << getToolChain().getTripleString();
6178 
6179  if (types::canTypeBeUserSpecified(II.getType())) {
6180  CmdArgs.push_back("-x");
6181  CmdArgs.push_back(types::getTypeName(II.getType()));
6182  }
6183 
6184  if (II.isFilename())
6185  CmdArgs.push_back(II.getFilename());
6186  else {
6187  const Arg &A = II.getInputArg();
6188 
6189  // Reverse translate some rewritten options.
6190  if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6191  CmdArgs.push_back("-lstdc++");
6192  continue;
6193  }
6194 
6195  // Don't render as input, we need gcc to do the translations.
6196  A.render(Args, CmdArgs);
6197  }
6198  }
6199 
6200  const std::string customGCCName = D.getCCCGenericGCCName();
6201  const char *GCCName;
6202  if (!customGCCName.empty())
6203  GCCName = customGCCName.c_str();
6204  else if (D.CCCIsCXX()) {
6205  GCCName = "g++";
6206  } else
6207  GCCName = "gcc";
6208 
6209  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6210  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6211 }
6212 
6214  ArgStringList &CmdArgs) const {
6215  CmdArgs.push_back("-E");
6216 }
6217 
6219  ArgStringList &CmdArgs) const {
6220  const Driver &D = getToolChain().getDriver();
6221 
6222  switch (JA.getType()) {
6223  // If -flto, etc. are present then make sure not to force assembly output.
6224  case types::TY_LLVM_IR:
6225  case types::TY_LTO_IR:
6226  case types::TY_LLVM_BC:
6227  case types::TY_LTO_BC:
6228  CmdArgs.push_back("-c");
6229  break;
6230  // We assume we've got an "integrated" assembler in that gcc will produce an
6231  // object file itself.
6232  case types::TY_Object:
6233  CmdArgs.push_back("-c");
6234  break;
6235  case types::TY_PP_Asm:
6236  CmdArgs.push_back("-S");
6237  break;
6238  case types::TY_Nothing:
6239  CmdArgs.push_back("-fsyntax-only");
6240  break;
6241  default:
6242  D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6243  }
6244 }
6245 
6247  ArgStringList &CmdArgs) const {
6248  // The types are (hopefully) good enough.
6249 }
6250 
6251 // Hexagon tools start.
6253  ArgStringList &CmdArgs) const {
6254 }
6255 
6257  const InputInfo &Output,
6258  const InputInfoList &Inputs,
6259  const ArgList &Args,
6260  const char *LinkingOutput) const {
6261  claimNoWarnArgs(Args);
6262 
6263  auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6264  const Driver &D = HTC.getDriver();
6265  ArgStringList CmdArgs;
6266 
6267  std::string MArchString = "-march=hexagon";
6268  CmdArgs.push_back(Args.MakeArgString(MArchString));
6269 
6270  RenderExtraToolArgs(JA, CmdArgs);
6271 
6272  std::string AsName = "hexagon-llvm-mc";
6273  std::string MCpuString = "-mcpu=hexagon" +
6275  CmdArgs.push_back("-filetype=obj");
6276  CmdArgs.push_back(Args.MakeArgString(MCpuString));
6277 
6278  if (Output.isFilename()) {
6279  CmdArgs.push_back("-o");
6280  CmdArgs.push_back(Output.getFilename());
6281  } else {
6282  assert(Output.isNothing() && "Unexpected output");
6283  CmdArgs.push_back("-fsyntax-only");
6284  }
6285 
6287  std::string N = llvm::utostr(G.getValue());
6288  CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6289  }
6290 
6291  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6292 
6293  // Only pass -x if gcc will understand it; otherwise hope gcc
6294  // understands the suffix correctly. The main use case this would go
6295  // wrong in is for linker inputs if they happened to have an odd
6296  // suffix; really the only way to get this to happen is a command
6297  // like '-x foobar a.c' which will treat a.c like a linker input.
6298  //
6299  // FIXME: For the linker case specifically, can we safely convert
6300  // inputs into '-Wl,' options?
6301  for (const auto &II : Inputs) {
6302  // Don't try to pass LLVM or AST inputs to a generic gcc.
6303  if (types::isLLVMIR(II.getType()))
6304  D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6305  << HTC.getTripleString();
6306  else if (II.getType() == types::TY_AST)
6307  D.Diag(clang::diag::err_drv_no_ast_support)
6308  << HTC.getTripleString();
6309  else if (II.getType() == types::TY_ModuleFile)
6310  D.Diag(diag::err_drv_no_module_support)
6311  << HTC.getTripleString();
6312 
6313  if (II.isFilename())
6314  CmdArgs.push_back(II.getFilename());
6315  else
6316  // Don't render as input, we need gcc to do the translations.
6317  // FIXME: What is this?
6318  II.getInputArg().render(Args, CmdArgs);
6319  }
6320 
6321  auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6322  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6323 }
6324 
6326  ArgStringList &CmdArgs) const {
6327 }
6328 
6329 static void
6331  const toolchains::HexagonToolChain &HTC,
6332  const InputInfo &Output, const InputInfoList &Inputs,
6333  const ArgList &Args, ArgStringList &CmdArgs,
6334  const char *LinkingOutput) {
6335 
6336  const Driver &D = HTC.getDriver();
6337 
6338  //----------------------------------------------------------------------------
6339  //
6340  //----------------------------------------------------------------------------
6341  bool IsStatic = Args.hasArg(options::OPT_static);
6342  bool IsShared = Args.hasArg(options::OPT_shared);
6343  bool IsPIE = Args.hasArg(options::OPT_pie);
6344  bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6345  bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6346  bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6347  bool UseG0 = false;
6348  bool UseShared = IsShared && !IsStatic;
6349 
6350  //----------------------------------------------------------------------------
6351  // Silence warnings for various options
6352  //----------------------------------------------------------------------------
6353  Args.ClaimAllArgs(options::OPT_g_Group);
6354  Args.ClaimAllArgs(options::OPT_emit_llvm);
6355  Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6356  // handled somewhere else.
6357  Args.ClaimAllArgs(options::OPT_static_libgcc);
6358 
6359  //----------------------------------------------------------------------------
6360  //
6361  //----------------------------------------------------------------------------
6362  if (Args.hasArg(options::OPT_s))
6363  CmdArgs.push_back("-s");
6364 
6365  if (Args.hasArg(options::OPT_r))
6366  CmdArgs.push_back("-r");
6367 
6368  for (const auto &Opt : HTC.ExtraOpts)
6369  CmdArgs.push_back(Opt.c_str());
6370 
6371  CmdArgs.push_back("-march=hexagon");
6372  std::string CpuVer =
6374  std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6375  CmdArgs.push_back(Args.MakeArgString(MCpuString));
6376 
6377  if (IsShared) {
6378  CmdArgs.push_back("-shared");
6379  // The following should be the default, but doing as hexagon-gcc does.
6380  CmdArgs.push_back("-call_shared");
6381  }
6382 
6383  if (IsStatic)
6384  CmdArgs.push_back("-static");
6385 
6386  if (IsPIE && !IsShared)
6387  CmdArgs.push_back("-pie");
6388 
6390  std::string N = llvm::utostr(G.getValue());
6391  CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6392  UseG0 = G.getValue() == 0;
6393  }
6394 
6395  //----------------------------------------------------------------------------
6396  //
6397  //----------------------------------------------------------------------------
6398  CmdArgs.push_back("-o");
6399  CmdArgs.push_back(Output.getFilename());
6400 
6401  //----------------------------------------------------------------------------
6402  // moslib
6403  //----------------------------------------------------------------------------
6404  std::vector<std::string> OsLibs;
6405  bool HasStandalone = false;
6406 
6407  for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6408  A->claim();
6409  OsLibs.emplace_back(A->getValue());
6410  HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6411  }
6412  if (OsLibs.empty()) {
6413  OsLibs.push_back("standalone");
6414  HasStandalone = true;
6415  }
6416 
6417  //----------------------------------------------------------------------------
6418  // Start Files
6419  //----------------------------------------------------------------------------
6420  const std::string MCpuSuffix = "/" + CpuVer;
6421  const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6422  const std::string RootDir =
6424  const std::string StartSubDir =
6425  "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6426 
6427  auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6428  const char *Name) -> std::string {
6429  std::string RelName = SubDir + Name;
6430  std::string P = HTC.GetFilePath(RelName.c_str());
6431  if (llvm::sys::fs::exists(P))
6432  return P;
6433  return RootDir + RelName;
6434  };
6435 
6436  if (IncStdLib && IncStartFiles) {
6437  if (!IsShared) {
6438  if (HasStandalone) {
6439  std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6440  CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6441  }
6442  std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6443  CmdArgs.push_back(Args.MakeArgString(Crt0));
6444  }
6445  std::string Init = UseShared
6446  ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
6447  : Find(RootDir, StartSubDir, "/init.o");
6448  CmdArgs.push_back(Args.MakeArgString(Init));
6449  }
6450 
6451  //----------------------------------------------------------------------------
6452  // Library Search Paths
6453  //----------------------------------------------------------------------------
6454  const ToolChain::path_list &LibPaths = HTC.getFilePaths();
6455  for (const auto &LibPath : LibPaths)
6456  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
6457 
6458  //----------------------------------------------------------------------------
6459  //
6460  //----------------------------------------------------------------------------
6461  Args.AddAllArgs(CmdArgs,
6462  {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6463  options::OPT_t, options::OPT_u_Group});
6464 
6465  AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
6466 
6467  //----------------------------------------------------------------------------
6468  // Libraries
6469  //----------------------------------------------------------------------------
6470  if (IncStdLib && IncDefLibs) {
6471  if (D.CCCIsCXX()) {
6472  HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
6473  CmdArgs.push_back("-lm");
6474  }
6475 
6476  CmdArgs.push_back("--start-group");
6477 
6478  if (!IsShared) {
6479  for (const std::string &Lib : OsLibs)
6480  CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
6481  CmdArgs.push_back("-lc");
6482  }
6483  CmdArgs.push_back("-lgcc");
6484 
6485  CmdArgs.push_back("--end-group");
6486  }
6487 
6488  //----------------------------------------------------------------------------
6489  // End files
6490  //----------------------------------------------------------------------------
6491  if (IncStdLib && IncStartFiles) {
6492  std::string Fini = UseShared
6493  ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
6494  : Find(RootDir, StartSubDir, "/fini.o");
6495  CmdArgs.push_back(Args.MakeArgString(Fini));
6496  }
6497 }
6498 
6500  const InputInfo &Output,
6501  const InputInfoList &Inputs,
6502  const ArgList &Args,
6503  const char *LinkingOutput) const {
6504  auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6505 
6506  ArgStringList CmdArgs;
6507  constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
6508  LinkingOutput);
6509 
6510  std::string Linker = HTC.GetProgramPath("hexagon-link");
6511  C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6512  CmdArgs, Inputs));
6513 }
6514 // Hexagon tools end.
6515 
6517  const InputInfo &Output,
6518  const InputInfoList &Inputs,
6519  const ArgList &Args,
6520  const char *LinkingOutput) const {
6521 
6522  std::string Linker = getToolChain().GetProgramPath(getShortName());
6523  ArgStringList CmdArgs;
6524  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6525  CmdArgs.push_back("-o");
6526  CmdArgs.push_back(Output.getFilename());
6527  C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6528  CmdArgs, Inputs));
6529 }
6530 // AMDGPU tools end.
6531 
6533  : GnuTool("wasm::Linker", "lld", TC) {}
6534 
6536  return true;
6537 }
6538 
6540  return false;
6541 }
6542 
6544  const InputInfo &Output,
6545  const InputInfoList &Inputs,
6546  const ArgList &Args,
6547  const char *LinkingOutput) const {
6548  const char *Linker = Args.MakeArgString(getToolChain().GetLinkerPath());
6549  ArgStringList CmdArgs;
6550  CmdArgs.push_back("-flavor");
6551  CmdArgs.push_back("ld");
6552 
6553  // Enable garbage collection of unused input sections by default, since code
6554  // size is of particular importance. This is significantly facilitated by
6555  // the enabling of -ffunction-sections and -fdata-sections in
6556  // Clang::ConstructJob.
6557  if (areOptimizationsEnabled(Args))
6558  CmdArgs.push_back("--gc-sections");
6559 
6560  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6561  CmdArgs.push_back("-o");
6562  CmdArgs.push_back(Output.getFilename());
6563  C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
6564 }
6565 
6566 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
6567  std::string MArch;
6568  if (!Arch.empty())
6569  MArch = Arch;
6570  else
6571  MArch = Triple.getArchName();
6572  MArch = StringRef(MArch).split("+").first.lower();
6573 
6574  // Handle -march=native.
6575  if (MArch == "native") {
6576  std::string CPU = llvm::sys::getHostCPUName();
6577  if (CPU != "generic") {
6578  // Translate the native cpu into the architecture suffix for that CPU.
6579  StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
6580  // If there is no valid architecture suffix for this CPU we don't know how
6581  // to handle it, so return no architecture.
6582  if (Suffix.empty())
6583  MArch = "";
6584  else
6585  MArch = std::string("arm") + Suffix.str();
6586  }
6587  }
6588 
6589  return MArch;
6590 }
6591 
6592 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
6593 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
6594  std::string MArch = getARMArch(Arch, Triple);
6595  // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
6596  // here means an -march=native that we can't handle, so instead return no CPU.
6597  if (MArch.empty())
6598  return StringRef();
6599 
6600  // We need to return an empty string here on invalid MArch values as the
6601  // various places that call this function can't cope with a null result.
6602  return Triple.getARMCPUForArch(MArch);
6603 }
6604 
6605 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
6606 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
6607  const llvm::Triple &Triple) {
6608  // FIXME: Warn on inconsistent use of -mcpu and -march.
6609  // If we have -mcpu=, use that.
6610  if (!CPU.empty()) {
6611  std::string MCPU = StringRef(CPU).split("+").first.lower();
6612  // Handle -mcpu=native.
6613  if (MCPU == "native")
6614  return llvm::sys::getHostCPUName();
6615  else
6616  return MCPU;
6617  }
6618 
6619  return getARMCPUForMArch(Arch, Triple);
6620 }
6621 
6622 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
6623 /// CPU (or Arch, if CPU is generic).
6624 // FIXME: This is redundant with -mcpu, why does LLVM use this.
6625 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
6626  const llvm::Triple &Triple) {
6627  unsigned ArchKind;
6628  if (CPU == "generic") {
6629  std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
6630  ArchKind = llvm::ARM::parseArch(ARMArch);
6631  if (ArchKind == llvm::ARM::AK_INVALID)
6632  // In case of generic Arch, i.e. "arm",
6633  // extract arch from default cpu of the Triple
6634  ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
6635  } else {
6636  // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
6637  // armv7k triple if it's actually been specified via "-arch armv7k".
6638  ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
6639  ? (unsigned)llvm::ARM::AK_ARMV7K
6640  : llvm::ARM::parseCPUArch(CPU);
6641  }
6642  if (ArchKind == llvm::ARM::AK_INVALID)
6643  return "";
6644  return llvm::ARM::getSubArch(ArchKind);
6645 }
6646 
6647 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
6648  const llvm::Triple &Triple) {
6649  if (Args.hasArg(options::OPT_r))
6650  return;
6651 
6652  // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
6653  // to generate BE-8 executables.
6654  if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
6655  CmdArgs.push_back("--be8");
6656 }
6657 
6659  // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
6660  // was first introduced in Release 3. However, other compilers have
6661  // traditionally allowed it for Release 2 so we should do the same.
6662  return (NanEncoding)llvm::StringSwitch<int>(CPU)
6663  .Case("mips1", NanLegacy)
6664  .Case("mips2", NanLegacy)
6665  .Case("mips3", NanLegacy)
6666  .Case("mips4", NanLegacy)
6667  .Case("mips5", NanLegacy)
6668  .Case("mips32", NanLegacy)
6669  .Case("mips32r2", NanLegacy | Nan2008)
6670  .Case("mips32r3", NanLegacy | Nan2008)
6671  .Case("mips32r5", NanLegacy | Nan2008)
6672  .Case("mips32r6", Nan2008)
6673  .Case("mips64", NanLegacy)
6674  .Case("mips64r2", NanLegacy | Nan2008)
6675  .Case("mips64r3", NanLegacy | Nan2008)
6676  .Case("mips64r5", NanLegacy | Nan2008)
6677  .Case("mips64r6", Nan2008)
6678  .Default(NanLegacy);
6679 }
6680 
6681 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
6682  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6683  return A && (A->getValue() == StringRef(Value));
6684 }
6685 
6686 bool mips::isUCLibc(const ArgList &Args) {
6687  Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
6688  return A && A->getOption().matches(options::OPT_muclibc);
6689 }
6690 
6691 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
6692  if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
6693  return llvm::StringSwitch<bool>(NaNArg->getValue())
6694  .Case("2008", true)
6695  .Case("legacy", false)
6696  .Default(false);
6697 
6698  // NaN2008 is the default for MIPS32r6/MIPS64r6.
6699  return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6700  .Cases("mips32r6", "mips64r6", true)
6701  .Default(false);
6702 
6703  return false;
6704 }
6705 
6706 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6707  StringRef ABIName, mips::FloatABI FloatABI) {
6708  if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6709  Triple.getVendor() != llvm::Triple::MipsTechnologies)
6710  return false;
6711 
6712  if (ABIName != "32")
6713  return false;
6714 
6715  // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6716  // present.
6717  if (FloatABI == mips::FloatABI::Soft)
6718  return false;
6719 
6720  return llvm::StringSwitch<bool>(CPUName)
6721  .Cases("mips2", "mips3", "mips4", "mips5", true)
6722  .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6723  .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6724  .Default(false);
6725 }
6726 
6727 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6728  StringRef CPUName, StringRef ABIName,
6729  mips::FloatABI FloatABI) {
6730  bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6731 
6732  // FPXX shouldn't be used if -msingle-float is present.
6733  if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6734  options::OPT_mdouble_float))
6735  if (A->getOption().matches(options::OPT_msingle_float))
6736  UseFPXX = false;
6737 
6738  return UseFPXX;
6739 }
6740 
6741 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6742  // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6743  // archs which Darwin doesn't use.
6744 
6745  // The matching this routine does is fairly pointless, since it is neither the
6746  // complete architecture list, nor a reasonable subset. The problem is that
6747  // historically the driver driver accepts this and also ties its -march=
6748  // handling to the architecture name, so we need to be careful before removing
6749  // support for it.
6750 
6751  // This code must be kept in sync with Clang's Darwin specific argument
6752  // translation.
6753 
6754  return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6755  .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6756  .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6757  .Case("ppc64", llvm::Triple::ppc64)
6758  .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6759  .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6760  llvm::Triple::x86)
6761  .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6762  // This is derived from the driver driver.
6763  .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6764  .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6765  .Cases("armv7s", "xscale", llvm::Triple::arm)
6766  .Case("arm64", llvm::Triple::aarch64)
6767  .Case("r600", llvm::Triple::r600)
6768  .Case("amdgcn", llvm::Triple::amdgcn)
6769  .Case("nvptx", llvm::Triple::nvptx)
6770  .Case("nvptx64", llvm::Triple::nvptx64)
6771  .Case("amdil", llvm::Triple::amdil)
6772  .Case("spir", llvm::Triple::spir)
6773  .Default(llvm::Triple::UnknownArch);
6774 }
6775 
6776 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6777  const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6778  T.setArch(Arch);
6779 
6780  if (Str == "x86_64h")
6781  T.setArchName(Str);
6782  else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6783  T.setOS(llvm::Triple::UnknownOS);
6784  T.setObjectFormat(llvm::Triple::MachO);
6785  }
6786 }
6787 
6788 const char *Clang::getBaseInputName(const ArgList &Args,
6789  const InputInfo &Input) {
6790  return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6791 }
6792 
6793 const char *Clang::getBaseInputStem(const ArgList &Args,
6794  const InputInfoList &Inputs) {
6795  const char *Str = getBaseInputName(Args, Inputs[0]);
6796 
6797  if (const char *End = strrchr(Str, '.'))
6798  return Args.MakeArgString(std::string(Str, End));
6799 
6800  return Str;
6801 }
6802 
6803 const char *Clang::getDependencyFileName(const ArgList &Args,
6804  const InputInfoList &Inputs) {
6805  // FIXME: Think about this more.
6806  std::string Res;
6807 
6808  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6809  std::string Str(OutputOpt->getValue());
6810  Res = Str.substr(0, Str.rfind('.'));
6811  } else {
6812  Res = getBaseInputStem(Args, Inputs);
6813  }
6814  return Args.MakeArgString(Res + ".d");
6815 }
6816 
6818  const InputInfo &Output,
6819  const InputInfoList &Inputs,
6820  const ArgList &Args,
6821  const char *LinkingOutput) const {
6822  const ToolChain &ToolChain = getToolChain();
6823  const Driver &D = ToolChain.getDriver();
6824  ArgStringList CmdArgs;
6825 
6826  // Silence warning for "clang -g foo.o -o foo"
6827  Args.ClaimAllArgs(options::OPT_g_Group);
6828  // and "clang -emit-llvm foo.o -o foo"
6829  Args.ClaimAllArgs(options::OPT_emit_llvm);
6830  // and for "clang -w foo.o -o foo". Other warning options are already
6831  // handled somewhere else.
6832  Args.ClaimAllArgs(options::OPT_w);
6833 
6834  if (!D.SysRoot.empty())
6835  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6836 
6837  // CloudABI only supports static linkage.
6838  CmdArgs.push_back("-Bstatic");
6839  CmdArgs.push_back("--eh-frame-hdr");
6840  CmdArgs.push_back("--gc-sections");
6841 
6842  if (Output.isFilename()) {
6843  CmdArgs.push_back("-o");
6844  CmdArgs.push_back(Output.getFilename());
6845  } else {
6846  assert(Output.isNothing() && "Invalid output.");
6847  }
6848 
6849  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
6850  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6851  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6852  }
6853 
6854  Args.AddAllArgs(CmdArgs, options::OPT_L);
6855  ToolChain.AddFilePathLibArgs(Args, CmdArgs);
6856  Args.AddAllArgs(CmdArgs,
6857  {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6858  options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
6859 
6860  if (D.isUsingLTO())
6861  AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
6862 
6863  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6864 
6865  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6866  if (D.CCCIsCXX())
6867  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6868  CmdArgs.push_back("-lc");
6869  CmdArgs.push_back("-lcompiler_rt");
6870  }
6871 
6872  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
6873  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6874 
6875  const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6876  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6877 }
6878 
6880  const InputInfo &Output,
6881  const InputInfoList &Inputs,
6882  const ArgList &Args,
6883  const char *LinkingOutput) const {
6884  ArgStringList CmdArgs;
6885 
6886  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6887  const InputInfo &Input = Inputs[0];
6888 
6889  // Determine the original source input.
6890  const Action *SourceAction = &JA;
6891  while (SourceAction->getKind() != Action::InputClass) {
6892  assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6893  SourceAction = SourceAction->getInputs()[0];
6894  }
6895 
6896  // If -fno-integrated-as is used add -Q to the darwin assember driver to make
6897  // sure it runs its system assembler not clang's integrated assembler.
6898  // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
6899  // FIXME: at run-time detect assembler capabilities or rely on version
6900  // information forwarded by -target-assembler-version.
6901  if (Args.hasArg(options::OPT_fno_integrated_as)) {
6902  const llvm::Triple &T(getToolChain().getTriple());
6903  if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6904  CmdArgs.push_back("-Q");
6905  }
6906 
6907  // Forward -g, assuming we are dealing with an actual assembly file.
6908  if (SourceAction->getType() == types::TY_Asm ||
6909  SourceAction->getType() == types::TY_PP_Asm) {
6910  if (Args.hasArg(options::OPT_gstabs))
6911  CmdArgs.push_back("--gstabs");
6912  else if (Args.hasArg(options::OPT_g_Group))
6913  CmdArgs.push_back("-g");
6914  }
6915 
6916  // Derived from asm spec.
6917  AddMachOArch(Args, CmdArgs);
6918 
6919  // Use -force_cpusubtype_ALL on x86 by default.
6920  if (getToolChain().getArch() == llvm::Triple::x86 ||
6921  getToolChain().getArch() == llvm::Triple::x86_64 ||
6922  Args.hasArg(options::OPT_force__cpusubtype__ALL))
6923  CmdArgs.push_back("-force_cpusubtype_ALL");
6924 
6925  if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6926  (((Args.hasArg(options::OPT_mkernel) ||
6927  Args.hasArg(options::OPT_fapple_kext)) &&
6928  getMachOToolChain().isKernelStatic()) ||
6929  Args.hasArg(options::OPT_static)))
6930  CmdArgs.push_back("-static");
6931 
6932  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6933 
6934  assert(Output.isFilename() && "Unexpected lipo output.");
6935  CmdArgs.push_back("-o");
6936  CmdArgs.push_back(Output.getFilename());
6937 
6938  assert(Input.isFilename() && "Invalid input.");
6939  CmdArgs.push_back(Input.getFilename());
6940 
6941  // asm_final spec is empty.
6942 
6943  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6944  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6945 }
6946 
6947 void darwin::MachOTool::anchor() {}
6948 
6949 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6950  ArgStringList &CmdArgs) const {
6951  StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6952 
6953  // Derived from darwin_arch spec.
6954  CmdArgs.push_back("-arch");
6955  CmdArgs.push_back(Args.MakeArgString(ArchName));
6956 
6957  // FIXME: Is this needed anymore?
6958  if (ArchName == "arm")
6959  CmdArgs.push_back("-force_cpusubtype_ALL");
6960 }
6961 
6962 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6963  // We only need to generate a temp path for LTO if we aren't compiling object
6964  // files. When compiling source files, we run 'dsymutil' after linking. We
6965  // don't run 'dsymutil' when compiling object files.
6966  for (const auto &Input : Inputs)
6967  if (Input.getType() != types::TY_Object)
6968  return true;
6969 
6970  return false;
6971 }
6972 
6973 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6974  ArgStringList &CmdArgs,
6975  const InputInfoList &Inputs) const {
6976  const Driver &D = getToolChain().getDriver();
6977  const toolchains::MachO &MachOTC = getMachOToolChain();
6978 
6979  unsigned Version[3] = {0, 0, 0};
6980  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6981  bool HadExtra;
6982  if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6983  Version[2], HadExtra) ||
6984  HadExtra)
6985  D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6986  }
6987 
6988  // Newer linkers support -demangle. Pass it if supported and not disabled by
6989  // the user.
6990  if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6991  CmdArgs.push_back("-demangle");
6992 
6993  if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6994  CmdArgs.push_back("-export_dynamic");
6995 
6996  // If we are using App Extension restrictions, pass a flag to the linker
6997  // telling it that the compiled code has been audited.
6998  if (Args.hasFlag(options::OPT_fapplication_extension,
6999  options::OPT_fno_application_extension, false))
7000  CmdArgs.push_back("-application_extension");
7001 
7002  if (D.isUsingLTO()) {
7003  // If we are using LTO, then automatically create a temporary file path for
7004  // the linker to use, so that it's lifetime will extend past a possible
7005  // dsymutil step.
7006  if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7007  const char *TmpPath = C.getArgs().MakeArgString(
7008  D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7009  C.addTempFile(TmpPath);
7010  CmdArgs.push_back("-object_path_lto");
7011  CmdArgs.push_back(TmpPath);
7012  }
7013 
7014  // Use -lto_library option to specify the libLTO.dylib path. Try to find
7015  // it in clang installed libraries. If not found, the option is not used
7016  // and 'ld' will use its default mechanism to search for libLTO.dylib.
7017  if (Version[0] >= 133) {
7018  // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7019  StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
7020  SmallString<128> LibLTOPath(P);
7021  llvm::sys::path::append(LibLTOPath, "lib");
7022  llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7023  if (llvm::sys::fs::exists(LibLTOPath)) {
7024  CmdArgs.push_back("-lto_library");
7025  CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7026  } else {
7027  D.Diag(diag::warn_drv_lto_libpath);
7028  }
7029  }
7030  }
7031 
7032  // Derived from the "link" spec.
7033  Args.AddAllArgs(CmdArgs, options::OPT_static);
7034  if (!Args.hasArg(options::OPT_static))
7035  CmdArgs.push_back("-dynamic");
7036  if (Args.hasArg(options::OPT_fgnu_runtime)) {
7037  // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7038  // here. How do we wish to handle such things?
7039  }
7040 
7041  if (!Args.hasArg(options::OPT_dynamiclib)) {
7042  AddMachOArch(Args, CmdArgs);
7043  // FIXME: Why do this only on this path?
7044  Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7045 
7046  Args.AddLastArg(CmdArgs, options::OPT_bundle);
7047  Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7048  Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7049 
7050  Arg *A;
7051  if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7052  (A = Args.getLastArg(options::OPT_current__version)) ||
7053  (A = Args.getLastArg(options::OPT_install__name)))
7054  D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7055  << "-dynamiclib";
7056 
7057  Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7058  Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7059  Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7060  } else {
7061  CmdArgs.push_back("-dylib");
7062 
7063  Arg *A;
7064  if ((A = Args.getLastArg(options::OPT_bundle)) ||
7065  (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7066  (A = Args.getLastArg(options::OPT_client__name)) ||
7067  (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7068  (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7069  (A = Args.getLastArg(options::OPT_private__bundle)))
7070  D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7071  << "-dynamiclib";
7072 
7073  Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7074  "-dylib_compatibility_version");
7075  Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7076  "-dylib_current_version");
7077 
7078  AddMachOArch(Args, CmdArgs);
7079 
7080  Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7081  "-dylib_install_name");
7082  }
7083 
7084  Args.AddLastArg(CmdArgs, options::OPT_all__load);
7085  Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7086  Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7087  if (MachOTC.isTargetIOSBased())
7088  Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7089  Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7090  Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7091  Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7092  Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7093  Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7094  Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7095  Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7096  Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7097  Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7098  Args.AddAllArgs(CmdArgs, options::OPT_init);
7099 
7100  // Add the deployment target.
7101  MachOTC.addMinVersionArgs(Args, CmdArgs);
7102 
7103  Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7104  Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7105  Args.AddLastArg(CmdArgs, options::OPT_single__module);
7106  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7107  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7108 
7109  if (const Arg *A =
7110  Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7111  options::OPT_fno_pie, options::OPT_fno_PIE)) {
7112  if (A->getOption().matches(options::OPT_fpie) ||
7113  A->getOption().matches(options::OPT_fPIE))
7114  CmdArgs.push_back("-pie");
7115  else
7116  CmdArgs.push_back("-no_pie");
7117  }
7118 
7119  Args.AddLastArg(CmdArgs, options::OPT_prebind);
7120  Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7121  Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7122  Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7123  Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7124  Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7125  Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7126  Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7127  Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7128  Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7129  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7130  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7131  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7132  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7133  Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7134  Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7135 
7136  // Give --sysroot= preference, over the Apple specific behavior to also use
7137  // --isysroot as the syslibroot.
7138  StringRef sysroot = C.getSysRoot();
7139  if (sysroot != "") {
7140  CmdArgs.push_back("-syslibroot");
7141  CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7142  } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7143  CmdArgs.push_back("-syslibroot");
7144  CmdArgs.push_back(A->getValue());
7145  }
7146 
7147  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7148  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7149  Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7150  Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7151  Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7152  Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7153  Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7154  Args.AddAllArgs(CmdArgs, options::OPT_y);
7155  Args.AddLastArg(CmdArgs, options::OPT_w);
7156  Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7157  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7158  Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7159  Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7160  Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7161  Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7162  Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7163  Args.AddLastArg(CmdArgs, options::OPT_whyload);
7164  Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7165  Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7166  Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7167  Args.AddLastArg(CmdArgs, options::OPT_Mach);
7168 }
7169 
7171  const InputInfo &Output,
7172  const InputInfoList &Inputs,
7173  const ArgList &Args,
7174  const char *LinkingOutput) const {
7175  assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7176 
7177  // If the number of arguments surpasses the system limits, we will encode the
7178  // input files in a separate file, shortening the command line. To this end,
7179  // build a list of input file names that can be passed via a file with the
7180  // -filelist linker option.
7181  llvm::opt::ArgStringList InputFileList;
7182 
7183  // The logic here is derived from gcc's behavior; most of which
7184  // comes from specs (starting with link_command). Consult gcc for
7185  // more information.
7186  ArgStringList CmdArgs;
7187 
7188  /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7189  if (Args.hasArg(options::OPT_ccc_arcmt_check,
7190  options::OPT_ccc_arcmt_migrate)) {
7191  for (const auto &Arg : Args)
7192  Arg->claim();
7193  const char *Exec =
7194  Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7195  CmdArgs.push_back(Output.getFilename());
7196  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7197  return;
7198  }
7199 
7200  // I'm not sure why this particular decomposition exists in gcc, but
7201  // we follow suite for ease of comparison.
7202  AddLinkArgs(C, Args, CmdArgs, Inputs);
7203 
7204  // It seems that the 'e' option is completely ignored for dynamic executables
7205  // (the default), and with static executables, the last one wins, as expected.
7206  Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7207  options::OPT_Z_Flag, options::OPT_u_Group,
7208  options::OPT_e, options::OPT_r});
7209 
7210  // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7211  // members of static archive libraries which implement Objective-C classes or
7212  // categories.
7213  if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7214  CmdArgs.push_back("-ObjC");
7215 
7216  CmdArgs.push_back("-o");
7217  CmdArgs.push_back(Output.getFilename());
7218 
7219  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7220  getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7221 
7222  // SafeStack requires its own runtime libraries
7223  // These libraries should be linked first, to make sure the
7224  // __safestack_init constructor executes before everything else
7225  if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7226  getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7227  "libclang_rt.safestack_osx.a",
7228  /*AlwaysLink=*/true);
7229  }
7230 
7231  Args.AddAllArgs(CmdArgs, options::OPT_L);
7232 
7233  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7234  // Build the input file for -filelist (list of linker input files) in case we
7235  // need it later
7236  for (const auto &II : Inputs) {
7237  if (!II.isFilename()) {
7238  // This is a linker input argument.
7239  // We cannot mix input arguments and file names in a -filelist input, thus
7240  // we prematurely stop our list (remaining files shall be passed as
7241  // arguments).
7242  if (InputFileList.size() > 0)
7243  break;
7244 
7245  continue;
7246  }
7247 
7248  InputFileList.push_back(II.getFilename());
7249  }
7250 
7251  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7252  addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7253 
7254  if (isObjCRuntimeLinked(Args) &&
7255  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7256  // We use arclite library for both ARC and subscripting support.
7257  getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7258 
7259  CmdArgs.push_back("-framework");
7260  CmdArgs.push_back("Foundation");
7261  // Link libobj.
7262  CmdArgs.push_back("-lobjc");
7263  }
7264 
7265  if (LinkingOutput) {
7266  CmdArgs.push_back("-arch_multiple");
7267  CmdArgs.push_back("-final_output");
7268  CmdArgs.push_back(LinkingOutput);
7269  }
7270 
7271  if (Args.hasArg(options::OPT_fnested_functions))
7272  CmdArgs.push_back("-allow_stack_execute");
7273 
7274  getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7275 
7276  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7277  if (getToolChain().getDriver().CCCIsCXX())
7278  getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7279 
7280  // link_ssp spec is empty.
7281 
7282  // Let the tool chain choose which runtime library to link.
7283  getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7284  }
7285 
7286  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7287  // endfile_spec is empty.
7288  }
7289 
7290  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7291  Args.AddAllArgs(CmdArgs, options::OPT_F);
7292 
7293  // -iframework should be forwarded as -F.
7294  for (const Arg *A : Args.filtered(options::OPT_iframework))
7295  CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7296 
7297  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7298  if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7299  if (A->getValue() == StringRef("Accelerate")) {
7300  CmdArgs.push_back("-framework");
7301  CmdArgs.push_back("Accelerate");
7302  }
7303  }
7304  }
7305 
7306  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7307  std::unique_ptr<Command> Cmd =
7308  llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7309  Cmd->setInputFileList(std::move(InputFileList));
7310  C.addCommand(std::move(Cmd));
7311 }
7312 
7314  const InputInfo &Output,
7315  const InputInfoList &Inputs,
7316  const ArgList &Args,
7317  const char *LinkingOutput) const {
7318  ArgStringList CmdArgs;
7319 
7320  CmdArgs.push_back("-create");
7321  assert(Output.isFilename() && "Unexpected lipo output.");
7322 
7323  CmdArgs.push_back("-output");
7324  CmdArgs.push_back(Output.getFilename());
7325 
7326  for (const auto &II : Inputs) {
7327  assert(II.isFilename() && "Unexpected lipo input.");
7328  CmdArgs.push_back(II.getFilename());
7329  }
7330 
7331  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7332  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7333 }
7334 
7336  const InputInfo &Output,
7337  const InputInfoList &Inputs,
7338  const ArgList &Args,
7339  const char *LinkingOutput) const {
7340  ArgStringList CmdArgs;
7341 
7342  CmdArgs.push_back("-o");
7343  CmdArgs.push_back(Output.getFilename());
7344 
7345  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7346  const InputInfo &Input = Inputs[0];
7347  assert(Input.isFilename() && "Unexpected dsymutil input.");
7348  CmdArgs.push_back(Input.getFilename());
7349 
7350  const char *Exec =
7351  Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7352  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7353 }
7354 
7356  const InputInfo &Output,
7357  const InputInfoList &Inputs,
7358  const ArgList &Args,
7359  const char *LinkingOutput) const {
7360  ArgStringList CmdArgs;
7361  CmdArgs.push_back("--verify");
7362  CmdArgs.push_back("--debug-info");
7363  CmdArgs.push_back("--eh-frame");
7364  CmdArgs.push_back("--quiet");
7365 
7366  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7367  const InputInfo &Input = Inputs[0];
7368  assert(Input.isFilename() && "Unexpected verify input");
7369 
7370  // Grabbing the output of the earlier dsymutil run.
7371  CmdArgs.push_back(Input.getFilename());
7372 
7373  const char *Exec =
7374  Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
7375  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7376 }
7377 
7379  const InputInfo &Output,
7380  const InputInfoList &Inputs,
7381  const ArgList &Args,
7382  const char *LinkingOutput) const {
7383  claimNoWarnArgs(Args);
7384  ArgStringList CmdArgs;
7385 
7386  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7387 
7388  CmdArgs.push_back("-o");
7389  CmdArgs.push_back(Output.getFilename());
7390 
7391  for (const auto &II : Inputs)
7392  CmdArgs.push_back(II.getFilename());
7393 
7394  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7395  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7396 }
7397 
7399  const InputInfo &Output,
7400  const InputInfoList &Inputs,
7401  const ArgList &Args,
7402  const char *LinkingOutput) const {
7403  ArgStringList CmdArgs;
7404 
7405  // Demangle C++ names in errors
7406  CmdArgs.push_back("-C");
7407 
7408  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7409  CmdArgs.push_back("-e");
7410  CmdArgs.push_back("_start");
7411  }
7412 
7413  if (Args.hasArg(options::OPT_static)) {
7414  CmdArgs.push_back("-Bstatic");
7415  CmdArgs.push_back("-dn");
7416  } else {
7417  CmdArgs.push_back("-Bdynamic");
7418  if (Args.hasArg(options::OPT_shared)) {
7419  CmdArgs.push_back("-shared");
7420  } else {
7421  CmdArgs.push_back("--dynamic-linker");
7422  CmdArgs.push_back(
7423  Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
7424  }
7425  }
7426 
7427  if (Output.isFilename()) {
7428  CmdArgs.push_back("-o");
7429  CmdArgs.push_back(Output.getFilename());
7430  } else {
7431  assert(Output.isNothing() && "Invalid output.");
7432  }
7433 
7434  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7435  if (!Args.hasArg(options::OPT_shared))
7436  CmdArgs.push_back(
7437  Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
7438 
7439  CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7440  CmdArgs.push_back(
7441  Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
7442  CmdArgs.push_back(
7443  Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7444  }
7445 
7446  getToolChain().AddFilePathLibArgs(Args, CmdArgs);
7447 
7448  Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7449  options::OPT_e, options::OPT_r});
7450 
7451  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7452 
7453  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7454  if (getToolChain().getDriver().CCCIsCXX())
7455  getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7456  CmdArgs.push_back("-lgcc_s");
7457  CmdArgs.push_back("-lc");
7458  if (!Args.hasArg(options::OPT_shared)) {
7459  CmdArgs.push_back("-lgcc");
7460  CmdArgs.push_back("-lm");
7461  }
7462  }
7463 
7464  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7465  CmdArgs.push_back(
7466  Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7467  }
7468  CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7469 
7470  getToolChain().addProfileRTLibs(Args, CmdArgs);
7471 
7472  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7473  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7474 }
7475 
7477  const InputInfo &Output,
7478  const InputInfoList &Inputs,
7479  const ArgList &Args,
7480  const char *LinkingOutput) const {
7481  claimNoWarnArgs(Args);
7482  ArgStringList CmdArgs;
7483 
7484  switch (getToolChain().getArch()) {
7485  case llvm::Triple::x86:
7486  // When building 32-bit code on OpenBSD/amd64, we have to explicitly
7487  // instruct as in the base system to assemble 32-bit code.
7488  CmdArgs.push_back("--32");
7489  break;
7490 
7491  case llvm::Triple::ppc:
7492  CmdArgs.push_back("-mppc");
7493  CmdArgs.push_back("-many");
7494  break;
7495 
7496  case llvm::Triple::sparc:
7497  case llvm::Triple::sparcel: {
7498  CmdArgs.push_back("-32");
7499  std::string CPU = getCPUName(Args, getToolChain().getTriple());
7500  CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7501  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7502  break;
7503  }
7504 
7505  case llvm::Triple::sparcv9: {
7506  CmdArgs.push_back("-64");
7507  std::string CPU = getCPUName(Args, getToolChain().getTriple());
7508  CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7509  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7510  break;
7511  }
7512 
7513  case llvm::Triple::mips64:
7514  case llvm::Triple::mips64el: {
7515  StringRef CPUName;
7516  StringRef ABIName;
7517  mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7518 
7519  CmdArgs.push_back("-mabi");
7520  CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7521 
7522  if (getToolChain().getArch() == llvm::Triple::mips64)
7523  CmdArgs.push_back("-EB");
7524  else
7525  CmdArgs.push_back("-EL");
7526 
7527  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7528  break;
7529  }
7530 
7531  default:
7532  break;
7533  }
7534 
7535  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7536 
7537  CmdArgs.push_back("-o");
7538  CmdArgs.push_back(Output.getFilename());
7539 
7540  for (const auto &II : Inputs)
7541  CmdArgs.push_back(II.getFilename());
7542 
7543  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7544  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7545 }
7546 
7548  const InputInfo &Output,
7549  const InputInfoList &Inputs,
7550  const ArgList &Args,
7551  const char *LinkingOutput) const {
7552  const Driver &D = getToolChain().getDriver();
7553  ArgStringList CmdArgs;
7554 
7555  // Silence warning for "clang -g foo.o -o foo"
7556  Args.ClaimAllArgs(options::OPT_g_Group);
7557  // and "clang -emit-llvm foo.o -o foo"
7558  Args.ClaimAllArgs(options::OPT_emit_llvm);
7559  // and for "clang -w foo.o -o foo". Other warning options are already
7560  // handled somewhere else.
7561  Args.ClaimAllArgs(options::OPT_w);
7562 
7563  if (getToolChain().getArch() == llvm::Triple::mips64)
7564  CmdArgs.push_back("-EB");
7565  else if (getToolChain().getArch() == llvm::Triple::mips64el)
7566  CmdArgs.push_back("-EL");
7567 
7568  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7569  CmdArgs.push_back("-e");
7570  CmdArgs.push_back("__start");
7571  }
7572 
7573  if (Args.hasArg(options::OPT_static)) {
7574  CmdArgs.push_back("-Bstatic");
7575  } else {
7576  if (Args.hasArg(options::OPT_rdynamic))
7577  CmdArgs.push_back("-export-dynamic");
7578  CmdArgs.push_back("--eh-frame-hdr");
7579  CmdArgs.push_back("-Bdynamic");
7580  if (Args.hasArg(options::OPT_shared)) {
7581  CmdArgs.push_back("-shared");
7582  } else {
7583  CmdArgs.push_back("-dynamic-linker");
7584  CmdArgs.push_back("/usr/libexec/ld.so");
7585  }
7586  }
7587 
7588  if (Args.hasArg(options::OPT_nopie))
7589  CmdArgs.push_back("-nopie");
7590 
7591  if (Output.isFilename()) {
7592  CmdArgs.push_back("-o");
7593  CmdArgs.push_back(Output.getFilename());
7594  } else {
7595  assert(Output.isNothing() && "Invalid output.");
7596  }
7597 
7598  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7599  if (!Args.hasArg(options::OPT_shared)) {
7600  if (Args.hasArg(options::OPT_pg))
7601  CmdArgs.push_back(
7602  Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7603  else
7604  CmdArgs.push_back(
7605  Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7606  CmdArgs.push_back(
7607  Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7608  } else {
7609  CmdArgs.push_back(
7610  Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7611  }
7612  }
7613 
7614  std::string Triple = getToolChain().getTripleString();
7615  if (Triple.substr(0, 6) == "x86_64")
7616  Triple.replace(0, 6, "amd64");
7617  CmdArgs.push_back(
7618  Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
7619 
7620  Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7621  options::OPT_e, options::OPT_s, options::OPT_t,
7622  options::OPT_Z_Flag, options::OPT_r});
7623 
7624  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7625 
7626  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7627  if (D.CCCIsCXX()) {
7628  getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7629  if (Args.hasArg(options::OPT_pg))
7630  CmdArgs.push_back("-lm_p");
7631  else
7632  CmdArgs.push_back("-lm");
7633  }
7634 
7635  // FIXME: For some reason GCC passes -lgcc before adding
7636  // the default system libraries. Just mimic this for now.
7637  CmdArgs.push_back("-lgcc");
7638 
7639  if (Args.hasArg(options::OPT_pthread)) {
7640  if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7641  CmdArgs.push_back("-lpthread_p");
7642  else
7643  CmdArgs.push_back("-lpthread");
7644  }
7645 
7646  if (!Args.hasArg(options::OPT_shared)) {
7647  if (Args.hasArg(options::OPT_pg))
7648  CmdArgs.push_back("-lc_p");
7649  else
7650  CmdArgs.push_back("-lc");
7651  }
7652 
7653  CmdArgs.push_back("-lgcc");
7654  }
7655 
7656  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7657  if (!Args.hasArg(options::OPT_shared))
7658  CmdArgs.push_back(
7659  Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7660  else
7661  CmdArgs.push_back(
7662  Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7663  }
7664 
7665  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7666  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7667 }
7668 
7670  const InputInfo &Output,
7671  const InputInfoList &Inputs,
7672  const ArgList &Args,
7673  const char *LinkingOutput) const {
7674  claimNoWarnArgs(Args);
7675  ArgStringList CmdArgs;
7676 
7677  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7678 
7679  CmdArgs.push_back("-o");
7680  CmdArgs.push_back(Output.getFilename());
7681 
7682  for (const auto &II : Inputs)
7683  CmdArgs.push_back(II.getFilename());
7684 
7685  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7686  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7687 }
7688 
7690  const InputInfo &Output,
7691  const InputInfoList &Inputs,
7692  const ArgList &Args,
7693  const char *LinkingOutput) const {
7694  const Driver &D = getToolChain().getDriver();
7695  ArgStringList CmdArgs;
7696 
7697  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7698  CmdArgs.push_back("-e");
7699  CmdArgs.push_back("__start");
7700  }
7701 
7702  if (Args.hasArg(options::OPT_static)) {
7703  CmdArgs.push_back("-Bstatic");
7704  } else {
7705  if (Args.hasArg(options::OPT_rdynamic))
7706  CmdArgs.push_back("-export-dynamic");
7707  CmdArgs.push_back("--eh-frame-hdr");
7708  CmdArgs.push_back("-Bdynamic");
7709  if (Args.hasArg(options::OPT_shared)) {
7710  CmdArgs.push_back("-shared");
7711  } else {
7712  CmdArgs.push_back("-dynamic-linker");
7713  CmdArgs.push_back("/usr/libexec/ld.so");
7714  }
7715  }
7716 
7717  if (Output.isFilename()) {
7718  CmdArgs.push_back("-o");
7719  CmdArgs.push_back(Output.getFilename());
7720  } else {
7721  assert(Output.isNothing() && "Invalid output.");
7722  }
7723 
7724  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7725  if (!Args.hasArg(options::OPT_shared)) {
7726  if (Args.hasArg(options::OPT_pg))
7727  CmdArgs.push_back(
7728  Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7729  else
7730  CmdArgs.push_back(
7731  Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7732  CmdArgs.push_back(
7733  Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7734  } else {
7735  CmdArgs.push_back(
7736  Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7737  }
7738  }
7739 
7740  Args.AddAllArgs(CmdArgs,
7741  {options::OPT_L, options::OPT_T_Group, options::OPT_e});
7742 
7743  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7744 
7745  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7746  if (D.CCCIsCXX()) {
7747  getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7748  if (Args.hasArg(options::OPT_pg))
7749  CmdArgs.push_back("-lm_p");
7750  else
7751  CmdArgs.push_back("-lm");
7752  }
7753 
7754  if (Args.hasArg(options::OPT_pthread)) {
7755  if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7756  CmdArgs.push_back("-lpthread_p");
7757  else
7758  CmdArgs.push_back("-lpthread");
7759  }
7760 
7761  if (!Args.hasArg(options::OPT_shared)) {
7762  if (Args.hasArg(options::OPT_pg))
7763  CmdArgs.push_back("-lc_p");
7764  else
7765  CmdArgs.push_back("-lc");
7766  }
7767 
7768  StringRef MyArch;
7769  switch (getToolChain().getArch()) {
7770  case llvm::Triple::arm:
7771  MyArch = "arm";
7772  break;
7773  case llvm::Triple::x86:
7774  MyArch = "i386";
7775  break;
7776  case llvm::Triple::x86_64:
7777  MyArch = "amd64";
7778  break;
7779  default:
7780  llvm_unreachable("Unsupported architecture");
7781  }
7782  CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7783  }
7784 
7785  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7786  if (!Args.hasArg(options::OPT_shared))
7787  CmdArgs.push_back(
7788  Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7789  else
7790  CmdArgs.push_back(
7791  Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7792  }
7793 
7794  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7795  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7796 }
7797 
7799  const InputInfo &Output,
7800  const InputInfoList &Inputs,
7801  const ArgList &Args,
7802  const char *LinkingOutput) const {
7803  claimNoWarnArgs(Args);
7804  ArgStringList CmdArgs;
7805 
7806  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7807  // instruct as in the base system to assemble 32-bit code.
7808  switch (getToolChain().getArch()) {
7809  default:
7810  break;
7811  case llvm::Triple::x86:
7812  CmdArgs.push_back("--32");
7813  break;
7814  case llvm::Triple::ppc:
7815  CmdArgs.push_back("-a32");
7816  break;
7817  case llvm::Triple::mips:
7818  case llvm::Triple::mipsel:
7819  case llvm::Triple::mips64:
7820  case llvm::Triple::mips64el: {
7821  StringRef CPUName;
7822  StringRef ABIName;
7823  mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7824 
7825  CmdArgs.push_back("-march");
7826  CmdArgs.push_back(CPUName.data());
7827 
7828  CmdArgs.push_back("-mabi");
7829  CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7830 
7831  if (getToolChain().getArch() == llvm::Triple::mips ||
7832  getToolChain().getArch() == llvm::Triple::mips64)
7833  CmdArgs.push_back("-EB");
7834  else
7835  CmdArgs.push_back("-EL");
7836 
7837  if (Arg *A = Args.getLastArg(options::OPT_G)) {
7838  StringRef v = A->getValue();
7839  CmdArgs.push_back(Args.MakeArgString("-G" + v));
7840  A->claim();
7841  }
7842 
7843  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7844  break;
7845  }
7846  case llvm::Triple::arm:
7847  case llvm::Triple::armeb:
7848  case llvm::Triple::thumb:
7849  case llvm::Triple::thumbeb: {
7850  arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
7851 
7852  if (ABI == arm::FloatABI::Hard)
7853  CmdArgs.push_back("-mfpu=vfp");
7854  else
7855  CmdArgs.push_back("-mfpu=softvfp");
7856 
7857  switch (getToolChain().getTriple().getEnvironment()) {
7858  case llvm::Triple::GNUEABIHF:
7859  case llvm::Triple::GNUEABI:
7860  case llvm::Triple::EABI:
7861  CmdArgs.push_back("-meabi=5");
7862  break;
7863 
7864  default:
7865  CmdArgs.push_back("-matpcs");
7866  }
7867  break;
7868  }
7869  case llvm::Triple::sparc:
7870  case llvm::Triple::sparcel:
7871  case llvm::Triple::sparcv9: {
7872  std::string CPU = getCPUName(Args, getToolChain().getTriple());
7873  CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7874  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7875  break;
7876  }
7877  }
7878 
7879  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7880 
7881  CmdArgs.push_back("-o");
7882  CmdArgs.push_back(Output.getFilename());
7883 
7884  for (const auto &II : Inputs)
7885  CmdArgs.push_back(II.getFilename());
7886 
7887  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7888  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7889 }
7890 
7892  const InputInfo &Output,
7893  const InputInfoList &Inputs,
7894  const ArgList &Args,
7895  const char *LinkingOutput) const {
7897  static_cast<const toolchains::FreeBSD &>(getToolChain());
7898  const Driver &D = ToolChain.getDriver();
7899  const llvm::Triple::ArchType Arch = ToolChain.getArch();
7900  const bool IsPIE =
7901  !Args.hasArg(options::OPT_shared) &&
7902  (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7903  ArgStringList CmdArgs;
7904 
7905  // Silence warning for "clang -g foo.o -o foo"
7906  Args.ClaimAllArgs(options::OPT_g_Group);
7907  // and "clang -emit-llvm foo.o -o foo"
7908  Args.ClaimAllArgs(options::OPT_emit_llvm);
7909  // and for "clang -w foo.o -o foo". Other warning options are already
7910  // handled somewhere else.
7911  Args.ClaimAllArgs(options::OPT_w);
7912 
7913  if (!D.SysRoot.empty())
7914  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7915 
7916  if (IsPIE)
7917  CmdArgs.push_back("-pie");
7918 
7919  if (Args.hasArg(options::OPT_static)) {
7920  CmdArgs.push_back("-Bstatic");
7921  } else {
7922  if (Args.hasArg(options::OPT_rdynamic))
7923  CmdArgs.push_back("-export-dynamic");
7924  CmdArgs.push_back("--eh-frame-hdr");
7925  if (Args.hasArg(options::OPT_shared)) {
7926  CmdArgs.push_back("-Bshareable");
7927  } else {
7928  CmdArgs.push_back("-dynamic-linker");
7929  CmdArgs.push_back("/libexec/ld-elf.so.1");
7930  }
7931  if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7932  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7933  Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7934  CmdArgs.push_back("--hash-style=both");
7935  }
7936  }
7937  CmdArgs.push_back("--enable-new-dtags");
7938  }
7939 
7940  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7941  // instruct ld in the base system to link 32-bit code.
7942  if (Arch == llvm::Triple::x86) {
7943  CmdArgs.push_back("-m");
7944  CmdArgs.push_back("elf_i386_fbsd");
7945  }
7946 
7947  if (Arch == llvm::Triple::ppc) {
7948  CmdArgs.push_back("-m");
7949  CmdArgs.push_back("elf32ppc_fbsd");
7950  }
7951 
7952  if (Arg *A = Args.getLastArg(options::OPT_G)) {
7953  if (ToolChain.getArch() == llvm::Triple::mips ||
7954  ToolChain.getArch() == llvm::Triple::mipsel ||
7955  ToolChain.getArch() == llvm::Triple::mips64 ||
7956  ToolChain.getArch() == llvm::Triple::mips64el) {
7957  StringRef v = A->getValue();
7958  CmdArgs.push_back(Args.MakeArgString("-G" + v));
7959  A->claim();
7960  }
7961  }
7962 
7963  if (Output.isFilename()) {
7964  CmdArgs.push_back("-o");
7965  CmdArgs.push_back(Output.getFilename());
7966  } else {
7967  assert(Output.isNothing() && "Invalid output.");
7968  }
7969 
7970  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7971  const char *crt1 = nullptr;
7972  if (!Args.hasArg(options::OPT_shared)) {
7973  if (Args.hasArg(options::OPT_pg))
7974  crt1 = "gcrt1.o";
7975  else if (IsPIE)
7976  crt1 = "Scrt1.o";
7977  else
7978  crt1 = "crt1.o";
7979  }
7980  if (crt1)
7981  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7982 
7983  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7984 
7985  const char *crtbegin = nullptr;
7986  if (Args.hasArg(options::OPT_static))
7987  crtbegin = "crtbeginT.o";
7988  else if (Args.hasArg(options::OPT_shared) || IsPIE)
7989  crtbegin = "crtbeginS.o";
7990  else
7991  crtbegin = "crtbegin.o";
7992 
7993  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7994  }
7995 
7996  Args.AddAllArgs(CmdArgs, options::OPT_L);
7997  ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7998  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7999  Args.AddAllArgs(CmdArgs, options::OPT_e);
8000  Args.AddAllArgs(CmdArgs, options::OPT_s);
8001  Args.AddAllArgs(CmdArgs, options::OPT_t);
8002  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8003  Args.AddAllArgs(CmdArgs, options::OPT_r);
8004 
8005  if (D.isUsingLTO())
8006  AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8007 
8008  bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8009  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8010 
8011  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8012  addOpenMPRuntime(CmdArgs, ToolChain, Args);
8013  if (D.CCCIsCXX()) {
8014  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8015  if (Args.hasArg(options::OPT_pg))
8016  CmdArgs.push_back("-lm_p");
8017  else
8018  CmdArgs.push_back("-lm");
8019  }
8020  if (NeedsSanitizerDeps)
8021  linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8022  // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8023  // the default system libraries. Just mimic this for now.
8024  if (Args.hasArg(options::OPT_pg))
8025  CmdArgs.push_back("-lgcc_p");
8026  else
8027  CmdArgs.push_back("-lgcc");
8028  if (Args.hasArg(options::OPT_static)) {
8029  CmdArgs.push_back("-lgcc_eh");
8030  } else if (Args.hasArg(options::OPT_pg)) {
8031  CmdArgs.push_back("-lgcc_eh_p");
8032  } else {
8033  CmdArgs.push_back("--as-needed");
8034  CmdArgs.push_back("-lgcc_s");
8035  CmdArgs.push_back("--no-as-needed");
8036  }
8037 
8038  if (Args.hasArg(options::OPT_pthread)) {
8039  if (Args.hasArg(options::OPT_pg))
8040  CmdArgs.push_back("-lpthread_p");
8041  else
8042  CmdArgs.push_back("-lpthread");
8043  }
8044 
8045  if (Args.hasArg(options::OPT_pg)) {
8046  if (Args.hasArg(options::OPT_shared))
8047  CmdArgs.push_back("-lc");
8048  else
8049  CmdArgs.push_back("-lc_p");
8050  CmdArgs.push_back("-lgcc_p");
8051  } else {
8052  CmdArgs.push_back("-lc");
8053  CmdArgs.push_back("-lgcc");
8054  }
8055 
8056  if (Args.hasArg(options::OPT_static)) {
8057  CmdArgs.push_back("-lgcc_eh");
8058  } else if (Args.hasArg(options::OPT_pg)) {
8059  CmdArgs.push_back("-lgcc_eh_p");
8060  } else {
8061  CmdArgs.push_back("--as-needed");
8062  CmdArgs.push_back("-lgcc_s");
8063  CmdArgs.push_back("--no-as-needed");
8064  }
8065  }
8066 
8067  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8068  if (Args.hasArg(options::OPT_shared) || IsPIE)
8069  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8070  else
8071  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8072  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8073  }
8074 
8075  ToolChain.addProfileRTLibs(Args, CmdArgs);
8076 
8077  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8078  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8079 }
8080 
8082  const InputInfo &Output,
8083  const InputInfoList &Inputs,
8084  const ArgList &Args,
8085  const char *LinkingOutput) const {
8086  claimNoWarnArgs(Args);
8087  ArgStringList CmdArgs;
8088 
8089  // GNU as needs different flags for creating the correct output format
8090  // on architectures with different ABIs or optional feature sets.
8091  switch (getToolChain().getArch()) {
8092  case llvm::Triple::x86:
8093  CmdArgs.push_back("--32");
8094  break;
8095  case llvm::Triple::arm:
8096  case llvm::Triple::armeb:
8097  case llvm::Triple::thumb:
8098  case llvm::Triple::thumbeb: {
8099  StringRef MArch, MCPU;
8100  getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8101  std::string Arch =
8102  arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8103  CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8104  break;
8105  }
8106 
8107  case llvm::Triple::mips:
8108  case llvm::Triple::mipsel:
8109  case llvm::Triple::mips64:
8110  case llvm::Triple::mips64el: {
8111  StringRef CPUName;
8112  StringRef ABIName;
8113  mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8114 
8115  CmdArgs.push_back("-march");
8116  CmdArgs.push_back(CPUName.data());
8117 
8118  CmdArgs.push_back("-mabi");
8119  CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8120 
8121  if (getToolChain().getArch() == llvm::Triple::mips ||
8122  getToolChain().getArch() == llvm::Triple::mips64)
8123  CmdArgs.push_back("-EB");
8124  else
8125  CmdArgs.push_back("-EL");
8126 
8127  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8128  break;
8129  }
8130 
8131  case llvm::Triple::sparc:
8132  case llvm::Triple::sparcel: {
8133  CmdArgs.push_back("-32");
8134  std::string CPU = getCPUName(Args, getToolChain().getTriple());
8135  CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8136  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8137  break;
8138  }
8139 
8140  case llvm::Triple::sparcv9: {
8141  CmdArgs.push_back("-64");
8142  std::string CPU = getCPUName(Args, getToolChain().getTriple());
8143  CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8144  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8145  break;
8146  }
8147 
8148  default:
8149  break;
8150  }
8151 
8152  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8153 
8154  CmdArgs.push_back("-o");
8155  CmdArgs.push_back(Output.getFilename());
8156 
8157  for (const auto &II : Inputs)
8158  CmdArgs.push_back(II.getFilename());
8159 
8160  const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8161  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8162 }
8163 
8165  const InputInfo &Output,
8166  const InputInfoList &Inputs,
8167  const ArgList &Args,
8168  const char *LinkingOutput) const {
8169  const Driver &D = getToolChain().getDriver();
8170  ArgStringList CmdArgs;
8171 
8172  if (!D.SysRoot.empty())
8173  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8174 
8175  CmdArgs.push_back("--eh-frame-hdr");
8176  if (Args.hasArg(options::OPT_static)) {
8177  CmdArgs.push_back("-Bstatic");
8178  } else {
8179  if (Args.hasArg(options::OPT_rdynamic))
8180  CmdArgs.push_back("-export-dynamic");
8181  if (Args.hasArg(options::OPT_shared)) {
8182  CmdArgs.push_back("-Bshareable");
8183  } else {
8184  CmdArgs.push_back("-dynamic-linker");
8185  CmdArgs.push_back("/libexec/ld.elf_so");
8186  }
8187  }
8188 
8189  // Many NetBSD architectures support more than one ABI.
8190  // Determine the correct emulation for ld.
8191  switch (getToolChain().getArch()) {
8192  case llvm::Triple::x86:
8193  CmdArgs.push_back("-m");
8194  CmdArgs.push_back("elf_i386");
8195  break;
8196  case llvm::Triple::arm:
8197  case llvm::Triple::thumb:
8198  CmdArgs.push_back("-m");
8199  switch (getToolChain().getTriple().getEnvironment()) {
8200  case llvm::Triple::EABI:
8201  case llvm::Triple::GNUEABI:
8202  CmdArgs.push_back("armelf_nbsd_eabi");
8203  break;
8204  case llvm::Triple::EABIHF:
8205  case llvm::Triple::GNUEABIHF:
8206  CmdArgs.push_back("armelf_nbsd_eabihf");
8207  break;
8208  default:
8209  CmdArgs.push_back("armelf_nbsd");
8210  break;
8211  }
8212  break;
8213  case llvm::Triple::armeb:
8214  case llvm::Triple::thumbeb:
8216  Args, CmdArgs,
8217  llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8218  CmdArgs.push_back("-m");
8219  switch (getToolChain().getTriple().getEnvironment()) {
8220  case llvm::Triple::EABI:
8221  case llvm::Triple::GNUEABI:
8222  CmdArgs.push_back("armelfb_nbsd_eabi");
8223  break;
8224  case llvm::Triple::EABIHF:
8225  case llvm::Triple::GNUEABIHF:
8226  CmdArgs.push_back("armelfb_nbsd_eabihf");
8227  break;
8228  default:
8229  CmdArgs.push_back("armelfb_nbsd");
8230  break;
8231  }
8232  break;
8233  case llvm::Triple::mips64:
8234  case llvm::Triple::mips64el:
8235  if (mips::hasMipsAbiArg(Args, "32")) {
8236  CmdArgs.push_back("-m");
8237  if (getToolChain().getArch() == llvm::Triple::mips64)
8238  CmdArgs.push_back("elf32btsmip");
8239  else
8240  CmdArgs.push_back("elf32ltsmip");
8241  } else if (mips::hasMipsAbiArg(Args, "64")) {
8242  CmdArgs.push_back("-m");
8243  if (getToolChain().getArch() == llvm::Triple::mips64)
8244  CmdArgs.push_back("elf64btsmip");
8245  else
8246  CmdArgs.push_back("elf64ltsmip");
8247  }
8248  break;
8249  case llvm::Triple::ppc:
8250  CmdArgs.push_back("-m");
8251  CmdArgs.push_back("elf32ppc_nbsd");
8252  break;
8253 
8254  case llvm::Triple::ppc64:
8255  case llvm::Triple::ppc64le:
8256  CmdArgs.push_back("-m");
8257  CmdArgs.push_back("elf64ppc");
8258  break;
8259 
8260  case llvm::Triple::sparc:
8261  CmdArgs.push_back("-m");
8262  CmdArgs.push_back("elf32_sparc");
8263  break;
8264 
8265  case llvm::Triple::sparcv9:
8266  CmdArgs.push_back("-m");
8267  CmdArgs.push_back("elf64_sparc");
8268  break;
8269 
8270  default:
8271  break;
8272  }
8273 
8274  if (Output.isFilename()) {
8275  CmdArgs.push_back("-o");
8276  CmdArgs.push_back(Output.getFilename());
8277  } else {
8278  assert(Output.isNothing() && "Invalid output.");
8279  }
8280 
8281  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8282  if (!Args.hasArg(options::OPT_shared)) {
8283  CmdArgs.push_back(
8284  Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8285  CmdArgs.push_back(
8286  Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8287  CmdArgs.push_back(
8288  Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8289  } else {
8290  CmdArgs.push_back(
8291  Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8292  CmdArgs.push_back(
8293  Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8294  }
8295  }
8296 
8297  Args.AddAllArgs(CmdArgs, options::OPT_L);
8298  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8299  Args.AddAllArgs(CmdArgs, options::OPT_e);
8300  Args.AddAllArgs(CmdArgs, options::OPT_s);
8301  Args.AddAllArgs(CmdArgs, options::OPT_t);
8302  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8303  Args.AddAllArgs(CmdArgs, options::OPT_r);
8304 
8305  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8306 
8307  unsigned Major, Minor, Micro;
8308  getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8309  bool useLibgcc = true;
8310  if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
8311  switch (getToolChain().getArch()) {
8312  case llvm::Triple::aarch64:
8313  case llvm::Triple::arm:
8314  case llvm::Triple::armeb:
8315  case llvm::Triple::thumb:
8316  case llvm::Triple::thumbeb:
8317  case llvm::Triple::ppc:
8318  case llvm::Triple::ppc64:
8319  case llvm::Triple::ppc64le:
8320  case llvm::Triple::sparc:
8321  case llvm::Triple::sparcv9:
8322  case llvm::Triple::x86:
8323  case llvm::Triple::x86_64:
8324  useLibgcc = false;
8325  break;
8326  default:
8327  break;
8328  }
8329  }
8330 
8331  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8332  addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8333  if (D.CCCIsCXX()) {
8334  getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8335  CmdArgs.push_back("-lm");
8336  }
8337  if (Args.hasArg(options::OPT_pthread))
8338  CmdArgs.push_back("-lpthread");
8339  CmdArgs.push_back("-lc");
8340 
8341  if (useLibgcc) {
8342  if (Args.hasArg(options::OPT_static)) {
8343  // libgcc_eh depends on libc, so resolve as much as possible,
8344  // pull in any new requirements from libc and then get the rest
8345  // of libgcc.
8346  CmdArgs.push_back("-lgcc_eh");
8347  CmdArgs.push_back("-lc");
8348  CmdArgs.push_back("-lgcc");
8349  } else {
8350  CmdArgs.push_back("-lgcc");
8351  CmdArgs.push_back("--as-needed");
8352  CmdArgs.push_back("-lgcc_s");
8353  CmdArgs.push_back("--no-as-needed");
8354  }
8355  }
8356  }
8357 
8358  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8359  if (!Args.hasArg(options::OPT_shared))
8360  CmdArgs.push_back(
8361  Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8362  else
8363  CmdArgs.push_back(
8364  Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8365  CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8366  }
8367 
8368  getToolChain().addProfileRTLibs(Args, CmdArgs);
8369 
8370  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8371  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8372 }
8373 
8375  const InputInfo &Output,
8376  const InputInfoList &Inputs,
8377  const ArgList &Args,
8378  const char *LinkingOutput) const {
8379  claimNoWarnArgs(Args);
8380 
8381  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8382  llvm::Triple Triple = llvm::Triple(TripleStr);
8383 
8384  ArgStringList CmdArgs;
8385 
8386  llvm::Reloc::Model RelocationModel;
8387  unsigned PICLevel;
8388  bool IsPIE;
8389  std::tie(RelocationModel, PICLevel, IsPIE) =
8390  ParsePICArgs(getToolChain(), Triple, Args);
8391 
8392  switch (getToolChain().getArch()) {
8393  default:
8394  break;
8395  // Add --32/--64 to make sure we get the format we want.
8396  // This is incomplete
8397  case llvm::Triple::x86:
8398  CmdArgs.push_back("--32");
8399  break;
8400  case llvm::Triple::x86_64:
8401  if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
8402  CmdArgs.push_back("--x32");
8403  else
8404  CmdArgs.push_back("--64");
8405  break;
8406  case llvm::Triple::ppc:
8407  CmdArgs.push_back("-a32");
8408  CmdArgs.push_back("-mppc");
8409  CmdArgs.push_back("-many");
8410  break;
8411  case llvm::Triple::ppc64:
8412  CmdArgs.push_back("-a64");
8413  CmdArgs.push_back("-mppc64");
8414  CmdArgs.push_back("-many");
8415  break;
8416  case llvm::Triple::ppc64le:
8417  CmdArgs.push_back("-a64");
8418  CmdArgs.push_back("-mppc64");
8419  CmdArgs.push_back("-many");
8420  CmdArgs.push_back("-mlittle-endian");
8421  break;
8422  case llvm::Triple::sparc:
8423  case llvm::Triple::sparcel: {
8424  CmdArgs.push_back("-32");
8425  std::string CPU = getCPUName(Args, getToolChain().getTriple());
8426  CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8427  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8428  break;
8429  }
8430  case llvm::Triple::sparcv9: {
8431  CmdArgs.push_back("-64");
8432  std::string CPU = getCPUName(Args, getToolChain().getTriple());
8433  CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8434  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8435  break;
8436  }
8437  case llvm::Triple::arm:
8438  case llvm::Triple::armeb:
8439  case llvm::Triple::thumb:
8440  case llvm::Triple::thumbeb: {
8441  const llvm::Triple &Triple2 = getToolChain().getTriple();
8442  switch (Triple2.getSubArch()) {
8443  case llvm::Triple::ARMSubArch_v7:
8444  CmdArgs.push_back("-mfpu=neon");
8445  break;
8446  case llvm::Triple::ARMSubArch_v8:
8447  CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
8448  break;
8449  default:
8450  break;
8451  }
8452 
8453  switch (arm::getARMFloatABI(getToolChain(), Args)) {
8454  case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
8455  case arm::FloatABI::Soft:
8456  CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
8457  break;
8458  case arm::FloatABI::SoftFP:
8459  CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
8460  break;
8461  case arm::FloatABI::Hard:
8462  CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
8463  break;
8464  }
8465 
8466  Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
8467 
8468  // FIXME: remove krait check when GNU tools support krait cpu
8469  // for now replace it with -march=armv7-a to avoid a lower
8470  // march from being picked in the absence of a cpu flag.
8471  Arg *A;
8472  if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
8473  StringRef(A->getValue()).lower() == "krait")
8474  CmdArgs.push_back("-march=armv7-a");
8475  else
8476  Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
8477  Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
8478  break;
8479  }
8480  case llvm::Triple::mips:
8481  case llvm::Triple::mipsel:
8482  case llvm::Triple::mips64:
8483  case llvm::Triple::mips64el: {
8484  StringRef CPUName;
8485  StringRef ABIName;
8486  mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8487  ABIName = getGnuCompatibleMipsABIName(ABIName);
8488 
8489  CmdArgs.push_back("-march");
8490  CmdArgs.push_back(CPUName.data());
8491 
8492  CmdArgs.push_back("-mabi");
8493  CmdArgs.push_back(ABIName.data());
8494 
8495  // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
8496  // or -mshared (not implemented) is in effect.
8497  if (RelocationModel == llvm::Reloc::Static)
8498  CmdArgs.push_back("-mno-shared");
8499 
8500  // LLVM doesn't support -mplt yet and acts as if it is always given.
8501  // However, -mplt has no effect with the N64 ABI.
8502  CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
8503 
8504  if (getToolChain().getArch() == llvm::Triple::mips ||
8505  getToolChain().getArch() == llvm::Triple::mips64)
8506  CmdArgs.push_back("-EB");
8507  else
8508  CmdArgs.push_back("-EL");
8509 
8510  if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
8511  if (StringRef(A->getValue()) == "2008")
8512  CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
8513  }
8514 
8515  // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
8516  if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
8517  options::OPT_mfp64)) {
8518  A->claim();
8519  A->render(Args, CmdArgs);
8520  } else if (mips::shouldUseFPXX(
8521  Args, getToolChain().getTriple(), CPUName, ABIName,
8522  getMipsFloatABI(getToolChain().getDriver(), Args)))
8523  CmdArgs.push_back("-mfpxx");
8524 
8525  // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
8526  // -mno-mips16 is actually -no-mips16.
8527  if (Arg *A =
8528  Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
8529  if (A->getOption().matches(options::OPT_mips16)) {
8530  A->claim();
8531  A->render(Args, CmdArgs);
8532  } else {
8533  A->claim();
8534  CmdArgs.push_back("-no-mips16");
8535  }
8536  }
8537 
8538  Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
8539  options::OPT_mno_micromips);
8540  Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
8541  Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
8542 
8543  if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
8544  // Do not use AddLastArg because not all versions of MIPS assembler
8545  // support -mmsa / -mno-msa options.
8546  if (A->getOption().matches(options::OPT_mmsa))
8547  CmdArgs.push_back(Args.MakeArgString("-mmsa"));
8548  }
8549 
8550  Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
8551  options::OPT_msoft_float);
8552 
8553  Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
8554  options::OPT_msingle_float);
8555 
8556  Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
8557  options::OPT_mno_odd_spreg);
8558 
8559  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8560  break;
8561  }
8562  case llvm::Triple::systemz: {
8563  // Always pass an -march option, since our default of z10 is later
8564  // than the GNU assembler's default.
8565  StringRef CPUName = getSystemZTargetCPU(Args);
8566  CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
8567  break;
8568  }
8569  }
8570 
8571  Args.AddAllArgs(CmdArgs, options::OPT_I);
8572  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8573 
8574  CmdArgs.push_back("-o");
8575  CmdArgs.push_back(Output.getFilename());
8576 
8577  for (const auto &II : Inputs)
8578  CmdArgs.push_back(II.getFilename());
8579 
8580  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8581  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8582 
8583  // Handle the debug info splitting at object creation time if we're
8584  // creating an object.
8585  // TODO: Currently only works on linux with newer objcopy.
8586  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
8587  getToolChain().getTriple().isOSLinux())
8588  SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
8589  SplitDebugName(Args, Inputs[0]));
8590 }
8591 
8592 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
8593  ArgStringList &CmdArgs, const ArgList &Args) {
8594  bool isAndroid = Triple.isAndroid();
8595  bool isCygMing = Triple.isOSCygMing();
8596  bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
8597  Args.hasArg(options::OPT_static);
8598  if (!D.CCCIsCXX())
8599  CmdArgs.push_back("-lgcc");
8600 
8601  if (StaticLibgcc || isAndroid) {
8602  if (D.CCCIsCXX())
8603  CmdArgs.push_back("-lgcc");
8604  } else {
8605  if (!D.CCCIsCXX() && !isCygMing)
8606  CmdArgs.push_back("--as-needed");
8607  CmdArgs.push_back("-lgcc_s");
8608  if (!D.CCCIsCXX() && !isCygMing)
8609  CmdArgs.push_back("--no-as-needed");
8610  }
8611 
8612  if (StaticLibgcc && !isAndroid)
8613  CmdArgs.push_back("-lgcc_eh");
8614  else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
8615  CmdArgs.push_back("-lgcc");
8616 
8617  // According to Android ABI, we have to link with libdl if we are
8618  // linking with non-static libgcc.
8619  //
8620  // NOTE: This fixes a link error on Android MIPS as well. The non-static
8621  // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
8622  if (isAndroid && !StaticLibgcc)
8623  CmdArgs.push_back("-ldl");
8624 }
8625 
8626 static std::string getLinuxDynamicLinker(const ArgList &Args,
8627  const toolchains::Linux &ToolChain) {
8628  const llvm::Triple::ArchType Arch = ToolChain.getArch();
8629 
8630  if (ToolChain.getTriple().isAndroid()) {
8631  if (ToolChain.getTriple().isArch64Bit())
8632  return "/system/bin/linker64";
8633  else
8634  return "/system/bin/linker";
8635  } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
8636  Arch == llvm::Triple::sparcel)
8637  return "/lib/ld-linux.so.2";
8638  else if (Arch == llvm::Triple::aarch64)
8639  return "/lib/ld-linux-aarch64.so.1";
8640  else if (Arch == llvm::Triple::aarch64_be)
8641  return "/lib/ld-linux-aarch64_be.so.1";
8642  else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
8643  if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8644  arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8645  return "/lib/ld-linux-armhf.so.3";
8646  else
8647  return "/lib/ld-linux.so.3";
8648  } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
8649  // TODO: check which dynamic linker name.
8650  if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8651  arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8652  return "/lib/ld-linux-armhf.so.3";
8653  else
8654  return "/lib/ld-linux.so.3";
8655  } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
8656  Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
8657  std::string LibDir =
8658  "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
8659  StringRef LibName;
8660  bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
8661  if (mips::isUCLibc(Args))
8662  LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8663  else if (!ToolChain.getTriple().hasEnvironment()) {
8664  bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
8665  (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
8666  LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
8667  } else
8668  LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8669 
8670  return (LibDir + "/" + LibName).str();
8671  } else if (Arch == llvm::Triple::ppc)
8672  return "/lib/ld.so.1";
8673  else if (Arch == llvm::Triple::ppc64) {
8674  if (ppc::hasPPCAbiArg(Args, "elfv2"))
8675  return "/lib64/ld64.so.2";
8676  return "/lib64/ld64.so.1";
8677  } else if (Arch == llvm::Triple::ppc64le) {
8678  if (ppc::hasPPCAbiArg(Args, "elfv1"))
8679  return "/lib64/ld64.so.1";
8680  return "/lib64/ld64.so.2";
8681  } else if (Arch == llvm::Triple::systemz)
8682  return "/lib/ld64.so.1";
8683  else if (Arch == llvm::Triple::sparcv9)
8684  return "/lib64/ld-linux.so.2";
8685  else if (Arch == llvm::Triple::x86_64 &&
8686  ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8687  return "/libx32/ld-linux-x32.so.2";
8688  else
8689  return "/lib64/ld-linux-x86-64.so.2";
8690 }
8691 
8692 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8693  ArgStringList &CmdArgs, const ArgList &Args) {
8694  // Make use of compiler-rt if --rtlib option is used
8696 
8697  switch (RLT) {
8699  switch (TC.getTriple().getOS()) {
8700  default:
8701  llvm_unreachable("unsupported OS");
8702  case llvm::Triple::Win32:
8703  case llvm::Triple::Linux:
8704  addClangRT(TC, Args, CmdArgs);
8705  break;
8706  }
8707  break;
8708  case ToolChain::RLT_Libgcc:
8709  AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8710  break;
8711  }
8712 }
8713 
8714 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8715  switch (T.getArch()) {
8716  case llvm::Triple::x86:
8717  return "elf_i386";
8718  case llvm::Triple::aarch64:
8719  return "aarch64linux";
8720  case llvm::Triple::aarch64_be:
8721  return "aarch64_be_linux";
8722  case llvm::Triple::arm:
8723  case llvm::Triple::thumb:
8724  return "armelf_linux_eabi";
8725  case llvm::Triple::armeb:
8726  case llvm::Triple::thumbeb:
8727  return "armebelf_linux_eabi"; /* TODO: check which NAME. */
8728  case llvm::Triple::ppc:
8729  return "elf32ppclinux";
8730  case llvm::Triple::ppc64:
8731  return "elf64ppc";
8732  case llvm::Triple::ppc64le:
8733  return "elf64lppc";
8734  case llvm::Triple::sparc:
8735  case llvm::Triple::sparcel:
8736  return "elf32_sparc";
8737  case llvm::Triple::sparcv9:
8738  return "elf64_sparc";
8739  case llvm::Triple::mips:
8740  return "elf32btsmip";
8741  case llvm::Triple::mipsel:
8742  return "elf32ltsmip";
8743  case llvm::Triple::mips64:
8744  if (mips::hasMipsAbiArg(Args, "n32"))
8745  return "elf32btsmipn32";
8746  return "elf64btsmip";
8747  case llvm::Triple::mips64el:
8748  if (mips::hasMipsAbiArg(Args, "n32"))
8749  return "elf32ltsmipn32";
8750  return "elf64ltsmip";
8751  case llvm::Triple::systemz:
8752  return "elf64_s390";
8753  case llvm::Triple::x86_64:
8754  if (T.getEnvironment() == llvm::Triple::GNUX32)
8755  return "elf32_x86_64";
8756  return "elf_x86_64";
8757  default:
8758  llvm_unreachable("Unexpected arch");
8759  }
8760 }
8761 
8763  const InputInfo &Output,
8764  const InputInfoList &Inputs,
8765  const ArgList &Args,
8766  const char *LinkingOutput) const {
8767  const toolchains::Linux &ToolChain =
8768  static_cast<const toolchains::Linux &>(getToolChain());
8769  const Driver &D = ToolChain.getDriver();
8770 
8771  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8772  llvm::Triple Triple = llvm::Triple(TripleStr);
8773 
8774  const llvm::Triple::ArchType Arch = ToolChain.getArch();
8775  const bool isAndroid = ToolChain.getTriple().isAndroid();
8776  const bool IsPIE =
8777  !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8778  (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8779  const bool HasCRTBeginEndFiles =
8780  ToolChain.getTriple().hasEnvironment() ||
8781  (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
8782 
8783  ArgStringList CmdArgs;
8784 
8785  // Silence warning for "clang -g foo.o -o foo"
8786  Args.ClaimAllArgs(options::OPT_g_Group);
8787  // and "clang -emit-llvm foo.o -o foo"
8788  Args.ClaimAllArgs(options::OPT_emit_llvm);
8789  // and for "clang -w foo.o -o foo". Other warning options are already
8790  // handled somewhere else.
8791  Args.ClaimAllArgs(options::OPT_w);
8792 
8793  const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
8794  if (llvm::sys::path::filename(Exec) == "lld") {
8795  CmdArgs.push_back("-flavor");
8796  CmdArgs.push_back("old-gnu");
8797  CmdArgs.push_back("-target");
8798  CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
8799  }
8800 
8801  if (!D.SysRoot.empty())
8802  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8803 
8804  if (IsPIE)
8805  CmdArgs.push_back("-pie");
8806 
8807  if (Args.hasArg(options::OPT_rdynamic))
8808  CmdArgs.push_back("-export-dynamic");
8809 
8810  if (Args.hasArg(options::OPT_s))
8811  CmdArgs.push_back("-s");
8812 
8813  if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8814  arm::appendEBLinkFlags(Args, CmdArgs, Triple);
8815 
8816  for (const auto &Opt : ToolChain.ExtraOpts)
8817  CmdArgs.push_back(Opt.c_str());
8818 
8819  if (!Args.hasArg(options::OPT_static)) {
8820  CmdArgs.push_back("--eh-frame-hdr");
8821  }
8822 
8823  CmdArgs.push_back("-m");
8824  CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8825 
8826  if (Args.hasArg(options::OPT_static)) {
8827  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8828  Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8829  CmdArgs.push_back("-Bstatic");
8830  else
8831  CmdArgs.push_back("-static");
8832  } else if (Args.hasArg(options::OPT_shared)) {
8833  CmdArgs.push_back("-shared");
8834  }
8835 
8836  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8837  Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8838  (!Args.hasArg(options::OPT_static) &&
8839  !Args.hasArg(options::OPT_shared))) {
8840  CmdArgs.push_back("-dynamic-linker");
8841  CmdArgs.push_back(Args.MakeArgString(
8842  D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8843  }
8844 
8845  CmdArgs.push_back("-o");
8846  CmdArgs.push_back(Output.getFilename());
8847 
8848  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8849  if (!isAndroid) {
8850  const char *crt1 = nullptr;
8851  if (!Args.hasArg(options::OPT_shared)) {
8852  if (Args.hasArg(options::OPT_pg))
8853  crt1 = "gcrt1.o";
8854  else if (IsPIE)
8855  crt1 = "Scrt1.o";
8856  else
8857  crt1 = "crt1.o";
8858  }
8859  if (crt1)
8860  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8861 
8862  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8863  }
8864 
8865  const char *crtbegin;
8866  if (Args.hasArg(options::OPT_static))
8867  crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8868  else if (Args.hasArg(options::OPT_shared))
8869  crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8870  else if (IsPIE)
8871  crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8872  else
8873  crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8874 
8875  if (HasCRTBeginEndFiles)
8876  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8877 
8878  // Add crtfastmath.o if available and fast math is enabled.
8879  ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8880  }
8881 
8882  Args.AddAllArgs(CmdArgs, options::OPT_L);
8883  Args.AddAllArgs(CmdArgs, options::OPT_u);
8884 
8885  ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8886 
8887  if (D.isUsingLTO())
8888  AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8889 
8890  if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8891  CmdArgs.push_back("--no-demangle");
8892 
8893  bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8894  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8895  // The profile runtime also needs access to system libraries.
8896  getToolChain().addProfileRTLibs(Args, CmdArgs);
8897 
8898  if (D.CCCIsCXX() &&
8899  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8900  bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8901  !Args.hasArg(options::OPT_static);
8902  if (OnlyLibstdcxxStatic)
8903  CmdArgs.push_back("-Bstatic");
8904  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8905  if (OnlyLibstdcxxStatic)
8906  CmdArgs.push_back("-Bdynamic");
8907  CmdArgs.push_back("-lm");
8908  }
8909  // Silence warnings when linking C code with a C++ '-stdlib' argument.
8910  Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8911 
8912  if (!Args.hasArg(options::OPT_nostdlib)) {
8913  if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8914  if (Args.hasArg(options::OPT_static))
8915  CmdArgs.push_back("--start-group");
8916 
8917  if (NeedsSanitizerDeps)
8918  linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8919 
8920  bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8921  Args.hasArg(options::OPT_pthreads);
8922 
8923  if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8924  options::OPT_fno_openmp, false)) {
8925  // OpenMP runtimes implies pthreads when using the GNU toolchain.
8926  // FIXME: Does this really make sense for all GNU toolchains?
8927  WantPthread = true;
8928 
8929  // Also link the particular OpenMP runtimes.
8930  switch (getOpenMPRuntime(ToolChain, Args)) {
8931  case OMPRT_OMP:
8932  CmdArgs.push_back("-lomp");
8933  break;
8934  case OMPRT_GOMP:
8935  CmdArgs.push_back("-lgomp");
8936 
8937  // FIXME: Exclude this for platforms with libgomp that don't require
8938  // librt. Most modern Linux platforms require it, but some may not.
8939  CmdArgs.push_back("-lrt");
8940  break;
8941  case OMPRT_IOMP5:
8942  CmdArgs.push_back("-liomp5");
8943  break;
8944  case OMPRT_Unknown:
8945  // Already diagnosed.
8946  break;
8947  }
8948  }
8949 
8950  AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8951 
8952  if (WantPthread && !isAndroid)
8953  CmdArgs.push_back("-lpthread");
8954 
8955  CmdArgs.push_back("-lc");
8956 
8957  if (Args.hasArg(options::OPT_static))
8958  CmdArgs.push_back("--end-group");
8959  else
8960  AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8961  }
8962 
8963  if (!Args.hasArg(options::OPT_nostartfiles)) {
8964  const char *crtend;
8965  if (Args.hasArg(options::OPT_shared))
8966  crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8967  else if (IsPIE)
8968  crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8969  else
8970  crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8971 
8972  if (HasCRTBeginEndFiles)
8973  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8974  if (!isAndroid)
8975  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8976  }
8977  }
8978 
8979  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8980 }
8981 
8982 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8983 // for the various SFI requirements like register masking. The assembly tool
8984 // inserts the file containing the macros as an input into all the assembly
8985 // jobs.
8987  const InputInfo &Output,
8988  const InputInfoList &Inputs,
8989  const ArgList &Args,
8990  const char *LinkingOutput) const {
8992  static_cast<const toolchains::NaClToolChain &>(getToolChain());
8993  InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
8994  "nacl-arm-macros.s");
8995  InputInfoList NewInputs;
8996  NewInputs.push_back(NaClMacros);
8997  NewInputs.append(Inputs.begin(), Inputs.end());
8998  gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
8999  LinkingOutput);
9000 }
9001 
9002 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9003 // we use static by default, do not yet support sanitizers or LTO, and a few
9004 // others. Eventually we can support more of that and hopefully migrate back
9005 // to gnutools::Linker.
9007  const InputInfo &Output,
9008  const InputInfoList &Inputs,
9009  const ArgList &Args,
9010  const char *LinkingOutput) const {
9011 
9013  static_cast<const toolchains::NaClToolChain &>(getToolChain());
9014  const Driver &D = ToolChain.getDriver();
9015  const llvm::Triple::ArchType Arch = ToolChain.getArch();
9016  const bool IsStatic =
9017  !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9018 
9019  ArgStringList CmdArgs;
9020 
9021  // Silence warning for "clang -g foo.o -o foo"
9022  Args.ClaimAllArgs(options::OPT_g_Group);
9023  // and "clang -emit-llvm foo.o -o foo"
9024  Args.ClaimAllArgs(options::OPT_emit_llvm);
9025  // and for "clang -w foo.o -o foo". Other warning options are already
9026  // handled somewhere else.
9027  Args.ClaimAllArgs(options::OPT_w);
9028 
9029  if (!D.SysRoot.empty())
9030  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9031 
9032  if (Args.hasArg(options::OPT_rdynamic))
9033  CmdArgs.push_back("-export-dynamic");
9034 
9035  if (Args.hasArg(options::OPT_s))
9036  CmdArgs.push_back("-s");
9037 
9038  // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9039  // from there is --build-id, which we do want.
9040  CmdArgs.push_back("--build-id");
9041 
9042  if (!IsStatic)
9043  CmdArgs.push_back("--eh-frame-hdr");
9044 
9045  CmdArgs.push_back("-m");
9046  if (Arch == llvm::Triple::x86)
9047  CmdArgs.push_back("elf_i386_nacl");
9048  else if (Arch == llvm::Triple::arm)
9049  CmdArgs.push_back("armelf_nacl");
9050  else if (Arch == llvm::Triple::x86_64)
9051  CmdArgs.push_back("elf_x86_64_nacl");
9052  else if (Arch == llvm::Triple::mipsel)
9053  CmdArgs.push_back("mipselelf_nacl");
9054  else
9055  D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9056  << "Native Client";
9057 
9058  if (IsStatic)
9059  CmdArgs.push_back("-static");
9060  else if (Args.hasArg(options::OPT_shared))
9061  CmdArgs.push_back("-shared");
9062 
9063  CmdArgs.push_back("-o");
9064  CmdArgs.push_back(Output.getFilename());
9065  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9066  if (!Args.hasArg(options::OPT_shared))
9067  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9068  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9069 
9070  const char *crtbegin;
9071  if (IsStatic)
9072  crtbegin = "crtbeginT.o";
9073  else if (Args.hasArg(options::OPT_shared))
9074  crtbegin = "crtbeginS.o";
9075  else
9076  crtbegin = "crtbegin.o";
9077  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9078  }
9079 
9080  Args.AddAllArgs(CmdArgs, options::OPT_L);
9081  Args.AddAllArgs(CmdArgs, options::OPT_u);
9082 
9083  ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9084 
9085  if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9086  CmdArgs.push_back("--no-demangle");
9087 
9088  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9089 
9090  if (D.CCCIsCXX() &&
9091  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9092  bool OnlyLibstdcxxStatic =
9093  Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9094  if (OnlyLibstdcxxStatic)
9095  CmdArgs.push_back("-Bstatic");
9096  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9097  if (OnlyLibstdcxxStatic)
9098  CmdArgs.push_back("-Bdynamic");
9099  CmdArgs.push_back("-lm");
9100  }
9101 
9102  if (!Args.hasArg(options::OPT_nostdlib)) {
9103  if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9104  // Always use groups, since it has no effect on dynamic libraries.
9105  CmdArgs.push_back("--start-group");
9106  CmdArgs.push_back("-lc");
9107  // NaCl's libc++ currently requires libpthread, so just always include it
9108  // in the group for C++.
9109  if (Args.hasArg(options::OPT_pthread) ||
9110  Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9111  // Gold, used by Mips, handles nested groups differently than ld, and
9112  // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9113  // which is not a desired behaviour here.
9114  // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9115  if (getToolChain().getArch() == llvm::Triple::mipsel)
9116  CmdArgs.push_back("-lnacl");
9117 
9118  CmdArgs.push_back("-lpthread");
9119  }
9120 
9121  CmdArgs.push_back("-lgcc");
9122  CmdArgs.push_back("--as-needed");
9123  if (IsStatic)
9124  CmdArgs.push_back("-lgcc_eh");
9125  else
9126  CmdArgs.push_back("-lgcc_s");
9127  CmdArgs.push_back("--no-as-needed");
9128 
9129  // Mips needs to create and use pnacl_legacy library that contains
9130  // definitions from bitcode/pnaclmm.c and definitions for
9131  // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9132  if (getToolChain().getArch() == llvm::Triple::mipsel)
9133  CmdArgs.push_back("-lpnacl_legacy");
9134 
9135  CmdArgs.push_back("--end-group");
9136  }
9137 
9138  if (!Args.hasArg(options::OPT_nostartfiles)) {
9139  const char *crtend;
9140  if (Args.hasArg(options::OPT_shared))
9141  crtend = "crtendS.o";
9142  else
9143  crtend = "crtend.o";
9144 
9145  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9146  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9147  }
9148  }
9149 
9150  const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9151  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9152 }
9153 
9155  const InputInfo &Output,
9156  const InputInfoList &Inputs,
9157  const ArgList &Args,
9158  const char *LinkingOutput) const {
9159  claimNoWarnArgs(Args);
9160  ArgStringList CmdArgs;
9161 
9162  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9163 
9164  CmdArgs.push_back("-o");
9165  CmdArgs.push_back(Output.getFilename());
9166 
9167  for (const auto &II : Inputs)
9168  CmdArgs.push_back(II.getFilename());
9169 
9170  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9171  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9172 }
9173 
9175  const InputInfo &Output,
9176  const InputInfoList &Inputs,
9177  const ArgList &Args,
9178  const char *LinkingOutput) const {
9179  const Driver &D = getToolChain().getDriver();
9180  ArgStringList CmdArgs;
9181 
9182  if (Output.isFilename()) {
9183  CmdArgs.push_back("-o");
9184  CmdArgs.push_back(Output.getFilename());
9185  } else {
9186  assert(Output.isNothing() && "Invalid output.");
9187  }
9188 
9189  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9190  CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9191  CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9192  CmdArgs.push_back(
9193  Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9194  CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9195  }
9196 
9197  Args.AddAllArgs(CmdArgs,
9198  {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9199 
9200  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9201 
9202  getToolChain().addProfileRTLibs(Args, CmdArgs);
9203 
9204  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9205  if (D.CCCIsCXX()) {
9206  getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9207  CmdArgs.push_back("-lm");
9208  }
9209  }
9210 
9211  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9212  if (Args.hasArg(options::OPT_pthread))
9213  CmdArgs.push_back("-lpthread");
9214  CmdArgs.push_back("-lc");
9215  CmdArgs.push_back("-lCompilerRT-Generic");
9216  CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9217  CmdArgs.push_back(
9218  Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9219  }
9220 
9221  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9222  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9223 }
9224 
9225 /// DragonFly Tools
9226 
9227 // For now, DragonFly Assemble does just about the same as for
9228 // FreeBSD, but this may change soon.
9230  const InputInfo &Output,
9231  const InputInfoList &Inputs,
9232  const ArgList &Args,
9233  const char *LinkingOutput) const {
9234  claimNoWarnArgs(Args);
9235  ArgStringList CmdArgs;
9236 
9237  // When building 32-bit code on DragonFly/pc64, we have to explicitly
9238  // instruct as in the base system to assemble 32-bit code.
9239  if (getToolChain().getArch() == llvm::Triple::x86)
9240  CmdArgs.push_back("--32");
9241 
9242  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9243 
9244  CmdArgs.push_back("-o");
9245  CmdArgs.push_back(Output.getFilename());
9246 
9247  for (const auto &II : Inputs)
9248  CmdArgs.push_back(II.getFilename());
9249 
9250  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9251  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9252 }
9253 
9255  const InputInfo &Output,
9256  const InputInfoList &Inputs,
9257  const ArgList &Args,
9258  const char *LinkingOutput) const {
9259  const Driver &D = getToolChain().getDriver();
9260  ArgStringList CmdArgs;
9261 
9262  if (!D.SysRoot.empty())
9263  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9264 
9265  CmdArgs.push_back("--eh-frame-hdr");
9266  if (Args.hasArg(options::OPT_static)) {
9267  CmdArgs.push_back("-Bstatic");
9268  } else {
9269  if (Args.hasArg(options::OPT_rdynamic))
9270  CmdArgs.push_back("-export-dynamic");
9271  if (Args.hasArg(options::OPT_shared))
9272  CmdArgs.push_back("-Bshareable");
9273  else {
9274  CmdArgs.push_back("-dynamic-linker");
9275  CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9276  }
9277  CmdArgs.push_back("--hash-style=gnu");
9278  CmdArgs.push_back("--enable-new-dtags");
9279  }
9280 
9281  // When building 32-bit code on DragonFly/pc64, we have to explicitly
9282  // instruct ld in the base system to link 32-bit code.
9283  if (getToolChain().getArch() == llvm::Triple::x86) {
9284  CmdArgs.push_back("-m");
9285  CmdArgs.push_back("elf_i386");
9286  }
9287 
9288  if (Output.isFilename()) {
9289  CmdArgs.push_back("-o");
9290  CmdArgs.push_back(Output.getFilename());
9291  } else {
9292  assert(Output.isNothing() && "Invalid output.");
9293  }
9294 
9295  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9296  if (!Args.hasArg(options::OPT_shared)) {
9297  if (Args.hasArg(options::OPT_pg))
9298  CmdArgs.push_back(
9299  Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9300  else {
9301  if (Args.hasArg(options::OPT_pie))
9302  CmdArgs.push_back(
9303  Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9304  else
9305  CmdArgs.push_back(
9306  Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9307  }
9308  }
9309  CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9310  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9311  CmdArgs.push_back(
9312  Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9313  else
9314  CmdArgs.push_back(
9315  Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9316  }
9317 
9318  Args.AddAllArgs(CmdArgs,
9319  {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9320 
9321  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9322 
9323  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9324  CmdArgs.push_back("-L/usr/lib/gcc50");
9325 
9326  if (!Args.hasArg(options::OPT_static)) {
9327  CmdArgs.push_back("-rpath");
9328  CmdArgs.push_back("/usr/lib/gcc50");
9329  }
9330 
9331  if (D.CCCIsCXX()) {
9332  getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9333  CmdArgs.push_back("-lm");
9334  }
9335 
9336  if (Args.hasArg(options::OPT_pthread))
9337  CmdArgs.push_back("-lpthread");
9338 
9339  if (!Args.hasArg(options::OPT_nolibc)) {
9340  CmdArgs.push_back("-lc");
9341  }
9342 
9343  if (Args.hasArg(options::OPT_static) ||
9344  Args.hasArg(options::OPT_static_libgcc)) {
9345  CmdArgs.push_back("-lgcc");
9346  CmdArgs.push_back("-lgcc_eh");
9347  } else {
9348  if (Args.hasArg(options::OPT_shared_libgcc)) {
9349  CmdArgs.push_back("-lgcc_pic");
9350  if (!Args.hasArg(options::OPT_shared))
9351  CmdArgs.push_back("-lgcc");
9352  } else {
9353  CmdArgs.push_back("-lgcc");
9354  CmdArgs.push_back("--as-needed");
9355  CmdArgs.push_back("-lgcc_pic");
9356  CmdArgs.push_back("--no-as-needed");
9357  }
9358  }
9359  }
9360 
9361  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9362  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9363  CmdArgs.push_back(
9364  Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9365  else
9366  CmdArgs.push_back(
9367  Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9368  CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9369  }
9370 
9371  getToolChain().addProfileRTLibs(Args, CmdArgs);
9372 
9373  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9374  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9375 }
9376 
9377 // Try to find Exe from a Visual Studio distribution. This first tries to find
9378 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9379 // making sure that whatever executable that's found is not a same-named exe
9380 // from clang itself to prevent clang from falling back to itself.
9381 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9382  const char *Exe,
9383  const char *ClangProgramPath) {
9384  const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9385  std::string visualStudioBinDir;
9386  if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9387  visualStudioBinDir)) {
9388  SmallString<128> FilePath(visualStudioBinDir);
9389  llvm::sys::path::append(FilePath, Exe);
9390  if (llvm::sys::fs::can_execute(FilePath.c_str()))
9391  return FilePath.str();
9392  }
9393 
9394  return Exe;
9395 }
9396 
9398  const InputInfo &Output,
9399  const InputInfoList &Inputs,
9400  const ArgList &Args,
9401  const char *LinkingOutput) const {
9402  ArgStringList CmdArgs;
9403  const ToolChain &TC = getToolChain();
9404 
9405  assert((Output.isFilename() || Output.isNothing()) && "invalid output");
9406  if (Output.isFilename())
9407  CmdArgs.push_back(
9408  Args.MakeArgString(std::string("-out:") + Output.getFilename()));
9409 
9410  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
9411  !C.getDriver().IsCLMode())
9412  CmdArgs.push_back("-defaultlib:libcmt");
9413 
9414  if (!llvm::sys::Process::GetEnv("LIB")) {
9415  // If the VC environment hasn't been configured (perhaps because the user
9416  // did not run vcvarsall), try to build a consistent link environment. If
9417  // the environment variable is set however, assume the user knows what
9418  // they're doing.
9419  std::string VisualStudioDir;
9420  const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9421  if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
9422  SmallString<128> LibDir(VisualStudioDir);
9423  llvm::sys::path::append(LibDir, "VC", "lib");
9424  switch (MSVC.getArch()) {
9425  case llvm::Triple::x86:
9426  // x86 just puts the libraries directly in lib
9427  break;
9428  case llvm::Triple::x86_64:
9429  llvm::sys::path::append(LibDir, "amd64");
9430  break;
9431  case llvm::Triple::arm:
9432  llvm::sys::path::append(LibDir, "arm");
9433  break;
9434  default:
9435  break;
9436  }
9437  CmdArgs.push_back(
9438  Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
9439 
9440  if (MSVC.useUniversalCRT(VisualStudioDir)) {
9441  std::string UniversalCRTLibPath;
9442  if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
9443  CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9444  UniversalCRTLibPath.c_str()));
9445  }
9446  }
9447 
9448  std::string WindowsSdkLibPath;
9449  if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
9450  CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9451  WindowsSdkLibPath.c_str()));
9452  }
9453 
9454  CmdArgs.push_back("-nologo");
9455 
9456  if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
9457  CmdArgs.push_back("-debug");
9458 
9459  bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
9460  options::OPT_shared);
9461  if (DLL) {
9462  CmdArgs.push_back(Args.MakeArgString("-dll"));
9463 
9464  SmallString<128> ImplibName(Output.getFilename());
9465  llvm::sys::path::replace_extension(ImplibName, "lib");
9466  CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
9467  }
9468 
9469  if (TC.getSanitizerArgs().needsAsanRt()) {
9470  CmdArgs.push_back(Args.MakeArgString("-debug"));
9471  CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
9472  if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
9473  for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
9474  CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9475  // Make sure the dynamic runtime thunk is not optimized out at link time
9476  // to ensure proper SEH handling.
9477  CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
9478  } else if (DLL) {
9479  CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
9480  } else {
9481  for (const auto &Lib : {"asan", "asan_cxx"})
9482  CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9483  }
9484  }
9485 
9486  Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
9487 
9488  if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9489  options::OPT_fno_openmp, false)) {
9490  CmdArgs.push_back("-nodefaultlib:vcomp.lib");
9491  CmdArgs.push_back("-nodefaultlib:vcompd.lib");
9492  CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9493  TC.getDriver().Dir + "/../lib"));
9494  switch (getOpenMPRuntime(getToolChain(), Args)) {
9495  case OMPRT_OMP:
9496  CmdArgs.push_back("-defaultlib:libomp.lib");
9497  break;
9498  case OMPRT_IOMP5:
9499  CmdArgs.push_back("-defaultlib:libiomp5md.lib");
9500  break;
9501  case OMPRT_GOMP:
9502  break;
9503  case OMPRT_Unknown:
9504  // Already diagnosed.
9505  break;
9506  }
9507  }
9508 
9509  // Add filenames, libraries, and other linker inputs.
9510  for (const auto &Input : Inputs) {
9511  if (Input.isFilename()) {
9512  CmdArgs.push_back(Input.getFilename());
9513  continue;
9514  }
9515 
9516  const Arg &A = Input.getInputArg();
9517 
9518  // Render -l options differently for the MSVC linker.
9519  if (A.getOption().matches(options::OPT_l)) {
9520  StringRef Lib = A.getValue();
9521  const char *LinkLibArg;
9522  if (Lib.endswith(".lib"))
9523  LinkLibArg = Args.MakeArgString(Lib);
9524  else
9525  LinkLibArg = Args.MakeArgString(Lib + ".lib");
9526  CmdArgs.push_back(LinkLibArg);
9527  continue;
9528  }
9529 
9530  // Otherwise, this is some other kind of linker input option like -Wl, -z,
9531  // or -L. Render it, even if MSVC doesn't understand it.
9532  A.renderAsInput(Args, CmdArgs);
9533  }
9534 
9535  TC.addProfileRTLibs(Args, CmdArgs);
9536 
9537  // We need to special case some linker paths. In the case of lld, we need to
9538  // translate 'lld' into 'lld-link', and in the case of the regular msvc
9539  // linker, we need to use a special search algorithm.
9540  llvm::SmallString<128> linkPath;
9541  StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
9542  if (Linker.equals_lower("lld"))
9543  Linker = "lld-link";
9544 
9545  if (Linker.equals_lower("link")) {
9546  // If we're using the MSVC linker, it's not sufficient to just use link
9547  // from the program PATH, because other environments like GnuWin32 install
9548  // their own link.exe which may come first.
9549  linkPath = FindVisualStudioExecutable(TC, "link.exe",
9551  } else {
9552  linkPath = Linker;
9553  llvm::sys::path::replace_extension(linkPath, "exe");
9554  linkPath = TC.GetProgramPath(linkPath.c_str());
9555  }
9556 
9557  const char *Exec = Args.MakeArgString(linkPath);
9558  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9559 }
9560 
9562  const InputInfo &Output,
9563  const InputInfoList &Inputs,
9564  const ArgList &Args,
9565  const char *LinkingOutput) const {
9566  C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
9567 }
9568 
9569 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
9570  Compilation &C, const JobAction &JA, const InputInfo &Output,
9571  const InputInfoList &Inputs, const ArgList &Args,
9572  const char *LinkingOutput) const {
9573  ArgStringList CmdArgs;
9574  CmdArgs.push_back("/nologo");
9575  CmdArgs.push_back("/c"); // Compile only.
9576  CmdArgs.push_back("/W0"); // No warnings.
9577 
9578  // The goal is to be able to invoke this tool correctly based on
9579  // any flag accepted by clang-cl.
9580 
9581  // These are spelled the same way in clang and cl.exe,.
9582  Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
9583 
9584  // Optimization level.
9585  if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
9586  CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
9587  : "/Oi-");
9588  if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
9589  if (A->getOption().getID() == options::OPT_O0) {
9590  CmdArgs.push_back("/Od");
9591  } else {
9592  CmdArgs.push_back("/Og");
9593 
9594  StringRef OptLevel = A->getValue();
9595  if (OptLevel == "s" || OptLevel == "z")
9596  CmdArgs.push_back("/Os");
9597  else
9598  CmdArgs.push_back("/Ot");
9599 
9600  CmdArgs.push_back("/Ob2");
9601  }
9602  }
9603  if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
9604  options::OPT_fno_omit_frame_pointer))
9605  CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
9606  ? "/Oy"
9607  : "/Oy-");
9608  if (!Args.hasArg(options::OPT_fwritable_strings))
9609  CmdArgs.push_back("/GF");
9610 
9611  // Flags for which clang-cl has an alias.
9612  // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
9613 
9614  if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
9615  /*default=*/false))
9616  CmdArgs.push_back("/GR-");
9617  if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
9618  options::OPT_fno_function_sections))
9619  CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
9620  ? "/Gy"
9621  : "/Gy-");
9622  if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
9623  options::OPT_fno_data_sections))
9624  CmdArgs.push_back(
9625  A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
9626  if (Args.hasArg(options::OPT_fsyntax_only))
9627  CmdArgs.push_back("/Zs");
9628  if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
9629  options::OPT__SLASH_Z7))
9630  CmdArgs.push_back("/Z7");
9631 
9632  std::vector<std::string> Includes =
9633  Args.getAllArgValues(options::OPT_include);
9634  for (const auto &Include : Includes)
9635  CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
9636 
9637  // Flags that can simply be passed through.
9638  Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
9639  Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
9640  Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
9641  Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
9642 
9643  // The order of these flags is relevant, so pick the last one.
9644  if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
9645  options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
9646  A->render(Args, CmdArgs);
9647 
9648  // Input filename.
9649  assert(Inputs.size() == 1);
9650  const InputInfo &II = Inputs[0];
9651  assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9652  CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
9653  if (II.isFilename())
9654  CmdArgs.push_back(II.getFilename());
9655  else
9656  II.getInputArg().renderAsInput(Args, CmdArgs);
9657 
9658  // Output filename.
9659  assert(Output.getType() == types::TY_Object);
9660  const char *Fo =
9661  Args.MakeArgString(std::string("/Fo") + Output.getFilename());
9662  CmdArgs.push_back(Fo);
9663 
9664  const Driver &D = getToolChain().getDriver();
9665  std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
9666  D.getClangProgramPath());
9667  return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
9668  CmdArgs, Inputs);
9669 }
9670 
9671 /// MinGW Tools
9673  const InputInfo &Output,
9674  const InputInfoList &Inputs,
9675  const ArgList &Args,
9676  const char *LinkingOutput) const {
9677  claimNoWarnArgs(Args);
9678  ArgStringList CmdArgs;
9679 
9680  if (getToolChain().getArch() == llvm::Triple::x86) {
9681  CmdArgs.push_back("--32");
9682  } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9683  CmdArgs.push_back("--64");
9684  }
9685 
9686  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9687 
9688  CmdArgs.push_back("-o");
9689  CmdArgs.push_back(Output.getFilename());
9690 
9691  for (const auto &II : Inputs)
9692  CmdArgs.push_back(II.getFilename());
9693 
9694  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9695  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9696 
9697  if (Args.hasArg(options::OPT_gsplit_dwarf))
9698  SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9699  SplitDebugName(Args, Inputs[0]));
9700 }
9701 
9702 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9703  ArgStringList &CmdArgs) const {
9704  if (Args.hasArg(options::OPT_mthreads))
9705  CmdArgs.push_back("-lmingwthrd");
9706  CmdArgs.push_back("-lmingw32");
9707 
9708  // Make use of compiler-rt if --rtlib option is used
9709  ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
9710  if (RLT == ToolChain::RLT_Libgcc) {
9711  bool Static = Args.hasArg(options::OPT_static_libgcc) ||
9712  Args.hasArg(options::OPT_static);
9713  bool Shared = Args.hasArg(options::OPT_shared);
9714  bool CXX = getToolChain().getDriver().CCCIsCXX();
9715 
9716  if (Static || (!CXX && !Shared)) {
9717  CmdArgs.push_back("-lgcc");
9718  CmdArgs.push_back("-lgcc_eh");
9719  } else {
9720  CmdArgs.push_back("-lgcc_s");
9721  CmdArgs.push_back("-lgcc");
9722  }
9723  } else {
9724  AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9725  }
9726 
9727  CmdArgs.push_back("-lmoldname");
9728  CmdArgs.push_back("-lmingwex");
9729  CmdArgs.push_back("-lmsvcrt");
9730 }
9731 
9733  const InputInfo &Output,
9734  const InputInfoList &Inputs,
9735  const ArgList &Args,
9736  const char *LinkingOutput) const {
9737  const ToolChain &TC = getToolChain();
9738  const Driver &D = TC.getDriver();
9739  // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9740 
9741  ArgStringList CmdArgs;
9742 
9743  // Silence warning for "clang -g foo.o -o foo"
9744  Args.ClaimAllArgs(options::OPT_g_Group);
9745  // and "clang -emit-llvm foo.o -o foo"
9746  Args.ClaimAllArgs(options::OPT_emit_llvm);
9747  // and for "clang -w foo.o -o foo". Other warning options are already
9748  // handled somewhere else.
9749  Args.ClaimAllArgs(options::OPT_w);
9750 
9751  StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9752  if (LinkerName.equals_lower("lld")) {
9753  CmdArgs.push_back("-flavor");
9754  CmdArgs.push_back("gnu");
9755  } else if (!LinkerName.equals_lower("ld")) {
9756  D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
9757  }
9758 
9759  if (!D.SysRoot.empty())
9760  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9761 
9762  if (Args.hasArg(options::OPT_s))
9763  CmdArgs.push_back("-s");
9764 
9765  CmdArgs.push_back("-m");
9766  if (TC.getArch() == llvm::Triple::x86)
9767  CmdArgs.push_back("i386pe");
9768  if (TC.getArch() == llvm::Triple::x86_64)
9769  CmdArgs.push_back("i386pep");
9770  if (TC.getArch() == llvm::Triple::arm)
9771  CmdArgs.push_back("thumb2pe");
9772 
9773  if (Args.hasArg(options::OPT_mwindows)) {
9774  CmdArgs.push_back("--subsystem");
9775  CmdArgs.push_back("windows");
9776  } else if (Args.hasArg(options::OPT_mconsole)) {
9777  CmdArgs.push_back("--subsystem");
9778  CmdArgs.push_back("console");
9779  }
9780 
9781  if (Args.hasArg(options::OPT_static))
9782  CmdArgs.push_back("-Bstatic");
9783  else {
9784  if (Args.hasArg(options::OPT_mdll))
9785  CmdArgs.push_back("--dll");
9786  else if (Args.hasArg(options::OPT_shared))
9787  CmdArgs.push_back("--shared");
9788  CmdArgs.push_back("-Bdynamic");
9789  if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9790  CmdArgs.push_back("-e");
9791  if (TC.getArch() == llvm::Triple::x86)
9792  CmdArgs.push_back("_DllMainCRTStartup@12");
9793  else
9794  CmdArgs.push_back("DllMainCRTStartup");
9795  CmdArgs.push_back("--enable-auto-image-base");
9796  }
9797  }
9798 
9799  CmdArgs.push_back("-o");
9800  CmdArgs.push_back(Output.getFilename());
9801 
9802  Args.AddAllArgs(CmdArgs, options::OPT_e);
9803  // FIXME: add -N, -n flags
9804  Args.AddLastArg(CmdArgs, options::OPT_r);
9805  Args.AddLastArg(CmdArgs, options::OPT_s);
9806  Args.AddLastArg(CmdArgs, options::OPT_t);
9807  Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9808  Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9809 
9810  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9811  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9812  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9813  } else {
9814  if (Args.hasArg(options::OPT_municode))
9815  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9816  else
9817  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9818  }
9819  if (Args.hasArg(options::OPT_pg))
9820  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9821  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9822  }
9823 
9824  Args.AddAllArgs(CmdArgs, options::OPT_L);
9825  TC.AddFilePathLibArgs(Args, CmdArgs);
9826  AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9827 
9828  // TODO: Add ASan stuff here
9829 
9830  // TODO: Add profile stuff here
9831 
9832  if (D.CCCIsCXX() &&
9833  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9834  bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9835  !Args.hasArg(options::OPT_static);
9836  if (OnlyLibstdcxxStatic)
9837  CmdArgs.push_back("-Bstatic");
9838  TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9839  if (OnlyLibstdcxxStatic)
9840  CmdArgs.push_back("-Bdynamic");
9841  }
9842 
9843  if (!Args.hasArg(options::OPT_nostdlib)) {
9844  if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9845  if (Args.hasArg(options::OPT_static))
9846  CmdArgs.push_back("--start-group");
9847 
9848  if (Args.hasArg(options::OPT_fstack_protector) ||
9849  Args.hasArg(options::OPT_fstack_protector_strong) ||
9850  Args.hasArg(options::OPT_fstack_protector_all)) {
9851  CmdArgs.push_back("-lssp_nonshared");
9852  CmdArgs.push_back("-lssp");
9853  }
9854  if (Args.hasArg(options::OPT_fopenmp))
9855  CmdArgs.push_back("-lgomp");
9856 
9857  AddLibGCC(Args, CmdArgs);
9858 
9859  if (Args.hasArg(options::OPT_pg))
9860  CmdArgs.push_back("-lgmon");
9861 
9862  if (Args.hasArg(options::OPT_pthread))
9863  CmdArgs.push_back("-lpthread");
9864 
9865  // add system libraries
9866  if (Args.hasArg(options::OPT_mwindows)) {
9867  CmdArgs.push_back("-lgdi32");
9868  CmdArgs.push_back("-lcomdlg32");
9869  }
9870  CmdArgs.push_back("-ladvapi32");
9871  CmdArgs.push_back("-lshell32");
9872  CmdArgs.push_back("-luser32");
9873  CmdArgs.push_back("-lkernel32");
9874 
9875  if (Args.hasArg(options::OPT_static))
9876  CmdArgs.push_back("--end-group");
9877  else if (!LinkerName.equals_lower("lld"))
9878  AddLibGCC(Args, CmdArgs);
9879  }
9880 
9881  if (!Args.hasArg(options::OPT_nostartfiles)) {
9882  // Add crtfastmath.o if available and fast math is enabled.
9883  TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9884 
9885  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9886  }
9887  }
9888  const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9889  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9890 }
9891 
9892 /// XCore Tools
9893 // We pass assemble and link construction to the xcc tool.
9894 
9896  const InputInfo &Output,
9897  const InputInfoList &Inputs,
9898  const ArgList &Args,
9899  const char *LinkingOutput) const {
9900  claimNoWarnArgs(Args);
9901  ArgStringList CmdArgs;
9902 
9903  CmdArgs.push_back("-o");
9904  CmdArgs.push_back(Output.getFilename());
9905 
9906  CmdArgs.push_back("-c");
9907 
9908  if (Args.hasArg(options::OPT_v))
9909  CmdArgs.push_back("-v");
9910 
9911  if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9912  if (!A->getOption().matches(options::OPT_g0))
9913  CmdArgs.push_back("-g");
9914 
9915  if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9916  false))
9917  CmdArgs.push_back("-fverbose-asm");
9918 
9919  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9920 
9921  for (const auto &II : Inputs)
9922  CmdArgs.push_back(II.getFilename());
9923 
9924  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9925  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9926 }
9927 
9929  const InputInfo &Output,
9930  const InputInfoList &Inputs,
9931  const ArgList &Args,
9932  const char *LinkingOutput) const {
9933  ArgStringList CmdArgs;
9934 
9935  if (Output.isFilename()) {
9936  CmdArgs.push_back("-o");
9937  CmdArgs.push_back(Output.getFilename());
9938  } else {
9939  assert(Output.isNothing() && "Invalid output.");
9940  }
9941 
9942  if (Args.hasArg(options::OPT_v))
9943  CmdArgs.push_back("-v");
9944 
9945  // Pass -fexceptions through to the linker if it was present.
9946  if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9947  false))
9948  CmdArgs.push_back("-fexceptions");
9949 
9950  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9951 
9952  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9953  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9954 }
9955 
9957  const InputInfo &Output,
9958  const InputInfoList &Inputs,
9959  const ArgList &Args,
9960  const char *LinkingOutput) const {
9961  claimNoWarnArgs(Args);
9962  const auto &TC =
9963  static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9964  ArgStringList CmdArgs;
9965  const char *Exec;
9966 
9967  switch (TC.getArch()) {
9968  default:
9969  llvm_unreachable("unsupported architecture");
9970  case llvm::Triple::arm:
9971  case llvm::Triple::thumb:
9972  break;
9973  case llvm::Triple::x86:
9974  CmdArgs.push_back("--32");
9975  break;
9976  case llvm::Triple::x86_64:
9977  CmdArgs.push_back("--64");
9978  break;
9979  }
9980 
9981  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9982 
9983  CmdArgs.push_back("-o");
9984  CmdArgs.push_back(Output.getFilename());
9985 
9986  for (const auto &Input : Inputs)
9987  CmdArgs.push_back(Input.getFilename());
9988 
9989  const std::string Assembler = TC.GetProgramPath("as");
9990  Exec = Args.MakeArgString(Assembler);
9991 
9992  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9993 }
9994 
9996  const InputInfo &Output,
9997  const InputInfoList &Inputs,
9998  const ArgList &Args,
9999  const char *LinkingOutput) const {
10000  const auto &TC =
10001  static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10002  const llvm::Triple &T = TC.getTriple();
10003  const Driver &D = TC.getDriver();
10004  SmallString<128> EntryPoint;
10005  ArgStringList CmdArgs;
10006  const char *Exec;
10007 
10008  // Silence warning for "clang -g foo.o -o foo"
10009  Args.ClaimAllArgs(options::OPT_g_Group);
10010  // and "clang -emit-llvm foo.o -o foo"
10011  Args.ClaimAllArgs(options::OPT_emit_llvm);
10012  // and for "clang -w foo.o -o foo"
10013  Args.ClaimAllArgs(options::OPT_w);
10014  // Other warning options are already handled somewhere else.
10015 
10016  if (!D.SysRoot.empty())
10017  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10018 
10019  if (Args.hasArg(options::OPT_pie))
10020  CmdArgs.push_back("-pie");
10021  if (Args.hasArg(options::OPT_rdynamic))
10022  CmdArgs.push_back("-export-dynamic");
10023  if (Args.hasArg(options::OPT_s))
10024  CmdArgs.push_back("--strip-all");
10025 
10026  CmdArgs.push_back("-m");
10027  switch (TC.getArch()) {
10028  default:
10029  llvm_unreachable("unsupported architecture");
10030  case llvm::Triple::arm:
10031  case llvm::Triple::thumb:
10032  // FIXME: this is incorrect for WinCE
10033  CmdArgs.push_back("thumb2pe");
10034  break;
10035  case llvm::Triple::x86:
10036  CmdArgs.push_back("i386pe");
10037  EntryPoint.append("_");
10038  break;
10039  case llvm::Triple::x86_64:
10040  CmdArgs.push_back("i386pep");
10041  break;
10042  }
10043 
10044  if (Args.hasArg(options::OPT_shared)) {
10045  switch (T.getArch()) {
10046  default:
10047  llvm_unreachable("unsupported architecture");
10048  case llvm::Triple::arm:
10049  case llvm::Triple::thumb:
10050  case llvm::Triple::x86_64:
10051  EntryPoint.append("_DllMainCRTStartup");
10052  break;
10053  case llvm::Triple::x86:
10054  EntryPoint.append("_DllMainCRTStartup@12");
10055  break;
10056  }
10057 
10058  CmdArgs.push_back("-shared");
10059  CmdArgs.push_back("-Bdynamic");
10060 
10061  CmdArgs.push_back("--enable-auto-image-base");
10062 
10063  CmdArgs.push_back("--entry");
10064  CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10065  } else {
10066  EntryPoint.append("mainCRTStartup");
10067 
10068  CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10069  : "-Bdynamic");
10070 
10071  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10072  CmdArgs.push_back("--entry");
10073  CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10074  }
10075 
10076  // FIXME: handle subsystem
10077  }
10078 
10079  // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10080  CmdArgs.push_back("--allow-multiple-definition");
10081 
10082  CmdArgs.push_back("-o");
10083  CmdArgs.push_back(Output.getFilename());
10084 
10085  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10086  SmallString<261> ImpLib(Output.getFilename());
10087  llvm::sys::path::replace_extension(ImpLib, ".lib");
10088 
10089  CmdArgs.push_back("--out-implib");
10090  CmdArgs.push_back(Args.MakeArgString(ImpLib));
10091  }
10092 
10093  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10094  const std::string CRTPath(D.SysRoot + "/usr/lib/");
10095  const char *CRTBegin;
10096 
10097  CRTBegin =
10098  Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10099  CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10100  }
10101 
10102  Args.AddAllArgs(CmdArgs, options::OPT_L);
10103  TC.AddFilePathLibArgs(Args, CmdArgs);
10104  AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10105 
10106  if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10107  !Args.hasArg(options::OPT_nodefaultlibs)) {
10108  bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10109  !Args.hasArg(options::OPT_static);
10110  if (StaticCXX)
10111  CmdArgs.push_back("-Bstatic");
10112  TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10113  if (StaticCXX)
10114  CmdArgs.push_back("-Bdynamic");
10115  }
10116 
10117  if (!Args.hasArg(options::OPT_nostdlib)) {
10118  if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10119  // TODO handle /MT[d] /MD[d]
10120  CmdArgs.push_back("-lmsvcrt");
10121  AddRunTimeLibs(TC, D, CmdArgs, Args);
10122  }
10123  }
10124 
10125  if (TC.getSanitizerArgs().needsAsanRt()) {
10126  // TODO handle /MT[d] /MD[d]
10127  if (Args.hasArg(options::OPT_shared)) {
10128  CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10129  } else {
10130  for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10131  CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10132  // Make sure the dynamic runtime thunk is not optimized out at link time
10133  // to ensure proper SEH handling.
10134  CmdArgs.push_back(Args.MakeArgString("--undefined"));
10135  CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10136  ? "___asan_seh_interceptor"
10137  : "__asan_seh_interceptor"));
10138  }
10139  }
10140 
10141  Exec = Args.MakeArgString(TC.GetLinkerPath());
10142 
10143  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10144 }
10145 
10147  const InputInfo &Output,
10148  const InputInfoList &Inputs,
10149  const ArgList &Args,
10150  const char *LinkingOutput) const {
10151  ArgStringList CmdArgs;
10152  assert(Inputs.size() == 1);
10153  const InputInfo &II = Inputs[0];
10154  assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10155  II.getType() == types::TY_PP_CXX);
10156 
10157  if (JA.getKind() == Action::PreprocessJobClass) {
10158  Args.ClaimAllArgs();
10159  CmdArgs.push_back("-E");
10160  } else {
10161  assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10162  CmdArgs.push_back("-S");
10163  CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10164  }
10165  CmdArgs.push_back("-mcpu=myriad2");
10166  CmdArgs.push_back("-DMYRIAD2");
10167 
10168  // Append all -I, -iquote, -isystem paths, defines/undefines,
10169  // 'f' flags, optimize flags, and warning options.
10170  // These are spelled the same way in clang and moviCompile.
10171  Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10172  options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10173  options::OPT_f_Group, options::OPT_f_clang_Group,
10174  options::OPT_g_Group, options::OPT_M_Group,
10175  options::OPT_O_Group, options::OPT_W_Group});
10176 
10177  // If we're producing a dependency file, and assembly is the final action,
10178  // then the name of the target in the dependency file should be the '.o'
10179  // file, not the '.s' file produced by this step. For example, instead of
10180  // /tmp/mumble.s: mumble.c .../someheader.h
10181  // the filename on the lefthand side should be "mumble.o"
10182  if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10183  C.getActions().size() == 1 &&
10184  C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10185  Arg *A = Args.getLastArg(options::OPT_o);
10186  if (A) {
10187  CmdArgs.push_back("-MT");
10188  CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10189  }
10190  }
10191 
10192  CmdArgs.push_back(II.getFilename());
10193  CmdArgs.push_back("-o");
10194  CmdArgs.push_back(Output.getFilename());
10195 
10196  std::string Exec =
10197  Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10198  C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10199  CmdArgs, Inputs));
10200 }
10201 
10203  const InputInfo &Output,
10204  const InputInfoList &Inputs,
10205  const ArgList &Args,
10206  const char *LinkingOutput) const {
10207  ArgStringList CmdArgs;
10208 
10209  assert(Inputs.size() == 1);
10210  const InputInfo &II = Inputs[0];
10211  assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10212  assert(Output.getType() == types::TY_Object);
10213 
10214  CmdArgs.push_back("-no6thSlotCompression");
10215  CmdArgs.push_back("-cv:myriad2"); // Chip Version
10216  CmdArgs.push_back("-noSPrefixing");
10217  CmdArgs.push_back("-a"); // Mystery option.
10218  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10219  for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10220  A->claim();
10221  CmdArgs.push_back(
10222  Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10223  }
10224  CmdArgs.push_back("-elf"); // Output format.
10225  CmdArgs.push_back(II.getFilename());
10226  CmdArgs.push_back(
10227  Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10228 
10229  std::string Exec =
10230  Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10231  C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10232  CmdArgs, Inputs));
10233 }
10234 
10236  const InputInfo &Output,
10237  const InputInfoList &Inputs,
10238  const ArgList &Args,
10239  const char *LinkingOutput) const {
10240  const auto &TC =
10241  static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10242  const llvm::Triple &T = TC.getTriple();
10243  ArgStringList CmdArgs;
10244  bool UseStartfiles =
10245  !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10246  bool UseDefaultLibs =
10247  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10248 
10249  if (T.getArch() == llvm::Triple::sparc)
10250  CmdArgs.push_back("-EB");
10251  else // SHAVE assumes little-endian, and sparcel is expressly so.
10252  CmdArgs.push_back("-EL");
10253 
10254  // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10255  // but we never pass through a --sysroot option and various other bits.
10256  // For example, there are no sanitizers (yet) nor gold linker.
10257 
10258  // Eat some arguments that may be present but have no effect.
10259  Args.ClaimAllArgs(options::OPT_g_Group);
10260  Args.ClaimAllArgs(options::OPT_w);
10261  Args.ClaimAllArgs(options::OPT_static_libgcc);
10262 
10263  if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10264  CmdArgs.push_back("-s");
10265 
10266  CmdArgs.push_back("-o");
10267  CmdArgs.push_back(Output.getFilename());
10268 
10269  if (UseStartfiles) {
10270  // If you want startfiles, it means you want the builtin crti and crtbegin,
10271  // but not crt0. Myriad link commands provide their own crt0.o as needed.
10272  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10273  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10274  }
10275 
10276  Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10277  options::OPT_e, options::OPT_s, options::OPT_t,
10278  options::OPT_Z_Flag, options::OPT_r});
10279 
10280  TC.AddFilePathLibArgs(Args, CmdArgs);
10281 
10282  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10283 
10284  if (UseDefaultLibs) {
10285  if (C.getDriver().CCCIsCXX())
10286  CmdArgs.push_back("-lstdc++");
10287  if (T.getOS() == llvm::Triple::RTEMS) {
10288  CmdArgs.push_back("--start-group");
10289  CmdArgs.push_back("-lc");
10290  // You must provide your own "-L" option to enable finding these.
10291  CmdArgs.push_back("-lrtemscpu");
10292  CmdArgs.push_back("-lrtemsbsp");
10293  CmdArgs.push_back("--end-group");
10294  } else {
10295  CmdArgs.push_back("-lc");
10296  }
10297  CmdArgs.push_back("-lgcc");
10298  }
10299  if (UseStartfiles) {
10300  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10301  CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10302  }
10303 
10304  std::string Exec =
10305  Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10306  C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10307  CmdArgs, Inputs));
10308 }
10309 
10311  const InputInfo &Output,
10312  const InputInfoList &Inputs,
10313  const ArgList &Args,
10314  const char *LinkingOutput) const {
10315  claimNoWarnArgs(Args);
10316  ArgStringList CmdArgs;
10317 
10318  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10319 
10320  CmdArgs.push_back("-o");
10321  CmdArgs.push_back(Output.getFilename());
10322 
10323  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10324  const InputInfo &Input = Inputs[0];
10325  assert(Input.isFilename() && "Invalid input.");
10326  CmdArgs.push_back(Input.getFilename());
10327 
10328  const char *Exec =
10329  Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
10330  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10331 }
10332 
10333 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10334  const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10335  if (SanArgs.needsUbsanRt()) {
10336  CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10337  }
10338  if (SanArgs.needsAsanRt()) {
10339  CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10340  }
10341 }
10342 
10343 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10344  const JobAction &JA, const InputInfo &Output,
10345  const InputInfoList &Inputs,
10346  const ArgList &Args,
10347  const char *LinkingOutput) {
10349  static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10350  const Driver &D = ToolChain.getDriver();
10351  ArgStringList CmdArgs;
10352 
10353  // Silence warning for "clang -g foo.o -o foo"
10354  Args.ClaimAllArgs(options::OPT_g_Group);
10355  // and "clang -emit-llvm foo.o -o foo"
10356  Args.ClaimAllArgs(options::OPT_emit_llvm);
10357  // and for "clang -w foo.o -o foo". Other warning options are already
10358  // handled somewhere else.
10359  Args.ClaimAllArgs(options::OPT_w);
10360 
10361  if (!D.SysRoot.empty())
10362  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10363 
10364  if (Args.hasArg(options::OPT_pie))
10365  CmdArgs.push_back("-pie");
10366 
10367  if (Args.hasArg(options::OPT_rdynamic))
10368  CmdArgs.push_back("-export-dynamic");
10369  if (Args.hasArg(options::OPT_shared))
10370  CmdArgs.push_back("--oformat=so");
10371 
10372  if (Output.isFilename()) {
10373  CmdArgs.push_back("-o");
10374  CmdArgs.push_back(Output.getFilename());
10375  } else {
10376  assert(Output.isNothing() && "Invalid output.");
10377  }
10378 
10379  AddPS4SanitizerArgs(ToolChain, CmdArgs);
10380 
10381  Args.AddAllArgs(CmdArgs, options::OPT_L);
10382  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10383  Args.AddAllArgs(CmdArgs, options::OPT_e);
10384  Args.AddAllArgs(CmdArgs, options::OPT_s);
10385  Args.AddAllArgs(CmdArgs, options::OPT_t);
10386  Args.AddAllArgs(CmdArgs, options::OPT_r);
10387 
10388  if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10389  CmdArgs.push_back("--no-demangle");
10390 
10391  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10392 
10393  if (Args.hasArg(options::OPT_pthread)) {
10394  CmdArgs.push_back("-lpthread");
10395  }
10396 
10397  const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10398 
10399  C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10400 }
10401 
10402 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
10403  const JobAction &JA, const InputInfo &Output,
10404  const InputInfoList &Inputs,
10405  const ArgList &Args,
10406  const char *LinkingOutput) {
10408  static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10409  const Driver &D = ToolChain.getDriver();
10410  ArgStringList CmdArgs;
10411 
10412  // Silence warning for "clang -g foo.o -o foo"
10413  Args.ClaimAllArgs(options::OPT_g_Group);
10414  // and "clang -emit-llvm foo.o -o foo"
10415  Args.ClaimAllArgs(options::OPT_emit_llvm);
10416  // and for "clang -w foo.o -o foo". Other warning options are already
10417  // handled somewhere else.
10418  Args.ClaimAllArgs(options::OPT_w);
10419 
10420  if (!D.SysRoot.empty())
10421  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10422 
10423  if (Args.hasArg(options::OPT_pie))
10424  CmdArgs.push_back("-pie");
10425 
10426  if (Args.hasArg(options::OPT_static)) {
10427  CmdArgs.push_back("-Bstatic");
10428  } else {
10429  if (Args.hasArg(options::OPT_rdynamic))
10430  CmdArgs.push_back("-export-dynamic");
10431  CmdArgs.push_back("--eh-frame-hdr");
10432  if (Args.hasArg(options::OPT_shared)) {
10433  CmdArgs.push_back("-Bshareable");
10434  } else {
10435  CmdArgs.push_back("-dynamic-linker");
10436  CmdArgs.push_back("/libexec/ld-elf.so.1");
10437  }
10438  CmdArgs.push_back("--enable-new-dtags");
10439  }
10440 
10441  if (Output.isFilename()) {
10442  CmdArgs.push_back("-o");
10443  CmdArgs.push_back(Output.getFilename());
10444  } else {
10445  assert(Output.isNothing() && "Invalid output.");
10446  }
10447 
10448  AddPS4SanitizerArgs(ToolChain, CmdArgs);
10449 
10450  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10451  const char *crt1 = nullptr;
10452  if (!Args.hasArg(options::OPT_shared)) {
10453  if (Args.hasArg(options::OPT_pg))
10454  crt1 = "gcrt1.o";
10455  else if (Args.hasArg(options::OPT_pie))
10456  crt1 = "Scrt1.o";
10457  else
10458  crt1 = "crt1.o";
10459  }
10460  if (crt1)
10461  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
10462 
10463  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
10464 
10465  const char *crtbegin = nullptr;
10466  if (Args.hasArg(options::OPT_static))
10467  crtbegin = "crtbeginT.o";
10468  else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10469  crtbegin = "crtbeginS.o";
10470  else
10471  crtbegin = "crtbegin.o";
10472 
10473  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
10474  }
10475 
10476  Args.AddAllArgs(CmdArgs, options::OPT_L);
10477  ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10478  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10479  Args.AddAllArgs(CmdArgs, options::OPT_e);
10480  Args.AddAllArgs(CmdArgs, options::OPT_s);
10481  Args.AddAllArgs(CmdArgs, options::OPT_t);
10482  Args.AddAllArgs(CmdArgs, options::OPT_r);
10483 
10484  if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10485  CmdArgs.push_back("--no-demangle");
10486 
10487  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10488 
10489  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10490  // For PS4, we always want to pass libm, libstdc++ and libkernel
10491  // libraries for both C and C++ compilations.
10492  CmdArgs.push_back("-lkernel");
10493  if (D.CCCIsCXX()) {
10494  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10495  if (Args.hasArg(options::OPT_pg))
10496  CmdArgs.push_back("-lm_p");
10497  else
10498  CmdArgs.push_back("-lm");
10499  }
10500  // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
10501  // the default system libraries. Just mimic this for now.
10502  if (Args.hasArg(options::OPT_pg))
10503  CmdArgs.push_back("-lgcc_p");
10504  else
10505  CmdArgs.push_back("-lcompiler_rt");
10506  if (Args.hasArg(options::OPT_static)) {
10507  CmdArgs.push_back("-lstdc++");
10508  } else if (Args.hasArg(options::OPT_pg)) {
10509  CmdArgs.push_back("-lgcc_eh_p");
10510  } else {
10511  CmdArgs.push_back("--as-needed");
10512  CmdArgs.push_back("-lstdc++");
10513  CmdArgs.push_back("--no-as-needed");
10514  }
10515 
10516  if (Args.hasArg(options::OPT_pthread)) {
10517  if (Args.hasArg(options::OPT_pg))
10518  CmdArgs.push_back("-lpthread_p");
10519  else
10520  CmdArgs.push_back("-lpthread");
10521  }
10522 
10523  if (Args.hasArg(options::OPT_pg)) {
10524  if (Args.hasArg(options::OPT_shared))
10525  CmdArgs.push_back("-lc");
10526  else {
10527  if (Args.hasArg(options::OPT_static)) {
10528  CmdArgs.push_back("--start-group");
10529  CmdArgs.push_back("-lc_p");
10530  CmdArgs.push_back("-lpthread_p");
10531  CmdArgs.push_back("--end-group");
10532  } else {
10533  CmdArgs.push_back("-lc_p");
10534  }
10535  }
10536  CmdArgs.push_back("-lgcc_p");
10537  } else {
10538  if (Args.hasArg(options::OPT_static)) {
10539  CmdArgs.push_back("--start-group");
10540  CmdArgs.push_back("-lc");
10541  CmdArgs.push_back("-lpthread");
10542  CmdArgs.push_back("--end-group");
10543  } else {
10544  CmdArgs.push_back("-lc");
10545  }
10546  CmdArgs.push_back("-lcompiler_rt");
10547  }
10548 
10549  if (Args.hasArg(options::OPT_static)) {
10550  CmdArgs.push_back("-lstdc++");
10551  } else if (Args.hasArg(options::OPT_pg)) {
10552  CmdArgs.push_back("-lgcc_eh_p");
10553  } else {
10554  CmdArgs.push_back("--as-needed");
10555  CmdArgs.push_back("-lstdc++");
10556  CmdArgs.push_back("--no-as-needed");
10557  }
10558  }
10559 
10560  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10561  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10562  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
10563  else
10564  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
10565  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
10566  }
10567 
10568  const char *Exec =
10569 #ifdef LLVM_ON_WIN32
10570  Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
10571 #else
10572  Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10573 #endif
10574 
10575  C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10576 }
10577 
10579  const InputInfo &Output,
10580  const InputInfoList &Inputs,
10581  const ArgList &Args,
10582  const char *LinkingOutput) const {
10584  static_cast<const toolchains::FreeBSD &>(getToolChain());
10585  const Driver &D = ToolChain.getDriver();
10586  bool PS4Linker;
10587  StringRef LinkerOptName;
10588  if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
10589  LinkerOptName = A->getValue();
10590  if (LinkerOptName != "ps4" && LinkerOptName != "gold")
10591  D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
10592  }
10593 
10594  if (LinkerOptName == "gold")
10595  PS4Linker = false;
10596  else if (LinkerOptName == "ps4")
10597  PS4Linker = true;
10598  else
10599  PS4Linker = !Args.hasArg(options::OPT_shared);
10600 
10601  if (PS4Linker)
10602  ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10603  else
10604  ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10605 }
static std::string getR600TargetGPU(const ArgList &Args)
Get the (LLVM) name of the R600 gpu we are targeting.
Definition: Tools.cpp:1541
static void AddLibgcc(const llvm::Triple &Triple, const Driver &D, ArgStringList &CmdArgs, const ArgList &Args)
Definition: Tools.cpp:8592
const Driver & getDriver() const
Definition: Compilation.h:89
const llvm::Triple & getTriple() const
Definition: ToolChain.h:129
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
int Position
virtual void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
Definition: ToolChain.cpp:513
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9154
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition: Tools.cpp:6788
static VersionTuple getMSCompatibilityVersion(unsigned Version)
Definition: Tools.cpp:3039
types::ID getType() const
Definition: InputInfo.h:78
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:8986
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
NanEncoding getSupportedNanEncoding(StringRef &CPU)
Definition: Tools.cpp:6658
static bool UseRelaxAll(Compilation &C, const ArgList &Args)
Check if -relax-all should be passed to the internal assembler.
Definition: Tools.cpp:2476
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number...
Definition: Version.cpp:118
std::string GetProgramPath(const char *Name) const
Definition: ToolChain.cpp:338
prefix_list PrefixDirs
Definition: Driver.h:117
bool shouldUseFPXX(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef CPUName, StringRef ABIName, mips::FloatABI FloatABI)
virtual bool AddFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFastMathRuntimeIfAvailable - If a runtime library exists that sets global flags for unsafe floatin...
Definition: ToolChain.cpp:631
static void EscapeSpacesAndBackslashes(const char *Arg, SmallVectorImpl< char > &Res)
Definition: Tools.cpp:130
unsigned CCPrintHeaders
Set CC_PRINT_HEADERS mode, which causes the frontend to log header include information to CCPrintHead...
Definition: Driver.h:168
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:47
static void addExceptionArgs(const ArgList &Args, types::ID InputType, const ToolChain &TC, bool KernelOrKext, const ObjCRuntime &objcRuntime, ArgStringList &CmdArgs)
Adds exception related arguments to the driver command arguments.
Definition: Tools.cpp:2370
static void collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, SmallVectorImpl< StringRef > &SharedRuntimes, SmallVectorImpl< StringRef > &StaticRuntimes, SmallVectorImpl< StringRef > &HelperStaticRuntimes)
Definition: Tools.cpp:2787
unsigned CCCUsePCH
Use lazy precompiled headers for PCH support.
Definition: Driver.h:188
static void linkSanitizerRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs)
Definition: Tools.cpp:2773
static void appendUserToPath(SmallVectorImpl< char > &Result)
Definition: Tools.cpp:3063
Defines types useful for describing an Objective-C runtime.
std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const
GetTemporaryPath - Return the pathname of a temporary file to use as part of compilation; the file wi...
Definition: Driver.cpp:2191
Emit only debug info necessary for generating line number tables (-gline-tables-only).
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:8762
std::string DyldPrefix
Dynamic loader prefix, if present.
Definition: Driver.h:123
bool canTypeBeUserSpecified(ID Id)
canTypeBeUserSpecified - Can this type be specified on the command line (by the type name); this is u...
Definition: Types.cpp:65
bool allowsWeak() const
Does this runtime allow the use of __weak?
Definition: ObjCRuntime.h:192
StringRef getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple)
Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
Definition: Tools.cpp:6593
bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
Definition: ToolChain.cpp:82
static void AddRunTimeLibs(const ToolChain &TC, const Driver &D, ArgStringList &CmdArgs, const ArgList &Args)
Definition: Tools.cpp:8692
bool isFilename() const
Definition: InputInfo.h:76
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:90
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7398
StringRef getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch, const llvm::Triple &Triple)
getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular CPU (or Arch, if CPU is generic).
Definition: Tools.cpp:6625
static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch, llvm::StringRef &CPU, bool FromAs=false)
Definition: Tools.cpp:568
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI ...
Definition: ObjCRuntime.h:50
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:131
static bool GetReleaseVersion(const char *Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra)
GetReleaseVersion - Parse (([0-9]+)(.
Definition: Driver.cpp:2333
static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC)
Definition: Tools.cpp:2443
static void ConstructPS4LinkJob(const Tool &T, Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput)
Definition: Tools.cpp:10343
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9732
static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 option to specify the debug compilation directory.
Definition: Tools.cpp:2943
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7170
MyriadToolChain - A tool chain using either clang or the external compiler installed by the Movidius ...
Definition: ToolChains.h:1067
virtual void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const
Definition: Tools.cpp:6325
virtual bool isPICDefaultForced() const =0
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
static void QuoteTarget(StringRef Target, SmallVectorImpl< char > &Res)
Definition: Tools.cpp:147
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args)
CheckCodeGenerationOptions - Perform some validation of code generation arguments that is shared with...
Definition: Tools.cpp:118
static const char * getSystemZTargetCPU(const ArgList &Args)
Definition: Tools.cpp:1580
types::ID getType() const
Definition: Action.h:94
std::string getHexagonTargetDir(const std::string &InstalledDir, const SmallVectorImpl< std::string > &PrefixDirs) const
Hexagon Toolchain.
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:68
virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCCKextLibArgs - Add the system specific linker arguments to use for kernel extensions (Darwin-spec...
Definition: ToolChain.cpp:626
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition: Driver.h:151
static bool ShouldDisableDwarfDirectory(const ArgList &Args, const ToolChain &TC)
Definition: Tools.cpp:2454
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9254
const StringRef FilePath
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:37
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
static bool shouldUseFramePointer(const ArgList &Args, const llvm::Triple &Triple)
Definition: Tools.cpp:2917
static void addPGOAndCoverageFlags(Compilation &C, const Driver &D, const InputInfo &Output, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Tools.cpp:3142
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: ToolChain.cpp:369
ActionList & getInputs()
Definition: Action.h:96
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition: Driver.h:173
static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args, llvm::StringRef CPUName, llvm::StringRef ArchName, std::vector< const char * > &Features, const llvm::Triple &Triple)
Definition: Tools.cpp:638
void addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const
static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:2199
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition: Driver.h:101
static const char * RelocationModelName(llvm::Reloc::Model Model)
Definition: Tools.cpp:3393
Emit location information but do not generate debug info in the output.
void appendEBLinkFlags(const llvm::opt::ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple)
ActionClass getKind() const
Definition: Action.h:93
std::string getARMTargetCPU(StringRef CPU, StringRef Arch, const llvm::Triple &Triple)
getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
Definition: Tools.cpp:6606
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
Definition: ToolChain.cpp:373
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:8081
static bool shouldUseLeafFramePointer(const ArgList &Args, const llvm::Triple &Triple)
Definition: Tools.cpp:2928
static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Tools.cpp:3238
static void handleTargetFeaturesGroup(const ArgList &Args, std::vector< const char * > &Features, OptSpecifier Group)
Definition: Tools.cpp:55
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition: Tools.cpp:2557
bool isNaN2008(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
static bool isNoCommonDefault(const llvm::Triple &Triple)
Definition: Tools.cpp:540
Action - Represent an abstract compilation step to perform.
Definition: Action.h:41
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9928
static bool isObjCRuntimeLinked(const ArgList &Args)
Determine whether we are linking the ObjC runtime.
Definition: Tools.cpp:276
static bool isARMMProfile(const llvm::Triple &Triple)
Definition: Tools.cpp:561
static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, const JobAction &JA, const ArgList &Args, const InputInfo &Output, const char *OutFile)
Definition: Tools.cpp:2968
std::string getAsString() const
Retrieve a string representation of the version number.
static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Tools.cpp:3407
static bool DecodeAArch64Features(const Driver &D, StringRef text, std::vector< const char * > &Features)
Definition: Tools.cpp:2083
uint32_t Offset
Definition: CacheTokens.cpp:44
const char * getInstalledDir() const
Get the path to where the clang executable was installed.
Definition: Driver.h:252
static void getSystemZTargetFeatures(const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:1586
static std::string FindVisualStudioExecutable(const ToolChain &TC, const char *Exe, const char *ClangProgramPath)
Definition: Tools.cpp:9381
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:23
const llvm::opt::DerivedArgList & getArgs() const
Definition: Compilation.h:106
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition: ToolChain.cpp:604
static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple, const ArgList &Args, ArgStringList &CmdArgs, bool ForAS)
Definition: Tools.cpp:2280
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
std::string getTripleString() const
Definition: ToolChain.h:140
path_list & getFilePaths()
Definition: ToolChain.h:144
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition: Driver.h:157
static const char * getSparcAsmModeForCPU(StringRef Name, const llvm::Triple &Triple)
Definition: Tools.cpp:73
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, CodeGenOptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition: Tools.cpp:2522
static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, StringRef Sanitizer, bool IsShared)
Definition: Tools.cpp:2750
static std::string getCPUName(const ArgList &Args, const llvm::Triple &T, bool FromAs=false)
Definition: Tools.cpp:1707
FloatABI getPPCFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:65
const Driver & getDriver() const
Definition: ToolChain.h:127
const ToolChain & getToolChain() const
Definition: Tool.h:84
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:10310
bool hasMipsAbiArg(const llvm::opt::ArgList &Args, const char *Value)
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
MinGW Tools.
Definition: Tools.cpp:9672
const char * GetNaClArmMacrosPath() const
Definition: ToolChains.h:930
const ToolChain * getCudaHostToolChain() const
Definition: Compilation.h:92
detail::InMemoryDirectory::const_iterator I
static void claimNoWarnArgs(const ArgList &Args)
Definition: Tools.cpp:3055
StringRef getArchName() const
Definition: ToolChain.h:132
bool isSaveTempsEnabled() const
Definition: Driver.h:261
static StringRef getGnuCompatibleMipsABIName(StringRef ABI)
Definition: Tools.cpp:1182
static bool getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune, const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:2172
AnnotatingParser & P
static StringRef getWebAssemblyTargetCPU(const ArgList &Args)
Get the (LLVM) name of the WebAssembly cpu we are targeting.
Definition: Tools.cpp:1689
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9956
static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Tools.cpp:2840
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, bool Shared=false) const
Definition: ToolChain.cpp:286
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7689
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
static void addClangRT(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Tools.cpp:2674
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition: Tools.cpp:5706
static std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple, const ArgList &Args)
Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.
Definition: Tools.cpp:3260
static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC, const ArgList &Args)
Compute the desired OpenMP runtime from the flag provided.
Definition: Tools.cpp:2702
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:521
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
Definition: ObjCRuntime.h:133
static void getARMFPUFeatures(const Driver &D, const Arg *A, const ArgList &Args, StringRef FPU, std::vector< const char * > &Features)
Definition: Tools.cpp:598
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:39
Defines the clang::LangOptions interface.
static const char * SplitDebugName(const ArgList &Args, const InputInfo &Input)
Definition: Tools.cpp:2951
static bool shouldUseFramePointerForTarget(const ArgList &Args, const llvm::Triple &Triple)
Definition: Tools.cpp:2870
StringRef getName() const
Return the actual identifier string.
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition: ObjCRuntime.h:32
virtual bool isPICDefault() const =0
Test whether this toolchain defaults to PIC.
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9995
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:8164
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
XCore Tools.
Definition: Tools.cpp:9895
bool isForDiagnostics() const
Return true if we're compiling for diagnostics.
Definition: Compilation.h:210
static bool areOptimizationsEnabled(const ArgList &Args)
Definition: Tools.cpp:2862
VersionTuple getMSVCVersion(const Driver *D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, bool IsWindowsMSVC)
Definition: Tools.cpp:3095
std::unique_ptr< Command > GetCommand(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const
Definition: Tools.cpp:9569
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:6090
Defines version macros and version-related utility functions for Clang.
static const StringRef GetTargetCPUVersion(const llvm::opt::ArgList &Args)
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7476
static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args)
/EH controls whether to run destructor cleanups when exceptions are thrown.
Definition: Tools.cpp:5729
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
Definition: ObjCRuntime.cpp:44
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const override
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode...
Definition: Tools.cpp:6213
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9006
static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args, llvm::StringRef ArchName, std::vector< const char * > &Features, const llvm::Triple &Triple)
Definition: Tools.cpp:625
void addCommand(std::unique_ptr< Command > C)
Definition: Compilation.h:125
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9561
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition: Tools.cpp:6803
static int getARMSubArchVersionNumber(const llvm::Triple &Triple)
Definition: Tools.cpp:555
static unsigned DwarfVersionNum(StringRef ArgValue)
Definition: Tools.cpp:2513
'gnustep' is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:53
llvm::Triple::ArchType getArchTypeForMachOArchName(StringRef Str)
Definition: Tools.cpp:6741
do v
Definition: arm_acle.h:77
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:6817
const char * getFilename() const
Definition: InputInfo.h:84
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:10202
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:80
#define false
Definition: stdbool.h:33
static bool forwardToGCC(const Option &O)
Definition: Tools.cpp:284
const std::string getARMArch(StringRef Arch, const llvm::Triple &Triple)
Definition: Tools.cpp:6566
const llvm::opt::Arg * getRTTIArg() const
Definition: ToolChain.h:155
const ToolChain * getCudaDeviceToolChain() const
Definition: Compilation.h:93
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const override
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode...
Definition: Tools.cpp:6218
const TemplateArgument * iterator
Definition: Type.h:4070
static LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition: CharInfo.h:118
static void getWebAssemblyTargetFeatures(const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:2275
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
bool isTargetIOSBased() const
Is the target either iOS or an iOS simulator?
Definition: ToolChains.h:280
Base class for all GNU tools that provide the same behavior when it comes to response files support...
Definition: Tools.h:139
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: ToolChain.cpp:590
bool isCuda(ID Id)
isCuda - Is this a CUDA input.
Definition: Types.cpp:144
bool hasPPCAbiArg(const llvm::opt::ArgList &Args, const char *Value)
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition: Tools.cpp:511
std::string InstalledDir
The path to the installed clang directory, if any.
Definition: Driver.h:107
bool isUCLibc(const llvm::opt::ArgList &Args)
static std::string getLinuxDynamicLinker(const ArgList &Args, const toolchains::Linux &ToolChain)
Definition: Tools.cpp:8626
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7547
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const
Definition: Tools.cpp:6252
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:4095
unsigned getMajor() const
Retrieve the major version number.
Definition: VersionTuple.h:69
bool isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName, StringRef ABIName, mips::FloatABI FloatABI)
Definition: Tools.cpp:6706
LTOKind getLTOMode() const
Get the specific kind of LTO being performed.
Definition: Driver.h:424
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:497
bool isLegacyDispatchDefaultForArch(llvm::Triple::ArchType Arch)
The default dispatch mechanism to use for the specified architecture.
Definition: ObjCRuntime.h:98
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
static const char * getX86TargetCPU(const ArgList &Args, const llvm::Triple &Triple)
Definition: Tools.cpp:1604
static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
Definition: Tools.cpp:173
static bool getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March, const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:2137
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
DragonFly Tools.
Definition: Tools.cpp:9229
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7669
static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, StringRef Sanitizer)
Definition: Tools.cpp:2762
'#include ""' paths, added by 'gcc -iquote'.
const ToolChain & getDefaultToolChain() const
Definition: Compilation.h:91
static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple, const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:1236
bool isLinkJob() const override
Definition: Tools.cpp:6535
static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple, const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:1953
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:3419
static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU, std::vector< const char * > &Features)
Definition: Tools.cpp:2115
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition: Driver.h:154
RTTIMode getRTTIMode() const
Definition: ToolChain.h:158
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:10235
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7355
const char * CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition: Driver.h:141
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7335
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:6516
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:6879
bool tryParse(StringRef string)
Try to parse the given string as a version number.
bool empty() const
Determine whether this version information is empty (e.g., all version components are zero)...
Definition: VersionTuple.h:64
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:25
static bool getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu, const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:2187
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Tools.cpp:5903
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, bool Shared=false) const
Definition: ToolChain.cpp:306
bool hasIntegratedCPP() const override
Definition: Tools.cpp:6539
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:6543
std::string SysRoot
sysroot, if present
Definition: Driver.h:120
Tool - Information on a specific compilation tool.
Definition: Tool.h:34
void setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str)
Definition: Tools.cpp:6776
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:10146
static bool ContainsCompileAction(const Action *A)
Check whether the given input tree contains any compilation actions.
Definition: Tools.cpp:2463
static bool getRefinementStep(StringRef In, const Driver &D, const Arg &A, size_t &Position)
This is a helper function for validating the optional refinement step parameter in reciprocal argumen...
Definition: Tools.cpp:1826
static bool isObjCAutoRefCount(const ArgList &Args)
Determine whether Objective-C automated reference counting is enabled.
Definition: Tools.cpp:271
static void getARMHWDivFeatures(const Driver &D, const Arg *A, const ArgList &Args, StringRef HWDiv, std::vector< const char * > &Features)
Definition: Tools.cpp:589
detail::InMemoryDirectory::const_iterator E
virtual void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: ToolChains.h:272
static void ConstructGoldLinkJob(const Tool &T, Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput)
Definition: Tools.cpp:10402
ActionList & getActions()
Definition: Compilation.h:110
const char * getClangProgramPath() const
Get the path to the main clang executable.
Definition: Driver.h:247
unsigned Map[Count]
The type of a lookup table which maps from language-specific address spaces to target-specific ones...
Definition: AddressSpaces.h:45
static CodeGenOptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A)
Definition: Tools.cpp:2498
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
CheckPreprocessingOptions - Perform some validation of preprocessing arguments that is shared with gc...
Definition: Tools.cpp:105
static bool shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, const llvm::Triple &Triple)
Definition: Tools.cpp:2350
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const override
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode...
Definition: Tools.cpp:6246
virtual bool isPIEDefault() const =0
Test whether this toolchain defaults to PIE.
static void AddTargetFeature(const ArgList &Args, std::vector< const char * > &Features, OptSpecifier OnOpt, OptSpecifier OffOpt, StringRef FeatureName)
Definition: Tools.cpp:1224
bool isCXX(ID Id)
isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
Definition: Types.cpp:117
static bool DecodeARMFeatures(const Driver &D, StringRef text, std::vector< const char * > &Features)
Definition: Tools.cpp:607
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9174
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:34
static std::string getAArch64TargetCPU(const ArgList &Args)
getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are targeting.
Definition: Tools.cpp:1025
static void getHexagonTargetFeatures(const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:2249
static const char * getLDMOption(const llvm::Triple &T, const ArgList &Args)
Definition: Tools.cpp:8714
static Optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
static void getARMTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple, const ArgList &Args, std::vector< const char * > &Features, bool ForAS)
Definition: Tools.cpp:753
OpenMPRuntimeKind
Definition: Tools.cpp:2680
const char * CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition: Driver.h:144
StringRef getSysRoot() const
Returns the sysroot path.
bool isUsingLTO() const
Returns true if we are performing any kind of LTO.
Definition: Driver.h:421
const char * addFailureResultFile(const char *Name, const JobAction *JA)
addFailureResultFile - Add a file to remove if we crash, and returns its argument.
Definition: Compilation.h:161
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:6256
Kind getKind() const
Definition: ObjCRuntime.h:75
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7378
void AddMachOArch(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Tools.cpp:6949
static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs)
Definition: Tools.cpp:10333
static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args)
Definition: Tools.cpp:1191
bool isNothing() const
Definition: InputInfo.h:75
const char * getBaseInput() const
Definition: InputInfo.h:79
void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
Definition: ToolChain.cpp:619
static std::string getPPCTargetCPU(const ArgList &Args)
getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
Definition: Tools.cpp:1365
static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Tools.cpp:227
static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec)
Vectorize at all optimization levels greater than 1 except for -Oz.
Definition: Tools.cpp:2994
const StringRef Input
const char * addTempFile(const char *Name)
addTempFile - Add a file to remove on exit, and returns its argument.
Definition: Compilation.h:147
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:8374
static bool getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu, const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:2160
static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, const ArgList &Args)
Definition: Tools.cpp:2728
const std::string & getCCCGenericGCCName() const
Name to use when invoking gcc/g++.
Definition: Driver.h:231
Limit generated debug info to reduce size (-fno-standalone-debug).
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:5914
static void constructHexagonLinkArgs(Compilation &C, const JobAction &JA, const toolchains::HexagonToolChain &HTC, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, ArgStringList &CmdArgs, const char *LinkingOutput)
Definition: Tools.cpp:6330
std::string getAsString() const
Definition: ObjCRuntime.cpp:19
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition: Tools.cpp:3025
Linker(const ToolChain &TC)
Definition: Tools.cpp:6532
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition: Tools.cpp:6793
static bool useAAPCSForMachO(const llvm::Triple &T)
Definition: Tools.cpp:650
std::vector< std::string > ExtraOpts
Definition: ToolChains.h:804
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition: Types.cpp:131
std::string getMipsABILibSuffix(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args, ArgStringList &CmdArgs, bool IsThinLTO)
Definition: Tools.cpp:1787
std::string GetLinkerPath() const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name...
Definition: ToolChain.cpp:342
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition: Driver.h:176
const SanitizerArgs & getSanitizerArgs() const
Definition: ToolChain.cpp:88
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition: Types.cpp:104
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:6499
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7313
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:334
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:9397
static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple, const ArgList &Args, std::vector< const char * > &Features)
Definition: Tools.cpp:1428
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7798
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:47
std::string ResourceDir
The path to the compiler resource directory.
Definition: Driver.h:110
static void ParseMRecip(const Driver &D, const ArgList &Args, ArgStringList &OutStrings)
The -mrecip flag requires processing of many optional parameters.
Definition: Tools.cpp:1854
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Tools.cpp:7891