clang  15.0.0git
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/AArch64.h"
11 #include "Arch/ARM.h"
12 #include "CommonArgs.h"
15 #include "clang/Config/config.h"
17 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/Options.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Option/ArgList.h"
23 #include "llvm/ProfileData/InstrProf.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/ScopedPrinter.h"
26 #include "llvm/Support/TargetParser.h"
27 #include "llvm/Support/Threading.h"
28 #include "llvm/Support/VirtualFileSystem.h"
29 #include <cstdlib> // ::getenv
30 
31 using namespace clang::driver;
32 using namespace clang::driver::tools;
33 using namespace clang::driver::toolchains;
34 using namespace clang;
35 using namespace llvm::opt;
36 
37 static VersionTuple minimumMacCatalystDeploymentTarget() {
38  return VersionTuple(13, 1);
39 }
40 
41 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
42  // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
43  // archs which Darwin doesn't use.
44 
45  // The matching this routine does is fairly pointless, since it is neither the
46  // complete architecture list, nor a reasonable subset. The problem is that
47  // historically the driver driver accepts this and also ties its -march=
48  // handling to the architecture name, so we need to be careful before removing
49  // support for it.
50 
51  // This code must be kept in sync with Clang's Darwin specific argument
52  // translation.
53 
54  return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
55  .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
56  .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
57  .Case("ppc64", llvm::Triple::ppc64)
58  .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
59  .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
60  llvm::Triple::x86)
61  .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
62  // This is derived from the driver driver.
63  .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
64  .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
65  .Cases("armv7s", "xscale", llvm::Triple::arm)
66  .Cases("arm64", "arm64e", llvm::Triple::aarch64)
67  .Case("arm64_32", llvm::Triple::aarch64_32)
68  .Case("r600", llvm::Triple::r600)
69  .Case("amdgcn", llvm::Triple::amdgcn)
70  .Case("nvptx", llvm::Triple::nvptx)
71  .Case("nvptx64", llvm::Triple::nvptx64)
72  .Case("amdil", llvm::Triple::amdil)
73  .Case("spir", llvm::Triple::spir)
74  .Default(llvm::Triple::UnknownArch);
75 }
76 
77 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
78  const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
79  llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
80  T.setArch(Arch);
81  if (Arch != llvm::Triple::UnknownArch)
82  T.setArchName(Str);
83 
84  if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
85  ArchKind == llvm::ARM::ArchKind::ARMV7M ||
86  ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
87  T.setOS(llvm::Triple::UnknownOS);
88  T.setObjectFormat(llvm::Triple::MachO);
89  }
90 }
91 
93  const InputInfo &Output,
94  const InputInfoList &Inputs,
95  const ArgList &Args,
96  const char *LinkingOutput) const {
97  const llvm::Triple &T(getToolChain().getTriple());
98 
99  ArgStringList CmdArgs;
100 
101  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
102  const InputInfo &Input = Inputs[0];
103 
104  // Determine the original source input.
105  const Action *SourceAction = &JA;
106  while (SourceAction->getKind() != Action::InputClass) {
107  assert(!SourceAction->getInputs().empty() && "unexpected root action!");
108  SourceAction = SourceAction->getInputs()[0];
109  }
110 
111  // If -fno-integrated-as is used add -Q to the darwin assembler driver to make
112  // sure it runs its system assembler not clang's integrated assembler.
113  // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
114  // FIXME: at run-time detect assembler capabilities or rely on version
115  // information forwarded by -target-assembler-version.
116  if (Args.hasArg(options::OPT_fno_integrated_as)) {
117  if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
118  CmdArgs.push_back("-Q");
119  }
120 
121  // Forward -g, assuming we are dealing with an actual assembly file.
122  if (SourceAction->getType() == types::TY_Asm ||
123  SourceAction->getType() == types::TY_PP_Asm) {
124  if (Args.hasArg(options::OPT_gstabs))
125  CmdArgs.push_back("--gstabs");
126  else if (Args.hasArg(options::OPT_g_Group))
127  CmdArgs.push_back("-g");
128  }
129 
130  // Derived from asm spec.
131  AddMachOArch(Args, CmdArgs);
132 
133  // Use -force_cpusubtype_ALL on x86 by default.
134  if (T.isX86() || Args.hasArg(options::OPT_force__cpusubtype__ALL))
135  CmdArgs.push_back("-force_cpusubtype_ALL");
136 
137  if (getToolChain().getArch() != llvm::Triple::x86_64 &&
138  (((Args.hasArg(options::OPT_mkernel) ||
139  Args.hasArg(options::OPT_fapple_kext)) &&
140  getMachOToolChain().isKernelStatic()) ||
141  Args.hasArg(options::OPT_static)))
142  CmdArgs.push_back("-static");
143 
144  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
145 
146  assert(Output.isFilename() && "Unexpected lipo output.");
147  CmdArgs.push_back("-o");
148  CmdArgs.push_back(Output.getFilename());
149 
150  assert(Input.isFilename() && "Invalid input.");
151  CmdArgs.push_back(Input.getFilename());
152 
153  // asm_final spec is empty.
154 
155  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
156  C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
157  Exec, CmdArgs, Inputs, Output));
158 }
159 
160 void darwin::MachOTool::anchor() {}
161 
162 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
163  ArgStringList &CmdArgs) const {
164  StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
165 
166  // Derived from darwin_arch spec.
167  CmdArgs.push_back("-arch");
168  CmdArgs.push_back(Args.MakeArgString(ArchName));
169 
170  // FIXME: Is this needed anymore?
171  if (ArchName == "arm")
172  CmdArgs.push_back("-force_cpusubtype_ALL");
173 }
174 
175 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
176  // We only need to generate a temp path for LTO if we aren't compiling object
177  // files. When compiling source files, we run 'dsymutil' after linking. We
178  // don't run 'dsymutil' when compiling object files.
179  for (const auto &Input : Inputs)
180  if (Input.getType() != types::TY_Object)
181  return true;
182 
183  return false;
184 }
185 
186 /// Pass -no_deduplicate to ld64 under certain conditions:
187 ///
188 /// - Either -O0 or -O1 is explicitly specified
189 /// - No -O option is specified *and* this is a compile+link (implicit -O0)
190 ///
191 /// Also do *not* add -no_deduplicate when no -O option is specified and this
192 /// is just a link (we can't imply -O0)
193 static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
194  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
195  if (A->getOption().matches(options::OPT_O0))
196  return true;
197  if (A->getOption().matches(options::OPT_O))
198  return llvm::StringSwitch<bool>(A->getValue())
199  .Case("1", true)
200  .Default(false);
201  return false; // OPT_Ofast & OPT_O4
202  }
203 
204  if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
205  return true;
206  return false;
207 }
208 
209 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
210  ArgStringList &CmdArgs,
211  const InputInfoList &Inputs,
212  VersionTuple Version, bool LinkerIsLLD) const {
213  const Driver &D = getToolChain().getDriver();
214  const toolchains::MachO &MachOTC = getMachOToolChain();
215 
216  // Newer linkers support -demangle. Pass it if supported and not disabled by
217  // the user.
218  if ((Version >= VersionTuple(100) || LinkerIsLLD) &&
219  !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
220  CmdArgs.push_back("-demangle");
221 
222  if (Args.hasArg(options::OPT_rdynamic) &&
223  (Version >= VersionTuple(137) || LinkerIsLLD))
224  CmdArgs.push_back("-export_dynamic");
225 
226  // If we are using App Extension restrictions, pass a flag to the linker
227  // telling it that the compiled code has been audited.
228  if (Args.hasFlag(options::OPT_fapplication_extension,
229  options::OPT_fno_application_extension, false))
230  CmdArgs.push_back("-application_extension");
231 
232  if (D.isUsingLTO() && (Version >= VersionTuple(116) || LinkerIsLLD) &&
233  NeedsTempPath(Inputs)) {
234  std::string TmpPathName;
235  if (D.getLTOMode() == LTOK_Full) {
236  // If we are using full LTO, then automatically create a temporary file
237  // path for the linker to use, so that it's lifetime will extend past a
238  // possible dsymutil step.
239  TmpPathName =
240  D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object));
241  } else if (D.getLTOMode() == LTOK_Thin)
242  // If we are using thin LTO, then create a directory instead.
243  TmpPathName = D.GetTemporaryDirectory("thinlto");
244 
245  if (!TmpPathName.empty()) {
246  auto *TmpPath = C.getArgs().MakeArgString(TmpPathName);
247  C.addTempFile(TmpPath);
248  CmdArgs.push_back("-object_path_lto");
249  CmdArgs.push_back(TmpPath);
250  }
251  }
252 
253  // Use -lto_library option to specify the libLTO.dylib path. Try to find
254  // it in clang installed libraries. ld64 will only look at this argument
255  // when it actually uses LTO, so libLTO.dylib only needs to exist at link
256  // time if ld64 decides that it needs to use LTO.
257  // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
258  // next to it. That's ok since ld64 using a libLTO.dylib not matching the
259  // clang version won't work anyways.
260  // lld is built at the same revision as clang and statically links in
261  // LLVM libraries, so it doesn't need libLTO.dylib.
262  if (Version >= VersionTuple(133) && !LinkerIsLLD) {
263  // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
264  StringRef P = llvm::sys::path::parent_path(D.Dir);
265  SmallString<128> LibLTOPath(P);
266  llvm::sys::path::append(LibLTOPath, "lib");
267  llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
268  CmdArgs.push_back("-lto_library");
269  CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
270  }
271 
272  // ld64 version 262 and above runs the deduplicate pass by default.
273  // FIXME: lld doesn't dedup by default. Should we pass `--icf=safe`
274  // if `!shouldLinkerNotDedup()` if LinkerIsLLD here?
275  if (Version >= VersionTuple(262) &&
276  shouldLinkerNotDedup(C.getJobs().empty(), Args))
277  CmdArgs.push_back("-no_deduplicate");
278 
279  // Derived from the "link" spec.
280  Args.AddAllArgs(CmdArgs, options::OPT_static);
281  if (!Args.hasArg(options::OPT_static))
282  CmdArgs.push_back("-dynamic");
283  if (Args.hasArg(options::OPT_fgnu_runtime)) {
284  // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
285  // here. How do we wish to handle such things?
286  }
287 
288  if (!Args.hasArg(options::OPT_dynamiclib)) {
289  AddMachOArch(Args, CmdArgs);
290  // FIXME: Why do this only on this path?
291  Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
292 
293  Args.AddLastArg(CmdArgs, options::OPT_bundle);
294  Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
295  Args.AddAllArgs(CmdArgs, options::OPT_client__name);
296 
297  Arg *A;
298  if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
299  (A = Args.getLastArg(options::OPT_current__version)) ||
300  (A = Args.getLastArg(options::OPT_install__name)))
301  D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
302  << "-dynamiclib";
303 
304  Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
305  Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
306  Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
307  } else {
308  CmdArgs.push_back("-dylib");
309 
310  Arg *A;
311  if ((A = Args.getLastArg(options::OPT_bundle)) ||
312  (A = Args.getLastArg(options::OPT_bundle__loader)) ||
313  (A = Args.getLastArg(options::OPT_client__name)) ||
314  (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
315  (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
316  (A = Args.getLastArg(options::OPT_private__bundle)))
317  D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
318  << "-dynamiclib";
319 
320  Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
321  "-dylib_compatibility_version");
322  Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
323  "-dylib_current_version");
324 
325  AddMachOArch(Args, CmdArgs);
326 
327  Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
328  "-dylib_install_name");
329  }
330 
331  Args.AddLastArg(CmdArgs, options::OPT_all__load);
332  Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
333  Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
334  if (MachOTC.isTargetIOSBased())
335  Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
336  Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
337  Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
338  Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
339  Args.AddLastArg(CmdArgs, options::OPT_dynamic);
340  Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
341  Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
342  Args.AddAllArgs(CmdArgs, options::OPT_force__load);
343  Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
344  Args.AddAllArgs(CmdArgs, options::OPT_image__base);
345  Args.AddAllArgs(CmdArgs, options::OPT_init);
346 
347  // Add the deployment target.
348  if (Version >= VersionTuple(520) || LinkerIsLLD)
349  MachOTC.addPlatformVersionArgs(Args, CmdArgs);
350  else
351  MachOTC.addMinVersionArgs(Args, CmdArgs);
352 
353  Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
354  Args.AddLastArg(CmdArgs, options::OPT_multi__module);
355  Args.AddLastArg(CmdArgs, options::OPT_single__module);
356  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
357  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
358 
359  if (const Arg *A =
360  Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
361  options::OPT_fno_pie, options::OPT_fno_PIE)) {
362  if (A->getOption().matches(options::OPT_fpie) ||
363  A->getOption().matches(options::OPT_fPIE))
364  CmdArgs.push_back("-pie");
365  else
366  CmdArgs.push_back("-no_pie");
367  }
368 
369  // for embed-bitcode, use -bitcode_bundle in linker command
370  if (C.getDriver().embedBitcodeEnabled()) {
371  // Check if the toolchain supports bitcode build flow.
372  if (MachOTC.SupportsEmbeddedBitcode()) {
373  CmdArgs.push_back("-bitcode_bundle");
374  // FIXME: Pass this if LinkerIsLLD too, once it implements this flag.
375  if (C.getDriver().embedBitcodeMarkerOnly() &&
376  Version >= VersionTuple(278)) {
377  CmdArgs.push_back("-bitcode_process_mode");
378  CmdArgs.push_back("marker");
379  }
380  } else
381  D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
382  }
383 
384  // If GlobalISel is enabled, pass it through to LLVM.
385  if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
386  options::OPT_fno_global_isel)) {
387  if (A->getOption().matches(options::OPT_fglobal_isel)) {
388  CmdArgs.push_back("-mllvm");
389  CmdArgs.push_back("-global-isel");
390  // Disable abort and fall back to SDAG silently.
391  CmdArgs.push_back("-mllvm");
392  CmdArgs.push_back("-global-isel-abort=0");
393  }
394  }
395 
396  Args.AddLastArg(CmdArgs, options::OPT_prebind);
397  Args.AddLastArg(CmdArgs, options::OPT_noprebind);
398  Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
399  Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
400  Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
401  Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
402  Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
403  Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
404  Args.AddAllArgs(CmdArgs, options::OPT_segprot);
405  Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
406  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
407  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
408  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
409  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
410  Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
411  Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
412 
413  // Give --sysroot= preference, over the Apple specific behavior to also use
414  // --isysroot as the syslibroot.
415  StringRef sysroot = C.getSysRoot();
416  if (sysroot != "") {
417  CmdArgs.push_back("-syslibroot");
418  CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
419  } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
420  CmdArgs.push_back("-syslibroot");
421  CmdArgs.push_back(A->getValue());
422  }
423 
424  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
425  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
426  Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
427  Args.AddAllArgs(CmdArgs, options::OPT_undefined);
428  Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
429  Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
430  Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
431  Args.AddAllArgs(CmdArgs, options::OPT_y);
432  Args.AddLastArg(CmdArgs, options::OPT_w);
433  Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
434  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
435  Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
436  Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
437  Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
438  Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
439  Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
440  Args.AddLastArg(CmdArgs, options::OPT_why_load);
441  Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
442  Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
443  Args.AddLastArg(CmdArgs, options::OPT_dylinker);
444  Args.AddLastArg(CmdArgs, options::OPT_Mach);
445 }
446 
447 /// Determine whether we are linking the ObjC runtime.
448 static bool isObjCRuntimeLinked(const ArgList &Args) {
449  if (isObjCAutoRefCount(Args)) {
450  Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
451  return true;
452  }
453  return Args.hasArg(options::OPT_fobjc_link_runtime);
454 }
455 
456 static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
457  const llvm::Triple &Triple) {
458  // When enabling remarks, we need to error if:
459  // * The remark file is specified but we're targeting multiple architectures,
460  // which means more than one remark file is being generated.
462  Args.getAllArgValues(options::OPT_arch).size() > 1;
463  bool hasExplicitOutputFile =
464  Args.getLastArg(options::OPT_foptimization_record_file_EQ);
465  if (hasMultipleInvocations && hasExplicitOutputFile) {
466  D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
467  << "-foptimization-record-file";
468  return false;
469  }
470  return true;
471 }
472 
473 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
474  const llvm::Triple &Triple,
475  const InputInfo &Output, const JobAction &JA) {
476  StringRef Format = "yaml";
477  if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
478  Format = A->getValue();
479 
480  CmdArgs.push_back("-mllvm");
481  CmdArgs.push_back("-lto-pass-remarks-output");
482  CmdArgs.push_back("-mllvm");
483 
484  const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
485  if (A) {
486  CmdArgs.push_back(A->getValue());
487  } else {
488  assert(Output.isFilename() && "Unexpected ld output.");
490  F = Output.getFilename();
491  F += ".opt.";
492  F += Format;
493 
494  CmdArgs.push_back(Args.MakeArgString(F));
495  }
496 
497  if (const Arg *A =
498  Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
499  CmdArgs.push_back("-mllvm");
500  std::string Passes =
501  std::string("-lto-pass-remarks-filter=") + A->getValue();
502  CmdArgs.push_back(Args.MakeArgString(Passes));
503  }
504 
505  if (!Format.empty()) {
506  CmdArgs.push_back("-mllvm");
507  Twine FormatArg = Twine("-lto-pass-remarks-format=") + Format;
508  CmdArgs.push_back(Args.MakeArgString(FormatArg));
509  }
510 
511  if (getLastProfileUseArg(Args)) {
512  CmdArgs.push_back("-mllvm");
513  CmdArgs.push_back("-lto-pass-remarks-with-hotness");
514 
515  if (const Arg *A =
516  Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
517  CmdArgs.push_back("-mllvm");
518  std::string Opt =
519  std::string("-lto-pass-remarks-hotness-threshold=") + A->getValue();
520  CmdArgs.push_back(Args.MakeArgString(Opt));
521  }
522  }
523 }
524 
526  const InputInfo &Output,
527  const InputInfoList &Inputs,
528  const ArgList &Args,
529  const char *LinkingOutput) const {
530  assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
531 
532  // If the number of arguments surpasses the system limits, we will encode the
533  // input files in a separate file, shortening the command line. To this end,
534  // build a list of input file names that can be passed via a file with the
535  // -filelist linker option.
536  llvm::opt::ArgStringList InputFileList;
537 
538  // The logic here is derived from gcc's behavior; most of which
539  // comes from specs (starting with link_command). Consult gcc for
540  // more information.
541  ArgStringList CmdArgs;
542 
543  /// Hack(tm) to ignore linking errors when we are doing ARC migration.
544  if (Args.hasArg(options::OPT_ccc_arcmt_check,
545  options::OPT_ccc_arcmt_migrate)) {
546  for (const auto &Arg : Args)
547  Arg->claim();
548  const char *Exec =
549  Args.MakeArgString(getToolChain().GetProgramPath("touch"));
550  CmdArgs.push_back(Output.getFilename());
551  C.addCommand(std::make_unique<Command>(
552  JA, *this, ResponseFileSupport::None(), Exec, CmdArgs, None, Output));
553  return;
554  }
555 
556  VersionTuple Version = getMachOToolChain().getLinkerVersion(Args);
557 
558  bool LinkerIsLLD;
559  const char *Exec =
560  Args.MakeArgString(getToolChain().GetLinkerPath(&LinkerIsLLD));
561 
562  // I'm not sure why this particular decomposition exists in gcc, but
563  // we follow suite for ease of comparison.
564  AddLinkArgs(C, Args, CmdArgs, Inputs, Version, LinkerIsLLD);
565 
566  if (willEmitRemarks(Args) &&
567  checkRemarksOptions(getToolChain().getDriver(), Args,
568  getToolChain().getTriple()))
569  renderRemarksOptions(Args, CmdArgs, getToolChain().getTriple(), Output, JA);
570 
571  // Propagate the -moutline flag to the linker in LTO.
572  if (Arg *A =
573  Args.getLastArg(options::OPT_moutline, options::OPT_mno_outline)) {
574  if (A->getOption().matches(options::OPT_moutline)) {
575  if (getMachOToolChain().getMachOArchName(Args) == "arm64") {
576  CmdArgs.push_back("-mllvm");
577  CmdArgs.push_back("-enable-machine-outliner");
578 
579  // Outline from linkonceodr functions by default in LTO.
580  CmdArgs.push_back("-mllvm");
581  CmdArgs.push_back("-enable-linkonceodr-outlining");
582  }
583  } else {
584  // Disable all outlining behaviour if we have mno-outline. We need to do
585  // this explicitly, because targets which support default outlining will
586  // try to do work if we don't.
587  CmdArgs.push_back("-mllvm");
588  CmdArgs.push_back("-enable-machine-outliner=never");
589  }
590  }
591 
592  // Setup statistics file output.
593  SmallString<128> StatsFile =
594  getStatsFileName(Args, Output, Inputs[0], getToolChain().getDriver());
595  if (!StatsFile.empty()) {
596  CmdArgs.push_back("-mllvm");
597  CmdArgs.push_back(Args.MakeArgString("-lto-stats-file=" + StatsFile.str()));
598  }
599 
600  // It seems that the 'e' option is completely ignored for dynamic executables
601  // (the default), and with static executables, the last one wins, as expected.
602  Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
603  options::OPT_Z_Flag, options::OPT_u_Group,
604  options::OPT_e, options::OPT_r});
605 
606  // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
607  // members of static archive libraries which implement Objective-C classes or
608  // categories.
609  if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
610  CmdArgs.push_back("-ObjC");
611 
612  CmdArgs.push_back("-o");
613  CmdArgs.push_back(Output.getFilename());
614 
615  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
616  getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
617 
618  Args.AddAllArgs(CmdArgs, options::OPT_L);
619 
620  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
621  // Build the input file for -filelist (list of linker input files) in case we
622  // need it later
623  for (const auto &II : Inputs) {
624  if (!II.isFilename()) {
625  // This is a linker input argument.
626  // We cannot mix input arguments and file names in a -filelist input, thus
627  // we prematurely stop our list (remaining files shall be passed as
628  // arguments).
629  if (InputFileList.size() > 0)
630  break;
631 
632  continue;
633  }
634 
635  InputFileList.push_back(II.getFilename());
636  }
637 
638  // Additional linker set-up and flags for Fortran. This is required in order
639  // to generate executables.
640  //
641  // NOTE: Generating executables by Flang is considered an "experimental"
642  // feature and hence this is guarded with a command line option.
643  // TODO: Make this work unconditionally once Flang is mature enough.
644  if (getToolChain().getDriver().IsFlangMode() &&
645  Args.hasArg(options::OPT_flang_experimental_exec)) {
646  addFortranRuntimeLibraryPath(getToolChain(), Args, CmdArgs);
647  addFortranRuntimeLibs(CmdArgs);
648  }
649 
650  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
651  addOpenMPRuntime(CmdArgs, getToolChain(), Args);
652 
653  if (isObjCRuntimeLinked(Args) &&
654  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
655  // We use arclite library for both ARC and subscripting support.
656  getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
657 
658  CmdArgs.push_back("-framework");
659  CmdArgs.push_back("Foundation");
660  // Link libobj.
661  CmdArgs.push_back("-lobjc");
662  }
663 
664  if (LinkingOutput) {
665  CmdArgs.push_back("-arch_multiple");
666  CmdArgs.push_back("-final_output");
667  CmdArgs.push_back(LinkingOutput);
668  }
669 
670  if (Args.hasArg(options::OPT_fnested_functions))
671  CmdArgs.push_back("-allow_stack_execute");
672 
673  getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
674 
675  StringRef Parallelism = getLTOParallelism(Args, getToolChain().getDriver());
676  if (!Parallelism.empty()) {
677  CmdArgs.push_back("-mllvm");
678  unsigned NumThreads =
679  llvm::get_threadpool_strategy(Parallelism)->compute_thread_count();
680  CmdArgs.push_back(Args.MakeArgString("-threads=" + Twine(NumThreads)));
681  }
682 
683  if (getToolChain().ShouldLinkCXXStdlib(Args))
684  getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
685 
686  bool NoStdOrDefaultLibs =
687  Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
688  bool ForceLinkBuiltins = Args.hasArg(options::OPT_fapple_link_rtlib);
689  if (!NoStdOrDefaultLibs || ForceLinkBuiltins) {
690  // link_ssp spec is empty.
691 
692  // If we have both -nostdlib/nodefaultlibs and -fapple-link-rtlib then
693  // we just want to link the builtins, not the other libs like libSystem.
694  if (NoStdOrDefaultLibs && ForceLinkBuiltins) {
695  getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs, "builtins");
696  } else {
697  // Let the tool chain choose which runtime library to link.
698  getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs,
699  ForceLinkBuiltins);
700 
701  // No need to do anything for pthreads. Claim argument to avoid warning.
702  Args.ClaimAllArgs(options::OPT_pthread);
703  Args.ClaimAllArgs(options::OPT_pthreads);
704  }
705  }
706 
707  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
708  // endfile_spec is empty.
709  }
710 
711  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
712  Args.AddAllArgs(CmdArgs, options::OPT_F);
713 
714  // -iframework should be forwarded as -F.
715  for (const Arg *A : Args.filtered(options::OPT_iframework))
716  CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
717 
718  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
719  if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
720  if (A->getValue() == StringRef("Accelerate")) {
721  CmdArgs.push_back("-framework");
722  CmdArgs.push_back("Accelerate");
723  }
724  }
725  }
726 
727  // DriverKit's framework doesn't have the same layout as other frameworks.
728  // Add missing search paths if necessary.
729  if (getToolChain().getTriple().getOS() == llvm::Triple::DriverKit) {
730  if (const Arg *Root = Args.getLastArg(options::OPT_isysroot)) {
731  // ld64 fixed the implicit -F and -L paths in ld64-605.1+.
732  if (Version.getMajor() < 605 ||
733  (Version.getMajor() == 605 && Version.getMinor().getValueOr(0) < 1)) {
734 
735  SmallString<128> L(Root->getValue());
736  llvm::sys::path::append(L, "System", "DriverKit", "usr", "lib");
737  CmdArgs.push_back(Args.MakeArgString(std::string("-L") + L));
738 
739  SmallString<128> F(Root->getValue());
740  llvm::sys::path::append(F, "System", "DriverKit");
741  llvm::sys::path::append(F, "System", "Library", "Frameworks");
742  CmdArgs.push_back(Args.MakeArgString(std::string("-F") + F));
743  }
744  }
745  }
746 
747  ResponseFileSupport ResponseSupport;
748  if (Version >= VersionTuple(705) || LinkerIsLLD) {
749  ResponseSupport = ResponseFileSupport::AtFileUTF8();
750  } else {
751  // For older versions of the linker, use the legacy filelist method instead.
752  ResponseSupport = {ResponseFileSupport::RF_FileList, llvm::sys::WEM_UTF8,
753  "-filelist"};
754  }
755 
756  std::unique_ptr<Command> Cmd = std::make_unique<Command>(
757  JA, *this, ResponseSupport, Exec, CmdArgs, Inputs, Output);
758  Cmd->setInputFileList(std::move(InputFileList));
759  C.addCommand(std::move(Cmd));
760 }
761 
763  const InputInfo &Output,
764  const InputInfoList &Inputs,
765  const ArgList &Args,
766  const char *LinkingOutput) const {
767  const Driver &D = getToolChain().getDriver();
768 
769  // Silence warning for "clang -g foo.o -o foo"
770  Args.ClaimAllArgs(options::OPT_g_Group);
771  // and "clang -emit-llvm foo.o -o foo"
772  Args.ClaimAllArgs(options::OPT_emit_llvm);
773  // and for "clang -w foo.o -o foo". Other warning options are already
774  // handled somewhere else.
775  Args.ClaimAllArgs(options::OPT_w);
776  // Silence warnings when linking C code with a C++ '-stdlib' argument.
777  Args.ClaimAllArgs(options::OPT_stdlib_EQ);
778 
779  // libtool <options> <output_file> <input_files>
780  ArgStringList CmdArgs;
781  // Create and insert file members with a deterministic index.
782  CmdArgs.push_back("-static");
783  CmdArgs.push_back("-D");
784  CmdArgs.push_back("-no_warning_for_no_symbols");
785  CmdArgs.push_back("-o");
786  CmdArgs.push_back(Output.getFilename());
787 
788  for (const auto &II : Inputs) {
789  if (II.isFilename()) {
790  CmdArgs.push_back(II.getFilename());
791  }
792  }
793 
794  // Delete old output archive file if it already exists before generating a new
795  // archive file.
796  const auto *OutputFileName = Output.getFilename();
797  if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) {
798  if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) {
799  D.Diag(diag::err_drv_unable_to_remove_file) << EC.message();
800  return;
801  }
802  }
803 
804  const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
805  C.addCommand(std::make_unique<Command>(JA, *this,
807  Exec, CmdArgs, Inputs, Output));
808 }
809 
811  const InputInfo &Output,
812  const InputInfoList &Inputs,
813  const ArgList &Args,
814  const char *LinkingOutput) const {
815  ArgStringList CmdArgs;
816 
817  CmdArgs.push_back("-create");
818  assert(Output.isFilename() && "Unexpected lipo output.");
819 
820  CmdArgs.push_back("-output");
821  CmdArgs.push_back(Output.getFilename());
822 
823  for (const auto &II : Inputs) {
824  assert(II.isFilename() && "Unexpected lipo input.");
825  CmdArgs.push_back(II.getFilename());
826  }
827 
828  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
829  C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
830  Exec, CmdArgs, Inputs, Output));
831 }
832 
834  const InputInfo &Output,
835  const InputInfoList &Inputs,
836  const ArgList &Args,
837  const char *LinkingOutput) const {
838  ArgStringList CmdArgs;
839 
840  CmdArgs.push_back("-o");
841  CmdArgs.push_back(Output.getFilename());
842 
843  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
844  const InputInfo &Input = Inputs[0];
845  assert(Input.isFilename() && "Unexpected dsymutil input.");
846  CmdArgs.push_back(Input.getFilename());
847 
848  const char *Exec =
849  Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
850  C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
851  Exec, CmdArgs, Inputs, Output));
852 }
853 
855  const InputInfo &Output,
856  const InputInfoList &Inputs,
857  const ArgList &Args,
858  const char *LinkingOutput) const {
859  ArgStringList CmdArgs;
860  CmdArgs.push_back("--verify");
861  CmdArgs.push_back("--debug-info");
862  CmdArgs.push_back("--eh-frame");
863  CmdArgs.push_back("--quiet");
864 
865  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
866  const InputInfo &Input = Inputs[0];
867  assert(Input.isFilename() && "Unexpected verify input");
868 
869  // Grabbing the output of the earlier dsymutil run.
870  CmdArgs.push_back(Input.getFilename());
871 
872  const char *Exec =
873  Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
874  C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
875  Exec, CmdArgs, Inputs, Output));
876 }
877 
878 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
879  : ToolChain(D, Triple, Args) {
880  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
881  getProgramPaths().push_back(getDriver().getInstalledDir());
882  if (getDriver().getInstalledDir() != getDriver().Dir)
883  getProgramPaths().push_back(getDriver().Dir);
884 }
885 
886 /// Darwin - Darwin tool chain for i386 and x86_64.
887 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
888  : MachO(D, Triple, Args), TargetInitialized(false),
889  CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) {}
890 
893 
894  // Darwin always preprocesses assembly files (unless -x is used explicitly).
895  if (Ty == types::TY_PP_Asm)
896  return types::TY_Asm;
897 
898  return Ty;
899 }
900 
901 bool MachO::HasNativeLLVMSupport() const { return true; }
902 
904  // Use libstdc++ on old targets (OSX < 10.9 and iOS < 7)
905  if ((isTargetMacOSBased() && isMacosxVersionLT(10, 9)) ||
908 
909  // On all other targets, use libc++
910  return ToolChain::CST_Libcxx;
911 }
912 
913 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
914 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
915  if (isTargetWatchOSBased())
917  if (isTargetIOSBased())
919  if (isNonFragile)
922 }
923 
924 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
927  return true;
928  else if (isTargetIOSBased())
929  return !isIPhoneOSVersionLT(3, 2);
930  else {
931  assert(isTargetMacOSBased() && "unexpected darwin target");
932  return !isMacosxVersionLT(10, 6);
933  }
934 }
935 
936 void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
937  ArgStringList &CC1Args) const {
938  CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
939 }
940 
941 void Darwin::AddHIPIncludeArgs(const ArgList &DriverArgs,
942  ArgStringList &CC1Args) const {
943  RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
944 }
945 
946 // This is just a MachO name translation routine and there's no
947 // way to join this into ARMTargetParser without breaking all
948 // other assumptions. Maybe MachO should consider standardising
949 // their nomenclature.
950 static const char *ArmMachOArchName(StringRef Arch) {
951  return llvm::StringSwitch<const char *>(Arch)
952  .Case("armv6k", "armv6")
953  .Case("armv6m", "armv6m")
954  .Case("armv5tej", "armv5")
955  .Case("xscale", "xscale")
956  .Case("armv4t", "armv4t")
957  .Case("armv7", "armv7")
958  .Cases("armv7a", "armv7-a", "armv7")
959  .Cases("armv7r", "armv7-r", "armv7")
960  .Cases("armv7em", "armv7e-m", "armv7em")
961  .Cases("armv7k", "armv7-k", "armv7k")
962  .Cases("armv7m", "armv7-m", "armv7m")
963  .Cases("armv7s", "armv7-s", "armv7s")
964  .Default(nullptr);
965 }
966 
967 static const char *ArmMachOArchNameCPU(StringRef CPU) {
968  llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
969  if (ArchKind == llvm::ARM::ArchKind::INVALID)
970  return nullptr;
971  StringRef Arch = llvm::ARM::getArchName(ArchKind);
972 
973  // FIXME: Make sure this MachO triple mangling is really necessary.
974  // ARMv5* normalises to ARMv5.
975  if (Arch.startswith("armv5"))
976  Arch = Arch.substr(0, 5);
977  // ARMv6*, except ARMv6M, normalises to ARMv6.
978  else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
979  Arch = Arch.substr(0, 5);
980  // ARMv7A normalises to ARMv7.
981  else if (Arch.endswith("v7a"))
982  Arch = Arch.substr(0, 5);
983  return Arch.data();
984 }
985 
986 StringRef MachO::getMachOArchName(const ArgList &Args) const {
987  switch (getTriple().getArch()) {
988  default:
990 
991  case llvm::Triple::aarch64_32:
992  return "arm64_32";
993 
994  case llvm::Triple::aarch64: {
995  if (getTriple().isArm64e())
996  return "arm64e";
997  return "arm64";
998  }
999 
1000  case llvm::Triple::thumb:
1001  case llvm::Triple::arm:
1002  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ))
1003  if (const char *Arch = ArmMachOArchName(A->getValue()))
1004  return Arch;
1005 
1006  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1007  if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
1008  return Arch;
1009 
1010  return "arm";
1011  }
1012 }
1013 
1014 VersionTuple MachO::getLinkerVersion(const llvm::opt::ArgList &Args) const {
1015  if (LinkerVersion) {
1016 #ifndef NDEBUG
1017  VersionTuple NewLinkerVersion;
1018  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ))
1019  (void)NewLinkerVersion.tryParse(A->getValue());
1020  assert(NewLinkerVersion == LinkerVersion);
1021 #endif
1022  return *LinkerVersion;
1023  }
1024 
1025  VersionTuple NewLinkerVersion;
1026  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ))
1027  if (NewLinkerVersion.tryParse(A->getValue()))
1028  getDriver().Diag(diag::err_drv_invalid_version_number)
1029  << A->getAsString(Args);
1030 
1031  LinkerVersion = NewLinkerVersion;
1032  return *LinkerVersion;
1033 }
1034 
1036 
1038 
1040  types::ID InputType) const {
1041  llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
1042 
1043  // If the target isn't initialized (e.g., an unknown Darwin platform, return
1044  // the default triple).
1045  if (!isTargetInitialized())
1046  return Triple.getTriple();
1047 
1048  SmallString<16> Str;
1049  if (isTargetWatchOSBased())
1050  Str += "watchos";
1051  else if (isTargetTvOSBased())
1052  Str += "tvos";
1053  else if (isTargetDriverKit())
1054  Str += "driverkit";
1055  else if (isTargetIOSBased() || isTargetMacCatalyst())
1056  Str += "ios";
1057  else
1058  Str += "macosx";
1059  Str += getTripleTargetVersion().getAsString();
1060  Triple.setOSName(Str);
1061 
1062  return Triple.getTriple();
1063 }
1064 
1066  switch (AC) {
1067  case Action::LipoJobClass:
1068  if (!Lipo)
1069  Lipo.reset(new tools::darwin::Lipo(*this));
1070  return Lipo.get();
1072  if (!Dsymutil)
1073  Dsymutil.reset(new tools::darwin::Dsymutil(*this));
1074  return Dsymutil.get();
1076  if (!VerifyDebug)
1077  VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
1078  return VerifyDebug.get();
1079  default:
1080  return ToolChain::getTool(AC);
1081  }
1082 }
1083 
1084 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
1085 
1087  return new tools::darwin::StaticLibTool(*this);
1088 }
1089 
1091  return new tools::darwin::Assembler(*this);
1092 }
1093 
1094 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
1095  const ArgList &Args)
1096  : Darwin(D, Triple, Args) {}
1097 
1098 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
1099  // Always error about undefined 'TARGET_OS_*' macros.
1100  CC1Args.push_back("-Wundef-prefix=TARGET_OS_");
1101  CC1Args.push_back("-Werror=undef-prefix");
1102 
1103  // For modern targets, promote certain warnings to errors.
1104  if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
1105  // Always enable -Wdeprecated-objc-isa-usage and promote it
1106  // to an error.
1107  CC1Args.push_back("-Wdeprecated-objc-isa-usage");
1108  CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
1109 
1110  // For iOS and watchOS, also error about implicit function declarations,
1111  // as that can impact calling conventions.
1112  if (!isTargetMacOS())
1113  CC1Args.push_back("-Werror=implicit-function-declaration");
1114  }
1115 }
1116 
1117 /// Take a path that speculatively points into Xcode and return the
1118 /// `XCODE/Contents/Developer` path if it is an Xcode path, or an empty path
1119 /// otherwise.
1120 static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode) {
1121  static constexpr llvm::StringLiteral XcodeAppSuffix(
1122  ".app/Contents/Developer");
1123  size_t Index = PathIntoXcode.find(XcodeAppSuffix);
1124  if (Index == StringRef::npos)
1125  return "";
1126  return PathIntoXcode.take_front(Index + XcodeAppSuffix.size());
1127 }
1128 
1129 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
1130  ArgStringList &CmdArgs) const {
1131  // Avoid linking compatibility stubs on i386 mac.
1132  if (isTargetMacOSBased() && getArch() == llvm::Triple::x86)
1133  return;
1135  return;
1136  // ARC runtime is supported everywhere on arm64e.
1137  if (getTriple().isArm64e())
1138  return;
1139 
1140  ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
1141 
1142  if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
1143  runtime.hasSubscripting())
1144  return;
1145 
1146  SmallString<128> P(getDriver().ClangExecutable);
1147  llvm::sys::path::remove_filename(P); // 'clang'
1148  llvm::sys::path::remove_filename(P); // 'bin'
1149 
1150  // 'libarclite' usually lives in the same toolchain as 'clang'. However, the
1151  // Swift open source toolchains for macOS distribute Clang without libarclite.
1152  // In that case, to allow the linker to find 'libarclite', we point to the
1153  // 'libarclite' in the XcodeDefault toolchain instead.
1154  if (getXcodeDeveloperPath(P).empty()) {
1155  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1156  // Try to infer the path to 'libarclite' in the toolchain from the
1157  // specified SDK path.
1158  StringRef XcodePathForSDK = getXcodeDeveloperPath(A->getValue());
1159  if (!XcodePathForSDK.empty()) {
1160  P = XcodePathForSDK;
1161  llvm::sys::path::append(P, "Toolchains/XcodeDefault.xctoolchain/usr");
1162  }
1163  }
1164  }
1165 
1166  CmdArgs.push_back("-force_load");
1167  llvm::sys::path::append(P, "lib", "arc", "libarclite_");
1168  // Mash in the platform.
1170  P += "watchsimulator";
1171  else if (isTargetWatchOS())
1172  P += "watchos";
1173  else if (isTargetTvOSSimulator())
1174  P += "appletvsimulator";
1175  else if (isTargetTvOS())
1176  P += "appletvos";
1177  else if (isTargetIOSSimulator())
1178  P += "iphonesimulator";
1179  else if (isTargetIPhoneOS())
1180  P += "iphoneos";
1181  else
1182  P += "macosx";
1183  P += ".a";
1184 
1185  CmdArgs.push_back(Args.MakeArgString(P));
1186 }
1187 
1189  // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
1190  if ((isTargetMacOSBased() && isMacosxVersionLT(10, 11)) ||
1192  return 2;
1193  return 4;
1194 }
1195 
1196 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
1197  StringRef Component, RuntimeLinkOptions Opts,
1198  bool IsShared) const {
1199  SmallString<64> DarwinLibName = StringRef("libclang_rt.");
1200  // an Darwin the builtins compomnent is not in the library name
1201  if (Component != "builtins") {
1202  DarwinLibName += Component;
1203  if (!(Opts & RLO_IsEmbedded))
1204  DarwinLibName += "_";
1205  }
1206 
1207  DarwinLibName += getOSLibraryNameSuffix();
1208  DarwinLibName += IsShared ? "_dynamic.dylib" : ".a";
1209  SmallString<128> Dir(getDriver().ResourceDir);
1210  llvm::sys::path::append(Dir, "lib", "darwin");
1211  if (Opts & RLO_IsEmbedded)
1212  llvm::sys::path::append(Dir, "macho_embedded");
1213 
1214  SmallString<128> P(Dir);
1215  llvm::sys::path::append(P, DarwinLibName);
1216 
1217  // For now, allow missing resource libraries to support developers who may
1218  // not have compiler-rt checked out or integrated into their build (unless
1219  // we explicitly force linking with this library).
1220  if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) {
1221  const char *LibArg = Args.MakeArgString(P);
1222  CmdArgs.push_back(LibArg);
1223  }
1224 
1225  // Adding the rpaths might negatively interact when other rpaths are involved,
1226  // so we should make sure we add the rpaths last, after all user-specified
1227  // rpaths. This is currently true from this place, but we need to be
1228  // careful if this function is ever called before user's rpaths are emitted.
1229  if (Opts & RLO_AddRPath) {
1230  assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
1231 
1232  // Add @executable_path to rpath to support having the dylib copied with
1233  // the executable.
1234  CmdArgs.push_back("-rpath");
1235  CmdArgs.push_back("@executable_path");
1236 
1237  // Add the path to the resource dir to rpath to support using the dylib
1238  // from the default location without copying.
1239  CmdArgs.push_back("-rpath");
1240  CmdArgs.push_back(Args.MakeArgString(Dir));
1241  }
1242 }
1243 
1244 StringRef Darwin::getPlatformFamily() const {
1245  switch (TargetPlatform) {
1246  case DarwinPlatformKind::MacOS:
1247  return "MacOSX";
1248  case DarwinPlatformKind::IPhoneOS:
1250  return "MacOSX";
1251  return "iPhone";
1252  case DarwinPlatformKind::TvOS:
1253  return "AppleTV";
1254  case DarwinPlatformKind::WatchOS:
1255  return "Watch";
1256  case DarwinPlatformKind::DriverKit:
1257  return "DriverKit";
1258  }
1259  llvm_unreachable("Unsupported platform");
1260 }
1261 
1262 StringRef Darwin::getSDKName(StringRef isysroot) {
1263  // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
1264  auto BeginSDK = llvm::sys::path::rbegin(isysroot);
1265  auto EndSDK = llvm::sys::path::rend(isysroot);
1266  for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
1267  StringRef SDK = *IT;
1268  if (SDK.endswith(".sdk"))
1269  return SDK.slice(0, SDK.size() - 4);
1270  }
1271  return "";
1272 }
1273 
1274 StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
1275  switch (TargetPlatform) {
1276  case DarwinPlatformKind::MacOS:
1277  return "osx";
1278  case DarwinPlatformKind::IPhoneOS:
1280  return "osx";
1281  return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
1282  : "iossim";
1283  case DarwinPlatformKind::TvOS:
1284  return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
1285  : "tvossim";
1286  case DarwinPlatformKind::WatchOS:
1287  return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
1288  : "watchossim";
1289  case DarwinPlatformKind::DriverKit:
1290  return "driverkit";
1291  }
1292  llvm_unreachable("Unsupported platform");
1293 }
1294 
1295 /// Check if the link command contains a symbol export directive.
1296 static bool hasExportSymbolDirective(const ArgList &Args) {
1297  for (Arg *A : Args) {
1298  if (A->getOption().matches(options::OPT_exported__symbols__list))
1299  return true;
1300  if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
1301  !A->getOption().matches(options::OPT_Xlinker))
1302  continue;
1303  if (A->containsValue("-exported_symbols_list") ||
1304  A->containsValue("-exported_symbol"))
1305  return true;
1306  }
1307  return false;
1308 }
1309 
1310 /// Add an export directive for \p Symbol to the link command.
1311 static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
1312  CmdArgs.push_back("-exported_symbol");
1313  CmdArgs.push_back(Symbol);
1314 }
1315 
1316 /// Add a sectalign directive for \p Segment and \p Section to the maximum
1317 /// expected page size for Darwin.
1318 ///
1319 /// On iPhone 6+ the max supported page size is 16K. On macOS, the max is 4K.
1320 /// Use a common alignment constant (16K) for now, and reduce the alignment on
1321 /// macOS if it proves important.
1322 static void addSectalignToPage(const ArgList &Args, ArgStringList &CmdArgs,
1323  StringRef Segment, StringRef Section) {
1324  for (const char *A : {"-sectalign", Args.MakeArgString(Segment),
1325  Args.MakeArgString(Section), "0x4000"})
1326  CmdArgs.push_back(A);
1327 }
1328 
1329 void Darwin::addProfileRTLibs(const ArgList &Args,
1330  ArgStringList &CmdArgs) const {
1331  if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1332  return;
1333 
1334  AddLinkRuntimeLib(Args, CmdArgs, "profile",
1336 
1337  bool ForGCOV = needsGCovInstrumentation(Args);
1338 
1339  // If we have a symbol export directive and we're linking in the profile
1340  // runtime, automatically export symbols necessary to implement some of the
1341  // runtime's functionality.
1342  if (hasExportSymbolDirective(Args)) {
1343  if (ForGCOV) {
1344  addExportedSymbol(CmdArgs, "___gcov_dump");
1345  addExportedSymbol(CmdArgs, "___gcov_reset");
1346  addExportedSymbol(CmdArgs, "_writeout_fn_list");
1347  addExportedSymbol(CmdArgs, "_reset_fn_list");
1348  } else {
1349  addExportedSymbol(CmdArgs, "___llvm_profile_filename");
1350  addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
1351  }
1352  addExportedSymbol(CmdArgs, "_lprofDirMode");
1353  }
1354 
1355  // Align __llvm_prf_{cnts,data} sections to the maximum expected page
1356  // alignment. This allows profile counters to be mmap()'d to disk. Note that
1357  // it's not enough to just page-align __llvm_prf_cnts: the following section
1358  // must also be page-aligned so that its data is not clobbered by mmap().
1359  //
1360  // The section alignment is only needed when continuous profile sync is
1361  // enabled, but this is expected to be the default in Xcode. Specifying the
1362  // extra alignment also allows the same binary to be used with/without sync
1363  // enabled.
1364  if (!ForGCOV) {
1365  for (auto IPSK : {llvm::IPSK_cnts, llvm::IPSK_data}) {
1367  Args, CmdArgs, "__DATA",
1368  llvm::getInstrProfSectionName(IPSK, llvm::Triple::MachO,
1369  /*AddSegmentInfo=*/false));
1370  }
1371  }
1372 }
1373 
1374 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1375  ArgStringList &CmdArgs,
1376  StringRef Sanitizer,
1377  bool Shared) const {
1378  auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1379  AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
1380 }
1381 
1383  const ArgList &Args) const {
1384  if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1385  StringRef Value = A->getValue();
1386  if (Value != "compiler-rt")
1387  getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1388  << Value << "darwin";
1389  }
1390 
1392 }
1393 
1394 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1395  ArgStringList &CmdArgs,
1396  bool ForceLinkBuiltinRT) const {
1397  // Call once to ensure diagnostic is printed if wrong value was specified
1398  GetRuntimeLibType(Args);
1399 
1400  // Darwin doesn't support real static executables, don't link any runtime
1401  // libraries with -static.
1402  if (Args.hasArg(options::OPT_static) ||
1403  Args.hasArg(options::OPT_fapple_kext) ||
1404  Args.hasArg(options::OPT_mkernel)) {
1405  if (ForceLinkBuiltinRT)
1406  AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1407  return;
1408  }
1409 
1410  // Reject -static-libgcc for now, we can deal with this when and if someone
1411  // cares. This is useful in situations where someone wants to statically link
1412  // something like libstdc++, and needs its runtime support routines.
1413  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1414  getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1415  return;
1416  }
1417 
1418  const SanitizerArgs &Sanitize = getSanitizerArgs(Args);
1419  if (Sanitize.needsAsanRt())
1420  AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1421  if (Sanitize.needsLsanRt())
1422  AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
1423  if (Sanitize.needsUbsanRt())
1424  AddLinkSanitizerLibArgs(Args, CmdArgs,
1425  Sanitize.requiresMinimalRuntime() ? "ubsan_minimal"
1426  : "ubsan",
1427  Sanitize.needsSharedRt());
1428  if (Sanitize.needsTsanRt())
1429  AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1430  if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
1431  AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
1432 
1433  // Libfuzzer is written in C++ and requires libcxx.
1434  AddCXXStdlibLibArgs(Args, CmdArgs);
1435  }
1436  if (Sanitize.needsStatsRt()) {
1437  AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
1438  AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1439  }
1440 
1441  const XRayArgs &XRay = getXRayArgs();
1442  if (XRay.needsXRayRt()) {
1443  AddLinkRuntimeLib(Args, CmdArgs, "xray");
1444  AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
1445  AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
1446  }
1447 
1448  if (isTargetDriverKit() && !Args.hasArg(options::OPT_nodriverkitlib)) {
1449  CmdArgs.push_back("-framework");
1450  CmdArgs.push_back("DriverKit");
1451  }
1452 
1453  // Otherwise link libSystem, then the dynamic runtime library, and finally any
1454  // target specific static runtime library.
1455  if (!isTargetDriverKit())
1456  CmdArgs.push_back("-lSystem");
1457 
1458  // Select the dynamic runtime library and the target specific static library.
1459  if (isTargetIOSBased()) {
1460  // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
1461  // it never went into the SDK.
1462  // Linking against libgcc_s.1 isn't needed for iOS 5.0+
1463  if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
1464  getTriple().getArch() != llvm::Triple::aarch64)
1465  CmdArgs.push_back("-lgcc_s.1");
1466  }
1467  AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1468 }
1469 
1470 /// Returns the most appropriate macOS target version for the current process.
1471 ///
1472 /// If the macOS SDK version is the same or earlier than the system version,
1473 /// then the SDK version is returned. Otherwise the system version is returned.
1474 static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1475  unsigned Major, Minor, Micro;
1476  llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1477  if (!SystemTriple.isMacOSX())
1478  return std::string(MacOSSDKVersion);
1479  VersionTuple SystemVersion;
1480  SystemTriple.getMacOSXVersion(SystemVersion);
1481  bool HadExtra;
1482  if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
1483  HadExtra))
1484  return std::string(MacOSSDKVersion);
1485  VersionTuple SDKVersion(Major, Minor, Micro);
1486  if (SDKVersion > SystemVersion)
1487  return SystemVersion.getAsString();
1488  return std::string(MacOSSDKVersion);
1489 }
1490 
1491 namespace {
1492 
1493 /// The Darwin OS that was selected or inferred from arguments / environment.
1494 struct DarwinPlatform {
1495  enum SourceKind {
1496  /// The OS was specified using the -target argument.
1497  TargetArg,
1498  /// The OS was specified using the -mtargetos= argument.
1499  MTargetOSArg,
1500  /// The OS was specified using the -m<os>-version-min argument.
1501  OSVersionArg,
1502  /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1503  DeploymentTargetEnv,
1504  /// The OS was inferred from the SDK.
1505  InferredFromSDK,
1506  /// The OS was inferred from the -arch.
1507  InferredFromArch
1508  };
1509 
1510  using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1511  using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1512 
1513  DarwinPlatformKind getPlatform() const { return Platform; }
1514 
1515  DarwinEnvironmentKind getEnvironment() const { return Environment; }
1516 
1517  void setEnvironment(DarwinEnvironmentKind Kind) {
1518  Environment = Kind;
1519  InferSimulatorFromArch = false;
1520  }
1521 
1522  StringRef getOSVersion() const {
1523  if (Kind == OSVersionArg)
1524  return Argument->getValue();
1525  return OSVersion;
1526  }
1527 
1528  void setOSVersion(StringRef S) {
1529  assert(Kind == TargetArg && "Unexpected kind!");
1530  OSVersion = std::string(S);
1531  }
1532 
1533  bool hasOSVersion() const { return HasOSVersion; }
1534 
1535  VersionTuple getNativeTargetVersion() const {
1536  assert(Environment == DarwinEnvironmentKind::MacCatalyst &&
1537  "native target version is specified only for Mac Catalyst");
1538  return NativeTargetVersion;
1539  }
1540 
1541  /// Returns true if the target OS was explicitly specified.
1542  bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1543 
1544  /// Returns true if the simulator environment can be inferred from the arch.
1545  bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1546 
1547  const Optional<llvm::Triple> &getTargetVariantTriple() const {
1548  return TargetVariantTriple;
1549  }
1550 
1551  /// Adds the -m<os>-version-min argument to the compiler invocation.
1552  void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1553  if (Argument)
1554  return;
1555  assert(Kind != TargetArg && Kind != MTargetOSArg && Kind != OSVersionArg &&
1556  "Invalid kind");
1557  options::ID Opt;
1558  switch (Platform) {
1559  case DarwinPlatformKind::MacOS:
1560  Opt = options::OPT_mmacosx_version_min_EQ;
1561  break;
1562  case DarwinPlatformKind::IPhoneOS:
1563  Opt = options::OPT_miphoneos_version_min_EQ;
1564  break;
1565  case DarwinPlatformKind::TvOS:
1566  Opt = options::OPT_mtvos_version_min_EQ;
1567  break;
1568  case DarwinPlatformKind::WatchOS:
1569  Opt = options::OPT_mwatchos_version_min_EQ;
1570  break;
1571  case DarwinPlatformKind::DriverKit:
1572  // DriverKit always explicitly provides a version in the triple.
1573  return;
1574  }
1575  Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
1576  Args.append(Argument);
1577  }
1578 
1579  /// Returns the OS version with the argument / environment variable that
1580  /// specified it.
1581  std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1582  switch (Kind) {
1583  case TargetArg:
1584  case MTargetOSArg:
1585  case OSVersionArg:
1586  case InferredFromSDK:
1587  case InferredFromArch:
1588  assert(Argument && "OS version argument not yet inferred");
1589  return Argument->getAsString(Args);
1590  case DeploymentTargetEnv:
1591  return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
1592  }
1593  llvm_unreachable("Unsupported Darwin Source Kind");
1594  }
1595 
1596  void setEnvironment(llvm::Triple::EnvironmentType EnvType,
1597  const VersionTuple &OSVersion,
1598  const Optional<DarwinSDKInfo> &SDKInfo) {
1599  switch (EnvType) {
1600  case llvm::Triple::Simulator:
1601  Environment = DarwinEnvironmentKind::Simulator;
1602  break;
1603  case llvm::Triple::MacABI: {
1604  Environment = DarwinEnvironmentKind::MacCatalyst;
1605  // The minimum native macOS target for MacCatalyst is macOS 10.15.
1606  NativeTargetVersion = VersionTuple(10, 15);
1607  if (HasOSVersion && SDKInfo) {
1608  if (const auto *MacCatalystToMacOSMapping = SDKInfo->getVersionMapping(
1610  if (auto MacOSVersion = MacCatalystToMacOSMapping->map(
1611  OSVersion, NativeTargetVersion, None)) {
1612  NativeTargetVersion = *MacOSVersion;
1613  }
1614  }
1615  }
1616  // In a zippered build, we could be building for a macOS target that's
1617  // lower than the version that's implied by the OS version. In that case
1618  // we need to use the minimum version as the native target version.
1619  if (TargetVariantTriple) {
1620  auto TargetVariantVersion = TargetVariantTriple->getOSVersion();
1621  if (TargetVariantVersion.getMajor()) {
1622  if (TargetVariantVersion < NativeTargetVersion)
1623  NativeTargetVersion = TargetVariantVersion;
1624  }
1625  }
1626  break;
1627  }
1628  default:
1629  break;
1630  }
1631  }
1632 
1633  static DarwinPlatform
1634  createFromTarget(const llvm::Triple &TT, StringRef OSVersion, Arg *A,
1635  Optional<llvm::Triple> TargetVariantTriple,
1636  const Optional<DarwinSDKInfo> &SDKInfo) {
1637  DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
1638  A);
1639  VersionTuple OsVersion = TT.getOSVersion();
1640  if (OsVersion.getMajor() == 0)
1641  Result.HasOSVersion = false;
1642  Result.TargetVariantTriple = TargetVariantTriple;
1643  Result.setEnvironment(TT.getEnvironment(), OsVersion, SDKInfo);
1644  return Result;
1645  }
1646  static DarwinPlatform
1647  createFromMTargetOS(llvm::Triple::OSType OS, VersionTuple OSVersion,
1648  llvm::Triple::EnvironmentType Environment, Arg *A,
1649  const Optional<DarwinSDKInfo> &SDKInfo) {
1650  DarwinPlatform Result(MTargetOSArg, getPlatformFromOS(OS),
1651  OSVersion.getAsString(), A);
1652  Result.InferSimulatorFromArch = false;
1653  Result.setEnvironment(Environment, OSVersion, SDKInfo);
1654  return Result;
1655  }
1656  static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform,
1657  Arg *A) {
1658  return DarwinPlatform(OSVersionArg, Platform, A);
1659  }
1660  static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
1661  StringRef EnvVarName,
1662  StringRef Value) {
1663  DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
1664  Result.EnvVarName = EnvVarName;
1665  return Result;
1666  }
1667  static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
1668  StringRef Value,
1669  bool IsSimulator = false) {
1670  DarwinPlatform Result(InferredFromSDK, Platform, Value);
1671  if (IsSimulator)
1672  Result.Environment = DarwinEnvironmentKind::Simulator;
1673  Result.InferSimulatorFromArch = false;
1674  return Result;
1675  }
1676  static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
1677  StringRef Value) {
1678  return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
1679  }
1680 
1681  /// Constructs an inferred SDKInfo value based on the version inferred from
1682  /// the SDK path itself. Only works for values that were created by inferring
1683  /// the platform from the SDKPath.
1684  DarwinSDKInfo inferSDKInfo() {
1685  assert(Kind == InferredFromSDK && "can infer SDK info only");
1686  llvm::VersionTuple Version;
1687  bool IsValid = !Version.tryParse(OSVersion);
1688  (void)IsValid;
1689  assert(IsValid && "invalid SDK version");
1690  return DarwinSDKInfo(
1691  Version,
1692  /*MaximumDeploymentTarget=*/VersionTuple(Version.getMajor(), 0, 99));
1693  }
1694 
1695 private:
1696  DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
1697  : Kind(Kind), Platform(Platform), Argument(Argument) {}
1698  DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
1699  Arg *Argument = nullptr)
1700  : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
1701 
1702  static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
1703  switch (OS) {
1704  case llvm::Triple::Darwin:
1705  case llvm::Triple::MacOSX:
1706  return DarwinPlatformKind::MacOS;
1707  case llvm::Triple::IOS:
1708  return DarwinPlatformKind::IPhoneOS;
1709  case llvm::Triple::TvOS:
1710  return DarwinPlatformKind::TvOS;
1711  case llvm::Triple::WatchOS:
1712  return DarwinPlatformKind::WatchOS;
1713  case llvm::Triple::DriverKit:
1714  return DarwinPlatformKind::DriverKit;
1715  default:
1716  llvm_unreachable("Unable to infer Darwin variant");
1717  }
1718  }
1719 
1720  SourceKind Kind;
1721  DarwinPlatformKind Platform;
1722  DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
1723  VersionTuple NativeTargetVersion;
1724  std::string OSVersion;
1725  bool HasOSVersion = true, InferSimulatorFromArch = true;
1726  Arg *Argument;
1727  StringRef EnvVarName;
1728  Optional<llvm::Triple> TargetVariantTriple;
1729 };
1730 
1731 /// Returns the deployment target that's specified using the -m<os>-version-min
1732 /// argument.
1734 getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
1735  const Driver &TheDriver) {
1736  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
1737  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
1738  options::OPT_mios_simulator_version_min_EQ);
1739  Arg *TvOSVersion =
1740  Args.getLastArg(options::OPT_mtvos_version_min_EQ,
1741  options::OPT_mtvos_simulator_version_min_EQ);
1742  Arg *WatchOSVersion =
1743  Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
1744  options::OPT_mwatchos_simulator_version_min_EQ);
1745  if (OSXVersion) {
1746  if (iOSVersion || TvOSVersion || WatchOSVersion) {
1747  TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1748  << OSXVersion->getAsString(Args)
1749  << (iOSVersion ? iOSVersion
1750  : TvOSVersion ? TvOSVersion : WatchOSVersion)
1751  ->getAsString(Args);
1752  }
1753  return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion);
1754  } else if (iOSVersion) {
1755  if (TvOSVersion || WatchOSVersion) {
1756  TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1757  << iOSVersion->getAsString(Args)
1758  << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1759  }
1760  return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion);
1761  } else if (TvOSVersion) {
1762  if (WatchOSVersion) {
1763  TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1764  << TvOSVersion->getAsString(Args)
1765  << WatchOSVersion->getAsString(Args);
1766  }
1767  return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion);
1768  } else if (WatchOSVersion)
1769  return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion);
1770  return None;
1771 }
1772 
1773 /// Returns the deployment target that's specified using the
1774 /// OS_DEPLOYMENT_TARGET environment variable.
1776 getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
1777  const llvm::Triple &Triple) {
1779  const char *EnvVars[] = {
1780  "MACOSX_DEPLOYMENT_TARGET",
1781  "IPHONEOS_DEPLOYMENT_TARGET",
1782  "TVOS_DEPLOYMENT_TARGET",
1783  "WATCHOS_DEPLOYMENT_TARGET",
1784  "DRIVERKIT_DEPLOYMENT_TARGET",
1785  };
1786  static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1,
1787  "Missing platform");
1788  for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) {
1789  if (char *Env = ::getenv(I.value()))
1790  Targets[I.index()] = Env;
1791  }
1792 
1793  // Allow conflicts among OSX and iOS for historical reasons, but choose the
1794  // default platform.
1795  if (!Targets[Darwin::MacOS].empty() &&
1796  (!Targets[Darwin::IPhoneOS].empty() ||
1797  !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) {
1798  if (Triple.getArch() == llvm::Triple::arm ||
1799  Triple.getArch() == llvm::Triple::aarch64 ||
1800  Triple.getArch() == llvm::Triple::thumb)
1801  Targets[Darwin::MacOS] = "";
1802  else
1803  Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
1804  Targets[Darwin::TvOS] = "";
1805  } else {
1806  // Don't allow conflicts in any other platform.
1807  unsigned FirstTarget = llvm::array_lengthof(Targets);
1808  for (unsigned I = 0; I != llvm::array_lengthof(Targets); ++I) {
1809  if (Targets[I].empty())
1810  continue;
1811  if (FirstTarget == llvm::array_lengthof(Targets))
1812  FirstTarget = I;
1813  else
1814  TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1815  << Targets[FirstTarget] << Targets[I];
1816  }
1817  }
1818 
1819  for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) {
1820  if (!Target.value().empty())
1821  return DarwinPlatform::createDeploymentTargetEnv(
1822  (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
1823  Target.value());
1824  }
1825  return None;
1826 }
1827 
1828 /// Returns the SDK name without the optional prefix that ends with a '.' or an
1829 /// empty string otherwise.
1830 static StringRef dropSDKNamePrefix(StringRef SDKName) {
1831  size_t PrefixPos = SDKName.find('.');
1832  if (PrefixPos == StringRef::npos)
1833  return "";
1834  return SDKName.substr(PrefixPos + 1);
1835 }
1836 
1837 /// Tries to infer the deployment target from the SDK specified by -isysroot
1838 /// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
1839 /// it's available.
1841 inferDeploymentTargetFromSDK(DerivedArgList &Args,
1842  const Optional<DarwinSDKInfo> &SDKInfo) {
1843  const Arg *A = Args.getLastArg(options::OPT_isysroot);
1844  if (!A)
1845  return None;
1846  StringRef isysroot = A->getValue();
1847  StringRef SDK = Darwin::getSDKName(isysroot);
1848  if (!SDK.size())
1849  return None;
1850 
1851  std::string Version;
1852  if (SDKInfo) {
1853  // Get the version from the SDKSettings.json if it's available.
1854  Version = SDKInfo->getVersion().getAsString();
1855  } else {
1856  // Slice the version number out.
1857  // Version number is between the first and the last number.
1858  size_t StartVer = SDK.find_first_of("0123456789");
1859  size_t EndVer = SDK.find_last_of("0123456789");
1860  if (StartVer != StringRef::npos && EndVer > StartVer)
1861  Version = std::string(SDK.slice(StartVer, EndVer + 1));
1862  }
1863  if (Version.empty())
1864  return None;
1865 
1866  auto CreatePlatformFromSDKName =
1867  [&](StringRef SDK) -> Optional<DarwinPlatform> {
1868  if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
1869  return DarwinPlatform::createFromSDK(
1870  Darwin::IPhoneOS, Version,
1871  /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
1872  else if (SDK.startswith("MacOSX"))
1873  return DarwinPlatform::createFromSDK(Darwin::MacOS,
1874  getSystemOrSDKMacOSVersion(Version));
1875  else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
1876  return DarwinPlatform::createFromSDK(
1877  Darwin::WatchOS, Version,
1878  /*IsSimulator=*/SDK.startswith("WatchSimulator"));
1879  else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
1880  return DarwinPlatform::createFromSDK(
1881  Darwin::TvOS, Version,
1882  /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
1883  else if (SDK.startswith("DriverKit"))
1884  return DarwinPlatform::createFromSDK(Darwin::DriverKit, Version);
1885  return None;
1886  };
1887  if (auto Result = CreatePlatformFromSDKName(SDK))
1888  return Result;
1889  // The SDK can be an SDK variant with a name like `<prefix>.<platform>`.
1890  return CreatePlatformFromSDKName(dropSDKNamePrefix(SDK));
1891 }
1892 
1893 std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
1894  const Driver &TheDriver) {
1895  VersionTuple OsVersion;
1896  llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1897  switch (OS) {
1898  case llvm::Triple::Darwin:
1899  case llvm::Triple::MacOSX:
1900  // If there is no version specified on triple, and both host and target are
1901  // macos, use the host triple to infer OS version.
1902  if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
1903  !Triple.getOSMajorVersion())
1904  SystemTriple.getMacOSXVersion(OsVersion);
1905  else if (!Triple.getMacOSXVersion(OsVersion))
1906  TheDriver.Diag(diag::err_drv_invalid_darwin_version)
1907  << Triple.getOSName();
1908  break;
1909  case llvm::Triple::IOS:
1910  if (Triple.isMacCatalystEnvironment() && !Triple.getOSMajorVersion()) {
1911  OsVersion = VersionTuple(13, 1);
1912  } else
1913  OsVersion = Triple.getiOSVersion();
1914  break;
1915  case llvm::Triple::TvOS:
1916  OsVersion = Triple.getOSVersion();
1917  break;
1918  case llvm::Triple::WatchOS:
1919  OsVersion = Triple.getWatchOSVersion();
1920  break;
1921  case llvm::Triple::DriverKit:
1922  OsVersion = Triple.getDriverKitVersion();
1923  break;
1924  default:
1925  llvm_unreachable("Unexpected OS type");
1926  break;
1927  }
1928 
1929  std::string OSVersion;
1930  llvm::raw_string_ostream(OSVersion)
1931  << OsVersion.getMajor() << '.' << OsVersion.getMinor().getValueOr(0)
1932  << '.' << OsVersion.getSubminor().getValueOr(0);
1933  return OSVersion;
1934 }
1935 
1936 /// Tries to infer the target OS from the -arch.
1938 inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
1939  const llvm::Triple &Triple,
1940  const Driver &TheDriver) {
1941  llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
1942 
1943  StringRef MachOArchName = Toolchain.getMachOArchName(Args);
1944  if (MachOArchName == "arm64" || MachOArchName == "arm64e")
1945  OSTy = llvm::Triple::MacOSX;
1946  else if (MachOArchName == "armv7" || MachOArchName == "armv7s")
1947  OSTy = llvm::Triple::IOS;
1948  else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
1949  OSTy = llvm::Triple::WatchOS;
1950  else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
1951  MachOArchName != "armv7em")
1952  OSTy = llvm::Triple::MacOSX;
1953  if (OSTy == llvm::Triple::UnknownOS)
1954  return None;
1955  return DarwinPlatform::createFromArch(OSTy,
1956  getOSVersion(OSTy, Triple, TheDriver));
1957 }
1958 
1959 /// Returns the deployment target that's specified using the -target option.
1960 Optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
1961  DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver,
1962  const Optional<DarwinSDKInfo> &SDKInfo) {
1963  if (!Args.hasArg(options::OPT_target))
1964  return None;
1965  if (Triple.getOS() == llvm::Triple::Darwin ||
1966  Triple.getOS() == llvm::Triple::UnknownOS)
1967  return None;
1968  std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
1969  Optional<llvm::Triple> TargetVariantTriple;
1970  for (const Arg *A : Args.filtered(options::OPT_darwin_target_variant)) {
1971  llvm::Triple TVT(A->getValue());
1972  // Find a matching <arch>-<vendor> target variant triple that can be used.
1973  if ((Triple.getArch() == llvm::Triple::aarch64 ||
1974  TVT.getArchName() == Triple.getArchName()) &&
1975  TVT.getArch() == Triple.getArch() &&
1976  TVT.getSubArch() == Triple.getSubArch() &&
1977  TVT.getVendor() == Triple.getVendor()) {
1978  if (TargetVariantTriple)
1979  continue;
1980  A->claim();
1981  // Accept a -target-variant triple when compiling code that may run on
1982  // macOS or Mac Catalust.
1983  if ((Triple.isMacOSX() && TVT.getOS() == llvm::Triple::IOS &&
1984  TVT.isMacCatalystEnvironment()) ||
1985  (TVT.isMacOSX() && Triple.getOS() == llvm::Triple::IOS &&
1986  Triple.isMacCatalystEnvironment())) {
1987  TargetVariantTriple = TVT;
1988  continue;
1989  }
1990  TheDriver.Diag(diag::err_drv_target_variant_invalid)
1991  << A->getSpelling() << A->getValue();
1992  }
1993  }
1994  return DarwinPlatform::createFromTarget(Triple, OSVersion,
1995  Args.getLastArg(options::OPT_target),
1996  TargetVariantTriple, SDKInfo);
1997 }
1998 
1999 /// Returns the deployment target that's specified using the -mtargetos option.
2001 getDeploymentTargetFromMTargetOSArg(DerivedArgList &Args,
2002  const Driver &TheDriver,
2003  const Optional<DarwinSDKInfo> &SDKInfo) {
2004  auto *A = Args.getLastArg(options::OPT_mtargetos_EQ);
2005  if (!A)
2006  return None;
2007  llvm::Triple TT(llvm::Twine("unknown-apple-") + A->getValue());
2008  switch (TT.getOS()) {
2009  case llvm::Triple::MacOSX:
2010  case llvm::Triple::IOS:
2011  case llvm::Triple::TvOS:
2012  case llvm::Triple::WatchOS:
2013  break;
2014  default:
2015  TheDriver.Diag(diag::err_drv_invalid_os_in_arg)
2016  << TT.getOSName() << A->getAsString(Args);
2017  return None;
2018  }
2019 
2020  VersionTuple Version = TT.getOSVersion();
2021  if (!Version.getMajor()) {
2022  TheDriver.Diag(diag::err_drv_invalid_version_number)
2023  << A->getAsString(Args);
2024  return None;
2025  }
2026  return DarwinPlatform::createFromMTargetOS(TT.getOS(), Version,
2027  TT.getEnvironment(), A, SDKInfo);
2028 }
2029 
2030 Optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
2031  const ArgList &Args,
2032  const Driver &TheDriver) {
2033  const Arg *A = Args.getLastArg(options::OPT_isysroot);
2034  if (!A)
2035  return None;
2036  StringRef isysroot = A->getValue();
2037  auto SDKInfoOrErr = parseDarwinSDKInfo(VFS, isysroot);
2038  if (!SDKInfoOrErr) {
2039  llvm::consumeError(SDKInfoOrErr.takeError());
2040  TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
2041  return None;
2042  }
2043  return *SDKInfoOrErr;
2044 }
2045 
2046 } // namespace
2047 
2048 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
2049  const OptTable &Opts = getDriver().getOpts();
2050 
2051  // Support allowing the SDKROOT environment variable used by xcrun and other
2052  // Xcode tools to define the default sysroot, by making it the default for
2053  // isysroot.
2054  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2055  // Warn if the path does not exist.
2056  if (!getVFS().exists(A->getValue()))
2057  getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
2058  } else {
2059  if (char *env = ::getenv("SDKROOT")) {
2060  // We only use this value as the default if it is an absolute path,
2061  // exists, and it is not the root path.
2062  if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
2063  StringRef(env) != "/") {
2064  Args.append(Args.MakeSeparateArg(
2065  nullptr, Opts.getOption(options::OPT_isysroot), env));
2066  }
2067  }
2068  }
2069 
2070  // Read the SDKSettings.json file for more information, like the SDK version
2071  // that we can pass down to the compiler.
2072  SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
2073 
2074  // The OS and the version can be specified using the -target argument.
2075  Optional<DarwinPlatform> OSTarget =
2076  getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver(), SDKInfo);
2077  if (OSTarget) {
2078  // Disallow mixing -target and -mtargetos=.
2079  if (const auto *MTargetOSArg = Args.getLastArg(options::OPT_mtargetos_EQ)) {
2080  std::string TargetArgStr = OSTarget->getAsString(Args, Opts);
2081  std::string MTargetOSArgStr = MTargetOSArg->getAsString(Args);
2082  getDriver().Diag(diag::err_drv_cannot_mix_options)
2083  << TargetArgStr << MTargetOSArgStr;
2084  }
2085  Optional<DarwinPlatform> OSVersionArgTarget =
2086  getDeploymentTargetFromOSVersionArg(Args, getDriver());
2087  if (OSVersionArgTarget) {
2088  unsigned TargetMajor, TargetMinor, TargetMicro;
2089  bool TargetExtra;
2090  unsigned ArgMajor, ArgMinor, ArgMicro;
2091  bool ArgExtra;
2092  if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
2093  (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
2094  TargetMinor, TargetMicro, TargetExtra) &&
2095  Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
2096  ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
2097  (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
2098  VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
2099  TargetExtra != ArgExtra))) {
2100  // Select the OS version from the -m<os>-version-min argument when
2101  // the -target does not include an OS version.
2102  if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
2103  !OSTarget->hasOSVersion()) {
2104  OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
2105  } else {
2106  // Warn about -m<os>-version-min that doesn't match the OS version
2107  // that's specified in the target.
2108  std::string OSVersionArg =
2109  OSVersionArgTarget->getAsString(Args, Opts);
2110  std::string TargetArg = OSTarget->getAsString(Args, Opts);
2111  getDriver().Diag(clang::diag::warn_drv_overriding_flag_option)
2112  << OSVersionArg << TargetArg;
2113  }
2114  }
2115  }
2116  } else if ((OSTarget = getDeploymentTargetFromMTargetOSArg(Args, getDriver(),
2117  SDKInfo))) {
2118  // The OS target can be specified using the -mtargetos= argument.
2119  // Disallow mixing -mtargetos= and -m<os>version-min=.
2120  Optional<DarwinPlatform> OSVersionArgTarget =
2121  getDeploymentTargetFromOSVersionArg(Args, getDriver());
2122  if (OSVersionArgTarget) {
2123  std::string MTargetOSArgStr = OSTarget->getAsString(Args, Opts);
2124  std::string OSVersionArgStr = OSVersionArgTarget->getAsString(Args, Opts);
2125  getDriver().Diag(diag::err_drv_cannot_mix_options)
2126  << MTargetOSArgStr << OSVersionArgStr;
2127  }
2128  } else {
2129  // The OS target can be specified using the -m<os>version-min argument.
2130  OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
2131  // If no deployment target was specified on the command line, check for
2132  // environment defines.
2133  if (!OSTarget) {
2134  OSTarget =
2135  getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
2136  if (OSTarget) {
2137  // Don't infer simulator from the arch when the SDK is also specified.
2138  Optional<DarwinPlatform> SDKTarget =
2139  inferDeploymentTargetFromSDK(Args, SDKInfo);
2140  if (SDKTarget)
2141  OSTarget->setEnvironment(SDKTarget->getEnvironment());
2142  }
2143  }
2144  // If there is no command-line argument to specify the Target version and
2145  // no environment variable defined, see if we can set the default based
2146  // on -isysroot using SDKSettings.json if it exists.
2147  if (!OSTarget) {
2148  OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo);
2149  /// If the target was successfully constructed from the SDK path, try to
2150  /// infer the SDK info if the SDK doesn't have it.
2151  if (OSTarget && !SDKInfo)
2152  SDKInfo = OSTarget->inferSDKInfo();
2153  }
2154  // If no OS targets have been specified, try to guess platform from -target
2155  // or arch name and compute the version from the triple.
2156  if (!OSTarget)
2157  OSTarget =
2158  inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
2159  }
2160 
2161  assert(OSTarget && "Unable to infer Darwin variant");
2162  OSTarget->addOSVersionMinArgument(Args, Opts);
2163  DarwinPlatformKind Platform = OSTarget->getPlatform();
2164 
2165  unsigned Major, Minor, Micro;
2166  bool HadExtra;
2167  // Set the tool chain target information.
2168  if (Platform == MacOS) {
2169  if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2170  Micro, HadExtra) ||
2171  HadExtra || Major < 10 || Major >= 100 || Minor >= 100 || Micro >= 100)
2172  getDriver().Diag(diag::err_drv_invalid_version_number)
2173  << OSTarget->getAsString(Args, Opts);
2174  } else if (Platform == IPhoneOS) {
2175  if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2176  Micro, HadExtra) ||
2177  HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
2178  getDriver().Diag(diag::err_drv_invalid_version_number)
2179  << OSTarget->getAsString(Args, Opts);
2180  ;
2181  if (OSTarget->getEnvironment() == MacCatalyst &&
2182  (Major < 13 || (Major == 13 && Minor < 1))) {
2183  getDriver().Diag(diag::err_drv_invalid_version_number)
2184  << OSTarget->getAsString(Args, Opts);
2185  Major = 13;
2186  Minor = 1;
2187  Micro = 0;
2188  }
2189  // For 32-bit targets, the deployment target for iOS has to be earlier than
2190  // iOS 11.
2191  if (getTriple().isArch32Bit() && Major >= 11) {
2192  // If the deployment target is explicitly specified, print a diagnostic.
2193  if (OSTarget->isExplicitlySpecified()) {
2194  if (OSTarget->getEnvironment() == MacCatalyst)
2195  getDriver().Diag(diag::err_invalid_macos_32bit_deployment_target);
2196  else
2197  getDriver().Diag(diag::warn_invalid_ios_deployment_target)
2198  << OSTarget->getAsString(Args, Opts);
2199  // Otherwise, set it to 10.99.99.
2200  } else {
2201  Major = 10;
2202  Minor = 99;
2203  Micro = 99;
2204  }
2205  }
2206  } else if (Platform == TvOS) {
2207  if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2208  Micro, HadExtra) ||
2209  HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
2210  getDriver().Diag(diag::err_drv_invalid_version_number)
2211  << OSTarget->getAsString(Args, Opts);
2212  } else if (Platform == WatchOS) {
2213  if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2214  Micro, HadExtra) ||
2215  HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
2216  getDriver().Diag(diag::err_drv_invalid_version_number)
2217  << OSTarget->getAsString(Args, Opts);
2218  } else if (Platform == DriverKit) {
2219  if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2220  Micro, HadExtra) ||
2221  HadExtra || Major < 19 || Major >= 100 || Minor >= 100 || Micro >= 100)
2222  getDriver().Diag(diag::err_drv_invalid_version_number)
2223  << OSTarget->getAsString(Args, Opts);
2224  } else
2225  llvm_unreachable("unknown kind of Darwin platform");
2226 
2227  DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
2228  // Recognize iOS targets with an x86 architecture as the iOS simulator.
2229  if (Environment == NativeEnvironment && Platform != MacOS &&
2230  Platform != DriverKit && OSTarget->canInferSimulatorFromArch() &&
2231  getTriple().isX86())
2232  Environment = Simulator;
2233 
2234  VersionTuple NativeTargetVersion;
2235  if (Environment == MacCatalyst)
2236  NativeTargetVersion = OSTarget->getNativeTargetVersion();
2237  setTarget(Platform, Environment, Major, Minor, Micro, NativeTargetVersion);
2238  TargetVariantTriple = OSTarget->getTargetVariantTriple();
2239 
2240  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2241  StringRef SDK = getSDKName(A->getValue());
2242  if (SDK.size() > 0) {
2243  size_t StartVer = SDK.find_first_of("0123456789");
2244  StringRef SDKName = SDK.slice(0, StartVer);
2245  if (!SDKName.startswith(getPlatformFamily()) &&
2246  !dropSDKNamePrefix(SDKName).startswith(getPlatformFamily()))
2247  getDriver().Diag(diag::warn_incompatible_sysroot)
2248  << SDKName << getPlatformFamily();
2249  }
2250  }
2251 }
2252 
2253 // Returns the effective header sysroot path to use. This comes either from
2254 // -isysroot or --sysroot.
2255 llvm::StringRef DarwinClang::GetHeaderSysroot(const llvm::opt::ArgList &DriverArgs) const {
2256  if(DriverArgs.hasArg(options::OPT_isysroot))
2257  return DriverArgs.getLastArgValue(options::OPT_isysroot);
2258  if (!getDriver().SysRoot.empty())
2259  return getDriver().SysRoot;
2260  return "/";
2261 }
2262 
2263 void DarwinClang::AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
2264  llvm::opt::ArgStringList &CC1Args) const {
2265  const Driver &D = getDriver();
2266 
2267  llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
2268 
2269  bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
2270  bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
2271  bool NoBuiltinInc = DriverArgs.hasFlag(
2272  options::OPT_nobuiltininc, options::OPT_ibuiltininc, /*Default=*/false);
2273  bool ForceBuiltinInc = DriverArgs.hasFlag(
2274  options::OPT_ibuiltininc, options::OPT_nobuiltininc, /*Default=*/false);
2275 
2276  // Add <sysroot>/usr/local/include
2277  if (!NoStdInc && !NoStdlibInc) {
2278  SmallString<128> P(Sysroot);
2279  llvm::sys::path::append(P, "usr", "local", "include");
2280  addSystemInclude(DriverArgs, CC1Args, P);
2281  }
2282 
2283  // Add the Clang builtin headers (<resource>/include)
2284  if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
2286  llvm::sys::path::append(P, "include");
2287  addSystemInclude(DriverArgs, CC1Args, P);
2288  }
2289 
2290  if (NoStdInc || NoStdlibInc)
2291  return;
2292 
2293  // Check for configure-time C include directories.
2294  llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
2295  if (!CIncludeDirs.empty()) {
2297  CIncludeDirs.split(dirs, ":");
2298  for (llvm::StringRef dir : dirs) {
2299  llvm::StringRef Prefix =
2300  llvm::sys::path::is_absolute(dir) ? "" : llvm::StringRef(Sysroot);
2301  addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
2302  }
2303  } else {
2304  // Otherwise, add <sysroot>/usr/include.
2305  SmallString<128> P(Sysroot);
2306  llvm::sys::path::append(P, "usr", "include");
2307  addExternCSystemInclude(DriverArgs, CC1Args, P.str());
2308  }
2309 }
2310 
2311 bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
2312  llvm::opt::ArgStringList &CC1Args,
2314  llvm::StringRef Version,
2315  llvm::StringRef ArchDir,
2316  llvm::StringRef BitDir) const {
2317  llvm::sys::path::append(Base, Version);
2318 
2319  // Add the base dir
2320  addSystemInclude(DriverArgs, CC1Args, Base);
2321 
2322  // Add the multilib dirs
2323  {
2325  if (!ArchDir.empty())
2326  llvm::sys::path::append(P, ArchDir);
2327  if (!BitDir.empty())
2328  llvm::sys::path::append(P, BitDir);
2329  addSystemInclude(DriverArgs, CC1Args, P);
2330  }
2331 
2332  // Add the backward dir
2333  {
2335  llvm::sys::path::append(P, "backward");
2336  addSystemInclude(DriverArgs, CC1Args, P);
2337  }
2338 
2339  return getVFS().exists(Base);
2340 }
2341 
2343  const llvm::opt::ArgList &DriverArgs,
2344  llvm::opt::ArgStringList &CC1Args) const {
2345  // The implementation from a base class will pass through the -stdlib to
2346  // CC1Args.
2347  // FIXME: this should not be necessary, remove usages in the frontend
2348  // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
2349  // Also check whether this is used for setting library search paths.
2350  ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
2351 
2352  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2353  DriverArgs.hasArg(options::OPT_nostdincxx))
2354  return;
2355 
2356  llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
2357 
2358  switch (GetCXXStdlibType(DriverArgs)) {
2359  case ToolChain::CST_Libcxx: {
2360  // On Darwin, libc++ can be installed in one of the following two places:
2361  // 1. Alongside the compiler in <install>/include/c++/v1
2362  // 2. In a SDK (or a custom sysroot) in <sysroot>/usr/include/c++/v1
2363  //
2364  // The precendence of paths is as listed above, i.e. we take the first path
2365  // that exists. Also note that we never include libc++ twice -- we take the
2366  // first path that exists and don't send the other paths to CC1 (otherwise
2367  // include_next could break).
2368 
2369  // Check for (1)
2370  // Get from '<install>/bin' to '<install>/include/c++/v1'.
2371  // Note that InstallBin can be relative, so we use '..' instead of
2372  // parent_path.
2373  llvm::SmallString<128> InstallBin =
2374  llvm::StringRef(getDriver().getInstalledDir()); // <install>/bin
2375  llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
2376  if (getVFS().exists(InstallBin)) {
2377  addSystemInclude(DriverArgs, CC1Args, InstallBin);
2378  return;
2379  } else if (DriverArgs.hasArg(options::OPT_v)) {
2380  llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
2381  << "\"\n";
2382  }
2383 
2384  // Otherwise, check for (2)
2385  llvm::SmallString<128> SysrootUsr = Sysroot;
2386  llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");
2387  if (getVFS().exists(SysrootUsr)) {
2388  addSystemInclude(DriverArgs, CC1Args, SysrootUsr);
2389  return;
2390  } else if (DriverArgs.hasArg(options::OPT_v)) {
2391  llvm::errs() << "ignoring nonexistent directory \"" << SysrootUsr
2392  << "\"\n";
2393  }
2394 
2395  // Otherwise, don't add any path.
2396  break;
2397  }
2398 
2400  llvm::SmallString<128> UsrIncludeCxx = Sysroot;
2401  llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
2402 
2403  llvm::Triple::ArchType arch = getTriple().getArch();
2404  bool IsBaseFound = true;
2405  switch (arch) {
2406  default: break;
2407 
2408  case llvm::Triple::ppc:
2409  case llvm::Triple::ppc64:
2410  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2411  "4.2.1",
2412  "powerpc-apple-darwin10",
2413  arch == llvm::Triple::ppc64 ? "ppc64" : "");
2414  IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2415  "4.0.0", "powerpc-apple-darwin10",
2416  arch == llvm::Triple::ppc64 ? "ppc64" : "");
2417  break;
2418 
2419  case llvm::Triple::x86:
2420  case llvm::Triple::x86_64:
2421  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2422  "4.2.1",
2423  "i686-apple-darwin10",
2424  arch == llvm::Triple::x86_64 ? "x86_64" : "");
2425  IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2426  "4.0.0", "i686-apple-darwin8",
2427  "");
2428  break;
2429 
2430  case llvm::Triple::arm:
2431  case llvm::Triple::thumb:
2432  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2433  "4.2.1",
2434  "arm-apple-darwin10",
2435  "v7");
2436  IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2437  "4.2.1",
2438  "arm-apple-darwin10",
2439  "v6");
2440  break;
2441 
2442  case llvm::Triple::aarch64:
2443  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2444  "4.2.1",
2445  "arm64-apple-darwin10",
2446  "");
2447  break;
2448  }
2449 
2450  if (!IsBaseFound) {
2451  getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
2452  }
2453 
2454  break;
2455  }
2456 }
2457 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
2458  ArgStringList &CmdArgs) const {
2460 
2461  switch (Type) {
2462  case ToolChain::CST_Libcxx:
2463  CmdArgs.push_back("-lc++");
2464  break;
2465 
2467  // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
2468  // it was previously found in the gcc lib dir. However, for all the Darwin
2469  // platforms we care about it was -lstdc++.6, so we search for that
2470  // explicitly if we can't see an obvious -lstdc++ candidate.
2471 
2472  // Check in the sysroot first.
2473  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2474  SmallString<128> P(A->getValue());
2475  llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
2476 
2477  if (!getVFS().exists(P)) {
2478  llvm::sys::path::remove_filename(P);
2479  llvm::sys::path::append(P, "libstdc++.6.dylib");
2480  if (getVFS().exists(P)) {
2481  CmdArgs.push_back(Args.MakeArgString(P));
2482  return;
2483  }
2484  }
2485  }
2486 
2487  // Otherwise, look in the root.
2488  // FIXME: This should be removed someday when we don't have to care about
2489  // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
2490  if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
2491  getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
2492  CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
2493  return;
2494  }
2495 
2496  // Otherwise, let the linker search.
2497  CmdArgs.push_back("-lstdc++");
2498  break;
2499  }
2500 }
2501 
2502 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
2503  ArgStringList &CmdArgs) const {
2504  // For Darwin platforms, use the compiler-rt-based support library
2505  // instead of the gcc-provided one (which is also incidentally
2506  // only present in the gcc lib dir, which makes it hard to find).
2507 
2508  SmallString<128> P(getDriver().ResourceDir);
2509  llvm::sys::path::append(P, "lib", "darwin");
2510 
2511  // Use the newer cc_kext for iOS ARM after 6.0.
2512  if (isTargetWatchOS()) {
2513  llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
2514  } else if (isTargetTvOS()) {
2515  llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
2516  } else if (isTargetIPhoneOS()) {
2517  llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
2518  } else if (isTargetDriverKit()) {
2519  // DriverKit doesn't want extra runtime support.
2520  } else {
2521  llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
2522  }
2523 
2524  // For now, allow missing resource libraries to support developers who may
2525  // not have compiler-rt checked out or integrated into their build.
2526  if (getVFS().exists(P))
2527  CmdArgs.push_back(Args.MakeArgString(P));
2528 }
2529 
2530 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
2531  StringRef BoundArch,
2532  Action::OffloadKind) const {
2533  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2534  const OptTable &Opts = getDriver().getOpts();
2535 
2536  // FIXME: We really want to get out of the tool chain level argument
2537  // translation business, as it makes the driver functionality much
2538  // more opaque. For now, we follow gcc closely solely for the
2539  // purpose of easily achieving feature parity & testability. Once we
2540  // have something that works, we should reevaluate each translation
2541  // and try to push it down into tool specific logic.
2542 
2543  for (Arg *A : Args) {
2544  if (A->getOption().matches(options::OPT_Xarch__)) {
2545  // Skip this argument unless the architecture matches either the toolchain
2546  // triple arch, or the arch being bound.
2547  StringRef XarchArch = A->getValue(0);
2548  if (!(XarchArch == getArchName() ||
2549  (!BoundArch.empty() && XarchArch == BoundArch)))
2550  continue;
2551 
2552  Arg *OriginalArg = A;
2553  TranslateXarchArgs(Args, A, DAL);
2554 
2555  // Linker input arguments require custom handling. The problem is that we
2556  // have already constructed the phase actions, so we can not treat them as
2557  // "input arguments".
2558  if (A->getOption().hasFlag(options::LinkerInput)) {
2559  // Convert the argument into individual Zlinker_input_args.
2560  for (const char *Value : A->getValues()) {
2561  DAL->AddSeparateArg(
2562  OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
2563  }
2564  continue;
2565  }
2566  }
2567 
2568  // Sob. These is strictly gcc compatible for the time being. Apple
2569  // gcc translates options twice, which means that self-expanding
2570  // options add duplicates.
2571  switch ((options::ID)A->getOption().getID()) {
2572  default:
2573  DAL->append(A);
2574  break;
2575 
2576  case options::OPT_mkernel:
2577  case options::OPT_fapple_kext:
2578  DAL->append(A);
2579  DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
2580  break;
2581 
2582  case options::OPT_dependency_file:
2583  DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
2584  break;
2585 
2586  case options::OPT_gfull:
2587  DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2588  DAL->AddFlagArg(
2589  A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
2590  break;
2591 
2592  case options::OPT_gused:
2593  DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2594  DAL->AddFlagArg(
2595  A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
2596  break;
2597 
2598  case options::OPT_shared:
2599  DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
2600  break;
2601 
2602  case options::OPT_fconstant_cfstrings:
2603  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
2604  break;
2605 
2606  case options::OPT_fno_constant_cfstrings:
2607  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
2608  break;
2609 
2610  case options::OPT_Wnonportable_cfstrings:
2611  DAL->AddFlagArg(A,
2612  Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
2613  break;
2614 
2615  case options::OPT_Wno_nonportable_cfstrings:
2616  DAL->AddFlagArg(
2617  A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
2618  break;
2619  }
2620  }
2621 
2622  // Add the arch options based on the particular spelling of -arch, to match
2623  // how the driver driver works.
2624  if (!BoundArch.empty()) {
2625  StringRef Name = BoundArch;
2626  const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
2627  const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
2628 
2629  // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
2630  // which defines the list of which architectures we accept.
2631  if (Name == "ppc")
2632  ;
2633  else if (Name == "ppc601")
2634  DAL->AddJoinedArg(nullptr, MCpu, "601");
2635  else if (Name == "ppc603")
2636  DAL->AddJoinedArg(nullptr, MCpu, "603");
2637  else if (Name == "ppc604")
2638  DAL->AddJoinedArg(nullptr, MCpu, "604");
2639  else if (Name == "ppc604e")
2640  DAL->AddJoinedArg(nullptr, MCpu, "604e");
2641  else if (Name == "ppc750")
2642  DAL->AddJoinedArg(nullptr, MCpu, "750");
2643  else if (Name == "ppc7400")
2644  DAL->AddJoinedArg(nullptr, MCpu, "7400");
2645  else if (Name == "ppc7450")
2646  DAL->AddJoinedArg(nullptr, MCpu, "7450");
2647  else if (Name == "ppc970")
2648  DAL->AddJoinedArg(nullptr, MCpu, "970");
2649 
2650  else if (Name == "ppc64" || Name == "ppc64le")
2651  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2652 
2653  else if (Name == "i386")
2654  ;
2655  else if (Name == "i486")
2656  DAL->AddJoinedArg(nullptr, MArch, "i486");
2657  else if (Name == "i586")
2658  DAL->AddJoinedArg(nullptr, MArch, "i586");
2659  else if (Name == "i686")
2660  DAL->AddJoinedArg(nullptr, MArch, "i686");
2661  else if (Name == "pentium")
2662  DAL->AddJoinedArg(nullptr, MArch, "pentium");
2663  else if (Name == "pentium2")
2664  DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2665  else if (Name == "pentpro")
2666  DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
2667  else if (Name == "pentIIm3")
2668  DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2669 
2670  else if (Name == "x86_64" || Name == "x86_64h")
2671  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2672 
2673  else if (Name == "arm")
2674  DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2675  else if (Name == "armv4t")
2676  DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2677  else if (Name == "armv5")
2678  DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
2679  else if (Name == "xscale")
2680  DAL->AddJoinedArg(nullptr, MArch, "xscale");
2681  else if (Name == "armv6")
2682  DAL->AddJoinedArg(nullptr, MArch, "armv6k");
2683  else if (Name == "armv6m")
2684  DAL->AddJoinedArg(nullptr, MArch, "armv6m");
2685  else if (Name == "armv7")
2686  DAL->AddJoinedArg(nullptr, MArch, "armv7a");
2687  else if (Name == "armv7em")
2688  DAL->AddJoinedArg(nullptr, MArch, "armv7em");
2689  else if (Name == "armv7k")
2690  DAL->AddJoinedArg(nullptr, MArch, "armv7k");
2691  else if (Name == "armv7m")
2692  DAL->AddJoinedArg(nullptr, MArch, "armv7m");
2693  else if (Name == "armv7s")
2694  DAL->AddJoinedArg(nullptr, MArch, "armv7s");
2695  }
2696 
2697  return DAL;
2698 }
2699 
2700 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
2701  ArgStringList &CmdArgs,
2702  bool ForceLinkBuiltinRT) const {
2703  // Embedded targets are simple at the moment, not supporting sanitizers and
2704  // with different libraries for each member of the product { static, PIC } x
2705  // { hard-float, soft-float }
2706  llvm::SmallString<32> CompilerRT = StringRef("");
2707  CompilerRT +=
2709  ? "hard"
2710  : "soft";
2711  CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
2712 
2713  AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
2714 }
2715 
2717  llvm::Triple::OSType OS;
2718 
2719  if (isTargetMacCatalyst())
2720  return TargetVersion < alignedAllocMinVersion(llvm::Triple::MacOSX);
2721  switch (TargetPlatform) {
2722  case MacOS: // Earlier than 10.13.
2723  OS = llvm::Triple::MacOSX;
2724  break;
2725  case IPhoneOS:
2726  OS = llvm::Triple::IOS;
2727  break;
2728  case TvOS: // Earlier than 11.0.
2729  OS = llvm::Triple::TvOS;
2730  break;
2731  case WatchOS: // Earlier than 4.0.
2732  OS = llvm::Triple::WatchOS;
2733  break;
2734  case DriverKit: // Always available.
2735  return false;
2736  }
2737 
2739 }
2740 
2741 void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
2742  llvm::opt::ArgStringList &CC1Args,
2743  Action::OffloadKind DeviceOffloadKind) const {
2744  // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
2745  // enabled or disabled aligned allocations.
2746  if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
2747  options::OPT_fno_aligned_allocation) &&
2749  CC1Args.push_back("-faligned-alloc-unavailable");
2750 
2751  if (TargetVariantTriple) {
2752  CC1Args.push_back("-darwin-target-variant-triple");
2753  CC1Args.push_back(
2754  DriverArgs.MakeArgString(TargetVariantTriple->getTriple()));
2755  }
2756 
2757  if (SDKInfo) {
2758  /// Pass the SDK version to the compiler when the SDK information is
2759  /// available.
2760  auto EmitTargetSDKVersionArg = [&](const VersionTuple &V) {
2761  std::string Arg;
2762  llvm::raw_string_ostream OS(Arg);
2763  OS << "-target-sdk-version=" << V;
2764  CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
2765  };
2766 
2767  if (isTargetMacCatalyst()) {
2768  if (const auto *MacOStoMacCatalystMapping = SDKInfo->getVersionMapping(
2770  Optional<VersionTuple> SDKVersion = MacOStoMacCatalystMapping->map(
2771  SDKInfo->getVersion(), minimumMacCatalystDeploymentTarget(), None);
2772  EmitTargetSDKVersionArg(
2773  SDKVersion ? *SDKVersion : minimumMacCatalystDeploymentTarget());
2774  }
2775  } else {
2776  EmitTargetSDKVersionArg(SDKInfo->getVersion());
2777  }
2778 
2779  /// Pass the target variant SDK version to the compiler when the SDK
2780  /// information is available and is required for target variant.
2781  if (TargetVariantTriple) {
2782  if (isTargetMacCatalyst()) {
2783  std::string Arg;
2784  llvm::raw_string_ostream OS(Arg);
2785  OS << "-darwin-target-variant-sdk-version=" << SDKInfo->getVersion();
2786  CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
2787  } else if (const auto *MacOStoMacCatalystMapping =
2788  SDKInfo->getVersionMapping(
2790  if (Optional<VersionTuple> SDKVersion = MacOStoMacCatalystMapping->map(
2792  None)) {
2793  std::string Arg;
2794  llvm::raw_string_ostream OS(Arg);
2795  OS << "-darwin-target-variant-sdk-version=" << *SDKVersion;
2796  CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
2797  }
2798  }
2799  }
2800  }
2801 
2802  // Enable compatibility mode for NSItemProviderCompletionHandler in
2803  // Foundation/NSItemProvider.h.
2804  CC1Args.push_back("-fcompatibility-qualified-id-block-type-checking");
2805 
2806  // Give static local variables in inline functions hidden visibility when
2807  // -fvisibility-inlines-hidden is enabled.
2808  if (!DriverArgs.getLastArgNoClaim(
2809  options::OPT_fvisibility_inlines_hidden_static_local_var,
2810  options::OPT_fno_visibility_inlines_hidden_static_local_var))
2811  CC1Args.push_back("-fvisibility-inlines-hidden-static-local-var");
2812 }
2813 
2814 DerivedArgList *
2815 Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
2816  Action::OffloadKind DeviceOffloadKind) const {
2817  // First get the generic Apple args, before moving onto Darwin-specific ones.
2818  DerivedArgList *DAL =
2819  MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
2820  const OptTable &Opts = getDriver().getOpts();
2821 
2822  // If no architecture is bound, none of the translations here are relevant.
2823  if (BoundArch.empty())
2824  return DAL;
2825 
2826  // Add an explicit version min argument for the deployment target. We do this
2827  // after argument translation because -Xarch_ arguments may add a version min
2828  // argument.
2829  AddDeploymentTarget(*DAL);
2830 
2831  // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
2832  // FIXME: It would be far better to avoid inserting those -static arguments,
2833  // but we can't check the deployment target in the translation code until
2834  // it is set here.
2836  (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
2837  for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
2838  Arg *A = *it;
2839  ++it;
2840  if (A->getOption().getID() != options::OPT_mkernel &&
2841  A->getOption().getID() != options::OPT_fapple_kext)
2842  continue;
2843  assert(it != ie && "unexpected argument translation");
2844  A = *it;
2845  assert(A->getOption().getID() == options::OPT_static &&
2846  "missing expected -static argument");
2847  *it = nullptr;
2848  ++it;
2849  }
2850  }
2851 
2852  if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
2854  DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
2855  "libc++");
2856 
2857  // Validate the C++ standard library choice.
2859  if (Type == ToolChain::CST_Libcxx) {
2860  // Check whether the target provides libc++.
2861  StringRef where;
2862 
2863  // Complain about targeting iOS < 5.0 in any way.
2864  if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
2865  where = "iOS 5.0";
2866 
2867  if (where != StringRef()) {
2868  getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
2869  }
2870  }
2871 
2872  auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
2873  if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
2874  if (Args.hasFlag(options::OPT_fomit_frame_pointer,
2875  options::OPT_fno_omit_frame_pointer, false))
2876  getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
2877  << "-fomit-frame-pointer" << BoundArch;
2878  }
2879 
2880  return DAL;
2881 }
2882 
2883 bool MachO::IsUnwindTablesDefault(const ArgList &Args) const {
2884  // Unwind tables are not emitted if -fno-exceptions is supplied (except when
2885  // targeting x86_64).
2886  return getArch() == llvm::Triple::x86_64 ||
2887  (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
2888  Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2889  true));
2890 }
2891 
2893  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
2894  return S[0] != '\0';
2895  return false;
2896 }
2897 
2899  if (const char *S = ::getenv("RC_DEBUG_PREFIX_MAP"))
2900  return S;
2901  return {};
2902 }
2903 
2904 llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
2905  // Darwin uses SjLj exceptions on ARM.
2906  if (getTriple().getArch() != llvm::Triple::arm &&
2907  getTriple().getArch() != llvm::Triple::thumb)
2909 
2910  // Only watchOS uses the new DWARF/Compact unwinding method.
2911  llvm::Triple Triple(ComputeLLVMTriple(Args));
2912  if (Triple.isWatchABI())
2913  return llvm::ExceptionHandling::DwarfCFI;
2914 
2915  return llvm::ExceptionHandling::SjLj;
2916 }
2917 
2919  assert(TargetInitialized && "Target not initialized!");
2920  if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
2921  return false;
2922  return true;
2923 }
2924 
2925 bool MachO::isPICDefault() const { return true; }
2926 
2927 bool MachO::isPIEDefault(const llvm::opt::ArgList &Args) const { return false; }
2928 
2930  return (getArch() == llvm::Triple::x86_64 ||
2931  getArch() == llvm::Triple::aarch64);
2932 }
2933 
2935  // Profiling instrumentation is only supported on x86.
2936  return getTriple().isX86();
2937 }
2938 
2939 void Darwin::addMinVersionArgs(const ArgList &Args,
2940  ArgStringList &CmdArgs) const {
2941  VersionTuple TargetVersion = getTripleTargetVersion();
2942 
2943  if (isTargetWatchOS())
2944  CmdArgs.push_back("-watchos_version_min");
2945  else if (isTargetWatchOSSimulator())
2946  CmdArgs.push_back("-watchos_simulator_version_min");
2947  else if (isTargetTvOS())
2948  CmdArgs.push_back("-tvos_version_min");
2949  else if (isTargetTvOSSimulator())
2950  CmdArgs.push_back("-tvos_simulator_version_min");
2951  else if (isTargetDriverKit())
2952  CmdArgs.push_back("-driverkit_version_min");
2953  else if (isTargetIOSSimulator())
2954  CmdArgs.push_back("-ios_simulator_version_min");
2955  else if (isTargetIOSBased())
2956  CmdArgs.push_back("-iphoneos_version_min");
2957  else if (isTargetMacCatalyst())
2958  CmdArgs.push_back("-maccatalyst_version_min");
2959  else {
2960  assert(isTargetMacOS() && "unexpected target");
2961  CmdArgs.push_back("-macosx_version_min");
2962  }
2963 
2964  VersionTuple MinTgtVers = getEffectiveTriple().getMinimumSupportedOSVersion();
2965  if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
2966  TargetVersion = MinTgtVers;
2967  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2968  if (TargetVariantTriple) {
2969  assert(isTargetMacOSBased() && "unexpected target");
2970  VersionTuple VariantTargetVersion;
2971  if (TargetVariantTriple->isMacOSX()) {
2972  CmdArgs.push_back("-macosx_version_min");
2973  TargetVariantTriple->getMacOSXVersion(VariantTargetVersion);
2974  } else {
2975  assert(TargetVariantTriple->isiOS() &&
2976  TargetVariantTriple->isMacCatalystEnvironment() &&
2977  "unexpected target variant triple");
2978  CmdArgs.push_back("-maccatalyst_version_min");
2979  VariantTargetVersion = TargetVariantTriple->getiOSVersion();
2980  }
2981  VersionTuple MinTgtVers =
2982  TargetVariantTriple->getMinimumSupportedOSVersion();
2983  if (MinTgtVers.getMajor() && MinTgtVers > VariantTargetVersion)
2984  VariantTargetVersion = MinTgtVers;
2985  CmdArgs.push_back(Args.MakeArgString(VariantTargetVersion.getAsString()));
2986  }
2987 }
2988 
2989 static const char *getPlatformName(Darwin::DarwinPlatformKind Platform,
2990  Darwin::DarwinEnvironmentKind Environment) {
2991  switch (Platform) {
2992  case Darwin::MacOS:
2993  return "macos";
2994  case Darwin::IPhoneOS:
2995  if (Environment == Darwin::MacCatalyst)
2996  return "mac catalyst";
2997  return "ios";
2998  case Darwin::TvOS:
2999  return "tvos";
3000  case Darwin::WatchOS:
3001  return "watchos";
3002  case Darwin::DriverKit:
3003  return "driverkit";
3004  }
3005  llvm_unreachable("invalid platform");
3006 }
3007 
3008 void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
3009  llvm::opt::ArgStringList &CmdArgs) const {
3010  auto EmitPlatformVersionArg =
3011  [&](const VersionTuple &TV, Darwin::DarwinPlatformKind TargetPlatform,
3013  const llvm::Triple &TT) {
3014  // -platform_version <platform> <target_version> <sdk_version>
3015  // Both the target and SDK version support only up to 3 components.
3016  CmdArgs.push_back("-platform_version");
3017  std::string PlatformName =
3020  PlatformName += "-simulator";
3021  CmdArgs.push_back(Args.MakeArgString(PlatformName));
3022  VersionTuple TargetVersion = TV.withoutBuild();
3023  if ((TargetPlatform == Darwin::IPhoneOS ||
3025  getTriple().getArchName() == "arm64e" &&
3026  TargetVersion.getMajor() < 14) {
3027  // arm64e slice is supported on iOS/tvOS 14+ only.
3028  TargetVersion = VersionTuple(14, 0);
3029  }
3030  VersionTuple MinTgtVers = TT.getMinimumSupportedOSVersion();
3031  if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3032  TargetVersion = MinTgtVers;
3033  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3034 
3036  // Mac Catalyst programs must use the appropriate iOS SDK version
3037  // that corresponds to the macOS SDK version used for the compilation.
3038  Optional<VersionTuple> iOSSDKVersion;
3039  if (SDKInfo) {
3040  if (const auto *MacOStoMacCatalystMapping =
3041  SDKInfo->getVersionMapping(
3043  iOSSDKVersion = MacOStoMacCatalystMapping->map(
3044  SDKInfo->getVersion().withoutBuild(),
3046  }
3047  }
3048  CmdArgs.push_back(Args.MakeArgString(
3049  (iOSSDKVersion ? *iOSSDKVersion
3051  .getAsString()));
3052  return;
3053  }
3054 
3055  if (SDKInfo) {
3056  VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
3057  CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
3058  } else {
3059  // Use an SDK version that's matching the deployment target if the SDK
3060  // version is missing. This is preferred over an empty SDK version
3061  // (0.0.0) as the system's runtime might expect the linked binary to
3062  // contain a valid SDK version in order for the binary to work
3063  // correctly. It's reasonable to use the deployment target version as
3064  // a proxy for the SDK version because older SDKs don't guarantee
3065  // support for deployment targets newer than the SDK versions, so that
3066  // rules out using some predetermined older SDK version, which leaves
3067  // the deployment target version as the only reasonable choice.
3068  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3069  }
3070  };
3071  EmitPlatformVersionArg(getTripleTargetVersion(), TargetPlatform,
3073  if (!TargetVariantTriple)
3074  return;
3075  Darwin::DarwinPlatformKind Platform;
3076  Darwin::DarwinEnvironmentKind Environment;
3077  VersionTuple TargetVariantVersion;
3078  if (TargetVariantTriple->isMacOSX()) {
3079  TargetVariantTriple->getMacOSXVersion(TargetVariantVersion);
3080  Platform = Darwin::MacOS;
3081  Environment = Darwin::NativeEnvironment;
3082  } else {
3083  assert(TargetVariantTriple->isiOS() &&
3084  TargetVariantTriple->isMacCatalystEnvironment() &&
3085  "unexpected target variant triple");
3086  TargetVariantVersion = TargetVariantTriple->getiOSVersion();
3087  Platform = Darwin::IPhoneOS;
3088  Environment = Darwin::MacCatalyst;
3089  }
3090  EmitPlatformVersionArg(TargetVariantVersion, Platform, Environment,
3092 }
3093 
3094 // Add additional link args for the -dynamiclib option.
3095 static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args,
3096  ArgStringList &CmdArgs) {
3097  // Derived from darwin_dylib1 spec.
3098  if (D.isTargetIPhoneOS()) {
3099  if (D.isIPhoneOSVersionLT(3, 1))
3100  CmdArgs.push_back("-ldylib1.o");
3101  return;
3102  }
3103 
3104  if (!D.isTargetMacOS())
3105  return;
3106  if (D.isMacosxVersionLT(10, 5))
3107  CmdArgs.push_back("-ldylib1.o");
3108  else if (D.isMacosxVersionLT(10, 6))
3109  CmdArgs.push_back("-ldylib1.10.5.o");
3110 }
3111 
3112 // Add additional link args for the -bundle option.
3113 static void addBundleLinkArgs(const Darwin &D, const ArgList &Args,
3114  ArgStringList &CmdArgs) {
3115  if (Args.hasArg(options::OPT_static))
3116  return;
3117  // Derived from darwin_bundle1 spec.
3118  if ((D.isTargetIPhoneOS() && D.isIPhoneOSVersionLT(3, 1)) ||
3119  (D.isTargetMacOS() && D.isMacosxVersionLT(10, 6)))
3120  CmdArgs.push_back("-lbundle1.o");
3121 }
3122 
3123 // Add additional link args for the -pg option.
3124 static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args,
3125  ArgStringList &CmdArgs) {
3126  if (D.isTargetMacOS() && D.isMacosxVersionLT(10, 9)) {
3127  if (Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_object) ||
3128  Args.hasArg(options::OPT_preload)) {
3129  CmdArgs.push_back("-lgcrt0.o");
3130  } else {
3131  CmdArgs.push_back("-lgcrt1.o");
3132 
3133  // darwin_crt2 spec is empty.
3134  }
3135  // By default on OS X 10.8 and later, we don't link with a crt1.o
3136  // file and the linker knows to use _main as the entry point. But,
3137  // when compiling with -pg, we need to link with the gcrt1.o file,
3138  // so pass the -no_new_main option to tell the linker to use the
3139  // "start" symbol as the entry point.
3140  if (!D.isMacosxVersionLT(10, 8))
3141  CmdArgs.push_back("-no_new_main");
3142  } else {
3143  D.getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
3144  << D.isTargetMacOSBased();
3145  }
3146 }
3147 
3148 static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args,
3149  ArgStringList &CmdArgs) {
3150  // Derived from darwin_crt1 spec.
3151  if (D.isTargetIPhoneOS()) {
3152  if (D.getArch() == llvm::Triple::aarch64)
3153  ; // iOS does not need any crt1 files for arm64
3154  else if (D.isIPhoneOSVersionLT(3, 1))
3155  CmdArgs.push_back("-lcrt1.o");
3156  else if (D.isIPhoneOSVersionLT(6, 0))
3157  CmdArgs.push_back("-lcrt1.3.1.o");
3158  return;
3159  }
3160 
3161  if (!D.isTargetMacOS())
3162  return;
3163  if (D.isMacosxVersionLT(10, 5))
3164  CmdArgs.push_back("-lcrt1.o");
3165  else if (D.isMacosxVersionLT(10, 6))
3166  CmdArgs.push_back("-lcrt1.10.5.o");
3167  else if (D.isMacosxVersionLT(10, 8))
3168  CmdArgs.push_back("-lcrt1.10.6.o");
3169  // darwin_crt2 spec is empty.
3170 }
3171 
3172 void Darwin::addStartObjectFileArgs(const ArgList &Args,
3173  ArgStringList &CmdArgs) const {
3174  // Derived from startfile spec.
3175  if (Args.hasArg(options::OPT_dynamiclib))
3176  addDynamicLibLinkArgs(*this, Args, CmdArgs);
3177  else if (Args.hasArg(options::OPT_bundle))
3178  addBundleLinkArgs(*this, Args, CmdArgs);
3179  else if (Args.hasArg(options::OPT_pg) && SupportsProfiling())
3180  addPgProfilingLinkArgs(*this, Args, CmdArgs);
3181  else if (Args.hasArg(options::OPT_static) ||
3182  Args.hasArg(options::OPT_object) ||
3183  Args.hasArg(options::OPT_preload))
3184  CmdArgs.push_back("-lcrt0.o");
3185  else
3186  addDefaultCRTLinkArgs(*this, Args, CmdArgs);
3187 
3188  if (isTargetMacOS() && Args.hasArg(options::OPT_shared_libgcc) &&
3189  isMacosxVersionLT(10, 5)) {
3190  const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
3191  CmdArgs.push_back(Str);
3192  }
3193 }
3194 
3195 void Darwin::CheckObjCARC() const {
3197  (isTargetMacOSBased() && !isMacosxVersionLT(10, 6)))
3198  return;
3199  getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
3200 }
3201 
3203  const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3204  const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
3206  Res |= SanitizerKind::Address;
3207  Res |= SanitizerKind::PointerCompare;
3208  Res |= SanitizerKind::PointerSubtract;
3209  Res |= SanitizerKind::Leak;
3210  Res |= SanitizerKind::Fuzzer;
3211  Res |= SanitizerKind::FuzzerNoLink;
3212  Res |= SanitizerKind::Function;
3213  Res |= SanitizerKind::ObjCCast;
3214 
3215  // Prior to 10.9, macOS shipped a version of the C++ standard library without
3216  // C++11 support. The same is true of iOS prior to version 5. These OS'es are
3217  // incompatible with -fsanitize=vptr.
3218  if (!(isTargetMacOSBased() && isMacosxVersionLT(10, 9)) &&
3219  !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)))
3220  Res |= SanitizerKind::Vptr;
3221 
3222  if ((IsX86_64 || IsAArch64) && isTargetMacOSBased()) {
3223  Res |= SanitizerKind::Thread;
3224  } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
3225  if (IsX86_64)
3226  Res |= SanitizerKind::Thread;
3227  }
3228  return Res;
3229 }
3230 
3231 void Darwin::printVerboseInfo(raw_ostream &OS) const {
3232  CudaInstallation.print(OS);
3233  RocmInstallation.print(OS);
3234 }
addBundleLinkArgs
static void addBundleLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Darwin.cpp:3113
clang::driver::toolchains
Definition: AIX.h:55
addDefaultCRTLinkArgs
static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Darwin.cpp:3148
clang::driver::toolchains::Darwin::isAlignedAllocationUnavailable
bool isAlignedAllocationUnavailable() const
Return true if c++17 aligned allocation/deallocation functions are not implemented in the c++ standar...
Definition: Darwin.cpp:2716
clang::driver::tools::darwin::Assembler::ConstructJob
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:92
clang::driver::toolchains::Darwin::SupportsEmbeddedBitcode
bool SupportsEmbeddedBitcode() const override
SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
Definition: Darwin.cpp:2918
Darwin.h
clang::driver::toolchains::MachO::TranslateArgs
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:2530
clang::driver::ToolChain::getEffectiveTriple
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition: ToolChain.h:255
clang::driver::options::LinkerInput
@ LinkerInput
Definition: Options.h:26
clang::driver::toolchains::MachO::addPlatformVersionArgs
virtual void addPlatformVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Darwin.h:188
clang::driver::ToolChain::getVFS
llvm::vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:99
ObjCRuntime.h
clang::driver::RocmInstallationDetector::AddHIPIncludeArgs
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: AMDGPU.cpp:486
clang::driver::ToolChain::getProgramPaths
path_list & getProgramPaths()
Definition: ToolChain.h:266
clang::driver::toolchains::DarwinClang::AddCXXStdlibLibArgs
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:2457
clang::driver::tools::addFortranRuntimeLibs
void addFortranRuntimeLibs(llvm::opt::ArgStringList &CmdArgs)
Adds Fortran runtime libraries to CmdArgs.
Definition: CommonArgs.cpp:751
clang::driver::toolchains::Darwin::isTargetAppleSiliconMac
bool isTargetAppleSiliconMac() const
Definition: Darwin.h:458
Driver.h
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
hasMultipleInvocations
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition: Clang.cpp:1528
clang::driver::Driver::Dir
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition: Driver.h:143
clang::driver::tools::darwin::Linker::ConstructJob
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:525
clang::driver::toolchains::Darwin::addProfileRTLibs
void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Add any profiling runtime libraries that are needed.
Definition: Darwin.cpp:1329
clang::driver::toolchains::MachO::RLO_AlwaysLink
@ RLO_AlwaysLink
Link the library in even if it can't be found in the VFS.
Definition: Darwin.h:202
clang::driver::toolchains::Darwin::addMinVersionArgs
void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition: Darwin.cpp:2939
clang::driver::ResponseFileSupport::AtFileUTF8
static constexpr ResponseFileSupport AtFileUTF8()
Definition: Job.h:85
clang::driver::tools::darwin::Assembler
Definition: Darwin.h:49
clang::driver::toolchains::MachO::RLO_IsEmbedded
@ RLO_IsEmbedded
Use the embedded runtime from the macho_embedded directory.
Definition: Darwin.h:205
clang::driver::Action::getInputs
ActionList & getInputs()
Definition: Action.h:151
clang::driver::ToolChain::TranslateXarchArgs
virtual void TranslateXarchArgs(const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A, llvm::opt::DerivedArgList *DAL, SmallVectorImpl< llvm::opt::Arg * > *AllocatedArgs=nullptr) const
Append the argument following A to DAL assuming A is an Xarch argument.
Definition: ToolChain.cpp:1196
llvm::SmallVector
Definition: LLVM.h:38
clang::driver::toolchains::Darwin::addPlatformVersionArgs
void addPlatformVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition: Darwin.cpp:3008
clang::driver::tools::arm::getARMFloatABI
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
clang::driver::Action::ActionClass
ActionClass
Definition: Action.h:55
clang::driver::toolchains::MachO::~MachO
~MachO() override
Definition: Darwin.cpp:1037
clang::driver::ToolChain::needsProfileRT
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
Definition: ToolChain.cpp:548
clang::driver::Action
Action - Represent an abstract compilation step to perform.
Definition: Action.h:47
clang::driver::toolchains::Darwin::TranslateArgs
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:2815
clang::driver::Action::getKind
ActionClass getKind() const
Definition: Action.h:148
clang::ObjCRuntime::hasNativeARC
bool hasNativeARC() const
Does this runtime natively provide the ARC entrypoints?
Definition: ObjCRuntime.h:162
clang::MultiVersionKind::Target
@ Target
clang::driver::toolchains::MachO::getTool
Tool * getTool(Action::ActionClass AC) const override
Definition: Darwin.cpp:1065
clang::driver::toolchains::Darwin::isTargetWatchOSBased
bool isTargetWatchOSBased() const
Definition: Darwin.h:434
clang::driver::Action::LipoJobClass
@ LipoJobClass
Definition: Action.h:70
clang::driver::toolchains::Darwin::TargetVersion
VersionTuple TargetVersion
The native OS version we are targeting.
Definition: Darwin.h:315
getSystemOrSDKMacOSVersion
static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion)
Returns the most appropriate macOS target version for the current process.
Definition: Darwin.cpp:1474
clang::driver::toolchains::MachO::AddLinkRuntimeLibArgs
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:2700
clang::driver::ToolChain::AddClangCXXStdlibIncludeArgs
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:940
clang::driver::tools
Definition: AIX.h:17
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:55
clang::driver::ToolChain::getDefaultUniversalArchName
StringRef getDefaultUniversalArchName() const
Provide the default architecture name (as expected by -arch) for this toolchain.
Definition: ToolChain.cpp:233
clang::driver::ToolChain::getDriver
const Driver & getDriver() const
Definition: ToolChain.h:225
clang::driver::toolchains::Darwin::getPlatformFamily
StringRef getPlatformFamily() const
Definition: Darwin.cpp:1244
clang::driver::toolchains::DarwinClang::GetRuntimeLibType
RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const override
Definition: Darwin.cpp:1382
clang::driver::toolchains::MachO::getLinkerVersion
VersionTuple getLinkerVersion(const llvm::opt::ArgList &Args) const
Get the version of the linker known to be available for a particular compiler invocation (via the -ml...
Definition: Darwin.cpp:1014
clang::driver::SanitizerArgs::needsTsanRt
bool needsTsanRt() const
Definition: SanitizerArgs.h:84
getXcodeDeveloperPath
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:1120
clang::driver::toolchains::Darwin::getOSLibraryNameSuffix
StringRef getOSLibraryNameSuffix(bool IgnoreSim=false) const override
Definition: Darwin.cpp:1274
clang::driver::toolchains::Darwin::isTargetIPhoneOS
bool isTargetIPhoneOS() const
Definition: Darwin.h:392
clang::driver::toolchains::Darwin::isTargetDriverKit
bool isTargetDriverKit() const
Definition: Darwin.h:439
llvm::Optional< llvm::Triple >
clang::driver::toolchains::Darwin::WatchOS
@ WatchOS
Definition: Darwin.h:301
clang::driver::toolchains::Darwin::isTargetMacOSBased
bool isTargetMacOSBased() const
Definition: Darwin.h:453
clang::driver::toolchains::Darwin::CheckObjCARC
void CheckObjCARC() const override
Complain if this tool chain doesn't support Objective-C ARC.
Definition: Darwin.cpp:3195
clang::driver::ToolChain::GetFilePath
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:577
clang::driver::toolchains::MachO::AddLinkRuntimeLib
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:1196
clang::driver::toolchains::DarwinClang::AddLinkARCArgs
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:1129
clang::driver::toolchains::MachO::isPICDefault
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition: Darwin.cpp:2925
clang::driver::tools::getLastProfileUseArg
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
AArch64.h
clang::driver::tools::darwin::MachOTool::AddMachOArch
void AddMachOArch(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Darwin.cpp:162
clang::driver::tools::darwin::getArchTypeForMachOArchName
llvm::Triple::ArchType getArchTypeForMachOArchName(StringRef Str)
Definition: Darwin.cpp:41
clang::driver::ToolChain::getArchName
StringRef getArchName() const
Definition: ToolChain.h:242
clang::driver::Driver::getOpts
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:358
clang::driver::ToolChain::getSanitizerArgs
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const
Definition: ToolChain.cpp:118
clang::driver::InputInfo
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
clang::driver::toolchains::Darwin::getSupportedSanitizers
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Definition: Darwin.cpp:3202
clang::driver::toolchains::Darwin::isTargetTvOSSimulator
bool isTargetTvOSSimulator() const
Definition: Darwin.h:414
addDynamicLibLinkArgs
static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Darwin.cpp:3095
clang::driver::toolchains::Darwin::getTripleTargetVersion
VersionTuple getTripleTargetVersion() const
The version of the OS that's used by the OS specified in the target triple.
Definition: Darwin.h:469
clang::driver::tools::darwin::Linker
Definition: Darwin.h:62
clang::driver::ToolChain::RuntimeLibType
RuntimeLibType
Definition: ToolChain.h:100
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1500
clang::driver::toolchains::Darwin::Darwin
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:887
clang::driver::XRayArgs
Definition: XRayArgs.h:21
clang::driver::tools::AddLinkerInputs
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
clang::driver::toolchains::DarwinClang::AddClangCXXStdlibIncludeArgs
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:2342
clang::driver::toolchains::Darwin::CudaInstallation
CudaInstallationDetector CudaInstallation
Definition: Darwin.h:325
getPlatformName
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition: Darwin.cpp:2989
U
clang::ObjCRuntime::FragileMacOSX
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:40
arch
CudaArch arch
Definition: Cuda.cpp:73
clang::driver::toolchains::Darwin::DriverKit
@ DriverKit
Definition: Darwin.h:302
clang::driver::Action::DsymutilJobClass
@ DsymutilJobClass
Definition: Action.h:71
clang::driver::Driver::getLTOMode
LTOKind getLTOMode(bool IsOffload=false) const
Get the specific kind of LTO being performed.
Definition: Driver.h:624
clang::getAsString
llvm::StringRef getAsString(SyncScope S)
Definition: SyncScope.h:55
clang::driver::toolchains::DarwinClang::AddClangSystemIncludeArgs
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:2263
V
#define V(N, I)
Definition: ASTContext.h:3176
clang::driver::Driver::Diag
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:132
clang::driver::toolchains::MachO::buildStaticLibTool
Tool * buildStaticLibTool() const override
Definition: Darwin.cpp:1086
clang::driver::SanitizerArgs::requiresMinimalRuntime
bool requiresMinimalRuntime() const
Definition: SanitizerArgs.h:94
clang::driver::toolchains::MachO::RuntimeLinkOptions
RuntimeLinkOptions
Options to control how a runtime library is linked.
Definition: Darwin.h:200
clang::driver::tools::darwin::StaticLibTool::ConstructJob
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:762
clang::driver::toolchains::Darwin::isTargetTvOSBased
bool isTargetTvOSBased() const
Definition: Darwin.h:419
clang::driver::toolchains::MachO::LookupTypeForExtension
types::ID LookupTypeForExtension(StringRef Ext) const override
LookupTypeForExtension - Return the default language type to use for the given extension.
Definition: Darwin.cpp:891
clang::driver::toolchains::Darwin::isTargetInitialized
bool isTargetInitialized() const
Definition: Darwin.h:463
clang::driver::Tool
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
clang::driver::toolchains::DarwinClang::AddLinkRuntimeLibArgs
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:1394
clang::ObjCRuntime::MacOSX
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition: ObjCRuntime.h:35
Options.h
clang::driver::InputInfo::isFilename
bool isFilename() const
Definition: InputInfo.h:75
clang::driver::tools::darwin::Lipo::ConstructJob
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:810
clang::driver::SanitizerArgs::needsFuzzer
bool needsFuzzer() const
Definition: SanitizerArgs.h:86
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::driver::toolchains::Darwin::SDKInfo
Optional< DarwinSDKInfo > SDKInfo
The information about the darwin SDK that was used.
Definition: Darwin.h:320
clang::driver::XRayArgs::needsXRayRt
bool needsXRayRt() const
Definition: XRayArgs.h:44
clang::driver::Action::getType
types::ID getType() const
Definition: Action.h:149
clang::driver::toolchains::Darwin::isIPhoneOSVersionLT
bool isIPhoneOSVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const
Definition: Darwin.h:474
clang::driver::LTOK_Thin
@ LTOK_Thin
Definition: Driver.h:55
llvm::opt
Definition: DiagnosticOptions.h:19
checkRemarksOptions
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition: Darwin.cpp:456
DriverDiagnostic.h
clang::driver::options::ID
ID
Definition: Options.h:42
clang::driver::toolchains::Darwin
Darwin - The base Darwin tool chain.
Definition: Darwin.h:288
clang::driver::toolchains::Darwin::isTargetMacCatalyst
bool isTargetMacCatalyst() const
Definition: Darwin.h:444
clang::driver::toolchains::Darwin::RocmInstallation
RocmInstallationDetector RocmInstallation
Definition: Darwin.h:326
clang::driver::ToolChain::CXXStdlibType
CXXStdlibType
Definition: ToolChain.h:95
clang::driver::toolchains::Darwin::isTargetMacOS
bool isTargetMacOS() const
Definition: Darwin.h:448
clang::driver::toolchains::MachO::isPICDefaultForced
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition: Darwin.cpp:2929
clang::driver::tools::arm::FloatABI::Hard
@ Hard
clang::driver::toolchains::Darwin::addStartObjectFileArgs
void addStartObjectFileArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition: Darwin.cpp:3172
clang::driver::tools::getLTOParallelism
llvm::StringRef getLTOParallelism(const llvm::opt::ArgList &Args, const Driver &D)
clang::driver::toolchains::Darwin::TargetInitialized
bool TargetInitialized
Whether the information on the target has been initialized.
Definition: Darwin.h:295
llvm::SmallString< 128 >
clang::driver::ToolChain::getTriple
const llvm::Triple & getTriple() const
Definition: ToolChain.h:227
clang::driver::Driver::SysRoot
std::string SysRoot
sysroot, if present
Definition: Driver.h:171
clang::driver::toolchains::MachO::isTargetIOSBased
bool isTargetIOSBased() const
Is the target either iOS or an iOS simulator?
Definition: Darwin.h:197
clang::driver::SanitizerArgs::needsAsanRt
bool needsAsanRt() const
Definition: SanitizerArgs.h:77
clang::driver::toolchains::Darwin::GetExceptionModel
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition: Darwin.cpp:2904
clang::ObjCRuntime::WatchOS
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Definition: ObjCRuntime.h:49
clang::driver::tools::darwin::Lipo
Definition: Darwin.h:95
clang::driver::toolchains::Darwin::addClangTargetOptions
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:2741
clang::driver::ToolChain::CST_Libcxx
@ CST_Libcxx
Definition: ToolChain.h:96
clang::driver::toolchains::Darwin::TargetPlatform
DarwinPlatformKind TargetPlatform
Definition: Darwin.h:311
clang::driver::toolchains::Darwin::setTarget
void setTarget(DarwinPlatformKind Platform, DarwinEnvironmentKind Environment, unsigned Major, unsigned Minor, unsigned Micro, VersionTuple NativeTargetVersion) const
Definition: Darwin.h:366
clang::driver::toolchains::MachO::isPIEDefault
bool isPIEDefault(const llvm::opt::ArgList &Args) const override
Test whether this toolchain defaults to PIE.
Definition: Darwin.cpp:2927
clang::driver::LTOK_Full
@ LTOK_Full
Definition: Driver.h:54
clang::driver::toolchains::Darwin::getDefaultObjCRuntime
ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const override
Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
Definition: Darwin.cpp:914
Base
clang::driver::toolchains::Darwin::isTargetTvOS
bool isTargetTvOS() const
Definition: Darwin.h:409
clang::driver::toolchains::Darwin::isTargetWatchOS
bool isTargetWatchOS() const
Definition: Darwin.h:424
clang::driver::toolchains::Darwin::IPhoneOS
@ IPhoneOS
Definition: Darwin.h:299
clang::driver::SanitizerArgs
Definition: SanitizerArgs.h:24
clang::driver::tools::darwin::Dsymutil
Definition: Darwin.h:107
SanitizerArgs.h
clang::driver::toolchains::MachO::buildLinker
Tool * buildLinker() const override
Definition: Darwin.cpp:1084
clang::driver::ToolChain::CST_Libstdcxx
@ CST_Libstdcxx
Definition: ToolChain.h:97
clang::driver::toolchains::DarwinClang::addClangWarningOptions
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Add warning options that need to be passed to cc1 for this target.
Definition: Darwin.cpp:1098
clang::driver::toolchains::Darwin::TargetVariantTriple
Optional< llvm::Triple > TargetVariantTriple
The target variant triple that was specified (if any).
Definition: Darwin.h:323
Cmd
CompileCommand Cmd
Definition: InterpolatingCompilationDatabase.cpp:130
clang::driver::Driver::ResourceDir
std::string ResourceDir
The path to the compiler resource directory.
Definition: Driver.h:155
clang::driver::ToolChain::getArch
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:241
clang::driver::toolchains::DarwinClang::DarwinClang
DarwinClang(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: Darwin.cpp:1094
clang::driver::toolchains::MachO::UseDwarfDebugFlags
bool UseDwarfDebugFlags() const override
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition: Darwin.cpp:2892
clang::driver::toolchains::Darwin::isMacosxVersionLT
bool isMacosxVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const
Returns true if the minimum supported macOS version for the slice that's being built is less than the...
Definition: Darwin.h:484
clang::driver::SanitizerArgs::needsLsanRt
bool needsLsanRt() const
Definition: SanitizerArgs.h:87
minimumMacCatalystDeploymentTarget
static VersionTuple minimumMacCatalystDeploymentTarget()
Definition: Darwin.cpp:37
clang::driver::RocmInstallationDetector::print
void print(raw_ostream &OS) const
Print information about the detected ROCm installation.
Definition: AMDGPU.cpp:480
clang::driver::toolchains::Darwin::ComputeEffectiveClangTriple
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:1039
clang::driver::toolchains::Darwin::GetDefaultCXXStdlibType
CXXStdlibType GetDefaultCXXStdlibType() const override
Definition: Darwin.cpp:903
AlignedAllocation.h
hasExportSymbolDirective
static bool hasExportSymbolDirective(const ArgList &Args)
Check if the link command contains a symbol export directive.
Definition: Darwin.cpp:1296
clang::transformer::remove
ASTEdit remove(RangeSelector S)
Removes the source selected by S.
Definition: RewriteRule.cpp:146
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::driver::ToolChain::getSupportedSanitizers
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:1031
clang::driver::Driver::isUsingLTO
bool isUsingLTO(bool IsOffload=false) const
Returns true if we are performing any kind of LTO.
Definition: Driver.h:619
clang::driver::ToolChain::getTool
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:344
false
#define false
Definition: stdbool.h:22
clang::driver::toolchains::Darwin::AddCudaIncludeArgs
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific CUDA includes.
Definition: Darwin.cpp:936
clang::driver::toolchains::Darwin::isTargetWatchOSSimulator
bool isTargetWatchOSSimulator() const
Definition: Darwin.h:429
Compilation.h
clang::driver::tools::darwin::StaticLibTool
Definition: Darwin.h:81
clang::driver::Driver::GetTemporaryPath
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:5832
clang::driver::types::getTypeTempSuffix
const char * getTypeTempSuffix(ID Id, bool CLMode=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type,...
Definition: Types.cpp:83
clang::driver::ToolChain
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:91
clang::driver::toolchains::MachO::buildAssembler
Tool * buildAssembler() const override
Definition: Darwin.cpp:1090
clang::driver::ToolChain::RLT_CompilerRT
@ RLT_CompilerRT
Definition: ToolChain.h:101
clang::driver::toolchains::Darwin::isTargetIOSSimulator
bool isTargetIOSSimulator() const
Definition: Darwin.h:398
Value
Value
Definition: UninitializedValues.cpp:102
clang::driver::ToolChain::LookupTypeForExtension
virtual types::ID LookupTypeForExtension(StringRef Ext) const
LookupTypeForExtension - Return the default language type to use for the given extension.
Definition: ToolChain.cpp:659
clang::driver::toolchains::Darwin::TvOS
@ TvOS
Definition: Darwin.h:300
clang::DarwinSDKInfo
The information about the darwin SDK that was used during this compilation.
Definition: DarwinSDKInfo.h:28
clang::driver::tools::darwin::VerifyDebug::ConstructJob
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:854
clang::driver::toolchains::MachO::getOSLibraryNameSuffix
virtual StringRef getOSLibraryNameSuffix(bool IgnoreSim=false) const
Definition: Darwin.h:277
clang::driver::toolchains::Darwin::MacOS
@ MacOS
Definition: Darwin.h:298
clang::driver::ToolChain::ComputeLLVMTriple
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:714
clang::driver::ToolChain::SupportsEmbeddedBitcode
virtual bool SupportsEmbeddedBitcode() const
SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
Definition: ToolChain.h:555
clang::driver::tools::darwin::setTripleTypeForMachOArchName
void setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str)
Definition: Darwin.cpp:77
clang::driver::toolchains::Darwin::isTargetIOSBased
bool isTargetIOSBased() const
Definition: Darwin.h:404
clang::driver::CudaInstallationDetector::AddCudaIncludeArgs
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: Cuda.cpp:284
clang::driver::toolchains::MachO::SupportsProfiling
bool SupportsProfiling() const override
SupportsProfiling - Does this tool chain support -pg.
Definition: Darwin.cpp:2934
clang::DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair
static constexpr OSEnvPair macOStoMacCatalystPair()
Returns the os-environment mapping pair that's used to represent the macOS -> Mac Catalyst version ma...
Definition: DarwinSDKInfo.h:48
clang::driver::types::ID
ID
Definition: Types.h:23
clang::driver::Compilation
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
clang::driver::toolchains::Darwin::NativeEnvironment
@ NativeEnvironment
Definition: Darwin.h:306
clang::ObjCRuntime
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
renderRemarksOptions
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Output, const JobAction &JA)
Definition: Darwin.cpp:473
clang::driver::toolchains::DarwinClang::GetDefaultDwarfVersion
unsigned GetDefaultDwarfVersion() const override
Definition: Darwin.cpp:1188
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::DarwinSDKInfo::OSEnvPair::macCatalystToMacOSPair
static constexpr OSEnvPair macCatalystToMacOSPair()
Returns the os-environment mapping pair that's used to represent the Mac Catalyst -> macOS version ma...
Definition: DarwinSDKInfo.h:55
clang::driver::willEmitRemarks
bool willEmitRemarks(const llvm::opt::ArgList &Args)
clang::driver::ToolChain::GetCXXStdlibType
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:852
clang::driver::toolchains::MachO::GetExceptionModel
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition: Darwin.h:273
clang::driver::toolchains::Darwin::hasBlocksRuntime
bool hasBlocksRuntime() const override
Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
Definition: Darwin.cpp:925
addExportedSymbol
static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol)
Add an export directive for Symbol to the link command.
Definition: Darwin.cpp:1311
clang::driver::toolchains::Darwin::Simulator
@ Simulator
Definition: Darwin.h:307
clang::driver::tools::addOpenMPRuntime
bool addOpenMPRuntime(llvm::opt::ArgStringList &CmdArgs, const ToolChain &TC, const llvm::opt::ArgList &Args, bool ForceStaticHostRuntime=false, bool IsOffloadingHost=false, bool GompNeedsRT=false)
Returns true, if an OpenMP runtime has been added.
clang::driver::InputInfo::getFilename
const char * getFilename() const
Definition: InputInfo.h:83
clang::driver::toolchains::MachO::getMachOArchName
StringRef getMachOArchName(const llvm::opt::ArgList &Args) const
Get the "MachO" arch name for a particular compiler invocation.
Definition: Darwin.cpp:986
clang::driver::toolchains::MachO::RLO_AddRPath
@ RLO_AddRPath
Emit rpaths for @executable_path as well as the resource directory.
Definition: Darwin.h:208
CommonArgs.h
clang
Definition: CalledOnceCheck.h:17
clang::driver::Driver
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:71
clang::driver::InputInfo::getType
types::ID getType() const
Definition: InputInfo.h:77
clang::driver::toolchains::Darwin::getSDKName
static StringRef getSDKName(StringRef isysroot)
Definition: Darwin.cpp:1262
clang::driver::toolchains::Darwin::~Darwin
~Darwin() override
Definition: Darwin.cpp:1035
clang::driver::Driver::GetTemporaryDirectory
std::string GetTemporaryDirectory(StringRef Prefix) const
GetTemporaryDirectory - Return the pathname of a temporary directory to use as part of compilation; t...
Definition: Driver.cpp:5843
clang::driver::toolchains::MachO
Definition: Darwin.h:138
isObjCRuntimeLinked
static bool isObjCRuntimeLinked(const ArgList &Args)
Determine whether we are linking the ObjC runtime.
Definition: Darwin.cpp:448
clang::driver::tools::darwin::Dsymutil::ConstructJob
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:833
clang::driver::toolchains::MachO::IsUnwindTablesDefault
bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const override
IsUnwindTablesDefault - Does this tool chain use -funwind-tables by default.
Definition: Darwin.cpp:2883
clang::driver::toolchains::Darwin::AddHIPIncludeArgs
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific HIP includes.
Definition: Darwin.cpp:941
clang::driver::SanitizerArgs::needsUbsanRt
bool needsUbsanRt() const
Definition: SanitizerArgs.cpp:257
clang::driver::Action::VerifyDebugInfoJobClass
@ VerifyDebugInfoJobClass
Definition: Action.h:72
clang::driver::tools::darwin::VerifyDebug
Definition: Darwin.h:121
clang::ObjCRuntime::hasSubscripting
bool hasSubscripting() const
Does this runtime directly support the subscripting methods?
Definition: ObjCRuntime.h:298
clang::driver::toolchains::MachO::HasNativeLLVMSupport
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: Darwin.cpp:901
clang::driver::ToolChain::addExternCSystemInclude
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:893
clang::driver::ResponseFileSupport::RF_FileList
@ RF_FileList
Definition: Job.h:51
addSectalignToPage
static void addSectalignToPage(const ArgList &Args, ArgStringList &CmdArgs, StringRef Segment, StringRef Section)
Add a sectalign directive for Segment and Section to the maximum expected page size for Darwin.
Definition: Darwin.cpp:1322
clang::driver::ToolChain::needsGCovInstrumentation
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
Definition: ToolChain.cpp:562
clang::driver::toolchains::Darwin::printVerboseInfo
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition: Darwin.cpp:3231
clang::ObjCRuntime::iOS
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition: ObjCRuntime.h:45
clang::driver::toolchains::Darwin::DarwinEnvironmentKind
DarwinEnvironmentKind
Definition: Darwin.h:305
ARM.h
clang::driver::ToolChain::getXRayArgs
const XRayArgs & getXRayArgs() const
Definition: ToolChain.cpp:124
clang::driver::toolchains::DarwinClang::AddCCKextLibArgs
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:2502
clang::driver::toolchains::MachO::addMinVersionArgs
virtual void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Darwin.h:185
clang::driver::Action::OffloadKind
OffloadKind
Definition: Action.h:88
clang::driver
Definition: Action.h:31
clang::alignedAllocMinVersion
llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS)
Definition: AlignedAllocation.h:24
clang::driver::ResponseFileSupport::None
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition: Job.h:78
clang::driver::ToolChain::addSystemInclude
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:878
clang::driver::CudaInstallationDetector::print
void print(raw_ostream &OS) const
Print information about the detected CUDA installation.
Definition: Cuda.cpp:325
clang::driver::SanitizerArgs::needsSharedRt
bool needsSharedRt() const
Definition: SanitizerArgs.h:74
ArmMachOArchName
static const char * ArmMachOArchName(StringRef Arch)
Definition: Darwin.cpp:950
clang::driver::JobAction
Definition: Action.h:395
clang::driver::toolchains::Darwin::DarwinPlatformKind
DarwinPlatformKind
Definition: Darwin.h:297
addPgProfilingLinkArgs
static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Darwin.cpp:3124
clang::driver::Driver::GetReleaseVersion
static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra)
GetReleaseVersion - Parse (([0-9]+)(.
Definition: Driver.cpp:6148
clang::driver::SanitizerArgs::needsStatsRt
bool needsStatsRt() const
Definition: SanitizerArgs.h:99
shouldLinkerNotDedup
static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args)
Pass -no_deduplicate to ld64 under certain conditions:
Definition: Darwin.cpp:193
clang::driver::toolchains::MachO::GetGlobalDebugPathRemapping
std::string GetGlobalDebugPathRemapping() const override
Add an additional -fdebug-prefix-map entry.
Definition: Darwin.cpp:2898
clang::driver::tools::getStatsFileName
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.
Definition: CommonArgs.cpp:1588
clang::driver::tools::addFortranRuntimeLibraryPath
void addFortranRuntimeLibraryPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds the path for the Fortran runtime libraries to CmdArgs.
ArmMachOArchNameCPU
static const char * ArmMachOArchNameCPU(StringRef CPU)
Definition: Darwin.cpp:967
clang::driver::toolchains::Darwin::TargetEnvironment
DarwinEnvironmentKind TargetEnvironment
Definition: Darwin.h:312
clang::SanitizerMask
Definition: Sanitizers.h:30
clang::driver::Action::InputClass
@ InputClass
Definition: Action.h:56
clang::driver::toolchains::Darwin::LastDarwinPlatform
@ LastDarwinPlatform
Definition: Darwin.h:303
clang::driver::toolchains::Darwin::MacCatalyst
@ MacCatalyst
Definition: Darwin.h:308
clang::driver::tools::isObjCAutoRefCount
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
clang::parseDarwinSDKInfo
Expected< Optional< DarwinSDKInfo > > parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath)
Parse the SDK information from the SDKSettings.json file.
Definition: DarwinSDKInfo.cpp:130
clang::driver::ResponseFileSupport
Definition: Job.h:44