clang  9.0.0svn
Darwin.cpp
Go to the documentation of this file.
1 //===--- Darwin.cpp - Darwin Tool and ToolChain Implementations -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Darwin.h"
10 #include "Arch/ARM.h"
11 #include "CommonArgs.h"
14 #include "clang/Config/config.h"
16 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/Options.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/ScopedPrinter.h"
24 #include "llvm/Support/TargetParser.h"
25 #include "llvm/Support/VirtualFileSystem.h"
26 #include <cstdlib> // ::getenv
27 
28 using namespace clang::driver;
29 using namespace clang::driver::tools;
30 using namespace clang::driver::toolchains;
31 using namespace clang;
32 using namespace llvm::opt;
33 
34 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
35  // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
36  // archs which Darwin doesn't use.
37 
38  // The matching this routine does is fairly pointless, since it is neither the
39  // complete architecture list, nor a reasonable subset. The problem is that
40  // historically the driver driver accepts this and also ties its -march=
41  // handling to the architecture name, so we need to be careful before removing
42  // support for it.
43 
44  // This code must be kept in sync with Clang's Darwin specific argument
45  // translation.
46 
47  return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
48  .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
49  .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
50  .Case("ppc64", llvm::Triple::ppc64)
51  .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
52  .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
53  llvm::Triple::x86)
54  .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
55  // This is derived from the driver driver.
56  .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
57  .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
58  .Cases("armv7s", "xscale", llvm::Triple::arm)
59  .Case("arm64", llvm::Triple::aarch64)
60  .Case("r600", llvm::Triple::r600)
61  .Case("amdgcn", llvm::Triple::amdgcn)
62  .Case("nvptx", llvm::Triple::nvptx)
63  .Case("nvptx64", llvm::Triple::nvptx64)
64  .Case("amdil", llvm::Triple::amdil)
65  .Case("spir", llvm::Triple::spir)
66  .Default(llvm::Triple::UnknownArch);
67 }
68 
69 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
70  const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
71  llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
72  T.setArch(Arch);
73 
74  if (Str == "x86_64h")
75  T.setArchName(Str);
76  else if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
77  ArchKind == llvm::ARM::ArchKind::ARMV7M ||
78  ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
79  T.setOS(llvm::Triple::UnknownOS);
80  T.setObjectFormat(llvm::Triple::MachO);
81  }
82 }
83 
85  const InputInfo &Output,
86  const InputInfoList &Inputs,
87  const ArgList &Args,
88  const char *LinkingOutput) const {
89  ArgStringList CmdArgs;
90 
91  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
92  const InputInfo &Input = Inputs[0];
93 
94  // Determine the original source input.
95  const Action *SourceAction = &JA;
96  while (SourceAction->getKind() != Action::InputClass) {
97  assert(!SourceAction->getInputs().empty() && "unexpected root action!");
98  SourceAction = SourceAction->getInputs()[0];
99  }
100 
101  // If -fno-integrated-as is used add -Q to the darwin assembler driver to make
102  // sure it runs its system assembler not clang's integrated assembler.
103  // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
104  // FIXME: at run-time detect assembler capabilities or rely on version
105  // information forwarded by -target-assembler-version.
106  if (Args.hasArg(options::OPT_fno_integrated_as)) {
107  const llvm::Triple &T(getToolChain().getTriple());
108  if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
109  CmdArgs.push_back("-Q");
110  }
111 
112  // Forward -g, assuming we are dealing with an actual assembly file.
113  if (SourceAction->getType() == types::TY_Asm ||
114  SourceAction->getType() == types::TY_PP_Asm) {
115  if (Args.hasArg(options::OPT_gstabs))
116  CmdArgs.push_back("--gstabs");
117  else if (Args.hasArg(options::OPT_g_Group))
118  CmdArgs.push_back("-g");
119  }
120 
121  // Derived from asm spec.
122  AddMachOArch(Args, CmdArgs);
123 
124  // Use -force_cpusubtype_ALL on x86 by default.
125  if (getToolChain().getArch() == llvm::Triple::x86 ||
126  getToolChain().getArch() == llvm::Triple::x86_64 ||
127  Args.hasArg(options::OPT_force__cpusubtype__ALL))
128  CmdArgs.push_back("-force_cpusubtype_ALL");
129 
130  if (getToolChain().getArch() != llvm::Triple::x86_64 &&
131  (((Args.hasArg(options::OPT_mkernel) ||
132  Args.hasArg(options::OPT_fapple_kext)) &&
133  getMachOToolChain().isKernelStatic()) ||
134  Args.hasArg(options::OPT_static)))
135  CmdArgs.push_back("-static");
136 
137  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
138 
139  assert(Output.isFilename() && "Unexpected lipo output.");
140  CmdArgs.push_back("-o");
141  CmdArgs.push_back(Output.getFilename());
142 
143  assert(Input.isFilename() && "Invalid input.");
144  CmdArgs.push_back(Input.getFilename());
145 
146  // asm_final spec is empty.
147 
148  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
149  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
150 }
151 
152 void darwin::MachOTool::anchor() {}
153 
154 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
155  ArgStringList &CmdArgs) const {
156  StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
157 
158  // Derived from darwin_arch spec.
159  CmdArgs.push_back("-arch");
160  CmdArgs.push_back(Args.MakeArgString(ArchName));
161 
162  // FIXME: Is this needed anymore?
163  if (ArchName == "arm")
164  CmdArgs.push_back("-force_cpusubtype_ALL");
165 }
166 
167 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
168  // We only need to generate a temp path for LTO if we aren't compiling object
169  // files. When compiling source files, we run 'dsymutil' after linking. We
170  // don't run 'dsymutil' when compiling object files.
171  for (const auto &Input : Inputs)
172  if (Input.getType() != types::TY_Object)
173  return true;
174 
175  return false;
176 }
177 
178 /// Pass -no_deduplicate to ld64 under certain conditions:
179 ///
180 /// - Either -O0 or -O1 is explicitly specified
181 /// - No -O option is specified *and* this is a compile+link (implicit -O0)
182 ///
183 /// Also do *not* add -no_deduplicate when no -O option is specified and this
184 /// is just a link (we can't imply -O0)
185 static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
186  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
187  if (A->getOption().matches(options::OPT_O0))
188  return true;
189  if (A->getOption().matches(options::OPT_O))
190  return llvm::StringSwitch<bool>(A->getValue())
191  .Case("1", true)
192  .Default(false);
193  return false; // OPT_Ofast & OPT_O4
194  }
195 
196  if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
197  return true;
198  return false;
199 }
200 
201 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
202  ArgStringList &CmdArgs,
203  const InputInfoList &Inputs) const {
204  const Driver &D = getToolChain().getDriver();
205  const toolchains::MachO &MachOTC = getMachOToolChain();
206 
207  unsigned Version[5] = {0, 0, 0, 0, 0};
208  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
209  if (!Driver::GetReleaseVersion(A->getValue(), Version))
210  D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
211  }
212 
213  // Newer linkers support -demangle. Pass it if supported and not disabled by
214  // the user.
215  if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
216  CmdArgs.push_back("-demangle");
217 
218  if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
219  CmdArgs.push_back("-export_dynamic");
220 
221  // If we are using App Extension restrictions, pass a flag to the linker
222  // telling it that the compiled code has been audited.
223  if (Args.hasFlag(options::OPT_fapplication_extension,
224  options::OPT_fno_application_extension, false))
225  CmdArgs.push_back("-application_extension");
226 
227  if (D.isUsingLTO() && Version[0] >= 116 && NeedsTempPath(Inputs)) {
228  std::string TmpPathName;
229  if (D.getLTOMode() == LTOK_Full) {
230  // If we are using full LTO, then automatically create a temporary file
231  // path for the linker to use, so that it's lifetime will extend past a
232  // possible dsymutil step.
233  TmpPathName =
234  D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object));
235  } else if (D.getLTOMode() == LTOK_Thin)
236  // If we are using thin LTO, then create a directory instead.
237  TmpPathName = D.GetTemporaryDirectory("thinlto");
238 
239  if (!TmpPathName.empty()) {
240  auto *TmpPath = C.getArgs().MakeArgString(TmpPathName);
241  C.addTempFile(TmpPath);
242  CmdArgs.push_back("-object_path_lto");
243  CmdArgs.push_back(TmpPath);
244  }
245  }
246 
247  // Use -lto_library option to specify the libLTO.dylib path. Try to find
248  // it in clang installed libraries. ld64 will only look at this argument
249  // when it actually uses LTO, so libLTO.dylib only needs to exist at link
250  // time if ld64 decides that it needs to use LTO.
251  // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
252  // next to it. That's ok since ld64 using a libLTO.dylib not matching the
253  // clang version won't work anyways.
254  if (Version[0] >= 133) {
255  // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
256  StringRef P = llvm::sys::path::parent_path(D.Dir);
257  SmallString<128> LibLTOPath(P);
258  llvm::sys::path::append(LibLTOPath, "lib");
259  llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
260  CmdArgs.push_back("-lto_library");
261  CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
262  }
263 
264  // ld64 version 262 and above run the deduplicate pass by default.
265  if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args))
266  CmdArgs.push_back("-no_deduplicate");
267 
268  // Derived from the "link" spec.
269  Args.AddAllArgs(CmdArgs, options::OPT_static);
270  if (!Args.hasArg(options::OPT_static))
271  CmdArgs.push_back("-dynamic");
272  if (Args.hasArg(options::OPT_fgnu_runtime)) {
273  // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
274  // here. How do we wish to handle such things?
275  }
276 
277  if (!Args.hasArg(options::OPT_dynamiclib)) {
278  AddMachOArch(Args, CmdArgs);
279  // FIXME: Why do this only on this path?
280  Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
281 
282  Args.AddLastArg(CmdArgs, options::OPT_bundle);
283  Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
284  Args.AddAllArgs(CmdArgs, options::OPT_client__name);
285 
286  Arg *A;
287  if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
288  (A = Args.getLastArg(options::OPT_current__version)) ||
289  (A = Args.getLastArg(options::OPT_install__name)))
290  D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
291  << "-dynamiclib";
292 
293  Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
294  Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
295  Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
296  } else {
297  CmdArgs.push_back("-dylib");
298 
299  Arg *A;
300  if ((A = Args.getLastArg(options::OPT_bundle)) ||
301  (A = Args.getLastArg(options::OPT_bundle__loader)) ||
302  (A = Args.getLastArg(options::OPT_client__name)) ||
303  (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
304  (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
305  (A = Args.getLastArg(options::OPT_private__bundle)))
306  D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
307  << "-dynamiclib";
308 
309  Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
310  "-dylib_compatibility_version");
311  Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
312  "-dylib_current_version");
313 
314  AddMachOArch(Args, CmdArgs);
315 
316  Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
317  "-dylib_install_name");
318  }
319 
320  Args.AddLastArg(CmdArgs, options::OPT_all__load);
321  Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
322  Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
323  if (MachOTC.isTargetIOSBased())
324  Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
325  Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
326  Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
327  Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
328  Args.AddLastArg(CmdArgs, options::OPT_dynamic);
329  Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
330  Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
331  Args.AddAllArgs(CmdArgs, options::OPT_force__load);
332  Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
333  Args.AddAllArgs(CmdArgs, options::OPT_image__base);
334  Args.AddAllArgs(CmdArgs, options::OPT_init);
335 
336  // Add the deployment target.
337  MachOTC.addMinVersionArgs(Args, CmdArgs);
338 
339  Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
340  Args.AddLastArg(CmdArgs, options::OPT_multi__module);
341  Args.AddLastArg(CmdArgs, options::OPT_single__module);
342  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
343  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
344 
345  if (const Arg *A =
346  Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
347  options::OPT_fno_pie, options::OPT_fno_PIE)) {
348  if (A->getOption().matches(options::OPT_fpie) ||
349  A->getOption().matches(options::OPT_fPIE))
350  CmdArgs.push_back("-pie");
351  else
352  CmdArgs.push_back("-no_pie");
353  }
354 
355  // for embed-bitcode, use -bitcode_bundle in linker command
356  if (C.getDriver().embedBitcodeEnabled()) {
357  // Check if the toolchain supports bitcode build flow.
358  if (MachOTC.SupportsEmbeddedBitcode()) {
359  CmdArgs.push_back("-bitcode_bundle");
360  if (C.getDriver().embedBitcodeMarkerOnly() && Version[0] >= 278) {
361  CmdArgs.push_back("-bitcode_process_mode");
362  CmdArgs.push_back("marker");
363  }
364  } else
365  D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
366  }
367 
368  Args.AddLastArg(CmdArgs, options::OPT_prebind);
369  Args.AddLastArg(CmdArgs, options::OPT_noprebind);
370  Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
371  Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
372  Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
373  Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
374  Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
375  Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
376  Args.AddAllArgs(CmdArgs, options::OPT_segprot);
377  Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
378  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
379  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
380  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
381  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
382  Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
383  Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
384 
385  // Give --sysroot= preference, over the Apple specific behavior to also use
386  // --isysroot as the syslibroot.
387  StringRef sysroot = C.getSysRoot();
388  if (sysroot != "") {
389  CmdArgs.push_back("-syslibroot");
390  CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
391  } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
392  CmdArgs.push_back("-syslibroot");
393  CmdArgs.push_back(A->getValue());
394  }
395 
396  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
397  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
398  Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
399  Args.AddAllArgs(CmdArgs, options::OPT_undefined);
400  Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
401  Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
402  Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
403  Args.AddAllArgs(CmdArgs, options::OPT_y);
404  Args.AddLastArg(CmdArgs, options::OPT_w);
405  Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
406  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
407  Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
408  Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
409  Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
410  Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
411  Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
412  Args.AddLastArg(CmdArgs, options::OPT_whyload);
413  Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
414  Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
415  Args.AddLastArg(CmdArgs, options::OPT_dylinker);
416  Args.AddLastArg(CmdArgs, options::OPT_Mach);
417 }
418 
419 /// Determine whether we are linking the ObjC runtime.
420 static bool isObjCRuntimeLinked(const ArgList &Args) {
421  if (isObjCAutoRefCount(Args)) {
422  Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
423  return true;
424  }
425  return Args.hasArg(options::OPT_fobjc_link_runtime);
426 }
427 
429  const InputInfo &Output,
430  const InputInfoList &Inputs,
431  const ArgList &Args,
432  const char *LinkingOutput) const {
433  assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
434 
435  // If the number of arguments surpasses the system limits, we will encode the
436  // input files in a separate file, shortening the command line. To this end,
437  // build a list of input file names that can be passed via a file with the
438  // -filelist linker option.
439  llvm::opt::ArgStringList InputFileList;
440 
441  // The logic here is derived from gcc's behavior; most of which
442  // comes from specs (starting with link_command). Consult gcc for
443  // more information.
444  ArgStringList CmdArgs;
445 
446  /// Hack(tm) to ignore linking errors when we are doing ARC migration.
447  if (Args.hasArg(options::OPT_ccc_arcmt_check,
448  options::OPT_ccc_arcmt_migrate)) {
449  for (const auto &Arg : Args)
450  Arg->claim();
451  const char *Exec =
452  Args.MakeArgString(getToolChain().GetProgramPath("touch"));
453  CmdArgs.push_back(Output.getFilename());
454  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
455  return;
456  }
457 
458  // I'm not sure why this particular decomposition exists in gcc, but
459  // we follow suite for ease of comparison.
460  AddLinkArgs(C, Args, CmdArgs, Inputs);
461 
462  // For LTO, pass the name of the optimization record file and other
463  // opt-remarks flags.
464  if (Args.hasFlag(options::OPT_fsave_optimization_record,
465  options::OPT_fno_save_optimization_record, false)) {
466  CmdArgs.push_back("-mllvm");
467  CmdArgs.push_back("-lto-pass-remarks-output");
468  CmdArgs.push_back("-mllvm");
469 
471  F = Output.getFilename();
472  F += ".opt.yaml";
473  CmdArgs.push_back(Args.MakeArgString(F));
474 
475  if (getLastProfileUseArg(Args)) {
476  CmdArgs.push_back("-mllvm");
477  CmdArgs.push_back("-lto-pass-remarks-with-hotness");
478 
479  if (const Arg *A =
480  Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
481  CmdArgs.push_back("-mllvm");
482  std::string Opt =
483  std::string("-lto-pass-remarks-hotness-threshold=") + A->getValue();
484  CmdArgs.push_back(Args.MakeArgString(Opt));
485  }
486  }
487 
488  if (const Arg *A =
489  Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
490  CmdArgs.push_back("-mllvm");
491  std::string Passes =
492  std::string("-lto-pass-remarks-filter=") + A->getValue();
493  CmdArgs.push_back(Args.MakeArgString(Passes));
494  }
495  }
496 
497  // Propagate the -moutline flag to the linker in LTO.
498  if (Arg *A =
499  Args.getLastArg(options::OPT_moutline, options::OPT_mno_outline)) {
500  if (A->getOption().matches(options::OPT_moutline)) {
501  if (getMachOToolChain().getMachOArchName(Args) == "arm64") {
502  CmdArgs.push_back("-mllvm");
503  CmdArgs.push_back("-enable-machine-outliner");
504 
505  // Outline from linkonceodr functions by default in LTO.
506  CmdArgs.push_back("-mllvm");
507  CmdArgs.push_back("-enable-linkonceodr-outlining");
508  }
509  } else {
510  // Disable all outlining behaviour if we have mno-outline. We need to do
511  // this explicitly, because targets which support default outlining will
512  // try to do work if we don't.
513  CmdArgs.push_back("-mllvm");
514  CmdArgs.push_back("-enable-machine-outliner=never");
515  }
516  }
517 
518  // Setup statistics file output.
519  SmallString<128> StatsFile =
520  getStatsFileName(Args, Output, Inputs[0], getToolChain().getDriver());
521  if (!StatsFile.empty()) {
522  CmdArgs.push_back("-mllvm");
523  CmdArgs.push_back(Args.MakeArgString("-lto-stats-file=" + StatsFile.str()));
524  }
525 
526  // It seems that the 'e' option is completely ignored for dynamic executables
527  // (the default), and with static executables, the last one wins, as expected.
528  Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
529  options::OPT_Z_Flag, options::OPT_u_Group,
530  options::OPT_e, options::OPT_r});
531 
532  // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
533  // members of static archive libraries which implement Objective-C classes or
534  // categories.
535  if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
536  CmdArgs.push_back("-ObjC");
537 
538  CmdArgs.push_back("-o");
539  CmdArgs.push_back(Output.getFilename());
540 
541  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
542  getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
543 
544  Args.AddAllArgs(CmdArgs, options::OPT_L);
545 
546  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
547  // Build the input file for -filelist (list of linker input files) in case we
548  // need it later
549  for (const auto &II : Inputs) {
550  if (!II.isFilename()) {
551  // This is a linker input argument.
552  // We cannot mix input arguments and file names in a -filelist input, thus
553  // we prematurely stop our list (remaining files shall be passed as
554  // arguments).
555  if (InputFileList.size() > 0)
556  break;
557 
558  continue;
559  }
560 
561  InputFileList.push_back(II.getFilename());
562  }
563 
564  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
565  addOpenMPRuntime(CmdArgs, getToolChain(), Args);
566 
567  if (isObjCRuntimeLinked(Args) &&
568  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
569  // We use arclite library for both ARC and subscripting support.
570  getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
571 
572  CmdArgs.push_back("-framework");
573  CmdArgs.push_back("Foundation");
574  // Link libobj.
575  CmdArgs.push_back("-lobjc");
576  }
577 
578  if (LinkingOutput) {
579  CmdArgs.push_back("-arch_multiple");
580  CmdArgs.push_back("-final_output");
581  CmdArgs.push_back(LinkingOutput);
582  }
583 
584  if (Args.hasArg(options::OPT_fnested_functions))
585  CmdArgs.push_back("-allow_stack_execute");
586 
587  getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
588 
589  if (unsigned Parallelism =
590  getLTOParallelism(Args, getToolChain().getDriver())) {
591  CmdArgs.push_back("-mllvm");
592  CmdArgs.push_back(Args.MakeArgString("-threads=" + Twine(Parallelism)));
593  }
594 
595  if (getToolChain().ShouldLinkCXXStdlib(Args))
596  getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
597 
598  bool NoStdOrDefaultLibs =
599  Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
600  bool ForceLinkBuiltins = Args.hasArg(options::OPT_fapple_link_rtlib);
601  if (!NoStdOrDefaultLibs || ForceLinkBuiltins) {
602  // link_ssp spec is empty.
603 
604  // If we have both -nostdlib/nodefaultlibs and -fapple-link-rtlib then
605  // we just want to link the builtins, not the other libs like libSystem.
606  if (NoStdOrDefaultLibs && ForceLinkBuiltins) {
607  getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs, "builtins");
608  } else {
609  // Let the tool chain choose which runtime library to link.
610  getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs,
611  ForceLinkBuiltins);
612 
613  // No need to do anything for pthreads. Claim argument to avoid warning.
614  Args.ClaimAllArgs(options::OPT_pthread);
615  Args.ClaimAllArgs(options::OPT_pthreads);
616  }
617  }
618 
619  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
620  // endfile_spec is empty.
621  }
622 
623  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
624  Args.AddAllArgs(CmdArgs, options::OPT_F);
625 
626  // -iframework should be forwarded as -F.
627  for (const Arg *A : Args.filtered(options::OPT_iframework))
628  CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
629 
630  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
631  if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
632  if (A->getValue() == StringRef("Accelerate")) {
633  CmdArgs.push_back("-framework");
634  CmdArgs.push_back("Accelerate");
635  }
636  }
637  }
638 
639  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
640  std::unique_ptr<Command> Cmd =
641  llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
642  Cmd->setInputFileList(std::move(InputFileList));
643  C.addCommand(std::move(Cmd));
644 }
645 
647  const InputInfo &Output,
648  const InputInfoList &Inputs,
649  const ArgList &Args,
650  const char *LinkingOutput) const {
651  ArgStringList CmdArgs;
652 
653  CmdArgs.push_back("-create");
654  assert(Output.isFilename() && "Unexpected lipo output.");
655 
656  CmdArgs.push_back("-output");
657  CmdArgs.push_back(Output.getFilename());
658 
659  for (const auto &II : Inputs) {
660  assert(II.isFilename() && "Unexpected lipo input.");
661  CmdArgs.push_back(II.getFilename());
662  }
663 
664  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
665  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
666 }
667 
669  const InputInfo &Output,
670  const InputInfoList &Inputs,
671  const ArgList &Args,
672  const char *LinkingOutput) const {
673  ArgStringList CmdArgs;
674 
675  CmdArgs.push_back("-o");
676  CmdArgs.push_back(Output.getFilename());
677 
678  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
679  const InputInfo &Input = Inputs[0];
680  assert(Input.isFilename() && "Unexpected dsymutil input.");
681  CmdArgs.push_back(Input.getFilename());
682 
683  const char *Exec =
684  Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
685  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
686 }
687 
689  const InputInfo &Output,
690  const InputInfoList &Inputs,
691  const ArgList &Args,
692  const char *LinkingOutput) const {
693  ArgStringList CmdArgs;
694  CmdArgs.push_back("--verify");
695  CmdArgs.push_back("--debug-info");
696  CmdArgs.push_back("--eh-frame");
697  CmdArgs.push_back("--quiet");
698 
699  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
700  const InputInfo &Input = Inputs[0];
701  assert(Input.isFilename() && "Unexpected verify input");
702 
703  // Grabbing the output of the earlier dsymutil run.
704  CmdArgs.push_back(Input.getFilename());
705 
706  const char *Exec =
707  Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
708  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
709 }
710 
711 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
712  : ToolChain(D, Triple, Args) {
713  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
714  getProgramPaths().push_back(getDriver().getInstalledDir());
715  if (getDriver().getInstalledDir() != getDriver().Dir)
716  getProgramPaths().push_back(getDriver().Dir);
717 }
718 
719 /// Darwin - Darwin tool chain for i386 and x86_64.
720 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
721  : MachO(D, Triple, Args), TargetInitialized(false),
722  CudaInstallation(D, Triple, Args) {}
723 
726 
727  // Darwin always preprocesses assembly files (unless -x is used explicitly).
728  if (Ty == types::TY_PP_Asm)
729  return types::TY_Asm;
730 
731  return Ty;
732 }
733 
734 bool MachO::HasNativeLLVMSupport() const { return true; }
735 
737  // Default to use libc++ on OS X 10.9+ and iOS 7+.
738  if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
739  (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
741  return ToolChain::CST_Libcxx;
742 
744 }
745 
746 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
747 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
748  if (isTargetWatchOSBased())
750  if (isTargetIOSBased())
752  if (isNonFragile)
755 }
756 
757 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
759  if (isTargetWatchOSBased())
760  return true;
761  else if (isTargetIOSBased())
762  return !isIPhoneOSVersionLT(3, 2);
763  else {
764  assert(isTargetMacOS() && "unexpected darwin target");
765  return !isMacosxVersionLT(10, 6);
766  }
767 }
768 
769 void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
770  ArgStringList &CC1Args) const {
771  CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
772 }
773 
774 // This is just a MachO name translation routine and there's no
775 // way to join this into ARMTargetParser without breaking all
776 // other assumptions. Maybe MachO should consider standardising
777 // their nomenclature.
778 static const char *ArmMachOArchName(StringRef Arch) {
779  return llvm::StringSwitch<const char *>(Arch)
780  .Case("armv6k", "armv6")
781  .Case("armv6m", "armv6m")
782  .Case("armv5tej", "armv5")
783  .Case("xscale", "xscale")
784  .Case("armv4t", "armv4t")
785  .Case("armv7", "armv7")
786  .Cases("armv7a", "armv7-a", "armv7")
787  .Cases("armv7r", "armv7-r", "armv7")
788  .Cases("armv7em", "armv7e-m", "armv7em")
789  .Cases("armv7k", "armv7-k", "armv7k")
790  .Cases("armv7m", "armv7-m", "armv7m")
791  .Cases("armv7s", "armv7-s", "armv7s")
792  .Default(nullptr);
793 }
794 
795 static const char *ArmMachOArchNameCPU(StringRef CPU) {
796  llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
797  if (ArchKind == llvm::ARM::ArchKind::INVALID)
798  return nullptr;
799  StringRef Arch = llvm::ARM::getArchName(ArchKind);
800 
801  // FIXME: Make sure this MachO triple mangling is really necessary.
802  // ARMv5* normalises to ARMv5.
803  if (Arch.startswith("armv5"))
804  Arch = Arch.substr(0, 5);
805  // ARMv6*, except ARMv6M, normalises to ARMv6.
806  else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
807  Arch = Arch.substr(0, 5);
808  // ARMv7A normalises to ARMv7.
809  else if (Arch.endswith("v7a"))
810  Arch = Arch.substr(0, 5);
811  return Arch.data();
812 }
813 
814 StringRef MachO::getMachOArchName(const ArgList &Args) const {
815  switch (getTriple().getArch()) {
816  default:
818 
819  case llvm::Triple::aarch64:
820  return "arm64";
821 
822  case llvm::Triple::thumb:
823  case llvm::Triple::arm:
824  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ))
825  if (const char *Arch = ArmMachOArchName(A->getValue()))
826  return Arch;
827 
828  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
829  if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
830  return Arch;
831 
832  return "arm";
833  }
834 }
835 
837 
839 
840 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
841  types::ID InputType) const {
842  llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
843 
844  // If the target isn't initialized (e.g., an unknown Darwin platform, return
845  // the default triple).
846  if (!isTargetInitialized())
847  return Triple.getTriple();
848 
849  SmallString<16> Str;
850  if (isTargetWatchOSBased())
851  Str += "watchos";
852  else if (isTargetTvOSBased())
853  Str += "tvos";
854  else if (isTargetIOSBased())
855  Str += "ios";
856  else
857  Str += "macosx";
858  Str += getTargetVersion().getAsString();
859  Triple.setOSName(Str);
860 
861  return Triple.getTriple();
862 }
863 
865  switch (AC) {
867  if (!Lipo)
868  Lipo.reset(new tools::darwin::Lipo(*this));
869  return Lipo.get();
871  if (!Dsymutil)
872  Dsymutil.reset(new tools::darwin::Dsymutil(*this));
873  return Dsymutil.get();
875  if (!VerifyDebug)
876  VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
877  return VerifyDebug.get();
878  default:
879  return ToolChain::getTool(AC);
880  }
881 }
882 
883 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
884 
886  return new tools::darwin::Assembler(*this);
887 }
888 
889 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
890  const ArgList &Args)
891  : Darwin(D, Triple, Args) {}
892 
893 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
894  // For modern targets, promote certain warnings to errors.
895  if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
896  // Always enable -Wdeprecated-objc-isa-usage and promote it
897  // to an error.
898  CC1Args.push_back("-Wdeprecated-objc-isa-usage");
899  CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
900 
901  // For iOS and watchOS, also error about implicit function declarations,
902  // as that can impact calling conventions.
903  if (!isTargetMacOS())
904  CC1Args.push_back("-Werror=implicit-function-declaration");
905  }
906 }
907 
908 /// Take a path that speculatively points into Xcode and return the
909 /// `XCODE/Contents/Developer` path if it is an Xcode path, or an empty path
910 /// otherwise.
911 static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode) {
912  static constexpr llvm::StringLiteral XcodeAppSuffix(
913  ".app/Contents/Developer");
914  size_t Index = PathIntoXcode.find(XcodeAppSuffix);
915  if (Index == StringRef::npos)
916  return "";
917  return PathIntoXcode.take_front(Index + XcodeAppSuffix.size());
918 }
919 
920 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
921  ArgStringList &CmdArgs) const {
922  // Avoid linking compatibility stubs on i386 mac.
923  if (isTargetMacOS() && getArch() == llvm::Triple::x86)
924  return;
925 
926  ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
927 
928  if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
929  runtime.hasSubscripting())
930  return;
931 
932  SmallString<128> P(getDriver().ClangExecutable);
933  llvm::sys::path::remove_filename(P); // 'clang'
934  llvm::sys::path::remove_filename(P); // 'bin'
935 
936  // 'libarclite' usually lives in the same toolchain as 'clang'. However, the
937  // Swift open source toolchains for macOS distribute Clang without libarclite.
938  // In that case, to allow the linker to find 'libarclite', we point to the
939  // 'libarclite' in the XcodeDefault toolchain instead.
940  if (getXcodeDeveloperPath(P).empty()) {
941  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
942  // Try to infer the path to 'libarclite' in the toolchain from the
943  // specified SDK path.
944  StringRef XcodePathForSDK = getXcodeDeveloperPath(A->getValue());
945  if (!XcodePathForSDK.empty()) {
946  P = XcodePathForSDK;
947  llvm::sys::path::append(P, "Toolchains/XcodeDefault.xctoolchain/usr");
948  }
949  }
950  }
951 
952  CmdArgs.push_back("-force_load");
953  llvm::sys::path::append(P, "lib", "arc", "libarclite_");
954  // Mash in the platform.
956  P += "watchsimulator";
957  else if (isTargetWatchOS())
958  P += "watchos";
959  else if (isTargetTvOSSimulator())
960  P += "appletvsimulator";
961  else if (isTargetTvOS())
962  P += "appletvos";
963  else if (isTargetIOSSimulator())
964  P += "iphonesimulator";
965  else if (isTargetIPhoneOS())
966  P += "iphoneos";
967  else
968  P += "macosx";
969  P += ".a";
970 
971  CmdArgs.push_back(Args.MakeArgString(P));
972 }
973 
975  // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
976  if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) ||
978  return 2;
979  return 4;
980 }
981 
982 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
983  StringRef Component, RuntimeLinkOptions Opts,
984  bool IsShared) const {
985  SmallString<64> DarwinLibName = StringRef("libclang_rt.");
986  // an Darwin the builtins compomnent is not in the library name
987  if (Component != "builtins") {
988  DarwinLibName += Component;
989  if (!(Opts & RLO_IsEmbedded))
990  DarwinLibName += "_";
991  DarwinLibName += getOSLibraryNameSuffix();
992  } else
993  DarwinLibName += getOSLibraryNameSuffix(true);
994 
995  DarwinLibName += IsShared ? "_dynamic.dylib" : ".a";
996  SmallString<128> Dir(getDriver().ResourceDir);
997  llvm::sys::path::append(
998  Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin");
999 
1000  SmallString<128> P(Dir);
1001  llvm::sys::path::append(P, DarwinLibName);
1002 
1003  // For now, allow missing resource libraries to support developers who may
1004  // not have compiler-rt checked out or integrated into their build (unless
1005  // we explicitly force linking with this library).
1006  if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) {
1007  const char *LibArg = Args.MakeArgString(P);
1008  if (Opts & RLO_FirstLink)
1009  CmdArgs.insert(CmdArgs.begin(), LibArg);
1010  else
1011  CmdArgs.push_back(LibArg);
1012  }
1013 
1014  // Adding the rpaths might negatively interact when other rpaths are involved,
1015  // so we should make sure we add the rpaths last, after all user-specified
1016  // rpaths. This is currently true from this place, but we need to be
1017  // careful if this function is ever called before user's rpaths are emitted.
1018  if (Opts & RLO_AddRPath) {
1019  assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
1020 
1021  // Add @executable_path to rpath to support having the dylib copied with
1022  // the executable.
1023  CmdArgs.push_back("-rpath");
1024  CmdArgs.push_back("@executable_path");
1025 
1026  // Add the path to the resource dir to rpath to support using the dylib
1027  // from the default location without copying.
1028  CmdArgs.push_back("-rpath");
1029  CmdArgs.push_back(Args.MakeArgString(Dir));
1030  }
1031 }
1032 
1033 StringRef Darwin::getPlatformFamily() const {
1034  switch (TargetPlatform) {
1035  case DarwinPlatformKind::MacOS:
1036  return "MacOSX";
1037  case DarwinPlatformKind::IPhoneOS:
1038  return "iPhone";
1039  case DarwinPlatformKind::TvOS:
1040  return "AppleTV";
1041  case DarwinPlatformKind::WatchOS:
1042  return "Watch";
1043  }
1044  llvm_unreachable("Unsupported platform");
1045 }
1046 
1047 StringRef Darwin::getSDKName(StringRef isysroot) {
1048  // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
1049  llvm::sys::path::const_iterator SDKDir;
1050  auto BeginSDK = llvm::sys::path::begin(isysroot);
1051  auto EndSDK = llvm::sys::path::end(isysroot);
1052  for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
1053  StringRef SDK = *IT;
1054  if (SDK.endswith(".sdk"))
1055  return SDK.slice(0, SDK.size() - 4);
1056  }
1057  return "";
1058 }
1059 
1060 StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
1061  switch (TargetPlatform) {
1062  case DarwinPlatformKind::MacOS:
1063  return "osx";
1064  case DarwinPlatformKind::IPhoneOS:
1065  return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
1066  : "iossim";
1067  case DarwinPlatformKind::TvOS:
1068  return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
1069  : "tvossim";
1070  case DarwinPlatformKind::WatchOS:
1071  return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
1072  : "watchossim";
1073  }
1074  llvm_unreachable("Unsupported platform");
1075 }
1076 
1077 /// Check if the link command contains a symbol export directive.
1078 static bool hasExportSymbolDirective(const ArgList &Args) {
1079  for (Arg *A : Args) {
1080  if (A->getOption().matches(options::OPT_exported__symbols__list))
1081  return true;
1082  if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
1083  !A->getOption().matches(options::OPT_Xlinker))
1084  continue;
1085  if (A->containsValue("-exported_symbols_list") ||
1086  A->containsValue("-exported_symbol"))
1087  return true;
1088  }
1089  return false;
1090 }
1091 
1092 /// Add an export directive for \p Symbol to the link command.
1093 static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
1094  CmdArgs.push_back("-exported_symbol");
1095  CmdArgs.push_back(Symbol);
1096 }
1097 
1098 void Darwin::addProfileRTLibs(const ArgList &Args,
1099  ArgStringList &CmdArgs) const {
1100  if (!needsProfileRT(Args)) return;
1101 
1102  AddLinkRuntimeLib(Args, CmdArgs, "profile",
1104 
1105  // If we have a symbol export directive and we're linking in the profile
1106  // runtime, automatically export symbols necessary to implement some of the
1107  // runtime's functionality.
1108  if (hasExportSymbolDirective(Args)) {
1109  if (needsGCovInstrumentation(Args)) {
1110  addExportedSymbol(CmdArgs, "___gcov_flush");
1111  addExportedSymbol(CmdArgs, "_flush_fn_list");
1112  addExportedSymbol(CmdArgs, "_writeout_fn_list");
1113  } else {
1114  addExportedSymbol(CmdArgs, "___llvm_profile_filename");
1115  addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
1116  addExportedSymbol(CmdArgs, "_lprofCurFilename");
1117  }
1118  addExportedSymbol(CmdArgs, "_lprofDirMode");
1119  }
1120 }
1121 
1122 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1123  ArgStringList &CmdArgs,
1124  StringRef Sanitizer,
1125  bool Shared) const {
1126  auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1127  AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
1128 }
1129 
1131  const ArgList &Args) const {
1132  if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1133  StringRef Value = A->getValue();
1134  if (Value != "compiler-rt")
1135  getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1136  << Value << "darwin";
1137  }
1138 
1140 }
1141 
1142 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1143  ArgStringList &CmdArgs,
1144  bool ForceLinkBuiltinRT) const {
1145  // Call once to ensure diagnostic is printed if wrong value was specified
1146  GetRuntimeLibType(Args);
1147 
1148  // Darwin doesn't support real static executables, don't link any runtime
1149  // libraries with -static.
1150  if (Args.hasArg(options::OPT_static) ||
1151  Args.hasArg(options::OPT_fapple_kext) ||
1152  Args.hasArg(options::OPT_mkernel)) {
1153  if (ForceLinkBuiltinRT)
1154  AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1155  return;
1156  }
1157 
1158  // Reject -static-libgcc for now, we can deal with this when and if someone
1159  // cares. This is useful in situations where someone wants to statically link
1160  // something like libstdc++, and needs its runtime support routines.
1161  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1162  getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1163  return;
1164  }
1165 
1166  const SanitizerArgs &Sanitize = getSanitizerArgs();
1167  if (Sanitize.needsAsanRt())
1168  AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1169  if (Sanitize.needsLsanRt())
1170  AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
1171  if (Sanitize.needsUbsanRt())
1172  AddLinkSanitizerLibArgs(Args, CmdArgs,
1173  Sanitize.requiresMinimalRuntime() ? "ubsan_minimal"
1174  : "ubsan",
1175  Sanitize.needsSharedRt());
1176  if (Sanitize.needsTsanRt())
1177  AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1178  if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
1179  AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
1180 
1181  // Libfuzzer is written in C++ and requires libcxx.
1182  AddCXXStdlibLibArgs(Args, CmdArgs);
1183  }
1184  if (Sanitize.needsStatsRt()) {
1185  AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
1186  AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1187  }
1188 
1189  const XRayArgs &XRay = getXRayArgs();
1190  if (XRay.needsXRayRt()) {
1191  AddLinkRuntimeLib(Args, CmdArgs, "xray");
1192  AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
1193  AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
1194  }
1195 
1196  // Otherwise link libSystem, then the dynamic runtime library, and finally any
1197  // target specific static runtime library.
1198  CmdArgs.push_back("-lSystem");
1199 
1200  // Select the dynamic runtime library and the target specific static library.
1201  if (isTargetIOSBased()) {
1202  // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
1203  // it never went into the SDK.
1204  // Linking against libgcc_s.1 isn't needed for iOS 5.0+
1205  if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
1206  getTriple().getArch() != llvm::Triple::aarch64)
1207  CmdArgs.push_back("-lgcc_s.1");
1208  }
1209  AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1210 }
1211 
1212 /// Returns the most appropriate macOS target version for the current process.
1213 ///
1214 /// If the macOS SDK version is the same or earlier than the system version,
1215 /// then the SDK version is returned. Otherwise the system version is returned.
1216 static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1217  unsigned Major, Minor, Micro;
1218  llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1219  if (!SystemTriple.isMacOSX())
1220  return MacOSSDKVersion;
1221  SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1222  VersionTuple SystemVersion(Major, Minor, Micro);
1223  bool HadExtra;
1224  if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
1225  HadExtra))
1226  return MacOSSDKVersion;
1227  VersionTuple SDKVersion(Major, Minor, Micro);
1228  if (SDKVersion > SystemVersion)
1229  return SystemVersion.getAsString();
1230  return MacOSSDKVersion;
1231 }
1232 
1233 namespace {
1234 
1235 /// The Darwin OS that was selected or inferred from arguments / environment.
1236 struct DarwinPlatform {
1237  enum SourceKind {
1238  /// The OS was specified using the -target argument.
1239  TargetArg,
1240  /// The OS was specified using the -m<os>-version-min argument.
1241  OSVersionArg,
1242  /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1243  DeploymentTargetEnv,
1244  /// The OS was inferred from the SDK.
1245  InferredFromSDK,
1246  /// The OS was inferred from the -arch.
1247  InferredFromArch
1248  };
1249 
1252 
1253  DarwinPlatformKind getPlatform() const { return Platform; }
1254 
1255  DarwinEnvironmentKind getEnvironment() const { return Environment; }
1256 
1257  void setEnvironment(DarwinEnvironmentKind Kind) {
1258  Environment = Kind;
1259  InferSimulatorFromArch = false;
1260  }
1261 
1262  StringRef getOSVersion() const {
1263  if (Kind == OSVersionArg)
1264  return Argument->getValue();
1265  return OSVersion;
1266  }
1267 
1268  void setOSVersion(StringRef S) {
1269  assert(Kind == TargetArg && "Unexpected kind!");
1270  OSVersion = S;
1271  }
1272 
1273  bool hasOSVersion() const { return HasOSVersion; }
1274 
1275  /// Returns true if the target OS was explicitly specified.
1276  bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1277 
1278  /// Returns true if the simulator environment can be inferred from the arch.
1279  bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1280 
1281  /// Adds the -m<os>-version-min argument to the compiler invocation.
1282  void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1283  if (Argument)
1284  return;
1285  assert(Kind != TargetArg && Kind != OSVersionArg && "Invalid kind");
1286  options::ID Opt;
1287  switch (Platform) {
1288  case DarwinPlatformKind::MacOS:
1289  Opt = options::OPT_mmacosx_version_min_EQ;
1290  break;
1291  case DarwinPlatformKind::IPhoneOS:
1292  Opt = options::OPT_miphoneos_version_min_EQ;
1293  break;
1294  case DarwinPlatformKind::TvOS:
1295  Opt = options::OPT_mtvos_version_min_EQ;
1296  break;
1297  case DarwinPlatformKind::WatchOS:
1298  Opt = options::OPT_mwatchos_version_min_EQ;
1299  break;
1300  }
1301  Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
1302  Args.append(Argument);
1303  }
1304 
1305  /// Returns the OS version with the argument / environment variable that
1306  /// specified it.
1307  std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1308  switch (Kind) {
1309  case TargetArg:
1310  case OSVersionArg:
1311  case InferredFromSDK:
1312  case InferredFromArch:
1313  assert(Argument && "OS version argument not yet inferred");
1314  return Argument->getAsString(Args);
1315  case DeploymentTargetEnv:
1316  return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
1317  }
1318  llvm_unreachable("Unsupported Darwin Source Kind");
1319  }
1320 
1321  static DarwinPlatform createFromTarget(const llvm::Triple &TT,
1322  StringRef OSVersion, Arg *A) {
1323  DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
1324  A);
1325  switch (TT.getEnvironment()) {
1326  case llvm::Triple::Simulator:
1327  Result.Environment = DarwinEnvironmentKind::Simulator;
1328  break;
1329  default:
1330  break;
1331  }
1332  unsigned Major, Minor, Micro;
1333  TT.getOSVersion(Major, Minor, Micro);
1334  if (Major == 0)
1335  Result.HasOSVersion = false;
1336  return Result;
1337  }
1338  static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform,
1339  Arg *A) {
1340  return DarwinPlatform(OSVersionArg, Platform, A);
1341  }
1342  static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
1343  StringRef EnvVarName,
1344  StringRef Value) {
1345  DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
1346  Result.EnvVarName = EnvVarName;
1347  return Result;
1348  }
1349  static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
1350  StringRef Value,
1351  bool IsSimulator = false) {
1352  DarwinPlatform Result(InferredFromSDK, Platform, Value);
1353  if (IsSimulator)
1354  Result.Environment = DarwinEnvironmentKind::Simulator;
1355  Result.InferSimulatorFromArch = false;
1356  return Result;
1357  }
1358  static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
1359  StringRef Value) {
1360  return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
1361  }
1362 
1363  /// Constructs an inferred SDKInfo value based on the version inferred from
1364  /// the SDK path itself. Only works for values that were created by inferring
1365  /// the platform from the SDKPath.
1366  DarwinSDKInfo inferSDKInfo() {
1367  assert(Kind == InferredFromSDK && "can infer SDK info only");
1368  llvm::VersionTuple Version;
1369  bool IsValid = !Version.tryParse(OSVersion);
1370  (void)IsValid;
1371  assert(IsValid && "invalid SDK version");
1372  return DarwinSDKInfo(Version);
1373  }
1374 
1375 private:
1376  DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
1377  : Kind(Kind), Platform(Platform), Argument(Argument) {}
1378  DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
1379  Arg *Argument = nullptr)
1380  : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
1381 
1382  static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
1383  switch (OS) {
1384  case llvm::Triple::Darwin:
1385  case llvm::Triple::MacOSX:
1386  return DarwinPlatformKind::MacOS;
1387  case llvm::Triple::IOS:
1388  return DarwinPlatformKind::IPhoneOS;
1389  case llvm::Triple::TvOS:
1390  return DarwinPlatformKind::TvOS;
1391  case llvm::Triple::WatchOS:
1392  return DarwinPlatformKind::WatchOS;
1393  default:
1394  llvm_unreachable("Unable to infer Darwin variant");
1395  }
1396  }
1397 
1398  SourceKind Kind;
1399  DarwinPlatformKind Platform;
1400  DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
1401  std::string OSVersion;
1402  bool HasOSVersion = true, InferSimulatorFromArch = true;
1403  Arg *Argument;
1404  StringRef EnvVarName;
1405 };
1406 
1407 /// Returns the deployment target that's specified using the -m<os>-version-min
1408 /// argument.
1410 getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
1411  const Driver &TheDriver) {
1412  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
1413  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
1414  options::OPT_mios_simulator_version_min_EQ);
1415  Arg *TvOSVersion =
1416  Args.getLastArg(options::OPT_mtvos_version_min_EQ,
1417  options::OPT_mtvos_simulator_version_min_EQ);
1418  Arg *WatchOSVersion =
1419  Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
1420  options::OPT_mwatchos_simulator_version_min_EQ);
1421  if (OSXVersion) {
1422  if (iOSVersion || TvOSVersion || WatchOSVersion) {
1423  TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1424  << OSXVersion->getAsString(Args)
1425  << (iOSVersion ? iOSVersion
1426  : TvOSVersion ? TvOSVersion : WatchOSVersion)
1427  ->getAsString(Args);
1428  }
1429  return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion);
1430  } else if (iOSVersion) {
1431  if (TvOSVersion || WatchOSVersion) {
1432  TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1433  << iOSVersion->getAsString(Args)
1434  << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1435  }
1436  return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion);
1437  } else if (TvOSVersion) {
1438  if (WatchOSVersion) {
1439  TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1440  << TvOSVersion->getAsString(Args)
1441  << WatchOSVersion->getAsString(Args);
1442  }
1443  return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion);
1444  } else if (WatchOSVersion)
1445  return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion);
1446  return None;
1447 }
1448 
1449 /// Returns the deployment target that's specified using the
1450 /// OS_DEPLOYMENT_TARGET environment variable.
1452 getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
1453  const llvm::Triple &Triple) {
1454  std::string Targets[Darwin::LastDarwinPlatform + 1];
1455  const char *EnvVars[] = {
1456  "MACOSX_DEPLOYMENT_TARGET",
1457  "IPHONEOS_DEPLOYMENT_TARGET",
1458  "TVOS_DEPLOYMENT_TARGET",
1459  "WATCHOS_DEPLOYMENT_TARGET",
1460  };
1461  static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1,
1462  "Missing platform");
1463  for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) {
1464  if (char *Env = ::getenv(I.value()))
1465  Targets[I.index()] = Env;
1466  }
1467 
1468  // Do not allow conflicts with the watchOS target.
1469  if (!Targets[Darwin::WatchOS].empty() &&
1470  (!Targets[Darwin::IPhoneOS].empty() || !Targets[Darwin::TvOS].empty())) {
1471  TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1472  << "WATCHOS_DEPLOYMENT_TARGET"
1473  << (!Targets[Darwin::IPhoneOS].empty() ? "IPHONEOS_DEPLOYMENT_TARGET"
1474  : "TVOS_DEPLOYMENT_TARGET");
1475  }
1476 
1477  // Do not allow conflicts with the tvOS target.
1478  if (!Targets[Darwin::TvOS].empty() && !Targets[Darwin::IPhoneOS].empty()) {
1479  TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1480  << "TVOS_DEPLOYMENT_TARGET"
1481  << "IPHONEOS_DEPLOYMENT_TARGET";
1482  }
1483 
1484  // Allow conflicts among OSX and iOS for historical reasons, but choose the
1485  // default platform.
1486  if (!Targets[Darwin::MacOS].empty() &&
1487  (!Targets[Darwin::IPhoneOS].empty() ||
1488  !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) {
1489  if (Triple.getArch() == llvm::Triple::arm ||
1490  Triple.getArch() == llvm::Triple::aarch64 ||
1491  Triple.getArch() == llvm::Triple::thumb)
1492  Targets[Darwin::MacOS] = "";
1493  else
1494  Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
1495  Targets[Darwin::TvOS] = "";
1496  }
1497 
1498  for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) {
1499  if (!Target.value().empty())
1500  return DarwinPlatform::createDeploymentTargetEnv(
1501  (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
1502  Target.value());
1503  }
1504  return None;
1505 }
1506 
1507 /// Tries to infer the deployment target from the SDK specified by -isysroot
1508 /// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
1509 /// it's available.
1511 inferDeploymentTargetFromSDK(DerivedArgList &Args,
1513  const Arg *A = Args.getLastArg(options::OPT_isysroot);
1514  if (!A)
1515  return None;
1516  StringRef isysroot = A->getValue();
1517  StringRef SDK = Darwin::getSDKName(isysroot);
1518  if (!SDK.size())
1519  return None;
1520 
1521  std::string Version;
1522  if (SDKInfo) {
1523  // Get the version from the SDKSettings.json if it's available.
1524  Version = SDKInfo->getVersion().getAsString();
1525  } else {
1526  // Slice the version number out.
1527  // Version number is between the first and the last number.
1528  size_t StartVer = SDK.find_first_of("0123456789");
1529  size_t EndVer = SDK.find_last_of("0123456789");
1530  if (StartVer != StringRef::npos && EndVer > StartVer)
1531  Version = SDK.slice(StartVer, EndVer + 1);
1532  }
1533  if (Version.empty())
1534  return None;
1535 
1536  if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
1537  return DarwinPlatform::createFromSDK(
1538  Darwin::IPhoneOS, Version,
1539  /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
1540  else if (SDK.startswith("MacOSX"))
1541  return DarwinPlatform::createFromSDK(Darwin::MacOS,
1542  getSystemOrSDKMacOSVersion(Version));
1543  else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
1544  return DarwinPlatform::createFromSDK(
1545  Darwin::WatchOS, Version,
1546  /*IsSimulator=*/SDK.startswith("WatchSimulator"));
1547  else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
1548  return DarwinPlatform::createFromSDK(
1549  Darwin::TvOS, Version,
1550  /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
1551  return None;
1552 }
1553 
1554 std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
1555  const Driver &TheDriver) {
1556  unsigned Major, Minor, Micro;
1557  llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1558  switch (OS) {
1559  case llvm::Triple::Darwin:
1560  case llvm::Triple::MacOSX:
1561  // If there is no version specified on triple, and both host and target are
1562  // macos, use the host triple to infer OS version.
1563  if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
1564  !Triple.getOSMajorVersion())
1565  SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1566  else if (!Triple.getMacOSXVersion(Major, Minor, Micro))
1567  TheDriver.Diag(diag::err_drv_invalid_darwin_version)
1568  << Triple.getOSName();
1569  break;
1570  case llvm::Triple::IOS:
1571  Triple.getiOSVersion(Major, Minor, Micro);
1572  break;
1573  case llvm::Triple::TvOS:
1574  Triple.getOSVersion(Major, Minor, Micro);
1575  break;
1576  case llvm::Triple::WatchOS:
1577  Triple.getWatchOSVersion(Major, Minor, Micro);
1578  break;
1579  default:
1580  llvm_unreachable("Unexpected OS type");
1581  break;
1582  }
1583 
1584  std::string OSVersion;
1585  llvm::raw_string_ostream(OSVersion) << Major << '.' << Minor << '.' << Micro;
1586  return OSVersion;
1587 }
1588 
1589 /// Tries to infer the target OS from the -arch.
1591 inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
1592  const llvm::Triple &Triple,
1593  const Driver &TheDriver) {
1594  llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
1595 
1596  StringRef MachOArchName = Toolchain.getMachOArchName(Args);
1597  if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
1598  MachOArchName == "arm64")
1599  OSTy = llvm::Triple::IOS;
1600  else if (MachOArchName == "armv7k")
1601  OSTy = llvm::Triple::WatchOS;
1602  else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
1603  MachOArchName != "armv7em")
1604  OSTy = llvm::Triple::MacOSX;
1605 
1606  if (OSTy == llvm::Triple::UnknownOS)
1607  return None;
1608  return DarwinPlatform::createFromArch(OSTy,
1609  getOSVersion(OSTy, Triple, TheDriver));
1610 }
1611 
1612 /// Returns the deployment target that's specified using the -target option.
1613 Optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
1614  DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver) {
1615  if (!Args.hasArg(options::OPT_target))
1616  return None;
1617  if (Triple.getOS() == llvm::Triple::Darwin ||
1618  Triple.getOS() == llvm::Triple::UnknownOS)
1619  return None;
1620  std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
1621  return DarwinPlatform::createFromTarget(Triple, OSVersion,
1622  Args.getLastArg(options::OPT_target));
1623 }
1624 
1625 Optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
1626  const ArgList &Args,
1627  const Driver &TheDriver) {
1628  const Arg *A = Args.getLastArg(options::OPT_isysroot);
1629  if (!A)
1630  return None;
1631  StringRef isysroot = A->getValue();
1632  auto SDKInfoOrErr = driver::parseDarwinSDKInfo(VFS, isysroot);
1633  if (!SDKInfoOrErr) {
1634  llvm::consumeError(SDKInfoOrErr.takeError());
1635  TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
1636  return None;
1637  }
1638  return *SDKInfoOrErr;
1639 }
1640 
1641 } // namespace
1642 
1643 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
1644  const OptTable &Opts = getDriver().getOpts();
1645 
1646  // Support allowing the SDKROOT environment variable used by xcrun and other
1647  // Xcode tools to define the default sysroot, by making it the default for
1648  // isysroot.
1649  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1650  // Warn if the path does not exist.
1651  if (!getVFS().exists(A->getValue()))
1652  getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
1653  } else {
1654  if (char *env = ::getenv("SDKROOT")) {
1655  // We only use this value as the default if it is an absolute path,
1656  // exists, and it is not the root path.
1657  if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
1658  StringRef(env) != "/") {
1659  Args.append(Args.MakeSeparateArg(
1660  nullptr, Opts.getOption(options::OPT_isysroot), env));
1661  }
1662  }
1663  }
1664 
1665  // Read the SDKSettings.json file for more information, like the SDK version
1666  // that we can pass down to the compiler.
1667  SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
1668 
1669  // The OS and the version can be specified using the -target argument.
1670  Optional<DarwinPlatform> OSTarget =
1671  getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver());
1672  if (OSTarget) {
1673  Optional<DarwinPlatform> OSVersionArgTarget =
1674  getDeploymentTargetFromOSVersionArg(Args, getDriver());
1675  if (OSVersionArgTarget) {
1676  unsigned TargetMajor, TargetMinor, TargetMicro;
1677  bool TargetExtra;
1678  unsigned ArgMajor, ArgMinor, ArgMicro;
1679  bool ArgExtra;
1680  if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
1681  (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
1682  TargetMinor, TargetMicro, TargetExtra) &&
1683  Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
1684  ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
1685  (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
1686  VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
1687  TargetExtra != ArgExtra))) {
1688  // Select the OS version from the -m<os>-version-min argument when
1689  // the -target does not include an OS version.
1690  if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
1691  !OSTarget->hasOSVersion()) {
1692  OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
1693  } else {
1694  // Warn about -m<os>-version-min that doesn't match the OS version
1695  // that's specified in the target.
1696  std::string OSVersionArg =
1697  OSVersionArgTarget->getAsString(Args, Opts);
1698  std::string TargetArg = OSTarget->getAsString(Args, Opts);
1699  getDriver().Diag(clang::diag::warn_drv_overriding_flag_option)
1700  << OSVersionArg << TargetArg;
1701  }
1702  }
1703  }
1704  } else {
1705  // The OS target can be specified using the -m<os>version-min argument.
1706  OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
1707  // If no deployment target was specified on the command line, check for
1708  // environment defines.
1709  if (!OSTarget) {
1710  OSTarget =
1711  getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
1712  if (OSTarget) {
1713  // Don't infer simulator from the arch when the SDK is also specified.
1714  Optional<DarwinPlatform> SDKTarget =
1715  inferDeploymentTargetFromSDK(Args, SDKInfo);
1716  if (SDKTarget)
1717  OSTarget->setEnvironment(SDKTarget->getEnvironment());
1718  }
1719  }
1720  // If there is no command-line argument to specify the Target version and
1721  // no environment variable defined, see if we can set the default based
1722  // on -isysroot using SDKSettings.json if it exists.
1723  if (!OSTarget) {
1724  OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo);
1725  /// If the target was successfully constructed from the SDK path, try to
1726  /// infer the SDK info if the SDK doesn't have it.
1727  if (OSTarget && !SDKInfo)
1728  SDKInfo = OSTarget->inferSDKInfo();
1729  }
1730  // If no OS targets have been specified, try to guess platform from -target
1731  // or arch name and compute the version from the triple.
1732  if (!OSTarget)
1733  OSTarget =
1734  inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
1735  }
1736 
1737  assert(OSTarget && "Unable to infer Darwin variant");
1738  OSTarget->addOSVersionMinArgument(Args, Opts);
1739  DarwinPlatformKind Platform = OSTarget->getPlatform();
1740 
1741  unsigned Major, Minor, Micro;
1742  bool HadExtra;
1743  // Set the tool chain target information.
1744  if (Platform == MacOS) {
1745  if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1746  Micro, HadExtra) ||
1747  HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
1748  getDriver().Diag(diag::err_drv_invalid_version_number)
1749  << OSTarget->getAsString(Args, Opts);
1750  } else if (Platform == IPhoneOS) {
1751  if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1752  Micro, HadExtra) ||
1753  HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1754  getDriver().Diag(diag::err_drv_invalid_version_number)
1755  << OSTarget->getAsString(Args, Opts);
1756  ;
1757  // For 32-bit targets, the deployment target for iOS has to be earlier than
1758  // iOS 11.
1759  if (getTriple().isArch32Bit() && Major >= 11) {
1760  // If the deployment target is explicitly specified, print a diagnostic.
1761  if (OSTarget->isExplicitlySpecified()) {
1762  getDriver().Diag(diag::warn_invalid_ios_deployment_target)
1763  << OSTarget->getAsString(Args, Opts);
1764  // Otherwise, set it to 10.99.99.
1765  } else {
1766  Major = 10;
1767  Minor = 99;
1768  Micro = 99;
1769  }
1770  }
1771  } else if (Platform == TvOS) {
1772  if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1773  Micro, HadExtra) ||
1774  HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1775  getDriver().Diag(diag::err_drv_invalid_version_number)
1776  << OSTarget->getAsString(Args, Opts);
1777  } else if (Platform == WatchOS) {
1778  if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1779  Micro, HadExtra) ||
1780  HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
1781  getDriver().Diag(diag::err_drv_invalid_version_number)
1782  << OSTarget->getAsString(Args, Opts);
1783  } else
1784  llvm_unreachable("unknown kind of Darwin platform");
1785 
1786  DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
1787  // Recognize iOS targets with an x86 architecture as the iOS simulator.
1788  if (Environment == NativeEnvironment && Platform != MacOS &&
1789  OSTarget->canInferSimulatorFromArch() &&
1790  (getTriple().getArch() == llvm::Triple::x86 ||
1791  getTriple().getArch() == llvm::Triple::x86_64))
1792  Environment = Simulator;
1793 
1794  setTarget(Platform, Environment, Major, Minor, Micro);
1795 
1796  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1797  StringRef SDK = getSDKName(A->getValue());
1798  if (SDK.size() > 0) {
1799  size_t StartVer = SDK.find_first_of("0123456789");
1800  StringRef SDKName = SDK.slice(0, StartVer);
1801  if (!SDKName.startswith(getPlatformFamily()))
1802  getDriver().Diag(diag::warn_incompatible_sysroot)
1803  << SDKName << getPlatformFamily();
1804  }
1805  }
1806 }
1807 
1808 // Returns the effective header sysroot path to use. This comes either from
1809 // -isysroot or --sysroot.
1810 llvm::StringRef DarwinClang::GetHeaderSysroot(const llvm::opt::ArgList &DriverArgs) const {
1811  if(DriverArgs.hasArg(options::OPT_isysroot))
1812  return DriverArgs.getLastArgValue(options::OPT_isysroot);
1813  if (!getDriver().SysRoot.empty())
1814  return getDriver().SysRoot;
1815  return "/";
1816 }
1817 
1818 void DarwinClang::AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
1819  llvm::opt::ArgStringList &CC1Args) const {
1820  const Driver &D = getDriver();
1821 
1822  llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
1823 
1824  bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
1825  bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
1826  bool NoBuiltinInc = DriverArgs.hasArg(options::OPT_nobuiltininc);
1827 
1828  // Add <sysroot>/usr/local/include
1829  if (!NoStdInc && !NoStdlibInc) {
1830  SmallString<128> P(Sysroot);
1831  llvm::sys::path::append(P, "usr", "local", "include");
1832  addSystemInclude(DriverArgs, CC1Args, P);
1833  }
1834 
1835  // Add the Clang builtin headers (<resource>/include)
1836  if (!NoStdInc && !NoBuiltinInc) {
1838  llvm::sys::path::append(P, "include");
1839  addSystemInclude(DriverArgs, CC1Args, P);
1840  }
1841 
1842  if (NoStdInc || NoStdlibInc)
1843  return;
1844 
1845  // Check for configure-time C include directories.
1846  llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
1847  if (!CIncludeDirs.empty()) {
1849  CIncludeDirs.split(dirs, ":");
1850  for (llvm::StringRef dir : dirs) {
1851  llvm::StringRef Prefix =
1852  llvm::sys::path::is_absolute(dir) ? llvm::StringRef(Sysroot) : "";
1853  addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
1854  }
1855  } else {
1856  // Otherwise, add <sysroot>/usr/include.
1857  SmallString<128> P(Sysroot);
1858  llvm::sys::path::append(P, "usr", "include");
1859  addExternCSystemInclude(DriverArgs, CC1Args, P.str());
1860  }
1861 }
1862 
1863 bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
1864  llvm::opt::ArgStringList &CC1Args,
1866  llvm::StringRef Version,
1867  llvm::StringRef ArchDir,
1868  llvm::StringRef BitDir) const {
1869  llvm::sys::path::append(Base, Version);
1870 
1871  // Add the base dir
1872  addSystemInclude(DriverArgs, CC1Args, Base);
1873 
1874  // Add the multilib dirs
1875  {
1876  llvm::SmallString<128> P = Base;
1877  if (!ArchDir.empty())
1878  llvm::sys::path::append(P, ArchDir);
1879  if (!BitDir.empty())
1880  llvm::sys::path::append(P, BitDir);
1881  addSystemInclude(DriverArgs, CC1Args, P);
1882  }
1883 
1884  // Add the backward dir
1885  {
1886  llvm::SmallString<128> P = Base;
1887  llvm::sys::path::append(P, "backward");
1888  addSystemInclude(DriverArgs, CC1Args, P);
1889  }
1890 
1891  return getVFS().exists(Base);
1892 }
1893 
1895  const llvm::opt::ArgList &DriverArgs,
1896  llvm::opt::ArgStringList &CC1Args) const {
1897  // The implementation from a base class will pass through the -stdlib to
1898  // CC1Args.
1899  // FIXME: this should not be necessary, remove usages in the frontend
1900  // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
1901  // Also check whether this is used for setting library search paths.
1902  ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
1903 
1904  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1905  DriverArgs.hasArg(options::OPT_nostdincxx))
1906  return;
1907 
1908  llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
1909 
1910  switch (GetCXXStdlibType(DriverArgs)) {
1911  case ToolChain::CST_Libcxx: {
1912  // On Darwin, libc++ is installed alongside the compiler in
1913  // include/c++/v1, so get from '<install>/bin' to '<install>/include/c++/v1'.
1914  {
1915  llvm::SmallString<128> P = llvm::StringRef(getDriver().getInstalledDir());
1916  // Note that P can be relative, so we have to '..' and not parent_path.
1917  llvm::sys::path::append(P, "..", "include", "c++", "v1");
1918  addSystemInclude(DriverArgs, CC1Args, P);
1919  }
1920  // Also add <sysroot>/usr/include/c++/v1 unless -nostdinc is used,
1921  // to match the legacy behavior in CC1.
1922  if (!DriverArgs.hasArg(options::OPT_nostdinc)) {
1923  llvm::SmallString<128> P = Sysroot;
1924  llvm::sys::path::append(P, "usr", "include", "c++", "v1");
1925  addSystemInclude(DriverArgs, CC1Args, P);
1926  }
1927  break;
1928  }
1929 
1931  llvm::SmallString<128> UsrIncludeCxx = Sysroot;
1932  llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
1933 
1934  llvm::Triple::ArchType arch = getTriple().getArch();
1935  bool IsBaseFound = true;
1936  switch (arch) {
1937  default: break;
1938 
1939  case llvm::Triple::ppc:
1940  case llvm::Triple::ppc64:
1941  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1942  "4.2.1",
1943  "powerpc-apple-darwin10",
1944  arch == llvm::Triple::ppc64 ? "ppc64" : "");
1945  IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1946  "4.0.0", "powerpc-apple-darwin10",
1947  arch == llvm::Triple::ppc64 ? "ppc64" : "");
1948  break;
1949 
1950  case llvm::Triple::x86:
1951  case llvm::Triple::x86_64:
1952  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1953  "4.2.1",
1954  "i686-apple-darwin10",
1955  arch == llvm::Triple::x86_64 ? "x86_64" : "");
1956  IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1957  "4.0.0", "i686-apple-darwin8",
1958  "");
1959  break;
1960 
1961  case llvm::Triple::arm:
1962  case llvm::Triple::thumb:
1963  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1964  "4.2.1",
1965  "arm-apple-darwin10",
1966  "v7");
1967  IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1968  "4.2.1",
1969  "arm-apple-darwin10",
1970  "v6");
1971  break;
1972 
1973  case llvm::Triple::aarch64:
1974  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1975  "4.2.1",
1976  "arm64-apple-darwin10",
1977  "");
1978  break;
1979  }
1980 
1981  if (!IsBaseFound) {
1982  getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
1983  }
1984 
1985  break;
1986  }
1987 }
1988 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
1989  ArgStringList &CmdArgs) const {
1991 
1992  switch (Type) {
1993  case ToolChain::CST_Libcxx:
1994  CmdArgs.push_back("-lc++");
1995  break;
1996 
1998  // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
1999  // it was previously found in the gcc lib dir. However, for all the Darwin
2000  // platforms we care about it was -lstdc++.6, so we search for that
2001  // explicitly if we can't see an obvious -lstdc++ candidate.
2002 
2003  // Check in the sysroot first.
2004  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2005  SmallString<128> P(A->getValue());
2006  llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
2007 
2008  if (!getVFS().exists(P)) {
2009  llvm::sys::path::remove_filename(P);
2010  llvm::sys::path::append(P, "libstdc++.6.dylib");
2011  if (getVFS().exists(P)) {
2012  CmdArgs.push_back(Args.MakeArgString(P));
2013  return;
2014  }
2015  }
2016  }
2017 
2018  // Otherwise, look in the root.
2019  // FIXME: This should be removed someday when we don't have to care about
2020  // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
2021  if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
2022  getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
2023  CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
2024  return;
2025  }
2026 
2027  // Otherwise, let the linker search.
2028  CmdArgs.push_back("-lstdc++");
2029  break;
2030  }
2031 }
2032 
2033 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
2034  ArgStringList &CmdArgs) const {
2035  // For Darwin platforms, use the compiler-rt-based support library
2036  // instead of the gcc-provided one (which is also incidentally
2037  // only present in the gcc lib dir, which makes it hard to find).
2038 
2039  SmallString<128> P(getDriver().ResourceDir);
2040  llvm::sys::path::append(P, "lib", "darwin");
2041 
2042  // Use the newer cc_kext for iOS ARM after 6.0.
2043  if (isTargetWatchOS()) {
2044  llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
2045  } else if (isTargetTvOS()) {
2046  llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
2047  } else if (isTargetIPhoneOS()) {
2048  llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
2049  } else {
2050  llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
2051  }
2052 
2053  // For now, allow missing resource libraries to support developers who may
2054  // not have compiler-rt checked out or integrated into their build.
2055  if (getVFS().exists(P))
2056  CmdArgs.push_back(Args.MakeArgString(P));
2057 }
2058 
2059 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
2060  StringRef BoundArch,
2061  Action::OffloadKind) const {
2062  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2063  const OptTable &Opts = getDriver().getOpts();
2064 
2065  // FIXME: We really want to get out of the tool chain level argument
2066  // translation business, as it makes the driver functionality much
2067  // more opaque. For now, we follow gcc closely solely for the
2068  // purpose of easily achieving feature parity & testability. Once we
2069  // have something that works, we should reevaluate each translation
2070  // and try to push it down into tool specific logic.
2071 
2072  for (Arg *A : Args) {
2073  if (A->getOption().matches(options::OPT_Xarch__)) {
2074  // Skip this argument unless the architecture matches either the toolchain
2075  // triple arch, or the arch being bound.
2076  llvm::Triple::ArchType XarchArch =
2078  if (!(XarchArch == getArch() ||
2079  (!BoundArch.empty() &&
2080  XarchArch ==
2082  continue;
2083 
2084  Arg *OriginalArg = A;
2085  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
2086  unsigned Prev = Index;
2087  std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
2088 
2089  // If the argument parsing failed or more than one argument was
2090  // consumed, the -Xarch_ argument's parameter tried to consume
2091  // extra arguments. Emit an error and ignore.
2092  //
2093  // We also want to disallow any options which would alter the
2094  // driver behavior; that isn't going to work in our model. We
2095  // use isDriverOption() as an approximation, although things
2096  // like -O4 are going to slip through.
2097  if (!XarchArg || Index > Prev + 1) {
2098  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
2099  << A->getAsString(Args);
2100  continue;
2101  } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
2102  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
2103  << A->getAsString(Args);
2104  continue;
2105  }
2106 
2107  XarchArg->setBaseArg(A);
2108 
2109  A = XarchArg.release();
2110  DAL->AddSynthesizedArg(A);
2111 
2112  // Linker input arguments require custom handling. The problem is that we
2113  // have already constructed the phase actions, so we can not treat them as
2114  // "input arguments".
2115  if (A->getOption().hasFlag(options::LinkerInput)) {
2116  // Convert the argument into individual Zlinker_input_args.
2117  for (const char *Value : A->getValues()) {
2118  DAL->AddSeparateArg(
2119  OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
2120  }
2121  continue;
2122  }
2123  }
2124 
2125  // Sob. These is strictly gcc compatible for the time being. Apple
2126  // gcc translates options twice, which means that self-expanding
2127  // options add duplicates.
2128  switch ((options::ID)A->getOption().getID()) {
2129  default:
2130  DAL->append(A);
2131  break;
2132 
2133  case options::OPT_mkernel:
2134  case options::OPT_fapple_kext:
2135  DAL->append(A);
2136  DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
2137  break;
2138 
2139  case options::OPT_dependency_file:
2140  DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
2141  break;
2142 
2143  case options::OPT_gfull:
2144  DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2145  DAL->AddFlagArg(
2146  A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
2147  break;
2148 
2149  case options::OPT_gused:
2150  DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2151  DAL->AddFlagArg(
2152  A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
2153  break;
2154 
2155  case options::OPT_shared:
2156  DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
2157  break;
2158 
2159  case options::OPT_fconstant_cfstrings:
2160  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
2161  break;
2162 
2163  case options::OPT_fno_constant_cfstrings:
2164  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
2165  break;
2166 
2167  case options::OPT_Wnonportable_cfstrings:
2168  DAL->AddFlagArg(A,
2169  Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
2170  break;
2171 
2172  case options::OPT_Wno_nonportable_cfstrings:
2173  DAL->AddFlagArg(
2174  A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
2175  break;
2176 
2177  case options::OPT_fpascal_strings:
2178  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
2179  break;
2180 
2181  case options::OPT_fno_pascal_strings:
2182  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
2183  break;
2184  }
2185  }
2186 
2187  if (getTriple().getArch() == llvm::Triple::x86 ||
2188  getTriple().getArch() == llvm::Triple::x86_64)
2189  if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
2190  DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
2191  "core2");
2192 
2193  // Add the arch options based on the particular spelling of -arch, to match
2194  // how the driver driver works.
2195  if (!BoundArch.empty()) {
2196  StringRef Name = BoundArch;
2197  const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
2198  const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
2199 
2200  // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
2201  // which defines the list of which architectures we accept.
2202  if (Name == "ppc")
2203  ;
2204  else if (Name == "ppc601")
2205  DAL->AddJoinedArg(nullptr, MCpu, "601");
2206  else if (Name == "ppc603")
2207  DAL->AddJoinedArg(nullptr, MCpu, "603");
2208  else if (Name == "ppc604")
2209  DAL->AddJoinedArg(nullptr, MCpu, "604");
2210  else if (Name == "ppc604e")
2211  DAL->AddJoinedArg(nullptr, MCpu, "604e");
2212  else if (Name == "ppc750")
2213  DAL->AddJoinedArg(nullptr, MCpu, "750");
2214  else if (Name == "ppc7400")
2215  DAL->AddJoinedArg(nullptr, MCpu, "7400");
2216  else if (Name == "ppc7450")
2217  DAL->AddJoinedArg(nullptr, MCpu, "7450");
2218  else if (Name == "ppc970")
2219  DAL->AddJoinedArg(nullptr, MCpu, "970");
2220 
2221  else if (Name == "ppc64" || Name == "ppc64le")
2222  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2223 
2224  else if (Name == "i386")
2225  ;
2226  else if (Name == "i486")
2227  DAL->AddJoinedArg(nullptr, MArch, "i486");
2228  else if (Name == "i586")
2229  DAL->AddJoinedArg(nullptr, MArch, "i586");
2230  else if (Name == "i686")
2231  DAL->AddJoinedArg(nullptr, MArch, "i686");
2232  else if (Name == "pentium")
2233  DAL->AddJoinedArg(nullptr, MArch, "pentium");
2234  else if (Name == "pentium2")
2235  DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2236  else if (Name == "pentpro")
2237  DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
2238  else if (Name == "pentIIm3")
2239  DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2240 
2241  else if (Name == "x86_64" || Name == "x86_64h")
2242  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2243 
2244  else if (Name == "arm")
2245  DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2246  else if (Name == "armv4t")
2247  DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2248  else if (Name == "armv5")
2249  DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
2250  else if (Name == "xscale")
2251  DAL->AddJoinedArg(nullptr, MArch, "xscale");
2252  else if (Name == "armv6")
2253  DAL->AddJoinedArg(nullptr, MArch, "armv6k");
2254  else if (Name == "armv6m")
2255  DAL->AddJoinedArg(nullptr, MArch, "armv6m");
2256  else if (Name == "armv7")
2257  DAL->AddJoinedArg(nullptr, MArch, "armv7a");
2258  else if (Name == "armv7em")
2259  DAL->AddJoinedArg(nullptr, MArch, "armv7em");
2260  else if (Name == "armv7k")
2261  DAL->AddJoinedArg(nullptr, MArch, "armv7k");
2262  else if (Name == "armv7m")
2263  DAL->AddJoinedArg(nullptr, MArch, "armv7m");
2264  else if (Name == "armv7s")
2265  DAL->AddJoinedArg(nullptr, MArch, "armv7s");
2266  }
2267 
2268  return DAL;
2269 }
2270 
2271 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
2272  ArgStringList &CmdArgs,
2273  bool ForceLinkBuiltinRT) const {
2274  // Embedded targets are simple at the moment, not supporting sanitizers and
2275  // with different libraries for each member of the product { static, PIC } x
2276  // { hard-float, soft-float }
2277  llvm::SmallString<32> CompilerRT = StringRef("");
2278  CompilerRT +=
2280  ? "hard"
2281  : "soft";
2282  CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
2283 
2284  AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
2285 }
2286 
2288  llvm::Triple::OSType OS;
2289 
2290  switch (TargetPlatform) {
2291  case MacOS: // Earlier than 10.13.
2292  OS = llvm::Triple::MacOSX;
2293  break;
2294  case IPhoneOS:
2295  OS = llvm::Triple::IOS;
2296  break;
2297  case TvOS: // Earlier than 11.0.
2298  OS = llvm::Triple::TvOS;
2299  break;
2300  case WatchOS: // Earlier than 4.0.
2301  OS = llvm::Triple::WatchOS;
2302  break;
2303  }
2304 
2306 }
2307 
2308 void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
2309  llvm::opt::ArgStringList &CC1Args,
2310  Action::OffloadKind DeviceOffloadKind) const {
2311  // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
2312  // enabled or disabled aligned allocations.
2313  if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
2314  options::OPT_fno_aligned_allocation) &&
2316  CC1Args.push_back("-faligned-alloc-unavailable");
2317 
2318  if (SDKInfo) {
2319  /// Pass the SDK version to the compiler when the SDK information is
2320  /// available.
2321  std::string Arg;
2322  llvm::raw_string_ostream OS(Arg);
2323  OS << "-target-sdk-version=" << SDKInfo->getVersion();
2324  CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
2325  }
2326 }
2327 
2328 DerivedArgList *
2329 Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
2330  Action::OffloadKind DeviceOffloadKind) const {
2331  // First get the generic Apple args, before moving onto Darwin-specific ones.
2332  DerivedArgList *DAL =
2333  MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
2334  const OptTable &Opts = getDriver().getOpts();
2335 
2336  // If no architecture is bound, none of the translations here are relevant.
2337  if (BoundArch.empty())
2338  return DAL;
2339 
2340  // Add an explicit version min argument for the deployment target. We do this
2341  // after argument translation because -Xarch_ arguments may add a version min
2342  // argument.
2343  AddDeploymentTarget(*DAL);
2344 
2345  // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
2346  // FIXME: It would be far better to avoid inserting those -static arguments,
2347  // but we can't check the deployment target in the translation code until
2348  // it is set here.
2349  if (isTargetWatchOSBased() ||
2350  (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
2351  for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
2352  Arg *A = *it;
2353  ++it;
2354  if (A->getOption().getID() != options::OPT_mkernel &&
2355  A->getOption().getID() != options::OPT_fapple_kext)
2356  continue;
2357  assert(it != ie && "unexpected argument translation");
2358  A = *it;
2359  assert(A->getOption().getID() == options::OPT_static &&
2360  "missing expected -static argument");
2361  *it = nullptr;
2362  ++it;
2363  }
2364  }
2365 
2366  if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
2368  DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
2369  "libc++");
2370 
2371  // Validate the C++ standard library choice.
2373  if (Type == ToolChain::CST_Libcxx) {
2374  // Check whether the target provides libc++.
2375  StringRef where;
2376 
2377  // Complain about targeting iOS < 5.0 in any way.
2378  if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
2379  where = "iOS 5.0";
2380 
2381  if (where != StringRef()) {
2382  getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
2383  }
2384  }
2385 
2386  auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
2387  if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
2388  if (Args.hasFlag(options::OPT_fomit_frame_pointer,
2389  options::OPT_fno_omit_frame_pointer, false))
2390  getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
2391  << "-fomit-frame-pointer" << BoundArch;
2392  }
2393 
2394  return DAL;
2395 }
2396 
2397 bool MachO::IsUnwindTablesDefault(const ArgList &Args) const {
2398  // Unwind tables are not emitted if -fno-exceptions is supplied (except when
2399  // targeting x86_64).
2400  return getArch() == llvm::Triple::x86_64 ||
2401  (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
2402  Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2403  true));
2404 }
2405 
2407  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
2408  return S[0] != '\0';
2409  return false;
2410 }
2411 
2412 llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
2413  // Darwin uses SjLj exceptions on ARM.
2414  if (getTriple().getArch() != llvm::Triple::arm &&
2415  getTriple().getArch() != llvm::Triple::thumb)
2417 
2418  // Only watchOS uses the new DWARF/Compact unwinding method.
2419  llvm::Triple Triple(ComputeLLVMTriple(Args));
2420  if (Triple.isWatchABI())
2421  return llvm::ExceptionHandling::DwarfCFI;
2422 
2423  return llvm::ExceptionHandling::SjLj;
2424 }
2425 
2427  assert(TargetInitialized && "Target not initialized!");
2428  if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
2429  return false;
2430  return true;
2431 }
2432 
2433 bool MachO::isPICDefault() const { return true; }
2434 
2435 bool MachO::isPIEDefault() const { return false; }
2436 
2438  return (getArch() == llvm::Triple::x86_64 ||
2439  getArch() == llvm::Triple::aarch64);
2440 }
2441 
2443  // Profiling instrumentation is only supported on x86.
2444  return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
2445 }
2446 
2447 void Darwin::addMinVersionArgs(const ArgList &Args,
2448  ArgStringList &CmdArgs) const {
2449  VersionTuple TargetVersion = getTargetVersion();
2450 
2451  if (isTargetWatchOS())
2452  CmdArgs.push_back("-watchos_version_min");
2453  else if (isTargetWatchOSSimulator())
2454  CmdArgs.push_back("-watchos_simulator_version_min");
2455  else if (isTargetTvOS())
2456  CmdArgs.push_back("-tvos_version_min");
2457  else if (isTargetTvOSSimulator())
2458  CmdArgs.push_back("-tvos_simulator_version_min");
2459  else if (isTargetIOSSimulator())
2460  CmdArgs.push_back("-ios_simulator_version_min");
2461  else if (isTargetIOSBased())
2462  CmdArgs.push_back("-iphoneos_version_min");
2463  else {
2464  assert(isTargetMacOS() && "unexpected target");
2465  CmdArgs.push_back("-macosx_version_min");
2466  }
2467 
2468  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2469 }
2470 
2471 void Darwin::addStartObjectFileArgs(const ArgList &Args,
2472  ArgStringList &CmdArgs) const {
2473  // Derived from startfile spec.
2474  if (Args.hasArg(options::OPT_dynamiclib)) {
2475  // Derived from darwin_dylib1 spec.
2476  if (isTargetWatchOSBased()) {
2477  ; // watchOS does not need dylib1.o.
2478  } else if (isTargetIOSSimulator()) {
2479  ; // iOS simulator does not need dylib1.o.
2480  } else if (isTargetIPhoneOS()) {
2481  if (isIPhoneOSVersionLT(3, 1))
2482  CmdArgs.push_back("-ldylib1.o");
2483  } else {
2484  if (isMacosxVersionLT(10, 5))
2485  CmdArgs.push_back("-ldylib1.o");
2486  else if (isMacosxVersionLT(10, 6))
2487  CmdArgs.push_back("-ldylib1.10.5.o");
2488  }
2489  } else {
2490  if (Args.hasArg(options::OPT_bundle)) {
2491  if (!Args.hasArg(options::OPT_static)) {
2492  // Derived from darwin_bundle1 spec.
2493  if (isTargetWatchOSBased()) {
2494  ; // watchOS does not need bundle1.o.
2495  } else if (isTargetIOSSimulator()) {
2496  ; // iOS simulator does not need bundle1.o.
2497  } else if (isTargetIPhoneOS()) {
2498  if (isIPhoneOSVersionLT(3, 1))
2499  CmdArgs.push_back("-lbundle1.o");
2500  } else {
2501  if (isMacosxVersionLT(10, 6))
2502  CmdArgs.push_back("-lbundle1.o");
2503  }
2504  }
2505  } else {
2506  if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
2507  if (isTargetMacOS() && isMacosxVersionLT(10, 9)) {
2508  if (Args.hasArg(options::OPT_static) ||
2509  Args.hasArg(options::OPT_object) ||
2510  Args.hasArg(options::OPT_preload)) {
2511  CmdArgs.push_back("-lgcrt0.o");
2512  } else {
2513  CmdArgs.push_back("-lgcrt1.o");
2514 
2515  // darwin_crt2 spec is empty.
2516  }
2517  // By default on OS X 10.8 and later, we don't link with a crt1.o
2518  // file and the linker knows to use _main as the entry point. But,
2519  // when compiling with -pg, we need to link with the gcrt1.o file,
2520  // so pass the -no_new_main option to tell the linker to use the
2521  // "start" symbol as the entry point.
2522  if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
2523  CmdArgs.push_back("-no_new_main");
2524  } else {
2525  getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
2526  << isTargetMacOS();
2527  }
2528  } else {
2529  if (Args.hasArg(options::OPT_static) ||
2530  Args.hasArg(options::OPT_object) ||
2531  Args.hasArg(options::OPT_preload)) {
2532  CmdArgs.push_back("-lcrt0.o");
2533  } else {
2534  // Derived from darwin_crt1 spec.
2535  if (isTargetWatchOSBased()) {
2536  ; // watchOS does not need crt1.o.
2537  } else if (isTargetIOSSimulator()) {
2538  ; // iOS simulator does not need crt1.o.
2539  } else if (isTargetIPhoneOS()) {
2540  if (getArch() == llvm::Triple::aarch64)
2541  ; // iOS does not need any crt1 files for arm64
2542  else if (isIPhoneOSVersionLT(3, 1))
2543  CmdArgs.push_back("-lcrt1.o");
2544  else if (isIPhoneOSVersionLT(6, 0))
2545  CmdArgs.push_back("-lcrt1.3.1.o");
2546  } else {
2547  if (isMacosxVersionLT(10, 5))
2548  CmdArgs.push_back("-lcrt1.o");
2549  else if (isMacosxVersionLT(10, 6))
2550  CmdArgs.push_back("-lcrt1.10.5.o");
2551  else if (isMacosxVersionLT(10, 8))
2552  CmdArgs.push_back("-lcrt1.10.6.o");
2553 
2554  // darwin_crt2 spec is empty.
2555  }
2556  }
2557  }
2558  }
2559  }
2560 
2561  if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
2562  !isTargetWatchOS() && isMacosxVersionLT(10, 5)) {
2563  const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
2564  CmdArgs.push_back(Str);
2565  }
2566 }
2567 
2568 void Darwin::CheckObjCARC() const {
2570  (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
2571  return;
2572  getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
2573 }
2574 
2576  const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
2578  Res |= SanitizerKind::Address;
2579  Res |= SanitizerKind::PointerCompare;
2580  Res |= SanitizerKind::PointerSubtract;
2581  Res |= SanitizerKind::Leak;
2582  Res |= SanitizerKind::Fuzzer;
2583  Res |= SanitizerKind::FuzzerNoLink;
2584  Res |= SanitizerKind::Function;
2585 
2586  // Prior to 10.9, macOS shipped a version of the C++ standard library without
2587  // C++11 support. The same is true of iOS prior to version 5. These OS'es are
2588  // incompatible with -fsanitize=vptr.
2589  if (!(isTargetMacOS() && isMacosxVersionLT(10, 9))
2590  && !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)))
2591  Res |= SanitizerKind::Vptr;
2592 
2593  if (isTargetMacOS()) {
2594  if (IsX86_64)
2595  Res |= SanitizerKind::Thread;
2596  } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
2597  if (IsX86_64)
2598  Res |= SanitizerKind::Thread;
2599  }
2600  return Res;
2601 }
2602 
2603 void Darwin::printVerboseInfo(raw_ostream &OS) const {
2604  CudaInstallation.print(OS);
2605 }
StringRef getSysRoot() const
Returns the sysroot path.
static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra)
GetReleaseVersion - Parse (([0-9]+)(.
Definition: Driver.cpp:4718
StringRef getMachOArchName(const llvm::opt::ArgList &Args) const
Get the "MachO" arch name for a particular compiler invocation.
Definition: Darwin.cpp:814
static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory with extern "C" semantics to CC1 arguments...
Definition: ToolChain.cpp:768
virtual std::string ComputeLLVMTriple(const llvm::opt::ArgList &Args, types::ID InputType=types::TY_INVALID) const
ComputeLLVMTriple - Return the LLVM target triple to use, after taking command line arguments into ac...
Definition: ToolChain.cpp:544
bool SupportsEmbeddedBitcode() const override
SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
Definition: Darwin.cpp:2426
bool isMacosxVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const
Definition: Darwin.h:415
Tool * buildAssembler() const override
Definition: Darwin.cpp:885
std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const
GetTemporaryPath - Return the pathname of a temporary file to use as part of compilation; the file wi...
Definition: Driver.cpp:4492
Link the library in even if it can&#39;t be found in the VFS.
Definition: Darwin.h:180
Use the embedded runtime from the macho_embedded directory.
Definition: Darwin.h:183
const char * getTypeTempSuffix(ID Id, bool CLMode=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type, or null if unspecified.
Definition: Types.cpp:54
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition: Darwin.cpp:1818
bool UseDwarfDebugFlags() const override
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information...
Definition: Darwin.cpp:2406
StringRef P
bool isUsingLTO() const
Returns true if we are performing any kind of LTO.
Definition: Driver.h:525
Defines types useful for describing an Objective-C runtime.
CXXStdlibType GetDefaultCXXStdlibType() const override
Definition: Darwin.cpp:736
The base class of the type hierarchy.
Definition: Type.h:1414
const XRayArgs & getXRayArgs() const
Definition: ToolChain.cpp:132
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:792
void AddLinkRuntimeLib(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, StringRef Component, RuntimeLinkOptions Opts=RuntimeLinkOptions(), bool IsShared=false) const
Add a runtime library to the list of items to link.
Definition: Darwin.cpp:982
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: Darwin.cpp:734
bool embedBitcodeEnabled() const
Definition: Driver.h:333
constexpr XRayInstrMask Function
Definition: XRayInstr.h:38
LTOKind getLTOMode() const
Get the specific kind of LTO being performed.
Definition: Driver.h:528
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:108
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: Darwin.cpp:428
void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Add any profiling runtime libraries that are needed.
Definition: Darwin.cpp:1098
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
DarwinEnvironmentKind TargetEnvironment
Definition: Darwin.h:287
CudaInstallationDetector CudaInstallation
Definition: Darwin.h:295
bool TargetInitialized
Whether the information on the target has been initialized.
Definition: Darwin.h:272
void print(raw_ostream &OS) const
Print information about the detected CUDA installation.
Definition: Cuda.cpp:275
bool hasBlocksRuntime() const override
Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
Definition: Darwin.cpp:758
types::ID LookupTypeForExtension(StringRef Ext) const override
LookupTypeForExtension - Return the default language type to use for the given extension.
Definition: Darwin.cpp:724
&#39;macosx-fragile&#39; is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:39
const char * getFilename() const
Definition: InputInfo.h:83
path_list & getProgramPaths()
Definition: ToolChain.h:234
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
Definition: Darwin.cpp:2435
bool embedBitcodeMarkerOnly() const
Definition: Driver.h:335
ActionList & getInputs()
Definition: Action.h:142
bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const override
IsUnwindTablesDefault - Does this tool chain use -funwind-tables by default.
Definition: Darwin.cpp:2397
StringRef getPlatformFamily() const
Definition: Darwin.cpp:1033
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition: Driver.h:119
Darwin - The base Darwin tool chain.
Definition: Darwin.h:265
ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const override
Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
Definition: Darwin.cpp:747
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition: Darwin.cpp:2433
Action - Represent an abstract compilation step to perform.
Definition: Action.h:47
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
Definition: ToolChain.cpp:426
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: Darwin.cpp:2059
The information about the darwin SDK that was used during this compilation.
Definition: DarwinSDKInfo.h:21
Tool * getTool(Action::ActionClass AC) const override
Definition: Darwin.cpp:864
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
static bool hasExportSymbolDirective(const ArgList &Args)
Check if the link command contains a symbol export directive.
Definition: Darwin.cpp:1078
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:455
types::ID getType() const
Definition: Action.h:140
CompileCommand Cmd
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:57
bool needsXRayRt() const
Definition: XRayArgs.h:40
types::ID getType() const
Definition: InputInfo.h:77
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Definition: Darwin.cpp:2575
bool isTargetInitialized() const
Definition: Darwin.h:402
void AddMachOArch(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Darwin.cpp:154
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition: Darwin.cpp:2437
StringRef getPlatform() const
Definition: ToolChain.h:211
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition: Darwin.cpp:2412
bool addOpenMPRuntime(llvm::opt::ArgStringList &CmdArgs, const ToolChain &TC, const llvm::opt::ArgList &Args, bool IsOffloadingHost=false, bool GompNeedsRT=false)
Returns true, if an OpenMP runtime has been added.
static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args)
Pass -no_deduplicate to ld64 under certain conditions:
Definition: Darwin.cpp:185
Darwin(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Darwin - Darwin tool chain for i386 and x86_64.
Definition: Darwin.cpp:720
&#39;watchos&#39; is a variant of iOS for Apple&#39;s watchOS.
Definition: ObjCRuntime.h:48
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition: Darwin.cpp:2603
Defines a function that returns the minimum OS versions supporting C++17&#39;s aligned allocation functio...
Expected< Optional< DarwinSDKInfo > > parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath)
Parse the SDK information from the SDKSettings.json file.
bool requiresMinimalRuntime() const
Definition: SanitizerArgs.h:72
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition: Darwin.cpp:2308
ActionClass getKind() const
Definition: Action.h:139
bool isTargetWatchOSBased() const
Definition: Darwin.h:392
std::string GetTemporaryDirectory(StringRef Prefix) const
GetTemporaryDirectory - Return the pathname of a temporary directory to use as part of compilation; t...
Definition: Driver.cpp:4503
&#39;macosx&#39; is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition: ObjCRuntime.h:34
llvm::StringRef getAsString(SyncScope S)
Definition: SyncScope.h:50
static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol)
Add an export directive for Symbol to the link command.
Definition: Darwin.cpp:1093
virtual bool SupportsEmbeddedBitcode() const
SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
Definition: ToolChain.h:468
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: Darwin.cpp:1894
VersionTuple TargetVersion
The OS version we are targeting.
Definition: Darwin.h:290
void AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForceLinkBuiltinRT=false) const override
Add the linker arguments to link the compiler runtime library.
Definition: Darwin.cpp:1142
static const char * ArmMachOArchNameCPU(StringRef CPU)
Definition: Darwin.cpp:795
SmallString< 128 > getStatsFileName(const llvm::opt::ArgList &Args, const InputInfo &Output, const InputInfo &Input, const Driver &D)
Handles the -save-stats option and returns the filename to save statistics to.
void addCommand(std::unique_ptr< Command > C)
Definition: Compilation.h:205
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific CUDA includes.
Definition: Darwin.cpp:769
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
bool isTargetIOSSimulator() const
Definition: Darwin.h:356
llvm::Triple::ArchType getArchTypeForMachOArchName(StringRef Str)
Definition: Darwin.cpp:34
unsigned GetDefaultDwarfVersion() const override
Definition: Darwin.cpp:974
virtual void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Darwin.h:167
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:209
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: Cuda.cpp:232
Link the library in before any others.
Definition: Darwin.h:189
static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion)
Returns the most appropriate macOS target version for the current process.
Definition: Darwin.cpp:1216
#define false
Definition: stdbool.h:17
Kind
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: Darwin.cpp:2329
bool SupportsProfiling() const override
SupportsProfiling - Does this tool chain support -pg.
Definition: Darwin.cpp:2442
const llvm::opt::DerivedArgList & getArgs() const
Definition: Compilation.h:186
VersionTuple getTargetVersion() const
Definition: Darwin.h:404
const Driver & getDriver() const
Definition: ToolChain.h:193
std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, types::ID InputType) const override
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
Definition: Darwin.cpp:840
static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode)
Take a path that speculatively points into Xcode and return the XCODE/Contents/Developer path if it i...
Definition: Darwin.cpp:911
bool isTargetIOSBased() const
Is the target either iOS or an iOS simulator?
Definition: Darwin.h:175
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
Definition: ToolChain.cpp:753
DarwinClang(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: Darwin.cpp:889
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
constexpr XRayInstrMask None
Definition: XRayInstr.h:37
Optional< DarwinSDKInfo > SDKInfo
The information about the darwin SDK that was used.
Definition: Darwin.h:293
llvm::vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:108
void addStartObjectFileArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition: Darwin.cpp:2471
static const char * ArmMachOArchName(StringRef Arch)
Definition: Darwin.cpp:778
void AddLinkARCArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Add the linker arguments to link the ARC runtime library.
Definition: Darwin.cpp:920
DarwinPlatformKind TargetPlatform
Definition: Darwin.h:286
Dataflow Directional Tag Classes.
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: Darwin.cpp:688
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: Darwin.cpp:668
static StringRef getSDKName(StringRef isysroot)
Definition: Darwin.cpp:1047
void CheckObjCARC() const override
Complain if this tool chain doesn&#39;t support Objective-C ARC.
Definition: Darwin.cpp:2568
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: Darwin.cpp:84
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:27
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
StringRef getOSLibraryNameSuffix(bool IgnoreSim=false) const override
Definition: Darwin.cpp:1060
llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS)
std::string SysRoot
sysroot, if present
Definition: Driver.h:147
unsigned getLTOParallelism(const llvm::opt::ArgList &Args, const Driver &D)
Tool - Information on a specific compilation tool.
Definition: Tool.h:33
void setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str)
Definition: Darwin.cpp:69
const SanitizerArgs & getSanitizerArgs() const
Definition: ToolChain.cpp:126
void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition: Darwin.cpp:2447
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...
Definition: Darwin.cpp:1988
&#39;ios&#39; is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition: ObjCRuntime.h:44
StringRef getDefaultUniversalArchName() const
Provide the default architecture name (as expected by -arch) for this toolchain.
Definition: ToolChain.cpp:236
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
const Driver & getDriver() const
Definition: Compilation.h:133
RuntimeLinkOptions
Options to control how a runtime library is linked.
Definition: Darwin.h:178
const llvm::Triple & getTriple() const
Definition: ToolChain.h:195
Tool * buildLinker() const override
Definition: Darwin.cpp:883
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:869
ID lookupTypeForExtension(llvm::StringRef Ext)
lookupTypeForExtension - Lookup the type to use for the file extension Ext.
Definition: Types.cpp:194
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:299
Emit rpaths for as well as the resource directory.
Definition: Darwin.h:186
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Add warning options that need to be passed to cc1 for this target.
Definition: Darwin.cpp:893
bool isTargetWatchOSSimulator() const
Definition: Darwin.h:387
bool isFilename() const
Definition: InputInfo.h:75
virtual void AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForceLinkBuiltinRT=false) const
Add the linker arguments to link the compiler runtime library.
Definition: Darwin.cpp:2271
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
Definition: ToolChain.cpp:441
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:298
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:734
const char * addTempFile(const char *Name)
addTempFile - Add a file to remove on exit, and returns its argument.
Definition: Compilation.h:232
RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const override
Definition: Darwin.cpp:1130
bool hasNativeARC() const
Does this runtime natively provide the ARC entrypoints?
Definition: ObjCRuntime.h:161
static bool isObjCRuntimeLinked(const ArgList &Args)
Determine whether we are linking the ObjC runtime.
Definition: Darwin.cpp:420
bool isTargetTvOSSimulator() const
Definition: Darwin.h:372
bool isIPhoneOSVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const
Definition: Darwin.h:409
bool hasSubscripting() const
Does this runtime directly support the subscripting methods?
Definition: ObjCRuntime.h:297
void setTarget(DarwinPlatformKind Platform, DarwinEnvironmentKind Environment, unsigned Major, unsigned Minor, unsigned Micro) const
Definition: Darwin.h:332
bool empty() const
Definition: Job.h:193
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: Darwin.cpp:646
bool isAlignedAllocationUnavailable() const
Return true if c++17 aligned allocation/deallocation functions are not implemented in the c++ standar...
Definition: Darwin.cpp:2287
void AddCCKextLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCCKextLibArgs - Add the system specific linker arguments to use for kernel extensions (Darwin-spec...
Definition: Darwin.cpp:2033
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:88
std::string ResourceDir
The path to the compiler resource directory.
Definition: Driver.h:131