1//===--- Darwin.cpp - Darwin Tool and ToolChain Implementations -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Darwin.h"
10#include "Arch/ARM.h"
11#include "clang/Basic/AlignedAllocation.h"
12#include "clang/Basic/ObjCRuntime.h"
13#include "clang/Config/config.h"
14#include "clang/Driver/CommonArgs.h"
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/Driver.h"
17#include "clang/Driver/SanitizerArgs.h"
18#include "clang/Options/Options.h"
19#include "llvm/ADT/StringSwitch.h"
20#include "llvm/Option/ArgList.h"
21#include "llvm/ProfileData/InstrProf.h"
22#include "llvm/ProfileData/MemProf.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/Threading.h"
25#include "llvm/Support/VirtualFileSystem.h"
26#include "llvm/TargetParser/TargetParser.h"
27#include "llvm/TargetParser/Triple.h"
28#include <cstdlib> // ::getenv
29
30#ifdef CLANG_USE_XCSELECT
31#include <xcselect.h> // ::xcselect_host_sdk_path
32#endif
33
34using namespace clang::driver;
35using namespace clang::driver::tools;
36using namespace clang::driver::toolchains;
37using namespace clang;
38using namespace llvm::opt;
39
40static VersionTuple minimumMacCatalystDeploymentTarget() {
41 return VersionTuple(13, 1);
42}
43
44llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
45 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
46 // archs which Darwin doesn't use.
47
48 // The matching this routine does is fairly pointless, since it is neither the
49 // complete architecture list, nor a reasonable subset. The problem is that
50 // historically the driver accepts this and also ties its -march=
51 // handling to the architecture name, so we need to be careful before removing
52 // support for it.
53
54 // This code must be kept in sync with Clang's Darwin specific argument
55 // translation.
56
57 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
58 .Cases(CaseStrings: {"i386", "i486", "i486SX", "i586", "i686"}, Value: llvm::Triple::x86)
59 .Cases(CaseStrings: {"pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4"},
60 Value: llvm::Triple::x86)
61 .Cases(CaseStrings: {"x86_64", "x86_64h"}, Value: llvm::Triple::x86_64)
62 // This is derived from the driver.
63 .Cases(CaseStrings: {"arm", "armv4t", "armv5", "armv6", "armv6m"}, Value: llvm::Triple::arm)
64 .Cases(CaseStrings: {"armv7", "armv7em", "armv7k", "armv7m"}, Value: llvm::Triple::arm)
65 .Cases(CaseStrings: {"armv7s", "xscale"}, Value: llvm::Triple::arm)
66 .Cases(CaseStrings: {"armv8m.base", "armv8m.main", "armv8.1m.main"}, Value: llvm::Triple::arm)
67 .Cases(CaseStrings: {"arm64", "arm64e"}, Value: llvm::Triple::aarch64)
68 .Case(S: "arm64_32", Value: llvm::Triple::aarch64_32)
69 .Cases(CaseStrings: {"amdgpu", "amdgcn"}, Value: llvm::Triple::amdgpu)
70 .Case(S: "r600", Value: llvm::Triple::r600)
71 .Case(S: "nvptx", Value: llvm::Triple::nvptx)
72 .Case(S: "nvptx64", Value: llvm::Triple::nvptx64)
73 .Case(S: "amdil", Value: llvm::Triple::amdil)
74 .Case(S: "spir", Value: llvm::Triple::spir)
75 .Default(Value: llvm::Triple::UnknownArch);
76}
77
78void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str,
79 const ArgList &Args) {
80 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
81 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Arch: Str);
82 T.setArch(Kind: Arch);
83 if (Arch != llvm::Triple::UnknownArch)
84 T.setArchName(Str);
85
86 // Standalone/bare metal compiles often unintentionally come out as
87 // armv6m-apple-ios (-target not specified, or set from Xcode). Change these
88 // cases to armv6m-apple-unknown-macho to better reflect intent.
89 if ((T.getOS() != llvm::Triple::Firmware) &&
90 (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
91 ArchKind == llvm::ARM::ArchKind::ARMV7M ||
92 ArchKind == llvm::ARM::ArchKind::ARMV7EM ||
93 ArchKind == llvm::ARM::ArchKind::ARMV8MBaseline ||
94 ArchKind == llvm::ARM::ArchKind::ARMV8MMainline ||
95 ArchKind == llvm::ARM::ArchKind::ARMV8_1MMainline)) {
96 // Don't reject these -version-min= if we have the appropriate triple.
97 if (T.getOS() == llvm::Triple::IOS)
98 for (Arg *A : Args.filtered(Ids: options::OPT_mios_version_min_EQ))
99 A->ignoreTargetSpecific();
100 if (T.getOS() == llvm::Triple::WatchOS)
101 for (Arg *A : Args.filtered(Ids: options::OPT_mwatchos_version_min_EQ))
102 A->ignoreTargetSpecific();
103 if (T.getOS() == llvm::Triple::TvOS)
104 for (Arg *A : Args.filtered(Ids: options::OPT_mtvos_version_min_EQ))
105 A->ignoreTargetSpecific();
106
107 T.setOS(llvm::Triple::UnknownOS);
108 T.setObjectFormat(llvm::Triple::MachO);
109 }
110}
111
112void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
113 const InputInfo &Output,
114 const InputInfoList &Inputs,
115 const ArgList &Args,
116 const char *LinkingOutput) const {
117 const llvm::Triple &T(getToolChain().getTriple());
118
119 ArgStringList CmdArgs;
120
121 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
122 const InputInfo &Input = Inputs[0];
123
124 // Determine the original source input.
125 const Action *SourceAction = &JA;
126 while (SourceAction->getKind() != Action::InputClass) {
127 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
128 SourceAction = SourceAction->getInputs()[0];
129 }
130
131 // If -fno-integrated-as is used add -Q to the darwin assembler driver to make
132 // sure it runs its system assembler not clang's integrated assembler.
133 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
134 // FIXME: at run-time detect assembler capabilities or rely on version
135 // information forwarded by -target-assembler-version.
136 if (Args.hasArg(Ids: options::OPT_fno_integrated_as)) {
137 if (!(T.isMacOSX() && T.isMacOSXVersionLT(Major: 10, Minor: 7)))
138 CmdArgs.push_back(Elt: "-Q");
139 }
140
141 // Forward -g, assuming we are dealing with an actual assembly file.
142 if (SourceAction->getType() == types::TY_Asm ||
143 SourceAction->getType() == types::TY_PP_Asm) {
144 if (Args.hasArg(Ids: options::OPT_gstabs))
145 CmdArgs.push_back(Elt: "--gstabs");
146 else if (Args.hasArg(Ids: options::OPT_g_Group))
147 CmdArgs.push_back(Elt: "-g");
148 }
149
150 // Derived from asm spec.
151 AddMachOArch(Args, CmdArgs);
152
153 // Use -force_cpusubtype_ALL on x86 by default.
154 if (T.isX86() || Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL))
155 CmdArgs.push_back(Elt: "-force_cpusubtype_ALL");
156
157 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
158 (((Args.hasArg(Ids: options::OPT_mkernel) ||
159 Args.hasArg(Ids: options::OPT_fapple_kext)) &&
160 getMachOToolChain().isKernelStatic()) ||
161 Args.hasArg(Ids: options::OPT_static)))
162 CmdArgs.push_back(Elt: "-static");
163
164 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wa_COMMA, Id1: options::OPT_Xassembler);
165
166 assert(Output.isFilename() && "Unexpected lipo output.");
167 CmdArgs.push_back(Elt: "-o");
168 CmdArgs.push_back(Elt: Output.getFilename());
169
170 assert(Input.isFilename() && "Invalid input.");
171 CmdArgs.push_back(Elt: Input.getFilename());
172
173 // asm_final spec is empty.
174
175 const char *Exec = Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "as"));
176 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: *this, args: ResponseFileSupport::None(),
177 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
178}
179
180void darwin::MachOTool::anchor() {}
181
182void darwin::MachOTool::AddMachOArch(const ArgList &Args,
183 ArgStringList &CmdArgs) const {
184 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
185
186 // Derived from darwin_arch spec.
187 CmdArgs.push_back(Elt: "-arch");
188 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArchName));
189
190 // FIXME: Is this needed anymore?
191 if (ArchName == "arm")
192 CmdArgs.push_back(Elt: "-force_cpusubtype_ALL");
193}
194
195void darwin::MachOTool::AddMachOArchOnly(const ArgList &Args,
196 ArgStringList &CmdArgs) const {
197 const toolchains::MachO &MachOTC = getMachOToolChain();
198
199 StringRef ArchName;
200 if (MachOTC.getTriple().isOSFirmware())
201 // Firmware uses the full triple as the arch name.
202 ArchName = MachOTC.getEffectiveTriple().getTriple();
203 else
204 ArchName = MachOTC.getMachOArchName(Args);
205
206 CmdArgs.push_back(Elt: "-arch_only");
207 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArchName));
208}
209
210static void AddMachOSysLibRoot(Compilation &C, const ArgList &Args,
211 ArgStringList &CmdArgs) {
212 // Give --sysroot= preference, over the Apple specific behavior to also use
213 // --isysroot as the syslibroot.
214 // We check `OPT__sysroot_EQ` directly instead of `getSysRoot` to make sure we
215 // prioritise command line arguments over configuration of `DEFAULT_SYSROOT`.
216 if (const Arg *A = Args.getLastArg(Ids: options::OPT__sysroot_EQ)) {
217 CmdArgs.push_back(Elt: "-syslibroot");
218 CmdArgs.push_back(Elt: A->getValue());
219 } else if (const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot)) {
220 CmdArgs.push_back(Elt: "-syslibroot");
221 CmdArgs.push_back(Elt: A->getValue());
222 } else if (StringRef sysroot = C.getSysRoot(); sysroot != "") {
223 CmdArgs.push_back(Elt: "-syslibroot");
224 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
225 }
226}
227
228bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
229 // We only need to generate a temp path for LTO if we aren't compiling object
230 // files. When compiling source files, we run 'dsymutil' after linking. We
231 // don't run 'dsymutil' when compiling object files.
232 for (const auto &Input : Inputs)
233 if (Input.getType() != types::TY_Object)
234 return true;
235
236 return false;
237}
238
239/// Pass -no_deduplicate to ld64 under certain conditions:
240///
241/// - Either -O0 or -O1 is explicitly specified
242/// - No -O option is specified *and* this is a compile+link (implicit -O0)
243///
244/// Also do *not* add -no_deduplicate when no -O option is specified and this
245/// is just a link (we can't imply -O0)
246static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
247 if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
248 if (A->getOption().matches(ID: options::OPT_O0))
249 return true;
250 if (A->getOption().matches(ID: options::OPT_O))
251 return llvm::StringSwitch<bool>(A->getValue())
252 .Case(S: "1", Value: true)
253 .Default(Value: false);
254 return false; // OPT_Ofast & OPT_O4
255 }
256
257 if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
258 return true;
259 return false;
260}
261
262void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
263 ArgStringList &CmdArgs,
264 const InputInfoList &Inputs,
265 VersionTuple Version, bool LinkerIsLLD,
266 bool UsePlatformVersion) const {
267 const Driver &D = getToolChain().getDriver();
268 const toolchains::MachO &MachOTC = getMachOToolChain();
269
270 // Newer linkers support -demangle. Pass it if supported and not disabled by
271 // the user.
272 if ((Version >= VersionTuple(100) || LinkerIsLLD) &&
273 !Args.hasArg(Ids: options::OPT_Z_Xlinker__no_demangle))
274 CmdArgs.push_back(Elt: "-demangle");
275
276 if (Args.hasArg(Ids: options::OPT_rdynamic) &&
277 (Version >= VersionTuple(137) || LinkerIsLLD))
278 CmdArgs.push_back(Elt: "-export_dynamic");
279
280 // If we are using App Extension restrictions, pass a flag to the linker
281 // telling it that the compiled code has been audited.
282 if (Args.hasFlag(Pos: options::OPT_fapplication_extension,
283 Neg: options::OPT_fno_application_extension, Default: false))
284 CmdArgs.push_back(Elt: "-application_extension");
285
286 if (auto LTO = getToolChain().getLTOMode(Args);
287 LTO != LTOK_None && (Version >= VersionTuple(116) || LinkerIsLLD) &&
288 NeedsTempPath(Inputs)) {
289 std::string TmpPathName;
290 if (LTO == LTOK_Full) {
291 // If we are using full LTO, then automatically create a temporary file
292 // path for the linker to use, so that it's lifetime will extend past a
293 // possible dsymutil step.
294 TmpPathName =
295 D.GetTemporaryPath(Prefix: "cc", Suffix: types::getTypeTempSuffix(Id: types::TY_Object));
296 } else if (LTO == LTOK_Thin)
297 // If we are using thin LTO, then create a directory instead.
298 TmpPathName = D.GetTemporaryDirectory(Prefix: "thinlto");
299
300 if (!TmpPathName.empty()) {
301 auto *TmpPath = C.getArgs().MakeArgString(Str: TmpPathName);
302 C.addTempFile(Name: TmpPath);
303 CmdArgs.push_back(Elt: "-object_path_lto");
304 CmdArgs.push_back(Elt: TmpPath);
305 }
306 }
307
308 // Use -lto_library option to specify the libLTO.dylib path. Try to find
309 // it in clang installed libraries. ld64 will only look at this argument
310 // when it actually uses LTO, so libLTO.dylib only needs to exist at link
311 // time if ld64 decides that it needs to use LTO.
312 // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
313 // next to it. That's ok since ld64 using a libLTO.dylib not matching the
314 // clang version won't work anyways.
315 // lld is built at the same revision as clang and statically links in
316 // LLVM libraries, so it doesn't need libLTO.dylib.
317 if (Version >= VersionTuple(133) && !LinkerIsLLD) {
318 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
319 StringRef P = llvm::sys::path::parent_path(path: D.Dir);
320 SmallString<128> LibLTOPath(P);
321 llvm::sys::path::append(path&: LibLTOPath, a: "lib");
322 llvm::sys::path::append(path&: LibLTOPath, a: "libLTO.dylib");
323 CmdArgs.push_back(Elt: "-lto_library");
324 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: LibLTOPath));
325 }
326
327 // ld64 version 262 and above runs the deduplicate pass by default.
328 // FIXME: lld doesn't dedup by default. Should we pass `--icf=safe`
329 // if `!shouldLinkerNotDedup()` if LinkerIsLLD here?
330 if (Version >= VersionTuple(262) &&
331 shouldLinkerNotDedup(IsLinkerOnlyAction: C.getJobs().empty(), Args))
332 CmdArgs.push_back(Elt: "-no_deduplicate");
333
334 // Derived from the "link" spec.
335 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_static);
336 if (!Args.hasArg(Ids: options::OPT_static))
337 CmdArgs.push_back(Elt: "-dynamic");
338 if (Args.hasArg(Ids: options::OPT_fgnu_runtime)) {
339 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
340 // here. How do we wish to handle such things?
341 }
342
343 if (!Args.hasArg(Ids: options::OPT_dynamiclib)) {
344 AddMachOArch(Args, CmdArgs);
345 // FIXME: Why do this only on this path?
346 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_force__cpusubtype__ALL);
347
348 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_bundle);
349 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_bundle__loader);
350 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_client__name);
351
352 Arg *A;
353 if ((A = Args.getLastArg(Ids: options::OPT_compatibility__version)) ||
354 (A = Args.getLastArg(Ids: options::OPT_current__version)) ||
355 (A = Args.getLastArg(Ids: options::OPT_install__name)))
356 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
357 << "-dynamiclib";
358
359 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_force__flat__namespace);
360 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_keep__private__externs);
361 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_private__bundle);
362 } else {
363 CmdArgs.push_back(Elt: "-dylib");
364
365 Arg *A;
366 if ((A = Args.getLastArg(Ids: options::OPT_bundle)) ||
367 (A = Args.getLastArg(Ids: options::OPT_bundle__loader)) ||
368 (A = Args.getLastArg(Ids: options::OPT_client__name)) ||
369 (A = Args.getLastArg(Ids: options::OPT_force__flat__namespace)) ||
370 (A = Args.getLastArg(Ids: options::OPT_keep__private__externs)) ||
371 (A = Args.getLastArg(Ids: options::OPT_private__bundle)))
372 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
373 << "-dynamiclib";
374
375 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_compatibility__version,
376 Translation: "-dylib_compatibility_version");
377 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_current__version,
378 Translation: "-dylib_current_version");
379
380 AddMachOArch(Args, CmdArgs);
381
382 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_install__name,
383 Translation: "-dylib_install_name");
384 }
385
386 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_all__load);
387 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_allowable__client);
388 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_bind__at__load);
389 if (MachOTC.isTargetIOSBased())
390 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_arch__errors__fatal);
391 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dead__strip);
392 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_no__dead__strip__inits__and__terms);
393 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_dylib__file);
394 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dynamic);
395 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_exported__symbols__list);
396 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_flat__namespace);
397 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_force__load);
398 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_headerpad__max__install__names);
399 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_image__base);
400 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_init);
401
402 // Add the deployment target.
403 if (Version >= VersionTuple(520) || LinkerIsLLD || UsePlatformVersion)
404 MachOTC.addPlatformVersionArgs(Args, CmdArgs);
405 else
406 MachOTC.addMinVersionArgs(Args, CmdArgs);
407
408 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nomultidefs);
409 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_multi__module);
410 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_single__module);
411 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_multiply__defined);
412 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_multiply__defined__unused);
413
414 if (const Arg *A =
415 Args.getLastArg(Ids: options::OPT_fpie, Ids: options::OPT_fPIE,
416 Ids: options::OPT_fno_pie, Ids: options::OPT_fno_PIE)) {
417 if (A->getOption().matches(ID: options::OPT_fpie) ||
418 A->getOption().matches(ID: options::OPT_fPIE))
419 CmdArgs.push_back(Elt: "-pie");
420 else
421 CmdArgs.push_back(Elt: "-no_pie");
422 }
423
424 // for embed-bitcode, use -bitcode_bundle in linker command
425 if (C.getDriver().embedBitcodeEnabled()) {
426 // Check if the toolchain supports bitcode build flow.
427 if (MachOTC.SupportsEmbeddedBitcode()) {
428 CmdArgs.push_back(Elt: "-bitcode_bundle");
429 // FIXME: Pass this if LinkerIsLLD too, once it implements this flag.
430 if (C.getDriver().embedBitcodeMarkerOnly() &&
431 Version >= VersionTuple(278)) {
432 CmdArgs.push_back(Elt: "-bitcode_process_mode");
433 CmdArgs.push_back(Elt: "marker");
434 }
435 } else
436 D.Diag(DiagID: diag::err_drv_bitcode_unsupported_on_toolchain);
437 }
438
439 // If GlobalISel is enabled, pass it through to LLVM.
440 if (Arg *A = Args.getLastArg(Ids: options::OPT_fglobal_isel,
441 Ids: options::OPT_fno_global_isel)) {
442 if (A->getOption().matches(ID: options::OPT_fglobal_isel)) {
443 CmdArgs.push_back(Elt: "-mllvm");
444 CmdArgs.push_back(Elt: "-global-isel");
445 // Disable abort and fall back to SDAG silently.
446 CmdArgs.push_back(Elt: "-mllvm");
447 CmdArgs.push_back(Elt: "-global-isel-abort=0");
448 }
449 }
450
451 if (Args.hasArg(Ids: options::OPT_mkernel) ||
452 Args.hasArg(Ids: options::OPT_fapple_kext) ||
453 Args.hasArg(Ids: options::OPT_ffreestanding)) {
454 CmdArgs.push_back(Elt: "-mllvm");
455 CmdArgs.push_back(Elt: "-disable-atexit-based-global-dtor-lowering");
456 }
457
458 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_prebind);
459 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_noprebind);
460 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nofixprebinding);
461 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_prebind__all__twolevel__modules);
462 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_read__only__relocs);
463 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_sectcreate);
464 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_sectorder);
465 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_seg1addr);
466 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_segprot);
467 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_segaddr);
468 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_segs__read__only__addr);
469 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_segs__read__write__addr);
470 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_seg__addr__table);
471 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_seg__addr__table__filename);
472 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_sub__library);
473 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_sub__umbrella);
474
475 AddMachOSysLibRoot(C, Args, CmdArgs);
476
477 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_twolevel__namespace);
478 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_twolevel__namespace__hints);
479 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_umbrella);
480 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_undefined);
481 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_unexported__symbols__list);
482 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_weak__reference__mismatches);
483 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_X_Flag);
484 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_y);
485 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_w);
486 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_pagezero__size);
487 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_segs__read__);
488 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_seglinkedit);
489 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_noseglinkedit);
490 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_sectalign);
491 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_sectobjectsymbols);
492 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_segcreate);
493 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_why_load);
494 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_whatsloaded);
495 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_dylinker__install__name);
496 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dylinker);
497 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_Mach);
498
499 if (LinkerIsLLD) {
500 if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) {
501 SmallString<128> Path(CSPGOGenerateArg->getNumValues() == 0
502 ? ""
503 : CSPGOGenerateArg->getValue());
504 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
505 CmdArgs.push_back(Elt: "--cs-profile-generate");
506 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--cs-profile-path=") + Path));
507 } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) {
508 SmallString<128> Path(
509 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
510 if (Path.empty() || llvm::sys::fs::is_directory(Path))
511 llvm::sys::path::append(path&: Path, a: "default.profdata");
512 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--cs-profile-path=") + Path));
513 }
514
515 auto *CodeGenDataGenArg =
516 Args.getLastArg(Ids: options::OPT_fcodegen_data_generate_EQ);
517 if (CodeGenDataGenArg)
518 CmdArgs.push_back(
519 Elt: Args.MakeArgString(Str: Twine("--codegen-data-generate-path=") +
520 CodeGenDataGenArg->getValue()));
521 } else {
522 if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) {
523 SmallString<128> Path(CSPGOGenerateArg->getNumValues() == 0
524 ? ""
525 : CSPGOGenerateArg->getValue());
526 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
527 CmdArgs.push_back(Elt: "-mllvm");
528 CmdArgs.push_back(Elt: "-cs-profile-generate");
529 CmdArgs.push_back(Elt: "-mllvm");
530 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cs-profile-path=") + Path));
531 } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) {
532 SmallString<128> Path(
533 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
534 if (Path.empty() || llvm::sys::fs::is_directory(Path))
535 llvm::sys::path::append(path&: Path, a: "default.profdata");
536 CmdArgs.push_back(Elt: "-mllvm");
537 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cs-profile-path=") + Path));
538 }
539 }
540
541 if (Arg *A = getLastProfileSampleUseArg(Args)) {
542 CmdArgs.push_back(Elt: "-mllvm");
543 CmdArgs.push_back(
544 Elt: Args.MakeArgString(Str: Twine("-sample-profile-file=") + A->getValue()));
545 }
546}
547
548/// Determine whether we are linking the ObjC runtime.
549static bool isObjCRuntimeLinked(const ArgList &Args) {
550 if (isObjCAutoRefCount(Args)) {
551 Args.ClaimAllArgs(Id0: options::OPT_fobjc_link_runtime);
552 return true;
553 }
554 return Args.hasArg(Ids: options::OPT_fobjc_link_runtime);
555}
556
557static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
558 const llvm::Triple &Triple) {
559 // When enabling remarks, we need to error if:
560 // * The remark file is specified but we're targeting multiple architectures,
561 // which means more than one remark file is being generated.
562 bool hasMultipleInvocations =
563 Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
564 bool hasExplicitOutputFile =
565 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
566 if (hasMultipleInvocations && hasExplicitOutputFile) {
567 D.Diag(DiagID: diag::err_drv_invalid_output_with_multiple_archs)
568 << "-foptimization-record-file";
569 return false;
570 }
571 return true;
572}
573
574static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
575 const llvm::Triple &Triple,
576 const InputInfo &Output, const JobAction &JA) {
577 StringRef Format = "yaml";
578 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
579 Format = A->getValue();
580
581 CmdArgs.push_back(Elt: "-mllvm");
582 CmdArgs.push_back(Elt: "-lto-pass-remarks-output");
583 CmdArgs.push_back(Elt: "-mllvm");
584
585 const Arg *A = Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
586 if (A) {
587 CmdArgs.push_back(Elt: A->getValue());
588 } else {
589 assert(Output.isFilename() && "Unexpected ld output.");
590 SmallString<128> F;
591 F = Output.getFilename();
592 F += ".opt.";
593 F += Format;
594
595 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
596 }
597
598 if (const Arg *A =
599 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) {
600 CmdArgs.push_back(Elt: "-mllvm");
601 std::string Passes =
602 std::string("-lto-pass-remarks-filter=") + A->getValue();
603 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Passes));
604 }
605
606 if (!Format.empty()) {
607 CmdArgs.push_back(Elt: "-mllvm");
608 Twine FormatArg = Twine("-lto-pass-remarks-format=") + Format;
609 CmdArgs.push_back(Elt: Args.MakeArgString(Str: FormatArg));
610 }
611
612 if (getLastProfileUseArg(Args)) {
613 CmdArgs.push_back(Elt: "-mllvm");
614 CmdArgs.push_back(Elt: "-lto-pass-remarks-with-hotness");
615
616 if (const Arg *A =
617 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
618 CmdArgs.push_back(Elt: "-mllvm");
619 std::string Opt =
620 std::string("-lto-pass-remarks-hotness-threshold=") + A->getValue();
621 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
622 }
623 }
624}
625
626void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
627 const InputInfo &Output,
628 const InputInfoList &Inputs,
629 const ArgList &Args,
630 const char *LinkingOutput) const {
631 assert((Output.getType() == types::TY_Image ||
632 Output.getType() == types::TY_Object) &&
633 "Invalid linker output type.");
634
635 // If the number of arguments surpasses the system limits, we will encode the
636 // input files in a separate file, shortening the command line. To this end,
637 // build a list of input file names that can be passed via a file with the
638 // -filelist linker option.
639 llvm::opt::ArgStringList InputFileList;
640
641 // The logic here is derived from gcc's behavior; most of which
642 // comes from specs (starting with link_command). Consult gcc for
643 // more information.
644 ArgStringList CmdArgs;
645
646 VersionTuple Version = getMachOToolChain().getLinkerVersion(Args);
647
648 bool LinkerIsLLD;
649 const char *Exec =
650 Args.MakeArgString(Str: getToolChain().GetLinkerPath(LinkerIsLLD: &LinkerIsLLD));
651
652 // Newer triples always use -platform-version.
653 llvm::Triple Triple = getToolChain().getTriple();
654 bool UsePlatformVersion = Triple.isXROS() || Triple.isOSFirmware();
655
656 // I'm not sure why this particular decomposition exists in gcc, but
657 // we follow suite for ease of comparison.
658 AddLinkArgs(C, Args, CmdArgs, Inputs, Version, LinkerIsLLD,
659 UsePlatformVersion);
660
661 if (willEmitRemarks(Args) &&
662 checkRemarksOptions(D: getToolChain().getDriver(), Args,
663 Triple: getToolChain().getTriple()))
664 renderRemarksOptions(Args, CmdArgs, Triple: getToolChain().getTriple(), Output, JA);
665
666 // Propagate the -moutline flag to the linker in LTO.
667 if (Arg *A =
668 Args.getLastArg(Ids: options::OPT_moutline, Ids: options::OPT_mno_outline)) {
669 if (A->getOption().matches(ID: options::OPT_moutline)) {
670 if (getMachOToolChain().getMachOArchName(Args) == "arm64") {
671 CmdArgs.push_back(Elt: "-mllvm");
672 CmdArgs.push_back(Elt: "-enable-machine-outliner");
673 }
674 } else {
675 // Disable all outlining behaviour if we have mno-outline. We need to do
676 // this explicitly, because targets which support default outlining will
677 // try to do work if we don't.
678 CmdArgs.push_back(Elt: "-mllvm");
679 CmdArgs.push_back(Elt: "-enable-machine-outliner=never");
680 }
681 }
682
683 // Outline from linkonceodr functions by default in LTO, whenever the outliner
684 // is enabled. Note that the target may enable the machine outliner
685 // independently of -moutline.
686 CmdArgs.push_back(Elt: "-mllvm");
687 CmdArgs.push_back(Elt: "-enable-linkonceodr-outlining");
688
689 // Propagate codegen data flags to the linker for the LLVM backend.
690 auto *CodeGenDataGenArg =
691 Args.getLastArg(Ids: options::OPT_fcodegen_data_generate_EQ);
692 auto *CodeGenDataUseArg = Args.getLastArg(Ids: options::OPT_fcodegen_data_use_EQ);
693
694 // We only allow one of them to be specified.
695 const Driver &D = getToolChain().getDriver();
696 if (CodeGenDataGenArg && CodeGenDataUseArg)
697 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
698 << CodeGenDataGenArg->getAsString(Args)
699 << CodeGenDataUseArg->getAsString(Args);
700
701 // For codegen data gen, the output file is passed to the linker
702 // while a boolean flag is passed to the LLVM backend.
703 if (CodeGenDataGenArg) {
704 CmdArgs.push_back(Elt: "-mllvm");
705 CmdArgs.push_back(Elt: "-codegen-data-generate");
706 }
707
708 // For codegen data use, the input file is passed to the LLVM backend.
709 if (CodeGenDataUseArg) {
710 CmdArgs.push_back(Elt: "-mllvm");
711 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-codegen-data-use-path=") +
712 CodeGenDataUseArg->getValue()));
713 }
714
715 // Setup statistics file output.
716 SmallString<128> StatsFile =
717 getStatsFileName(Args, Output, Input: Inputs[0], D: getToolChain().getDriver());
718 if (!StatsFile.empty()) {
719 CmdArgs.push_back(Elt: "-mllvm");
720 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-lto-stats-file=" + StatsFile.str()));
721 }
722
723 // Set up stack usage file path.
724 if (Args.hasArg(Ids: options::OPT_fstack_usage)) {
725 SmallString<128> StackUsageFile(Output.getFilename());
726 llvm::sys::path::replace_extension(path&: StackUsageFile, extension: "su");
727 CmdArgs.push_back(Elt: "-mllvm");
728 CmdArgs.push_back(
729 Elt: Args.MakeArgString(Str: "-stack-usage-file=" + StackUsageFile));
730 }
731
732 // It seems that the 'e' option is completely ignored for dynamic executables
733 // (the default), and with static executables, the last one wins, as expected.
734 Args.addAllArgs(Output&: CmdArgs, Ids: {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
735 options::OPT_Z_Flag, options::OPT_u_Group});
736
737 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
738 // members of static archive libraries which implement Objective-C classes or
739 // categories.
740 if (Args.hasArg(Ids: options::OPT_ObjC) || Args.hasArg(Ids: options::OPT_ObjCXX))
741 CmdArgs.push_back(Elt: "-ObjC");
742
743 CmdArgs.push_back(Elt: "-o");
744 CmdArgs.push_back(Elt: Output.getFilename());
745
746 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nostartfiles))
747 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
748
749 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_L);
750
751 AddLinkerInputs(TC: getToolChain(), Inputs, Args, CmdArgs, JA);
752 // Build the input file for -filelist (list of linker input files) in case we
753 // need it later
754 for (const auto &II : Inputs) {
755 if (!II.isFilename()) {
756 // This is a linker input argument.
757 // We cannot mix input arguments and file names in a -filelist input, thus
758 // we prematurely stop our list (remaining files shall be passed as
759 // arguments).
760 if (InputFileList.size() > 0)
761 break;
762
763 continue;
764 }
765
766 InputFileList.push_back(Elt: II.getFilename());
767 }
768
769 // Additional linker set-up and flags for Fortran. This is required in order
770 // to generate executables.
771 if (getToolChain().getDriver().IsFlangMode() &&
772 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
773 getToolChain().addFortranRuntimeLibraryPath(Args, CmdArgs);
774 getToolChain().addFortranRuntimeLibs(Args, CmdArgs);
775 }
776
777 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs))
778 addOpenMPRuntime(C, CmdArgs, TC: getToolChain(), Args);
779
780 if (isObjCRuntimeLinked(Args) &&
781 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
782 // We use arclite library for both ARC and subscripting support.
783 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
784
785 CmdArgs.push_back(Elt: "-framework");
786 CmdArgs.push_back(Elt: "Foundation");
787 // Link libobj.
788 CmdArgs.push_back(Elt: "-lobjc");
789 }
790
791 if (LinkingOutput) {
792 CmdArgs.push_back(Elt: "-arch_multiple");
793 CmdArgs.push_back(Elt: "-final_output");
794 CmdArgs.push_back(Elt: LinkingOutput);
795 }
796
797 if (Args.hasArg(Ids: options::OPT_fnested_functions))
798 CmdArgs.push_back(Elt: "-allow_stack_execute");
799
800 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
801
802 StringRef Parallelism = getLTOParallelism(Args, D: getToolChain().getDriver());
803 if (!Parallelism.empty()) {
804 CmdArgs.push_back(Elt: "-mllvm");
805 unsigned NumThreads =
806 llvm::get_threadpool_strategy(Num: Parallelism)->compute_thread_count();
807 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-threads=" + Twine(NumThreads)));
808 }
809
810 if (getToolChain().ShouldLinkCXXStdlib(Args))
811 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
812
813 bool NoStdOrDefaultLibs =
814 Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs);
815 bool ForceLinkBuiltins = Args.hasArg(Ids: options::OPT_fapple_link_rtlib);
816 if (!NoStdOrDefaultLibs || ForceLinkBuiltins) {
817 // link_ssp spec is empty.
818
819 // If we have both -nostdlib/nodefaultlibs and -fapple-link-rtlib then
820 // we just want to link the builtins, not the other libs like libSystem.
821 if (NoStdOrDefaultLibs && ForceLinkBuiltins) {
822 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs, Component: "builtins");
823 } else {
824 // Let the tool chain choose which runtime library to link.
825 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs,
826 ForceLinkBuiltinRT: ForceLinkBuiltins);
827
828 // No need to do anything for pthreads. Claim argument to avoid warning.
829 Args.ClaimAllArgs(Id0: options::OPT_pthread);
830 Args.ClaimAllArgs(Id0: options::OPT_pthreads);
831 }
832 }
833
834 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nostartfiles)) {
835 // endfile_spec is empty.
836 }
837
838 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_T_Group);
839 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_F);
840
841 // -iframework should be forwarded as -F.
842 for (const Arg *A : Args.filtered(Ids: options::OPT_iframework))
843 CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string("-F") + A->getValue()));
844
845 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
846 if (Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
847 if (A->getValue() == StringRef("Accelerate")) {
848 CmdArgs.push_back(Elt: "-framework");
849 CmdArgs.push_back(Elt: "Accelerate");
850 }
851 }
852 }
853
854 // Add non-standard, platform-specific search paths, e.g., for DriverKit:
855 // -L<sysroot>/System/DriverKit/usr/lib
856 // -F<sysroot>/System/DriverKit/System/Library/Framework
857 {
858 bool NonStandardSearchPath = false;
859 const auto &Triple = getToolChain().getTriple();
860 if (Triple.isDriverKit()) {
861 // ld64 fixed the implicit -F and -L paths in ld64-605.1+.
862 NonStandardSearchPath =
863 Version.getMajor() < 605 ||
864 (Version.getMajor() == 605 && Version.getMinor().value_or(u: 0) < 1);
865 } else {
866 NonStandardSearchPath = getMachOToolChain().HasPlatformPrefix(T: Triple);
867 }
868
869 if (NonStandardSearchPath) {
870 if (auto *Sysroot = Args.getLastArg(Ids: options::OPT_isysroot)) {
871 auto AddSearchPath = [&](StringRef Flag, StringRef SearchPath) {
872 SmallString<128> P(Sysroot->getValue());
873 getMachOToolChain().AppendPlatformPrefix(Path&: P, T: Triple);
874 llvm::sys::path::append(path&: P, a: SearchPath);
875 if (getToolChain().getVFS().exists(Path: P)) {
876 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flag + P));
877 }
878 };
879 AddSearchPath("-L", "/usr/lib");
880 AddSearchPath("-F", "/System/Library/Frameworks");
881 }
882 }
883 }
884
885 ResponseFileSupport ResponseSupport;
886 if (Version >= VersionTuple(705) || LinkerIsLLD) {
887 ResponseSupport = ResponseFileSupport::AtFileUTF8();
888 } else {
889 // For older versions of the linker, use the legacy filelist method instead.
890 ResponseSupport = {.ResponseKind: ResponseFileSupport::RF_FileList, .ResponseEncoding: llvm::sys::WEM_UTF8,
891 .ResponseFlag: "-filelist"};
892 }
893
894 std::unique_ptr<Command> Cmd = std::make_unique<Command>(
895 args: JA, args: *this, args&: ResponseSupport, args&: Exec, args&: CmdArgs, args: Inputs, args: Output);
896 Cmd->setInputFileList(std::move(InputFileList));
897 C.addCommand(Cmd: std::move(Cmd));
898}
899
900void darwin::StaticLibTool::ConstructJob(Compilation &C, const JobAction &JA,
901 const InputInfo &Output,
902 const InputInfoList &Inputs,
903 const ArgList &Args,
904 const char *LinkingOutput) const {
905 const Driver &D = getToolChain().getDriver();
906
907 // Silence warning for "clang -g foo.o -o foo"
908 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
909 // and "clang -emit-llvm foo.o -o foo"
910 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
911 // and for "clang -w foo.o -o foo". Other warning options are already
912 // handled somewhere else.
913 Args.ClaimAllArgs(Id0: options::OPT_w);
914 // Silence warnings when linking C code with a C++ '-stdlib' argument.
915 Args.ClaimAllArgs(Id0: options::OPT_stdlib_EQ);
916
917 ArgStringList CmdArgs;
918 CmdArgs.push_back(Elt: "-static");
919
920 if (Args.hasArg(Ids: options::OPT_static_lib_target_arch_only))
921 AddMachOArchOnly(Args, CmdArgs);
922
923 if (Args.hasFlag(Pos: options::OPT_static_lib_deterministic,
924 Neg: options::OPT_no_static_lib_deterministic,
925 /*Default=*/true))
926 CmdArgs.push_back(Elt: "-D");
927
928 AddMachOSysLibRoot(C, Args, CmdArgs);
929 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_L);
930 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_F);
931
932 // -iframework should be forwarded as -F.
933 for (const Arg *A : Args.filtered(Ids: options::OPT_iframework))
934 CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string("-F") + A->getValue()));
935
936 if (!Args.hasFlag(Pos: options::OPT_static_lib_warn_no_symbols,
937 Neg: options::OPT_no_static_lib_warn_no_symbols,
938 /*Default=*/false))
939 CmdArgs.push_back(Elt: "-no_warning_for_no_symbols");
940
941 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Xstatic_lib_tool);
942
943 CmdArgs.push_back(Elt: "-o");
944 CmdArgs.push_back(Elt: Output.getFilename());
945
946 // Add extra linker input arguments which are not treated as inputs
947 // (constructed via -Xarch_).
948 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Zlinker_input);
949
950 for (const auto &II : Inputs) {
951 // Add filenames immediately.
952 if (II.isFilename()) {
953 CmdArgs.push_back(Elt: II.getFilename());
954 continue;
955 }
956
957 // In some error cases, the input could be Nothing; skip those.
958 if (II.isNothing())
959 continue;
960
961 // Otherwise, this is a linker input argument.
962 const Arg &A = II.getInputArg();
963
964 // libtool only supports a few of the linker input arguments, warn for the
965 // rest.
966 if (A.getOption().matches(ID: options::OPT_filelist) ||
967 A.getOption().matches(ID: options::OPT_l) ||
968 A.getOption().matches(ID: options::OPT_framework))
969 A.renderAsInput(Args, Output&: CmdArgs);
970 else
971 D.Diag(DiagID: diag::warn_drv_unused_argument) << A.getAsString(Args);
972 }
973
974 // Delete old output archive file if it already exists before generating a new
975 // archive file.
976 const auto *OutputFileName = Output.getFilename();
977 if (Output.isFilename() && llvm::sys::fs::exists(Path: OutputFileName)) {
978 if (std::error_code EC = llvm::sys::fs::remove(path: OutputFileName)) {
979 D.Diag(DiagID: diag::err_drv_unable_to_remove_file) << EC.message();
980 return;
981 }
982 }
983
984 const char *Exec = Args.MakeArgString(Str: getToolChain().GetStaticLibToolPath());
985 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: *this,
986 args: ResponseFileSupport::AtFileUTF8(),
987 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
988}
989
990void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
991 const InputInfo &Output,
992 const InputInfoList &Inputs,
993 const ArgList &Args,
994 const char *LinkingOutput) const {
995 ArgStringList CmdArgs;
996
997 CmdArgs.push_back(Elt: "-create");
998 assert(Output.isFilename() && "Unexpected lipo output.");
999
1000 CmdArgs.push_back(Elt: "-output");
1001 CmdArgs.push_back(Elt: Output.getFilename());
1002
1003 for (const auto &II : Inputs) {
1004 assert(II.isFilename() && "Unexpected lipo input.");
1005 CmdArgs.push_back(Elt: II.getFilename());
1006 }
1007
1008 StringRef LipoName = Args.getLastArgValue(Id: options::OPT_fuse_lipo_EQ, Default: "lipo");
1009 const char *Exec =
1010 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: LipoName.data()));
1011 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: *this, args: ResponseFileSupport::None(),
1012 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
1013}
1014
1015void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
1016 const InputInfo &Output,
1017 const InputInfoList &Inputs,
1018 const ArgList &Args,
1019 const char *LinkingOutput) const {
1020 ArgStringList CmdArgs;
1021
1022 CmdArgs.push_back(Elt: "-o");
1023 CmdArgs.push_back(Elt: Output.getFilename());
1024
1025 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
1026 const InputInfo &Input = Inputs[0];
1027 assert(Input.isFilename() && "Unexpected dsymutil input.");
1028 CmdArgs.push_back(Elt: Input.getFilename());
1029
1030 const char *Exec =
1031 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "dsymutil"));
1032 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: *this, args: ResponseFileSupport::None(),
1033 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
1034}
1035
1036void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
1037 const InputInfo &Output,
1038 const InputInfoList &Inputs,
1039 const ArgList &Args,
1040 const char *LinkingOutput) const {
1041 ArgStringList CmdArgs;
1042 CmdArgs.push_back(Elt: "--verify");
1043 CmdArgs.push_back(Elt: "--debug-info");
1044 CmdArgs.push_back(Elt: "--eh-frame");
1045 CmdArgs.push_back(Elt: "--quiet");
1046
1047 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
1048 const InputInfo &Input = Inputs[0];
1049 assert(Input.isFilename() && "Unexpected verify input");
1050
1051 // Grabbing the output of the earlier dsymutil run.
1052 CmdArgs.push_back(Elt: Input.getFilename());
1053
1054 const char *Exec =
1055 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "dwarfdump"));
1056 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: *this, args: ResponseFileSupport::None(),
1057 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
1058}
1059
1060MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
1061 : ToolChain(D, Triple, Args) {
1062 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
1063 getProgramPaths().push_back(Elt: getDriver().Dir);
1064}
1065
1066AppleMachO::AppleMachO(const Driver &D, const llvm::Triple &Triple,
1067 const ArgList &Args)
1068 : MachO(D, Triple, Args), CudaInstallation(D, Triple, Args),
1069 RocmInstallation(D, Triple, Args), SYCLInstallation(D, Triple, Args) {}
1070
1071/// Darwin - Darwin tool chain for i386 and x86_64.
1072Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
1073 : AppleMachO(D, Triple, Args), TargetInitialized(false) {}
1074
1075types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
1076 types::ID Ty = ToolChain::LookupTypeForExtension(Ext);
1077
1078 // Darwin always preprocesses assembly files (unless -x is used explicitly).
1079 if (Ty == types::TY_PP_Asm)
1080 return types::TY_Asm;
1081
1082 return Ty;
1083}
1084
1085bool MachO::HasNativeLLVMSupport() const { return true; }
1086
1087ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
1088 // Always use libc++ by default
1089 return ToolChain::CST_Libcxx;
1090}
1091
1092/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
1093ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
1094 if (isTargetWatchOSBased())
1095 return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
1096 if (isTargetIOSBased())
1097 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
1098 if (isTargetXROS()) {
1099 // XROS uses the iOS runtime.
1100 auto T = llvm::Triple(Twine("arm64-apple-") +
1101 llvm::Triple::getOSTypeName(Kind: llvm::Triple::XROS) +
1102 TargetVersion.getAsString());
1103 return ObjCRuntime(ObjCRuntime::iOS, T.getiOSVersion());
1104 }
1105 if (isNonFragile)
1106 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
1107 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
1108}
1109
1110/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
1111bool Darwin::hasBlocksRuntime() const {
1112 if (isTargetWatchOSBased() || isTargetDriverKit() || isTargetXROS())
1113 return true;
1114 else if (isTargetFirmware())
1115 return false;
1116 else if (isTargetIOSBased())
1117 return !isIPhoneOSVersionLT(V0: 3, V1: 2);
1118 else {
1119 assert(isTargetMacOSBased() && "unexpected darwin target");
1120 return !isMacosxVersionLT(V0: 10, V1: 6);
1121 }
1122}
1123
1124void AppleMachO::AddCudaIncludeArgs(const ArgList &DriverArgs,
1125 ArgStringList &CC1Args) const {
1126 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
1127}
1128
1129void AppleMachO::AddHIPIncludeArgs(const ArgList &DriverArgs,
1130 ArgStringList &CC1Args) const {
1131 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
1132}
1133
1134void AppleMachO::addSYCLIncludeArgs(const ArgList &DriverArgs,
1135 ArgStringList &CC1Args) const {
1136 SYCLInstallation->addSYCLIncludeArgs(DriverArgs, CC1Args);
1137}
1138
1139// This is just a MachO name translation routine and there's no
1140// way to join this into ARMTargetParser without breaking all
1141// other assumptions. Maybe MachO should consider standardising
1142// their nomenclature.
1143static const char *ArmMachOArchName(StringRef Arch) {
1144 return llvm::StringSwitch<const char *>(Arch)
1145 .Case(S: "armv6k", Value: "armv6")
1146 .Case(S: "armv6m", Value: "armv6m")
1147 .Case(S: "armv5tej", Value: "armv5")
1148 .Case(S: "xscale", Value: "xscale")
1149 .Case(S: "armv4t", Value: "armv4t")
1150 .Case(S: "armv7", Value: "armv7")
1151 .Cases(CaseStrings: {"armv7a", "armv7-a"}, Value: "armv7")
1152 .Cases(CaseStrings: {"armv7r", "armv7-r"}, Value: "armv7")
1153 .Cases(CaseStrings: {"armv7em", "armv7e-m"}, Value: "armv7em")
1154 .Cases(CaseStrings: {"armv7k", "armv7-k"}, Value: "armv7k")
1155 .Cases(CaseStrings: {"armv7m", "armv7-m"}, Value: "armv7m")
1156 .Cases(CaseStrings: {"armv7s", "armv7-s"}, Value: "armv7s")
1157 .Cases(CaseStrings: {"armv8-m.base", "armv8m.base"}, Value: "armv8m.base")
1158 .Cases(CaseStrings: {"armv8-m.main", "armv8m.main"}, Value: "armv8m.main")
1159 .Cases(CaseStrings: {"armv8.1-m.main", "armv8m.main"}, Value: "armv8.1m.main")
1160 .Default(Value: nullptr);
1161}
1162
1163static const char *ArmMachOArchNameCPU(StringRef CPU) {
1164 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
1165 if (ArchKind == llvm::ARM::ArchKind::INVALID)
1166 return nullptr;
1167 StringRef Arch = llvm::ARM::getArchName(AK: ArchKind);
1168
1169 // FIXME: Make sure this MachO triple mangling is really necessary.
1170 // ARMv5* normalises to ARMv5.
1171 if (Arch.starts_with(Prefix: "armv5"))
1172 Arch = Arch.substr(Start: 0, N: 5);
1173 // ARMv6*, except ARMv6M, normalises to ARMv6.
1174 else if (Arch.starts_with(Prefix: "armv6") && !Arch.ends_with(Suffix: "6m"))
1175 Arch = Arch.substr(Start: 0, N: 5);
1176 // ARMv7A normalises to ARMv7.
1177 else if (Arch.ends_with(Suffix: "v7a"))
1178 Arch = Arch.substr(Start: 0, N: 5);
1179 return Arch.data();
1180}
1181
1182StringRef MachO::getMachOArchName(const ArgList &Args) const {
1183 switch (getTriple().getArch()) {
1184 default:
1185 return getDefaultUniversalArchName();
1186
1187 case llvm::Triple::aarch64_32:
1188 return "arm64_32";
1189
1190 case llvm::Triple::aarch64: {
1191 if (getTriple().isArm64e())
1192 return "arm64e";
1193 return "arm64";
1194 }
1195
1196 case llvm::Triple::thumb:
1197 case llvm::Triple::arm:
1198 if (const Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ))
1199 if (const char *Arch = ArmMachOArchName(Arch: A->getValue()))
1200 return Arch;
1201
1202 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ))
1203 if (const char *Arch = ArmMachOArchNameCPU(CPU: A->getValue()))
1204 return Arch;
1205
1206 return "arm";
1207 }
1208}
1209
1210VersionTuple MachO::getLinkerVersion(const llvm::opt::ArgList &Args) const {
1211 if (LinkerVersion) {
1212#ifndef NDEBUG
1213 VersionTuple NewLinkerVersion;
1214 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ))
1215 (void)NewLinkerVersion.tryParse(A->getValue());
1216 assert(NewLinkerVersion == LinkerVersion);
1217#endif
1218 return *LinkerVersion;
1219 }
1220
1221 VersionTuple NewLinkerVersion;
1222 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlinker_version_EQ)) {
1223 // Rejecting subbuild version is probably not necessary, but some
1224 // existing tests depend on this.
1225 if (NewLinkerVersion.tryParse(string: A->getValue()) ||
1226 NewLinkerVersion.getSubbuild())
1227 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
1228 << A->getAsString(Args);
1229 }
1230
1231 LinkerVersion = NewLinkerVersion;
1232 return *LinkerVersion;
1233}
1234
1235Darwin::~Darwin() {}
1236
1237void Darwin::ensureTargetInitialized() const {
1238 if (TargetInitialized)
1239 return;
1240
1241 llvm::Triple::OSType OS = getTriple().getOS();
1242
1243 DarwinPlatformKind Platform;
1244 switch (OS) {
1245 case llvm::Triple::Darwin:
1246 case llvm::Triple::MacOSX:
1247 Platform = MacOS;
1248 break;
1249 case llvm::Triple::IOS:
1250 Platform = IPhoneOS;
1251 break;
1252 case llvm::Triple::TvOS:
1253 Platform = TvOS;
1254 break;
1255 case llvm::Triple::WatchOS:
1256 Platform = WatchOS;
1257 break;
1258 case llvm::Triple::XROS:
1259 Platform = XROS;
1260 break;
1261 case llvm::Triple::DriverKit:
1262 Platform = DriverKit;
1263 break;
1264 default:
1265 // Unknown platform; leave uninitialized.
1266 return;
1267 }
1268
1269 DarwinEnvironmentKind Environment = NativeEnvironment;
1270 if (getTriple().isSimulatorEnvironment())
1271 Environment = Simulator;
1272 else if (getTriple().isMacCatalystEnvironment())
1273 Environment = MacCatalyst;
1274
1275 VersionTuple OsVer;
1276 if (Platform == MacOS) {
1277 // Record the macOS product version (e.g. macosx15), not the Darwin kernel
1278 // version (e.g. darwin24.3): version checks against the lazily-recorded
1279 // target must behave as if AddDeploymentTarget() had computed it.
1280 if (!getTriple().getMacOSXVersion(Version&: OsVer))
1281 return;
1282 } else {
1283 OsVer = getTriple().getOSVersion();
1284 }
1285 setTarget(Platform, Environment, Major: OsVer.getMajor(),
1286 Minor: OsVer.getMinor().value_or(u: 0), Micro: OsVer.getSubminor().value_or(u: 0),
1287 NativeTargetVersion: VersionTuple());
1288 // The version above is a guess from the triple alone; AddDeploymentTarget()
1289 // may later derive a different deployment target from flags, environment
1290 // variables, or the SDK, and overwrite this initialization.
1291 TargetInitializedLazily = true;
1292}
1293
1294AppleMachO::~AppleMachO() {}
1295
1296MachO::~MachO() {}
1297
1298void Darwin::VerifyTripleForSDK(const llvm::opt::ArgList &Args,
1299 const llvm::Triple &Triple) const {
1300 if (SDKInfo) {
1301 if (!SDKInfo->supportsTriple(Triple))
1302 getDriver().Diag(DiagID: diag::warn_incompatible_sysroot)
1303 << SDKInfo->getDisplayName() << Triple.getTriple();
1304 } else if (const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot)) {
1305 // If there is no SDK info, assume this is building against an SDK that
1306 // predates SDKSettings.json. Try to match the triple to the SDK path.
1307 const char *isysroot = A->getValue();
1308 StringRef SDKName = getSDKName(isysroot);
1309 if (!SDKName.empty()) {
1310 bool supported = true;
1311 if (Triple.isWatchOS())
1312 supported = SDKName.starts_with(Prefix: "Watch");
1313 else if (Triple.isTvOS())
1314 supported = SDKName.starts_with(Prefix: "AppleTV");
1315 else if (Triple.isDriverKit())
1316 supported = SDKName.starts_with(Prefix: "DriverKit");
1317 else if (Triple.isiOS())
1318 supported = SDKName.starts_with(Prefix: "iPhone");
1319 else if (Triple.isMacOSX())
1320 supported = SDKName.starts_with(Prefix: "MacOSX");
1321 // If it's not an older SDK, then it might be a damaged SDK or a
1322 // non-standard -isysroot path. Don't try to diagnose that here.
1323
1324 if (!supported)
1325 getDriver().Diag(DiagID: diag::warn_incompatible_sysroot)
1326 << SDKName << Triple.getTriple();
1327 }
1328 }
1329}
1330
1331std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
1332 BoundArch BA,
1333 types::ID InputType) const {
1334 llvm::Triple Triple(ComputeLLVMTriple(Args, BA, InputType));
1335
1336 // If the target isn't initialized (e.g., an unknown Darwin platform, return
1337 // the default triple). Note: we intentionally do NOT call
1338 // ensureTargetInitialized() here because this method is called before
1339 // AddDeploymentTarget() in some code paths (e.g. -print-libgcc-file-name),
1340 // and lazy init with version 0.0.0 would conflict with the real version
1341 // that AddDeploymentTarget() later sets via setTarget().
1342 if (!isTargetInitialized())
1343 return Triple.getTriple();
1344
1345 SmallString<16> Str;
1346 if (isTargetWatchOSBased())
1347 Str += "watchos";
1348 else if (isTargetTvOSBased())
1349 Str += "tvos";
1350 else if (isTargetDriverKit())
1351 Str += "driverkit";
1352 else if (isTargetIOSBased() || isTargetMacCatalyst())
1353 Str += "ios";
1354 else if (isTargetXROS())
1355 Str += llvm::Triple::getOSTypeName(Kind: llvm::Triple::XROS);
1356 else if (isTargetFirmware())
1357 Str += llvm::Triple::getOSTypeName(Kind: llvm::Triple::Firmware);
1358 else
1359 Str += "macosx";
1360 Str += getTripleTargetVersion().getAsString();
1361 Triple.setOSName(Str);
1362
1363 VerifyTripleForSDK(Args, Triple);
1364
1365 return Triple.getTriple();
1366}
1367
1368Tool *MachO::getTool(Action::ActionClass AC) const {
1369 switch (AC) {
1370 case Action::LipoJobClass:
1371 if (!Lipo)
1372 Lipo.reset(p: new tools::darwin::Lipo(*this));
1373 return Lipo.get();
1374 case Action::DsymutilJobClass:
1375 if (!Dsymutil)
1376 Dsymutil.reset(p: new tools::darwin::Dsymutil(*this));
1377 return Dsymutil.get();
1378 case Action::VerifyDebugInfoJobClass:
1379 if (!VerifyDebug)
1380 VerifyDebug.reset(p: new tools::darwin::VerifyDebug(*this));
1381 return VerifyDebug.get();
1382 default:
1383 return ToolChain::getTool(AC);
1384 }
1385}
1386
1387Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
1388
1389Tool *MachO::buildStaticLibTool() const {
1390 return new tools::darwin::StaticLibTool(*this);
1391}
1392
1393Tool *MachO::buildAssembler() const {
1394 return new tools::darwin::Assembler(*this);
1395}
1396
1397DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
1398 const ArgList &Args)
1399 : Darwin(D, Triple, Args) {}
1400
1401void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
1402 // Always error about undefined 'TARGET_OS_*' macros.
1403 CC1Args.push_back(Elt: "-Wundef-prefix=TARGET_OS_");
1404 CC1Args.push_back(Elt: "-Werror=undef-prefix");
1405
1406 // For modern targets, promote certain warnings to errors.
1407 // Lazily initialize the target if needed (e.g. when Darwin is used as
1408 // a host toolchain for device offloading).
1409 ensureTargetInitialized();
1410 if (!isTargetInitialized())
1411 return;
1412 if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
1413 // Always enable -Wdeprecated-objc-isa-usage and promote it
1414 // to an error.
1415 CC1Args.push_back(Elt: "-Wdeprecated-objc-isa-usage");
1416 CC1Args.push_back(Elt: "-Werror=deprecated-objc-isa-usage");
1417
1418 // For iOS and watchOS, also error about implicit function declarations,
1419 // as that can impact calling conventions.
1420 if (!isTargetMacOS())
1421 CC1Args.push_back(Elt: "-Werror=implicit-function-declaration");
1422 }
1423}
1424
1425void DarwinClang::addClangTargetOptions(
1426 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
1427 BoundArch BA, Action::OffloadKind DeviceOffloadKind) const {
1428
1429 Darwin::addClangTargetOptions(DriverArgs, CC1Args, BA, DeviceOffloadKind);
1430}
1431
1432/// Take a path that speculatively points into Xcode and return the
1433/// `XCODE/Contents/Developer` path if it is an Xcode path, or an empty path
1434/// otherwise.
1435static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode) {
1436 static constexpr llvm::StringLiteral XcodeAppSuffix(
1437 ".app/Contents/Developer");
1438 size_t Index = PathIntoXcode.find(Str: XcodeAppSuffix);
1439 if (Index == StringRef::npos)
1440 return "";
1441 return PathIntoXcode.take_front(N: Index + XcodeAppSuffix.size());
1442}
1443
1444void DarwinClang::AddLinkARCArgs(const ArgList &Args,
1445 ArgStringList &CmdArgs) const {
1446 // Avoid linking compatibility stubs on i386 mac.
1447 if (isTargetMacOSBased() && getArch() == llvm::Triple::x86)
1448 return;
1449 if (isTargetAppleSiliconMac())
1450 return;
1451 // ARC runtime is supported everywhere on arm64e.
1452 if (getTriple().isArm64e())
1453 return;
1454 if (isTargetXROS())
1455 return;
1456
1457 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ isNonFragile: true);
1458
1459 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
1460 runtime.hasSubscripting())
1461 return;
1462
1463 SmallString<128> P(getDriver().DriverExecutable);
1464 llvm::sys::path::remove_filename(path&: P); // 'clang'
1465 llvm::sys::path::remove_filename(path&: P); // 'bin'
1466 llvm::sys::path::append(path&: P, a: "lib", b: "arc");
1467
1468 // 'libarclite' usually lives in the same toolchain as 'clang'. However, the
1469 // Swift open source toolchains for macOS distribute Clang without libarclite.
1470 // In that case, to allow the linker to find 'libarclite', we point to the
1471 // 'libarclite' in the XcodeDefault toolchain instead.
1472 if (!getVFS().exists(Path: P)) {
1473 auto updatePath = [&](const Arg *A) {
1474 // Try to infer the path to 'libarclite' in the toolchain from the
1475 // specified SDK path.
1476 StringRef XcodePathForSDK = getXcodeDeveloperPath(PathIntoXcode: A->getValue());
1477 if (XcodePathForSDK.empty())
1478 return false;
1479
1480 P = XcodePathForSDK;
1481 llvm::sys::path::append(path&: P, a: "Toolchains/XcodeDefault.xctoolchain/usr",
1482 b: "lib", c: "arc");
1483 return getVFS().exists(Path: P);
1484 };
1485
1486 bool updated = false;
1487 if (const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot))
1488 updated = updatePath(A);
1489
1490 if (!updated) {
1491 if (const Arg *A = Args.getLastArg(Ids: options::OPT__sysroot_EQ))
1492 updatePath(A);
1493 }
1494 }
1495
1496 CmdArgs.push_back(Elt: "-force_load");
1497 llvm::sys::path::append(path&: P, a: "libarclite_");
1498 // Mash in the platform.
1499 if (isTargetWatchOSSimulator())
1500 P += "watchsimulator";
1501 else if (isTargetWatchOS())
1502 P += "watchos";
1503 else if (isTargetTvOSSimulator())
1504 P += "appletvsimulator";
1505 else if (isTargetTvOS())
1506 P += "appletvos";
1507 else if (isTargetIOSSimulator())
1508 P += "iphonesimulator";
1509 else if (isTargetIPhoneOS())
1510 P += "iphoneos";
1511 else
1512 P += "macosx";
1513 P += ".a";
1514
1515 if (!getVFS().exists(Path: P))
1516 getDriver().Diag(DiagID: clang::diag::err_drv_darwin_sdk_missing_arclite) << P;
1517
1518 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1519}
1520
1521unsigned DarwinClang::GetDefaultDwarfVersion() const {
1522 // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
1523 if ((isTargetMacOSBased() && isMacosxVersionLT(V0: 10, V1: 11)) ||
1524 (isTargetIOSBased() && isIPhoneOSVersionLT(V0: 9)))
1525 return 2;
1526 // Default to use DWARF 4 on OS X 10.11 - macOS 14 / iOS 9 - iOS 17.
1527 if ((isTargetMacOSBased() && isMacosxVersionLT(V0: 15)) ||
1528 (isTargetIOSBased() && isIPhoneOSVersionLT(V0: 18)) ||
1529 (isTargetWatchOSBased() && TargetVersion < llvm::VersionTuple(11)) ||
1530 (isTargetXROS() && TargetVersion < llvm::VersionTuple(2)) ||
1531 (isTargetDriverKit() && TargetVersion < llvm::VersionTuple(24)) ||
1532 (isTargetMacOSBased() &&
1533 TargetVersion.empty())) // apple-darwin, no version.
1534 return 4;
1535 return 5;
1536}
1537
1538bool DarwinClang::getDefaultDebugSimpleTemplateNames() const {
1539 // Default to an OS version on which LLDB supports debugging
1540 // -gsimple-template-names programs.
1541 if ((isTargetMacOSBased() && isMacosxVersionLT(V0: 26)) ||
1542 (isTargetIOSBased() && isIPhoneOSVersionLT(V0: 26)) ||
1543 (isTargetWatchOSBased() && TargetVersion < llvm::VersionTuple(26)) ||
1544 (isTargetXROS() && TargetVersion < llvm::VersionTuple(26)) ||
1545 (isTargetDriverKit() && TargetVersion < llvm::VersionTuple(25)) ||
1546 (isTargetMacOSBased() &&
1547 TargetVersion.empty())) // apple-darwin, no version.
1548 return false;
1549
1550 return true;
1551}
1552
1553void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
1554 StringRef Component, RuntimeLinkOptions Opts,
1555 bool IsShared) const {
1556 std::string P = getCompilerRT(
1557 Args, Component, Type: IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static);
1558
1559 // For now, allow missing resource libraries to support developers who may
1560 // not have compiler-rt checked out or integrated into their build (unless
1561 // we explicitly force linking with this library).
1562 if ((Opts & RLO_AlwaysLink) || getVFS().exists(Path: P)) {
1563 const char *LibArg = Args.MakeArgString(Str: P);
1564 CmdArgs.push_back(Elt: LibArg);
1565 }
1566
1567 // Adding the rpaths might negatively interact when other rpaths are involved,
1568 // so we should make sure we add the rpaths last, after all user-specified
1569 // rpaths. This is currently true from this place, but we need to be
1570 // careful if this function is ever called before user's rpaths are emitted.
1571 if (Opts & RLO_AddRPath) {
1572 assert(StringRef(P).ends_with(".dylib") && "must be a dynamic library");
1573
1574 // Add @executable_path to rpath to support having the dylib copied with
1575 // the executable.
1576 CmdArgs.push_back(Elt: "-rpath");
1577 CmdArgs.push_back(Elt: "@executable_path");
1578
1579 // Add the compiler-rt library's directory to rpath to support using the
1580 // dylib from the default location without copying.
1581 CmdArgs.push_back(Elt: "-rpath");
1582 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::path::parent_path(path: P)));
1583 }
1584}
1585
1586std::string MachO::getCompilerRT(const ArgList &Args, StringRef Component,
1587 FileType Type, bool IsFortran) const {
1588 assert(Type != ToolChain::FT_Object &&
1589 "it doesn't make sense to ask for the compiler-rt library name as an "
1590 "object file");
1591 SmallString<64> MachOLibName = StringRef("libclang_rt");
1592 // On MachO, the builtins component is not in the library name
1593 if (Component != "builtins") {
1594 MachOLibName += '.';
1595 MachOLibName += Component;
1596 }
1597 MachOLibName += Type == ToolChain::FT_Shared ? "_dynamic.dylib" : ".a";
1598
1599 SmallString<128> FullPath(getDriver().ResourceDir);
1600 llvm::sys::path::append(path&: FullPath, a: "lib", b: "darwin", c: "macho_embedded",
1601 d: MachOLibName);
1602 return std::string(FullPath);
1603}
1604
1605std::string Darwin::getCompilerRT(const ArgList &Args, StringRef Component,
1606 FileType Type, bool IsFortran) const {
1607 // Firmware uses the "bare metal" RT.
1608 if (TargetPlatform == DarwinPlatformKind::Firmware)
1609 return MachO::getCompilerRT(Args, Component, Type, IsFortran);
1610
1611 assert(Type != ToolChain::FT_Object &&
1612 "it doesn't make sense to ask for the compiler-rt library name as an "
1613 "object file");
1614 SmallString<64> DarwinLibName = StringRef("libclang_rt.");
1615 // On Darwin, the builtins component is not in the library name
1616 if (Component != "builtins") {
1617 DarwinLibName += Component;
1618 DarwinLibName += '_';
1619 }
1620 DarwinLibName += getOSLibraryNameSuffix();
1621 DarwinLibName += Type == ToolChain::FT_Shared ? "_dynamic.dylib" : ".a";
1622
1623 SmallString<128> FullPath(getDriver().ResourceDir);
1624 llvm::sys::path::append(path&: FullPath, a: "lib", b: "darwin", c: DarwinLibName);
1625 return std::string(FullPath);
1626}
1627
1628StringRef Darwin::getSDKName(StringRef isysroot) {
1629 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
1630 auto BeginSDK = llvm::sys::path::rbegin(path: isysroot);
1631 auto EndSDK = llvm::sys::path::rend(path: isysroot);
1632 for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
1633 StringRef SDK = *IT;
1634 if (SDK.consume_back(Suffix: ".sdk"))
1635 return SDK;
1636 }
1637 return "";
1638}
1639
1640StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
1641 switch (TargetPlatform) {
1642 case DarwinPlatformKind::MacOS:
1643 return "osx";
1644 case DarwinPlatformKind::IPhoneOS:
1645 if (TargetEnvironment == MacCatalyst)
1646 return "osx";
1647 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
1648 : "iossim";
1649 case DarwinPlatformKind::TvOS:
1650 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
1651 : "tvossim";
1652 case DarwinPlatformKind::WatchOS:
1653 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
1654 : "watchossim";
1655 case DarwinPlatformKind::XROS:
1656 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "xros"
1657 : "xrossim";
1658 case DarwinPlatformKind::DriverKit:
1659 return "driverkit";
1660
1661 case DarwinPlatformKind::Firmware:
1662 break;
1663 }
1664 llvm_unreachable("Unsupported platform");
1665}
1666
1667/// Check if the link command contains a symbol export directive.
1668static bool hasExportSymbolDirective(const ArgList &Args) {
1669 for (Arg *A : Args) {
1670 if (A->getOption().matches(ID: options::OPT_exported__symbols__list))
1671 return true;
1672 if (!A->getOption().matches(ID: options::OPT_Wl_COMMA) &&
1673 !A->getOption().matches(ID: options::OPT_Xlinker))
1674 continue;
1675 if (A->containsValue(Value: "-exported_symbols_list") ||
1676 A->containsValue(Value: "-exported_symbol"))
1677 return true;
1678 }
1679 return false;
1680}
1681
1682/// Add an export directive for \p Symbol to the link command.
1683static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
1684 CmdArgs.push_back(Elt: "-exported_symbol");
1685 CmdArgs.push_back(Elt: Symbol);
1686}
1687
1688/// Add a sectalign directive for \p Segment and \p Section to the maximum
1689/// expected page size for Darwin.
1690///
1691/// On iPhone 6+ the max supported page size is 16K. On macOS, the max is 4K.
1692/// Use a common alignment constant (16K) for now, and reduce the alignment on
1693/// macOS if it proves important.
1694static void addSectalignToPage(const ArgList &Args, ArgStringList &CmdArgs,
1695 StringRef Segment, StringRef Section) {
1696 for (const char *A : {"-sectalign", Args.MakeArgString(Str: Segment),
1697 Args.MakeArgString(Str: Section), "0x4000"})
1698 CmdArgs.push_back(Elt: A);
1699}
1700
1701void Darwin::addProfileRTLibs(const ArgList &Args,
1702 ArgStringList &CmdArgs) const {
1703 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1704 return;
1705
1706 AddLinkRuntimeLib(Args, CmdArgs, Component: "profile",
1707 Opts: RuntimeLinkOptions(RLO_AlwaysLink));
1708
1709 bool ForGCOV = needsGCovInstrumentation(Args);
1710
1711 // If we have a symbol export directive and we're linking in the profile
1712 // runtime, automatically export symbols necessary to implement some of the
1713 // runtime's functionality.
1714 if (hasExportSymbolDirective(Args) && ForGCOV) {
1715 addExportedSymbol(CmdArgs, Symbol: "___gcov_dump");
1716 addExportedSymbol(CmdArgs, Symbol: "___gcov_reset");
1717 addExportedSymbol(CmdArgs, Symbol: "_writeout_fn_list");
1718 addExportedSymbol(CmdArgs, Symbol: "_reset_fn_list");
1719 }
1720
1721 // Align __llvm_prf_{cnts,bits,data} sections to the maximum expected page
1722 // alignment. This allows profile counters to be mmap()'d to disk. Note that
1723 // it's not enough to just page-align __llvm_prf_cnts: the following section
1724 // must also be page-aligned so that its data is not clobbered by mmap().
1725 //
1726 // The section alignment is only needed when continuous profile sync is
1727 // enabled, but this is expected to be the default in Xcode. Specifying the
1728 // extra alignment also allows the same binary to be used with/without sync
1729 // enabled.
1730 if (!ForGCOV) {
1731 for (auto IPSK : {llvm::IPSK_cnts, llvm::IPSK_bitmap, llvm::IPSK_data}) {
1732 addSectalignToPage(
1733 Args, CmdArgs, Segment: "__DATA",
1734 Section: llvm::getInstrProfSectionName(IPSK, OF: llvm::Triple::MachO,
1735 /*AddSegmentInfo=*/false));
1736 }
1737 }
1738}
1739
1740void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1741 ArgStringList &CmdArgs,
1742 StringRef Sanitizer,
1743 bool Shared) const {
1744 auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1745 AddLinkRuntimeLib(Args, CmdArgs, Component: Sanitizer, Opts: RLO, IsShared: Shared);
1746}
1747
1748ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
1749 const ArgList &Args) const {
1750 if (Arg* A = Args.getLastArg(Ids: options::OPT_rtlib_EQ)) {
1751 StringRef Value = A->getValue();
1752 if (Value != "compiler-rt" && Value != "platform")
1753 getDriver().Diag(DiagID: clang::diag::err_drv_unsupported_rtlib_for_platform)
1754 << Value << "darwin";
1755 }
1756
1757 return ToolChain::GetRuntimeLibType(Args);
1758}
1759
1760void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1761 ArgStringList &CmdArgs,
1762 bool ForceLinkBuiltinRT) const {
1763 // Firmware uses the "bare metal" runtime lib.
1764 if (TargetPlatform == DarwinPlatformKind::Firmware)
1765 return MachO::AddLinkRuntimeLibArgs(Args, CmdArgs, ForceLinkBuiltinRT);
1766
1767 // Call once to ensure diagnostic is printed if wrong value was specified
1768 GetRuntimeLibType(Args);
1769
1770 // Darwin doesn't support real static executables, don't link any runtime
1771 // libraries with -static.
1772 if (Args.hasArg(Ids: options::OPT_static) ||
1773 Args.hasArg(Ids: options::OPT_fapple_kext) ||
1774 Args.hasArg(Ids: options::OPT_mkernel)) {
1775 if (ForceLinkBuiltinRT)
1776 AddLinkRuntimeLib(Args, CmdArgs, Component: "builtins");
1777 return;
1778 }
1779
1780 // Reject -static-libgcc for now, we can deal with this when and if someone
1781 // cares. This is useful in situations where someone wants to statically link
1782 // something like libstdc++, and needs its runtime support routines.
1783 if (const Arg *A = Args.getLastArg(Ids: options::OPT_static_libgcc)) {
1784 getDriver().Diag(DiagID: diag::err_drv_unsupported_opt) << A->getAsString(Args);
1785 return;
1786 }
1787
1788 const SanitizerArgs &Sanitize = getSanitizerArgs(JobArgs: Args);
1789
1790 if (!Sanitize.needsSharedRt()) {
1791 const char *sanitizer = nullptr;
1792 if (Sanitize.needsUbsanRt()) {
1793 sanitizer = "UndefinedBehaviorSanitizer";
1794 } else if (Sanitize.needsRtsanRt()) {
1795 sanitizer = "RealtimeSanitizer";
1796 } else if (Sanitize.needsAsanRt()) {
1797 sanitizer = "AddressSanitizer";
1798 } else if (Sanitize.needsTsanRt()) {
1799 sanitizer = "ThreadSanitizer";
1800 }
1801 if (sanitizer) {
1802 getDriver().Diag(DiagID: diag::err_drv_unsupported_static_sanitizer_darwin)
1803 << sanitizer;
1804 return;
1805 }
1806 }
1807
1808 if (Sanitize.linkRuntimes()) {
1809 if (Sanitize.needsAsanRt()) {
1810 if (Sanitize.needsStableAbi()) {
1811 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "asan_abi", /*shared=*/Shared: false);
1812 } else {
1813 assert(Sanitize.needsSharedRt() &&
1814 "Static sanitizer runtimes not supported");
1815 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "asan");
1816 }
1817 }
1818 if (Sanitize.needsRtsanRt()) {
1819 assert(Sanitize.needsSharedRt() &&
1820 "Static sanitizer runtimes not supported");
1821 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "rtsan");
1822 }
1823 if (Sanitize.needsLsanRt())
1824 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "lsan");
1825 if (Sanitize.needsUbsanRt()) {
1826 assert(Sanitize.needsSharedRt() &&
1827 "Static sanitizer runtimes not supported");
1828 AddLinkSanitizerLibArgs(
1829 Args, CmdArgs,
1830 Sanitizer: Sanitize.requiresMinimalRuntime() ? "ubsan_minimal" : "ubsan");
1831 }
1832 if (Sanitize.needsTsanRt()) {
1833 assert(Sanitize.needsSharedRt() &&
1834 "Static sanitizer runtimes not supported");
1835 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "tsan");
1836 }
1837 if (Sanitize.needsTysanRt())
1838 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "tysan");
1839 if (Sanitize.needsFuzzer() && !Args.hasArg(Ids: options::OPT_dynamiclib)) {
1840 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "fuzzer", /*shared=*/Shared: false);
1841
1842 // Libfuzzer is written in C++ and requires libcxx.
1843 // Since darwin::Linker::ConstructJob already adds -lc++ for clang++
1844 // by default if ShouldLinkCXXStdlib(Args), we only add the option if
1845 // !ShouldLinkCXXStdlib(Args). This avoids duplicate library errors
1846 // on Darwin.
1847 if (!ShouldLinkCXXStdlib(Args))
1848 AddCXXStdlibLibArgs(Args, CmdArgs);
1849 }
1850 if (Sanitize.needsStatsRt()) {
1851 AddLinkRuntimeLib(Args, CmdArgs, Component: "stats_client", Opts: RLO_AlwaysLink);
1852 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "stats");
1853 }
1854 }
1855
1856 if (Sanitize.needsMemProfRt())
1857 if (hasExportSymbolDirective(Args))
1858 addExportedSymbol(
1859 CmdArgs,
1860 Symbol: llvm::memprof::getMemprofOptionsSymbolDarwinLinkageName().data());
1861
1862 const XRayArgs &XRay = getXRayArgs(Args);
1863 if (XRay.needsXRayRt()) {
1864 AddLinkRuntimeLib(Args, CmdArgs, Component: "xray");
1865 AddLinkRuntimeLib(Args, CmdArgs, Component: "xray-basic");
1866 AddLinkRuntimeLib(Args, CmdArgs, Component: "xray-fdr");
1867 }
1868
1869 if (isTargetDriverKit() && !Args.hasArg(Ids: options::OPT_nodriverkitlib)) {
1870 CmdArgs.push_back(Elt: "-framework");
1871 CmdArgs.push_back(Elt: "DriverKit");
1872 }
1873
1874 // Otherwise link libSystem, then the dynamic runtime library, and finally any
1875 // target specific static runtime library.
1876 if (!isTargetDriverKit())
1877 CmdArgs.push_back(Elt: "-lSystem");
1878
1879 // Select the dynamic runtime library and the target specific static library.
1880 // Some old Darwin versions put builtins, libunwind, and some other stuff in
1881 // libgcc_s.1.dylib. MacOS X 10.6 and iOS 5 moved those functions to
1882 // libSystem, and made libgcc_s.1.dylib a stub. We never link libgcc_s when
1883 // building for aarch64 or iOS simulator, since libgcc_s was made obsolete
1884 // before either existed.
1885 if (getTriple().getArch() != llvm::Triple::aarch64 &&
1886 ((isTargetIOSBased() && isIPhoneOSVersionLT(V0: 5, V1: 0) &&
1887 !isTargetIOSSimulator()) ||
1888 (isTargetMacOSBased() && isMacosxVersionLT(V0: 10, V1: 6))))
1889 CmdArgs.push_back(Elt: "-lgcc_s.1");
1890 AddLinkRuntimeLib(Args, CmdArgs, Component: "builtins");
1891}
1892
1893/// Returns the most appropriate macOS target version for the current process.
1894///
1895/// If the macOS SDK version is the same or earlier than the system version,
1896/// then the SDK version is returned. Otherwise the system version is returned.
1897static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1898 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1899 if (!SystemTriple.isMacOSX())
1900 return std::string(MacOSSDKVersion);
1901 VersionTuple SystemVersion;
1902 SystemTriple.getMacOSXVersion(Version&: SystemVersion);
1903
1904 unsigned Major, Minor, Micro;
1905 bool HadExtra;
1906 if (!Driver::GetReleaseVersion(Str: MacOSSDKVersion, Major, Minor, Micro,
1907 HadExtra))
1908 return std::string(MacOSSDKVersion);
1909 VersionTuple SDKVersion(Major, Minor, Micro);
1910
1911 if (SDKVersion > SystemVersion)
1912 return SystemVersion.getAsString();
1913 return std::string(MacOSSDKVersion);
1914}
1915
1916namespace {
1917
1918/// The Darwin OS and version that was selected or inferred from arguments or
1919/// environment.
1920struct DarwinPlatform {
1921 enum SourceKind {
1922 /// The OS was specified using the -target argument.
1923 TargetArg,
1924 /// The OS was specified using the -mtargetos= argument.
1925 MTargetOSArg,
1926 /// The OS was specified using the -m<os>-version-min argument.
1927 OSVersionArg,
1928 /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1929 DeploymentTargetEnv,
1930 /// The OS was inferred from the SDK.
1931 InferredFromSDK,
1932 /// The OS was inferred from the -arch.
1933 InferredFromArch
1934 };
1935
1936 using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1937 using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1938
1939 DarwinPlatformKind getPlatform() const { return Platform; }
1940
1941 DarwinEnvironmentKind getEnvironment() const { return Environment; }
1942
1943 void setEnvironment(DarwinEnvironmentKind Kind) {
1944 Environment = Kind;
1945 InferSimulatorFromArch = false;
1946 }
1947
1948 const VersionTuple getOSVersion() const {
1949 return UnderlyingOSVersion.value_or(u: VersionTuple());
1950 }
1951
1952 VersionTuple takeOSVersion() {
1953 assert(UnderlyingOSVersion.has_value() &&
1954 "attempting to get an unset OS version");
1955 VersionTuple Result = *UnderlyingOSVersion;
1956 UnderlyingOSVersion.reset();
1957 return Result;
1958 }
1959 bool isValidOSVersion() const {
1960 return llvm::Triple::isValidVersionForOS(OSKind: getOSFromPlatform(Platform),
1961 Version: getOSVersion());
1962 }
1963
1964 VersionTuple getCanonicalOSVersion() const {
1965 return llvm::Triple::getCanonicalVersionForOS(
1966 OSKind: getOSFromPlatform(Platform), Version: getOSVersion(), /*IsInValidRange=*/true);
1967 }
1968
1969 void setOSVersion(const VersionTuple &Version) {
1970 UnderlyingOSVersion = Version;
1971 }
1972
1973 bool hasOSVersion() const { return UnderlyingOSVersion.has_value(); }
1974
1975 VersionTuple getZipperedOSVersion() const {
1976 assert(Environment == DarwinEnvironmentKind::MacCatalyst &&
1977 "zippered target version is specified only for Mac Catalyst");
1978 return ZipperedOSVersion;
1979 }
1980
1981 /// Returns true if the target OS was explicitly specified.
1982 bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1983
1984 /// Returns true if the simulator environment can be inferred from the arch.
1985 bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1986
1987 const std::optional<llvm::Triple> &getTargetVariantTriple() const {
1988 return TargetVariantTriple;
1989 }
1990
1991 /// Adds the -m<os>-version-min argument to the compiler invocation.
1992 void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1993 auto &[Arg, OSVersionStr] = Arguments;
1994 if (Arg)
1995 return;
1996 assert(Kind != TargetArg && Kind != MTargetOSArg && Kind != OSVersionArg &&
1997 "Invalid kind");
1998 options::ID Opt;
1999 switch (Platform) {
2000 case DarwinPlatformKind::MacOS:
2001 Opt = options::OPT_mmacos_version_min_EQ;
2002 break;
2003 case DarwinPlatformKind::IPhoneOS:
2004 Opt = options::OPT_mios_version_min_EQ;
2005 break;
2006 case DarwinPlatformKind::TvOS:
2007 Opt = options::OPT_mtvos_version_min_EQ;
2008 break;
2009 case DarwinPlatformKind::WatchOS:
2010 Opt = options::OPT_mwatchos_version_min_EQ;
2011 break;
2012 default:
2013 // New platforms always explicitly provide a version in the triple.
2014 return;
2015 }
2016 Arg = Args.MakeJoinedArg(BaseArg: nullptr, Opt: Opts.getOption(Opt), Value: OSVersionStr);
2017 Args.append(A: Arg);
2018 }
2019
2020 /// Returns the OS version with the argument / environment variable that
2021 /// specified it.
2022 std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
2023 auto &[Arg, OSVersionStr] = Arguments;
2024 switch (Kind) {
2025 case TargetArg:
2026 case MTargetOSArg:
2027 case OSVersionArg:
2028 assert(Arg && "OS version argument not yet inferred");
2029 return Arg->getAsString(Args);
2030 case DeploymentTargetEnv:
2031 return (llvm::Twine(EnvVarName) + "=" + OSVersionStr).str();
2032 case InferredFromSDK:
2033 case InferredFromArch:
2034 llvm_unreachable("Cannot print arguments for inferred OS version");
2035 }
2036 llvm_unreachable("Unsupported Darwin Source Kind");
2037 }
2038
2039 // Returns the inferred source of how the OS version was resolved.
2040 std::string getInferredSource() {
2041 assert(!isExplicitlySpecified() && "OS version was not inferred");
2042 return InferredSource.str();
2043 }
2044
2045 void setEnvironment(llvm::Triple::EnvironmentType EnvType,
2046 const VersionTuple &OSVersion,
2047 const std::optional<DarwinSDKInfo> &SDKInfo) {
2048 switch (EnvType) {
2049 case llvm::Triple::Simulator:
2050 Environment = DarwinEnvironmentKind::Simulator;
2051 break;
2052 case llvm::Triple::MacABI: {
2053 Environment = DarwinEnvironmentKind::MacCatalyst;
2054 // The minimum native macOS target for MacCatalyst is macOS 10.15.
2055 ZipperedOSVersion = VersionTuple(10, 15);
2056 if (hasOSVersion() && SDKInfo) {
2057 if (const auto *MacCatalystToMacOSMapping = SDKInfo->getVersionMapping(
2058 Kind: DarwinSDKInfo::OSEnvPair::macCatalystToMacOSPair())) {
2059 if (auto MacOSVersion = MacCatalystToMacOSMapping->map(
2060 Key: OSVersion, MinimumValue: ZipperedOSVersion, MaximumValue: std::nullopt)) {
2061 ZipperedOSVersion = *MacOSVersion;
2062 }
2063 }
2064 }
2065 // In a zippered build, we could be building for a macOS target that's
2066 // lower than the version that's implied by the OS version. In that case
2067 // we need to use the minimum version as the native target version.
2068 if (TargetVariantTriple) {
2069 auto TargetVariantVersion = TargetVariantTriple->getOSVersion();
2070 if (TargetVariantVersion.getMajor()) {
2071 if (TargetVariantVersion < ZipperedOSVersion)
2072 ZipperedOSVersion = std::move(TargetVariantVersion);
2073 }
2074 }
2075 break;
2076 }
2077 default:
2078 break;
2079 }
2080 }
2081
2082 static DarwinPlatform
2083 createFromTarget(const llvm::Triple &TT, Arg *A,
2084 std::optional<llvm::Triple> TargetVariantTriple,
2085 const std::optional<DarwinSDKInfo> &SDKInfo) {
2086 DarwinPlatform Result(TargetArg, getPlatformFromOS(OS: TT.getOS()),
2087 TT.getOSVersion(), A);
2088 VersionTuple OsVersion = TT.getOSVersion();
2089 Result.TargetVariantTriple = std::move(TargetVariantTriple);
2090 Result.setEnvironment(EnvType: TT.getEnvironment(), OSVersion: OsVersion, SDKInfo);
2091 return Result;
2092 }
2093 static DarwinPlatform
2094 createFromMTargetOS(llvm::Triple::OSType OS, VersionTuple OSVersion,
2095 llvm::Triple::EnvironmentType Environment, Arg *A,
2096 const std::optional<DarwinSDKInfo> &SDKInfo) {
2097 DarwinPlatform Result(MTargetOSArg, getPlatformFromOS(OS), OSVersion, A);
2098 Result.InferSimulatorFromArch = false;
2099 Result.setEnvironment(EnvType: Environment, OSVersion, SDKInfo);
2100 return Result;
2101 }
2102 static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform, Arg *A,
2103 bool IsSimulator) {
2104 DarwinPlatform Result{OSVersionArg, Platform,
2105 getVersionFromString(Input: A->getValue()), A};
2106 if (IsSimulator)
2107 Result.Environment = DarwinEnvironmentKind::Simulator;
2108 return Result;
2109 }
2110 static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
2111 StringRef EnvVarName,
2112 StringRef OSVersion) {
2113 DarwinPlatform Result(DeploymentTargetEnv, Platform,
2114 getVersionFromString(Input: OSVersion));
2115 Result.EnvVarName = EnvVarName;
2116 return Result;
2117 }
2118 static DarwinPlatform createFromSDKInfo(StringRef SDKRoot,
2119 const DarwinSDKInfo &SDKInfo) {
2120 const llvm::Triple &PlatformTriple = SDKInfo.getCanonicalPlatformTriple();
2121 const llvm::Triple::OSType OS = PlatformTriple.getOS();
2122 VersionTuple Version = SDKInfo.getDefaultDeploymentTarget();
2123 if (OS == llvm::Triple::MacOSX)
2124 Version = getVersionFromString(
2125 Input: getSystemOrSDKMacOSVersion(MacOSSDKVersion: Version.getAsString()));
2126 DarwinPlatform Result(InferredFromSDK, getPlatformFromOS(OS), Version);
2127 Result.Environment = getEnvKindFromEnvType(EnvironmentType: PlatformTriple.getEnvironment());
2128 Result.InferSimulatorFromArch = false;
2129 Result.InferredSource = SDKRoot;
2130 return Result;
2131 }
2132 static DarwinPlatform createFromSDK(StringRef SDKRoot,
2133 DarwinPlatformKind Platform,
2134 StringRef Value,
2135 bool IsSimulator = false) {
2136 DarwinPlatform Result(InferredFromSDK, Platform,
2137 getVersionFromString(Input: Value));
2138 if (IsSimulator)
2139 Result.Environment = DarwinEnvironmentKind::Simulator;
2140 Result.InferSimulatorFromArch = false;
2141 Result.InferredSource = SDKRoot;
2142 return Result;
2143 }
2144 static DarwinPlatform createFromArch(StringRef Arch, llvm::Triple::OSType OS,
2145 VersionTuple Version) {
2146 auto Result =
2147 DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Version);
2148 Result.InferredSource = Arch;
2149 return Result;
2150 }
2151
2152 /// Constructs an inferred SDKInfo value based on the version inferred from
2153 /// the SDK path itself. Only works for values that were created by inferring
2154 /// the platform from the SDKPath.
2155 DarwinSDKInfo inferSDKInfo() {
2156 assert(Kind == InferredFromSDK && "can infer SDK info only");
2157 llvm::Triple::OSType OS = getOSFromPlatform(Platform);
2158 llvm::Triple::EnvironmentType EnvironmentType =
2159 getEnvTypeFromEnvKind(EnvironmentKind: Environment);
2160 return DarwinSDKInfo(OS, EnvironmentType, getOSVersion(),
2161 getDisplayName(TargetPlatform: Platform, TargetEnvironment: Environment, Version: getOSVersion()),
2162 /*MaximumDeploymentTarget=*/
2163 VersionTuple(getOSVersion().getMajor(), 0, 99));
2164 }
2165
2166private:
2167 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
2168 : Kind(Kind), Platform(Platform),
2169 Arguments({Argument, VersionTuple().getAsString()}) {}
2170 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform,
2171 VersionTuple Value, Arg *Argument = nullptr)
2172 : Kind(Kind), Platform(Platform),
2173 Arguments({Argument, Value.getAsString()}) {
2174 if (!Value.empty())
2175 UnderlyingOSVersion = Value;
2176 }
2177
2178 static VersionTuple getVersionFromString(const StringRef Input) {
2179 llvm::VersionTuple Version;
2180 bool IsValid = !Version.tryParse(string: Input);
2181 assert(IsValid && "unable to convert input version to version tuple");
2182 (void)IsValid;
2183 return Version;
2184 }
2185
2186 static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
2187 switch (OS) {
2188 case llvm::Triple::Darwin:
2189 case llvm::Triple::MacOSX:
2190 return DarwinPlatformKind::MacOS;
2191 case llvm::Triple::IOS:
2192 return DarwinPlatformKind::IPhoneOS;
2193 case llvm::Triple::TvOS:
2194 return DarwinPlatformKind::TvOS;
2195 case llvm::Triple::WatchOS:
2196 return DarwinPlatformKind::WatchOS;
2197 case llvm::Triple::XROS:
2198 return DarwinPlatformKind::XROS;
2199 case llvm::Triple::DriverKit:
2200 return DarwinPlatformKind::DriverKit;
2201 case llvm::Triple::Firmware:
2202 return DarwinPlatformKind::Firmware;
2203 default:
2204 llvm_unreachable("Unable to infer Darwin variant");
2205 }
2206 }
2207
2208 static llvm::Triple::OSType getOSFromPlatform(DarwinPlatformKind Platform) {
2209 switch (Platform) {
2210 case DarwinPlatformKind::MacOS:
2211 return llvm::Triple::MacOSX;
2212 case DarwinPlatformKind::IPhoneOS:
2213 return llvm::Triple::IOS;
2214 case DarwinPlatformKind::TvOS:
2215 return llvm::Triple::TvOS;
2216 case DarwinPlatformKind::WatchOS:
2217 return llvm::Triple::WatchOS;
2218 case DarwinPlatformKind::DriverKit:
2219 return llvm::Triple::DriverKit;
2220 case DarwinPlatformKind::XROS:
2221 return llvm::Triple::XROS;
2222 case DarwinPlatformKind::Firmware:
2223 return llvm::Triple::Firmware;
2224 }
2225 llvm_unreachable("Unknown DarwinPlatformKind enum");
2226 }
2227
2228 static DarwinEnvironmentKind
2229 getEnvKindFromEnvType(llvm::Triple::EnvironmentType EnvironmentType) {
2230 switch (EnvironmentType) {
2231 case llvm::Triple::UnknownEnvironment:
2232 return DarwinEnvironmentKind::NativeEnvironment;
2233 case llvm::Triple::Simulator:
2234 return DarwinEnvironmentKind::Simulator;
2235 case llvm::Triple::MacABI:
2236 return DarwinEnvironmentKind::MacCatalyst;
2237 default:
2238 llvm_unreachable("Unable to infer Darwin environment");
2239 }
2240 }
2241
2242 static llvm::Triple::EnvironmentType
2243 getEnvTypeFromEnvKind(DarwinEnvironmentKind EnvironmentKind) {
2244 switch (EnvironmentKind) {
2245 case DarwinEnvironmentKind::NativeEnvironment:
2246 return llvm::Triple::UnknownEnvironment;
2247 case DarwinEnvironmentKind::Simulator:
2248 return llvm::Triple::Simulator;
2249 case DarwinEnvironmentKind::MacCatalyst:
2250 return llvm::Triple::MacABI;
2251 }
2252 llvm_unreachable("Unknown DarwinEnvironmentKind enum");
2253 }
2254
2255 static std::string getDisplayName(DarwinPlatformKind TargetPlatform,
2256 DarwinEnvironmentKind TargetEnvironment,
2257 VersionTuple Version) {
2258 SmallVector<std::string, 3> Components;
2259 switch (TargetPlatform) {
2260 case DarwinPlatformKind::MacOS:
2261 Components.push_back(Elt: "macOS");
2262 break;
2263 case DarwinPlatformKind::IPhoneOS:
2264 Components.push_back(Elt: "iOS");
2265 break;
2266 case DarwinPlatformKind::TvOS:
2267 Components.push_back(Elt: "tvOS");
2268 break;
2269 case DarwinPlatformKind::WatchOS:
2270 Components.push_back(Elt: "watchOS");
2271 break;
2272 case DarwinPlatformKind::DriverKit:
2273 Components.push_back(Elt: "DriverKit");
2274 break;
2275 default:
2276 llvm::reportFatalUsageError(reason: Twine("Platform: '") +
2277 std::to_string(val: TargetPlatform) +
2278 "' is unsupported when inferring SDK Info.");
2279 }
2280 switch (TargetEnvironment) {
2281 case DarwinEnvironmentKind::NativeEnvironment:
2282 break;
2283 case DarwinEnvironmentKind::Simulator:
2284 Components.push_back(Elt: "Simulator");
2285 break;
2286 default:
2287 llvm::reportFatalUsageError(reason: Twine("Environment: '") +
2288 std::to_string(val: TargetEnvironment) +
2289 "' is unsupported when inferring SDK Info.");
2290 }
2291 Components.push_back(Elt: Version.getAsString());
2292 return join(R&: Components, Separator: " ");
2293 }
2294
2295 SourceKind Kind;
2296 DarwinPlatformKind Platform;
2297 DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
2298 // When compiling for a zippered target, this means both target &
2299 // target variant is set on the command line, ZipperedOSVersion holds the
2300 // OSVersion tied to the main target value.
2301 VersionTuple ZipperedOSVersion;
2302 // We allow multiple ways to set or default the OS
2303 // version used for compilation. When set, UnderlyingOSVersion represents
2304 // the intended version to match the platform information computed from
2305 // arguments.
2306 std::optional<VersionTuple> UnderlyingOSVersion;
2307 bool InferSimulatorFromArch = true;
2308 std::pair<Arg *, std::string> Arguments;
2309 StringRef EnvVarName;
2310 // If the DarwinPlatform information is derived from an inferred source, this
2311 // captures what that source input was for error reporting.
2312 StringRef InferredSource;
2313 // When compiling for a zippered target, this value represents the target
2314 // triple encoded in the target variant.
2315 std::optional<llvm::Triple> TargetVariantTriple;
2316};
2317
2318/// Returns the deployment target that's specified using the -m<os>-version-min
2319/// argument.
2320std::optional<DarwinPlatform>
2321getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
2322 const Driver &TheDriver) {
2323 Arg *macOSVersion = Args.getLastArg(Ids: options::OPT_mmacos_version_min_EQ);
2324 Arg *iOSVersion = Args.getLastArg(Ids: options::OPT_mios_version_min_EQ,
2325 Ids: options::OPT_mios_simulator_version_min_EQ);
2326 Arg *TvOSVersion =
2327 Args.getLastArg(Ids: options::OPT_mtvos_version_min_EQ,
2328 Ids: options::OPT_mtvos_simulator_version_min_EQ);
2329 Arg *WatchOSVersion =
2330 Args.getLastArg(Ids: options::OPT_mwatchos_version_min_EQ,
2331 Ids: options::OPT_mwatchos_simulator_version_min_EQ);
2332
2333 auto GetDarwinPlatform =
2334 [&](DarwinPlatform::DarwinPlatformKind Platform, Arg *VersionArg,
2335 bool IsSimulator) -> std::optional<DarwinPlatform> {
2336 if (StringRef(VersionArg->getValue()).empty()) {
2337 TheDriver.Diag(DiagID: diag::err_drv_missing_version_number)
2338 << VersionArg->getAsString(Args);
2339 return std::nullopt;
2340 }
2341 return DarwinPlatform::createOSVersionArg(Platform, A: VersionArg,
2342 /*IsSimulator=*/IsSimulator);
2343 };
2344
2345 if (macOSVersion) {
2346 if (iOSVersion || TvOSVersion || WatchOSVersion) {
2347 TheDriver.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
2348 << macOSVersion->getAsString(Args)
2349 << (iOSVersion ? iOSVersion
2350 : TvOSVersion ? TvOSVersion : WatchOSVersion)
2351 ->getAsString(Args);
2352 }
2353 return GetDarwinPlatform(Darwin::MacOS, macOSVersion,
2354 /*IsSimulator=*/false);
2355
2356 } else if (iOSVersion) {
2357 if (TvOSVersion || WatchOSVersion) {
2358 TheDriver.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
2359 << iOSVersion->getAsString(Args)
2360 << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
2361 }
2362 return GetDarwinPlatform(Darwin::IPhoneOS, iOSVersion,
2363 iOSVersion->getOption().getID() ==
2364 options::OPT_mios_simulator_version_min_EQ);
2365 } else if (TvOSVersion) {
2366 if (WatchOSVersion) {
2367 TheDriver.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
2368 << TvOSVersion->getAsString(Args)
2369 << WatchOSVersion->getAsString(Args);
2370 }
2371 return GetDarwinPlatform(Darwin::TvOS, TvOSVersion,
2372 TvOSVersion->getOption().getID() ==
2373 options::OPT_mtvos_simulator_version_min_EQ);
2374 } else if (WatchOSVersion)
2375 return GetDarwinPlatform(
2376 Darwin::WatchOS, WatchOSVersion,
2377 WatchOSVersion->getOption().getID() ==
2378 options::OPT_mwatchos_simulator_version_min_EQ);
2379 return std::nullopt;
2380}
2381
2382/// Returns the deployment target that's specified using the
2383/// OS_DEPLOYMENT_TARGET environment variable.
2384std::optional<DarwinPlatform>
2385getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
2386 const llvm::Triple &Triple) {
2387 const char *EnvVars[] = {
2388 "MACOSX_DEPLOYMENT_TARGET",
2389 "IPHONEOS_DEPLOYMENT_TARGET",
2390 "TVOS_DEPLOYMENT_TARGET",
2391 "WATCHOS_DEPLOYMENT_TARGET",
2392 "DRIVERKIT_DEPLOYMENT_TARGET",
2393 "XROS_DEPLOYMENT_TARGET"
2394 };
2395 std::string Targets[std::size(EnvVars)];
2396 for (const auto &I : llvm::enumerate(First: llvm::ArrayRef(EnvVars))) {
2397 if (char *Env = ::getenv(name: I.value()))
2398 Targets[I.index()] = Env;
2399 }
2400
2401 // Allow conflicts among OSX and iOS for historical reasons, but choose the
2402 // default platform.
2403 if (!Targets[Darwin::MacOS].empty() &&
2404 (!Targets[Darwin::IPhoneOS].empty() ||
2405 !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty() ||
2406 !Targets[Darwin::XROS].empty())) {
2407 if (Triple.getArch() == llvm::Triple::arm ||
2408 Triple.getArch() == llvm::Triple::aarch64 ||
2409 Triple.getArch() == llvm::Triple::thumb)
2410 Targets[Darwin::MacOS] = "";
2411 else
2412 Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
2413 Targets[Darwin::TvOS] = Targets[Darwin::XROS] = "";
2414 } else {
2415 // Don't allow conflicts in any other platform.
2416 unsigned FirstTarget = std::size(Targets);
2417 for (unsigned I = 0; I != std::size(Targets); ++I) {
2418 if (Targets[I].empty())
2419 continue;
2420 if (FirstTarget == std::size(Targets))
2421 FirstTarget = I;
2422 else
2423 TheDriver.Diag(DiagID: diag::err_drv_conflicting_deployment_targets)
2424 << Targets[FirstTarget] << Targets[I];
2425 }
2426 }
2427
2428 for (const auto &Target : llvm::enumerate(First: llvm::ArrayRef(Targets))) {
2429 if (!Target.value().empty())
2430 return DarwinPlatform::createDeploymentTargetEnv(
2431 Platform: (Darwin::DarwinPlatformKind)Target.index(), EnvVarName: EnvVars[Target.index()],
2432 OSVersion: Target.value());
2433 }
2434 return std::nullopt;
2435}
2436
2437/// Tries to infer the deployment target from the SDK specified by -isysroot
2438/// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
2439/// it's available.
2440std::optional<DarwinPlatform>
2441inferDeploymentTargetFromSDK(DerivedArgList &Args,
2442 const std::optional<DarwinSDKInfo> &SDKInfo) {
2443 const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot);
2444 if (!A)
2445 return std::nullopt;
2446 StringRef isysroot = A->getValue();
2447 if (SDKInfo)
2448 return DarwinPlatform::createFromSDKInfo(SDKRoot: isysroot, SDKInfo: *SDKInfo);
2449
2450 StringRef SDK = Darwin::getSDKName(isysroot);
2451 if (!SDK.size())
2452 return std::nullopt;
2453
2454 std::string Version;
2455 // Slice the version number out.
2456 // Version number is between the first and the last number.
2457 size_t StartVer = SDK.find_first_of(Chars: "0123456789");
2458 size_t EndVer = SDK.find_last_of(Chars: "0123456789");
2459 if (StartVer != StringRef::npos && EndVer > StartVer)
2460 Version = std::string(SDK.slice(Start: StartVer, End: EndVer + 1));
2461 if (Version.empty())
2462 return std::nullopt;
2463
2464 if (SDK.starts_with(Prefix: "iPhoneOS") || SDK.starts_with(Prefix: "iPhoneSimulator"))
2465 return DarwinPlatform::createFromSDK(
2466 SDKRoot: isysroot, Platform: Darwin::IPhoneOS, Value: Version,
2467 /*IsSimulator=*/SDK.starts_with(Prefix: "iPhoneSimulator"));
2468 else if (SDK.starts_with(Prefix: "MacOSX"))
2469 return DarwinPlatform::createFromSDK(SDKRoot: isysroot, Platform: Darwin::MacOS,
2470 Value: getSystemOrSDKMacOSVersion(MacOSSDKVersion: Version));
2471 else if (SDK.starts_with(Prefix: "WatchOS") || SDK.starts_with(Prefix: "WatchSimulator"))
2472 return DarwinPlatform::createFromSDK(
2473 SDKRoot: isysroot, Platform: Darwin::WatchOS, Value: Version,
2474 /*IsSimulator=*/SDK.starts_with(Prefix: "WatchSimulator"));
2475 else if (SDK.starts_with(Prefix: "AppleTVOS") || SDK.starts_with(Prefix: "AppleTVSimulator"))
2476 return DarwinPlatform::createFromSDK(
2477 SDKRoot: isysroot, Platform: Darwin::TvOS, Value: Version,
2478 /*IsSimulator=*/SDK.starts_with(Prefix: "AppleTVSimulator"));
2479 else if (SDK.starts_with(Prefix: "DriverKit"))
2480 return DarwinPlatform::createFromSDK(SDKRoot: isysroot, Platform: Darwin::DriverKit, Value: Version);
2481 return std::nullopt;
2482}
2483
2484// Compute & get the OS Version when the target triple omitted one.
2485VersionTuple getInferredOSVersion(llvm::Triple::OSType OS,
2486 const llvm::Triple &Triple,
2487 const Driver &TheDriver) {
2488 VersionTuple OsVersion;
2489 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
2490 switch (OS) {
2491 case llvm::Triple::Darwin:
2492 case llvm::Triple::MacOSX:
2493 // If there is no version specified on triple, and both host and target are
2494 // macos, use the host triple to infer OS version.
2495 if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
2496 !Triple.getOSMajorVersion())
2497 SystemTriple.getMacOSXVersion(Version&: OsVersion);
2498 else if (!Triple.getMacOSXVersion(Version&: OsVersion))
2499 TheDriver.Diag(DiagID: diag::err_drv_invalid_darwin_version)
2500 << Triple.getOSName();
2501 break;
2502 case llvm::Triple::IOS:
2503 if (Triple.isMacCatalystEnvironment() && !Triple.getOSMajorVersion()) {
2504 OsVersion = VersionTuple(13, 1);
2505 } else
2506 OsVersion = Triple.getiOSVersion();
2507 break;
2508 case llvm::Triple::TvOS:
2509 OsVersion = Triple.getOSVersion();
2510 break;
2511 case llvm::Triple::WatchOS:
2512 OsVersion = Triple.getWatchOSVersion();
2513 break;
2514 case llvm::Triple::DriverKit:
2515 OsVersion = Triple.getDriverKitVersion();
2516 break;
2517 default:
2518 OsVersion = Triple.getOSVersion();
2519 if (!OsVersion.getMajor())
2520 OsVersion = OsVersion.withMajorReplaced(NewMajor: 1);
2521 break;
2522 }
2523 return OsVersion;
2524}
2525
2526/// Tries to infer the target OS from the -arch.
2527std::optional<DarwinPlatform>
2528inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
2529 const llvm::Triple &Triple,
2530 const Driver &TheDriver) {
2531 llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
2532
2533 StringRef MachOArchName = Toolchain.getMachOArchName(Args);
2534 if (MachOArchName == "arm64" || MachOArchName == "arm64e")
2535 OSTy = llvm::Triple::MacOSX;
2536 else if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
2537 MachOArchName == "armv6")
2538 OSTy = llvm::Triple::IOS;
2539 else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
2540 OSTy = llvm::Triple::WatchOS;
2541 else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
2542 MachOArchName != "armv7em" && MachOArchName != "armv8m.base" &&
2543 MachOArchName != "armv8m.main" && MachOArchName != "armv8.1m.main")
2544 OSTy = llvm::Triple::MacOSX;
2545 if (OSTy == llvm::Triple::UnknownOS)
2546 return std::nullopt;
2547 return DarwinPlatform::createFromArch(
2548 Arch: MachOArchName, OS: OSTy, Version: getInferredOSVersion(OS: OSTy, Triple, TheDriver));
2549}
2550
2551/// Returns the deployment target that's specified using the -target option.
2552std::optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
2553 DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver,
2554 const std::optional<DarwinSDKInfo> &SDKInfo) {
2555 if (!Args.hasArg(Ids: options::OPT_target))
2556 return std::nullopt;
2557 if (Triple.getOS() == llvm::Triple::Darwin ||
2558 Triple.getOS() == llvm::Triple::UnknownOS)
2559 return std::nullopt;
2560 std::optional<llvm::Triple> TargetVariantTriple;
2561 for (const Arg *A : Args.filtered(Ids: options::OPT_darwin_target_variant)) {
2562 llvm::Triple TVT(A->getValue());
2563 // Find a matching <arch>-<vendor> target variant triple that can be used.
2564 if ((Triple.getArch() == llvm::Triple::aarch64 ||
2565 TVT.getArchName() == Triple.getArchName()) &&
2566 TVT.getArch() == Triple.getArch() &&
2567 TVT.getSubArch() == Triple.getSubArch() &&
2568 TVT.getVendor() == Triple.getVendor()) {
2569 if (TargetVariantTriple)
2570 continue;
2571 A->claim();
2572 // Accept a -target-variant triple when compiling code that may run on
2573 // macOS or Mac Catalyst.
2574 if ((Triple.isMacOSX() && TVT.getOS() == llvm::Triple::IOS &&
2575 TVT.isMacCatalystEnvironment()) ||
2576 (TVT.isMacOSX() && Triple.getOS() == llvm::Triple::IOS &&
2577 Triple.isMacCatalystEnvironment())) {
2578 TargetVariantTriple = TVT;
2579 continue;
2580 }
2581 TheDriver.Diag(DiagID: diag::err_drv_target_variant_invalid)
2582 << A->getSpelling() << A->getValue();
2583 }
2584 }
2585 DarwinPlatform PlatformAndVersion = DarwinPlatform::createFromTarget(
2586 TT: Triple, A: Args.getLastArg(Ids: options::OPT_target), TargetVariantTriple,
2587 SDKInfo);
2588
2589 return PlatformAndVersion;
2590}
2591
2592/// Returns the deployment target that's specified using the -mtargetos option.
2593std::optional<DarwinPlatform> getDeploymentTargetFromMTargetOSArg(
2594 DerivedArgList &Args, const Driver &TheDriver,
2595 const std::optional<DarwinSDKInfo> &SDKInfo) {
2596 auto *A = Args.getLastArg(Ids: options::OPT_mtargetos_EQ);
2597 if (!A)
2598 return std::nullopt;
2599 llvm::Triple TT(llvm::Twine("unknown-apple-") + A->getValue());
2600 switch (TT.getOS()) {
2601 case llvm::Triple::MacOSX:
2602 case llvm::Triple::IOS:
2603 case llvm::Triple::TvOS:
2604 case llvm::Triple::WatchOS:
2605 case llvm::Triple::XROS:
2606 break;
2607 default:
2608 TheDriver.Diag(DiagID: diag::err_drv_invalid_os_in_arg)
2609 << TT.getOSName() << A->getAsString(Args);
2610 return std::nullopt;
2611 }
2612
2613 VersionTuple Version = TT.getOSVersion();
2614 if (!Version.getMajor()) {
2615 TheDriver.Diag(DiagID: diag::err_drv_invalid_version_number)
2616 << A->getAsString(Args);
2617 return std::nullopt;
2618 }
2619 return DarwinPlatform::createFromMTargetOS(OS: TT.getOS(), OSVersion: Version,
2620 Environment: TT.getEnvironment(), A, SDKInfo);
2621}
2622
2623std::optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
2624 const ArgList &Args,
2625 const Driver &TheDriver) {
2626 const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot);
2627 if (!A)
2628 return std::nullopt;
2629 StringRef isysroot = A->getValue();
2630 auto SDKInfoOrErr = parseDarwinSDKInfo(VFS, SDKRootPath: isysroot);
2631 if (!SDKInfoOrErr) {
2632 llvm::consumeError(Err: SDKInfoOrErr.takeError());
2633 TheDriver.Diag(DiagID: diag::warn_drv_darwin_sdk_invalid_settings);
2634 return std::nullopt;
2635 }
2636 return *SDKInfoOrErr;
2637}
2638
2639} // namespace
2640
2641void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
2642 const OptTable &Opts = getDriver().getOpts();
2643 // TryXcselect keeps track of whether we use xcselect to find the SDK
2644 // when CLANG_USE_XCSELECT is enabled. Currently, we do this when we
2645 // do not have a sysroot from -isysroot, --sysroot, or SDKROOT, and
2646 // we do not have --no-xcselect.
2647 bool TryXcselect = false;
2648 (void)TryXcselect;
2649
2650 // Support allowing the SDKROOT environment variable used by xcrun and other
2651 // Xcode tools to define the default sysroot, by making it the default for
2652 // isysroot.
2653 if (const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot)) {
2654 // Warn if the path does not exist.
2655 if (!getVFS().exists(Path: A->getValue()))
2656 getDriver().Diag(DiagID: clang::diag::warn_missing_sysroot) << A->getValue();
2657 } else if (const char *env = ::getenv(name: "SDKROOT")) {
2658 // We only use this value as the default if it is an absolute path,
2659 // exists, and it is not the root path.
2660 if (llvm::sys::path::is_absolute(path: env) && getVFS().exists(Path: env) &&
2661 StringRef(env) != "/") {
2662 Args.append(A: Args.MakeSeparateArg(
2663 BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_isysroot), Value: env));
2664 }
2665 } else {
2666 TryXcselect = !Args.hasArg(Ids: options::OPT__sysroot_EQ) &&
2667 !Args.hasArg(Ids: options::OPT_no_xcselect);
2668 }
2669
2670 // Read the SDKSettings.json file for more information, like the SDK version
2671 // that we can pass down to the compiler.
2672 SDKInfo = parseSDKSettings(VFS&: getVFS(), Args, TheDriver: getDriver());
2673 // FIXME: If SDKInfo is std::nullopt, diagnose a bad isysroot value (e.g.
2674 // doesn't end in .sdk).
2675
2676 // The OS and the version can be specified using the -target argument.
2677 std::optional<DarwinPlatform> PlatformAndVersion =
2678 getDeploymentTargetFromTargetArg(Args, Triple: getTriple(), TheDriver: getDriver(), SDKInfo);
2679 if (PlatformAndVersion) {
2680 // Disallow mixing -target and -mtargetos=.
2681 if (const auto *MTargetOSArg = Args.getLastArg(Ids: options::OPT_mtargetos_EQ)) {
2682 std::string TargetArgStr = PlatformAndVersion->getAsString(Args, Opts);
2683 std::string MTargetOSArgStr = MTargetOSArg->getAsString(Args);
2684 getDriver().Diag(DiagID: diag::err_drv_cannot_mix_options)
2685 << TargetArgStr << MTargetOSArgStr;
2686 }
2687 // Implicitly allow resolving the OS version when it wasn't explicitly set.
2688 bool TripleProvidedOSVersion = PlatformAndVersion->hasOSVersion();
2689 if (!TripleProvidedOSVersion)
2690 PlatformAndVersion->setOSVersion(
2691 getInferredOSVersion(OS: getTriple().getOS(), Triple: getTriple(), TheDriver: getDriver()));
2692
2693 std::optional<DarwinPlatform> PlatformAndVersionFromOSVersionArg =
2694 getDeploymentTargetFromOSVersionArg(Args, TheDriver: getDriver());
2695 if (PlatformAndVersionFromOSVersionArg) {
2696 unsigned TargetMajor, TargetMinor, TargetMicro;
2697 bool TargetExtra;
2698 unsigned ArgMajor, ArgMinor, ArgMicro;
2699 bool ArgExtra;
2700 if (PlatformAndVersion->getPlatform() !=
2701 PlatformAndVersionFromOSVersionArg->getPlatform() ||
2702 (Driver::GetReleaseVersion(
2703 Str: PlatformAndVersion->getOSVersion().getAsString(), Major&: TargetMajor,
2704 Minor&: TargetMinor, Micro&: TargetMicro, HadExtra&: TargetExtra) &&
2705 Driver::GetReleaseVersion(
2706 Str: PlatformAndVersionFromOSVersionArg->getOSVersion().getAsString(),
2707 Major&: ArgMajor, Minor&: ArgMinor, Micro&: ArgMicro, HadExtra&: ArgExtra) &&
2708 (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
2709 VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
2710 TargetExtra != ArgExtra))) {
2711 // Select the OS version from the -m<os>-version-min argument when
2712 // the -target does not include an OS version.
2713 if (PlatformAndVersion->getPlatform() ==
2714 PlatformAndVersionFromOSVersionArg->getPlatform() &&
2715 !TripleProvidedOSVersion) {
2716 PlatformAndVersion->setOSVersion(
2717 PlatformAndVersionFromOSVersionArg->getOSVersion());
2718 } else {
2719 // Warn about -m<os>-version-min that doesn't match the OS version
2720 // that's specified in the target.
2721 std::string OSVersionArg =
2722 PlatformAndVersionFromOSVersionArg->getAsString(Args, Opts);
2723 std::string TargetArg = PlatformAndVersion->getAsString(Args, Opts);
2724 getDriver().Diag(DiagID: clang::diag::warn_drv_overriding_option)
2725 << OSVersionArg << TargetArg;
2726 }
2727 }
2728 }
2729 } else if ((PlatformAndVersion = getDeploymentTargetFromMTargetOSArg(
2730 Args, TheDriver: getDriver(), SDKInfo))) {
2731 // The OS target can be specified using the -mtargetos= argument.
2732 // Disallow mixing -mtargetos= and -m<os>version-min=.
2733 std::optional<DarwinPlatform> PlatformAndVersionFromOSVersionArg =
2734 getDeploymentTargetFromOSVersionArg(Args, TheDriver: getDriver());
2735 if (PlatformAndVersionFromOSVersionArg) {
2736 std::string MTargetOSArgStr = PlatformAndVersion->getAsString(Args, Opts);
2737 std::string OSVersionArgStr =
2738 PlatformAndVersionFromOSVersionArg->getAsString(Args, Opts);
2739 getDriver().Diag(DiagID: diag::err_drv_cannot_mix_options)
2740 << MTargetOSArgStr << OSVersionArgStr;
2741 }
2742 } else {
2743 // The OS target can be specified using the -m<os>version-min argument.
2744 PlatformAndVersion = getDeploymentTargetFromOSVersionArg(Args, TheDriver: getDriver());
2745 // If no deployment target was specified on the command line, check for
2746 // environment defines.
2747 if (!PlatformAndVersion) {
2748 PlatformAndVersion =
2749 getDeploymentTargetFromEnvironmentVariables(TheDriver: getDriver(), Triple: getTriple());
2750 if (PlatformAndVersion) {
2751 // Don't infer simulator from the arch when the SDK is also specified.
2752 std::optional<DarwinPlatform> SDKTarget =
2753 inferDeploymentTargetFromSDK(Args, SDKInfo);
2754 if (SDKTarget)
2755 PlatformAndVersion->setEnvironment(SDKTarget->getEnvironment());
2756 }
2757 }
2758 // If there is no command-line argument to specify the Target version and
2759 // no environment variable defined, see if we can set the default based
2760 // on -isysroot using SDKSettings.json if it exists.
2761 if (!PlatformAndVersion) {
2762 PlatformAndVersion = inferDeploymentTargetFromSDK(Args, SDKInfo);
2763 /// If the target was successfully constructed from the SDK path, try to
2764 /// infer the SDK info if the SDK doesn't have it.
2765 if (PlatformAndVersion && !SDKInfo)
2766 SDKInfo = PlatformAndVersion->inferSDKInfo();
2767 }
2768 // If no OS targets have been specified, try to guess platform from -target
2769 // or arch name and compute the version from the triple.
2770 if (!PlatformAndVersion)
2771 PlatformAndVersion =
2772 inferDeploymentTargetFromArch(Args, Toolchain: *this, Triple: getTriple(), TheDriver: getDriver());
2773 }
2774
2775 assert(PlatformAndVersion && "Unable to infer Darwin variant");
2776 if (!PlatformAndVersion->isValidOSVersion()) {
2777 if (PlatformAndVersion->isExplicitlySpecified())
2778 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2779 << PlatformAndVersion->getAsString(Args, Opts);
2780 else
2781 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number_inferred)
2782 << PlatformAndVersion->getOSVersion().getAsString()
2783 << PlatformAndVersion->getInferredSource();
2784 }
2785 // After the deployment OS version has been resolved, set it to the canonical
2786 // version before further error detection and converting to a proper target
2787 // triple.
2788 VersionTuple CanonicalVersion = PlatformAndVersion->getCanonicalOSVersion();
2789 if (CanonicalVersion != PlatformAndVersion->getOSVersion()) {
2790 getDriver().Diag(DiagID: diag::warn_drv_overriding_deployment_version)
2791 << PlatformAndVersion->getOSVersion().getAsString()
2792 << CanonicalVersion.getAsString();
2793 PlatformAndVersion->setOSVersion(CanonicalVersion);
2794 }
2795
2796 PlatformAndVersion->addOSVersionMinArgument(Args, Opts);
2797 DarwinPlatformKind Platform = PlatformAndVersion->getPlatform();
2798
2799 unsigned Major, Minor, Micro;
2800 bool HadExtra;
2801 // The major version should not be over this number.
2802 const unsigned MajorVersionLimit = 1000;
2803 const VersionTuple OSVersion = PlatformAndVersion->takeOSVersion();
2804 const std::string OSVersionStr = OSVersion.getAsString();
2805 // Set the tool chain target information.
2806 if (Platform == MacOS) {
2807#ifdef CLANG_USE_XCSELECT
2808 if (TryXcselect) {
2809 char *p;
2810 if (!::xcselect_host_sdk_path(CLANG_XCSELECT_HOST_SDK_POLICY, &p)) {
2811 Args.append(Args.MakeSeparateArg(
2812 nullptr, Opts.getOption(options::OPT_isysroot), p));
2813 ::free(p);
2814 if (!SDKInfo)
2815 SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
2816 }
2817 }
2818#endif
2819 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2820 HadExtra) ||
2821 HadExtra || Major < 10 || Major >= MajorVersionLimit || Minor >= 100 ||
2822 Micro >= 100)
2823 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2824 << PlatformAndVersion->getAsString(Args, Opts);
2825 } else if (Platform == IPhoneOS) {
2826 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2827 HadExtra) ||
2828 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2829 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2830 << PlatformAndVersion->getAsString(Args, Opts);
2831 ;
2832 if (PlatformAndVersion->getEnvironment() == MacCatalyst &&
2833 (Major < 13 || (Major == 13 && Minor < 1))) {
2834 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2835 << PlatformAndVersion->getAsString(Args, Opts);
2836 Major = 13;
2837 Minor = 1;
2838 Micro = 0;
2839 }
2840 // For 32-bit targets, the deployment target for iOS has to be earlier than
2841 // iOS 11.
2842 if (getTriple().isArch32Bit() && Major >= 11) {
2843 // If the deployment target is explicitly specified, print a diagnostic.
2844 if (PlatformAndVersion->isExplicitlySpecified()) {
2845 if (PlatformAndVersion->getEnvironment() == MacCatalyst)
2846 getDriver().Diag(DiagID: diag::err_invalid_macos_32bit_deployment_target);
2847 else
2848 getDriver().Diag(DiagID: diag::warn_invalid_ios_deployment_target)
2849 << PlatformAndVersion->getAsString(Args, Opts);
2850 // Otherwise, set it to 10.99.99.
2851 } else {
2852 Major = 10;
2853 Minor = 99;
2854 Micro = 99;
2855 }
2856 }
2857 } else if (Platform == TvOS) {
2858 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2859 HadExtra) ||
2860 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2861 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2862 << PlatformAndVersion->getAsString(Args, Opts);
2863 } else if (Platform == WatchOS) {
2864 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2865 HadExtra) ||
2866 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2867 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2868 << PlatformAndVersion->getAsString(Args, Opts);
2869 } else if (Platform == DriverKit) {
2870 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2871 HadExtra) ||
2872 HadExtra || Major < 19 || Major >= MajorVersionLimit || Minor >= 100 ||
2873 Micro >= 100)
2874 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2875 << PlatformAndVersion->getAsString(Args, Opts);
2876 } else {
2877 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2878 HadExtra) ||
2879 HadExtra || Major < 1 || Major >= MajorVersionLimit || Minor >= 100 ||
2880 Micro >= 100)
2881 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2882 << PlatformAndVersion->getAsString(Args, Opts);
2883 }
2884
2885 DarwinEnvironmentKind Environment = PlatformAndVersion->getEnvironment();
2886 // Recognize iOS targets with an x86 architecture as the iOS simulator.
2887 if (Environment == NativeEnvironment && Platform != MacOS &&
2888 Platform != DriverKit &&
2889 PlatformAndVersion->canInferSimulatorFromArch() && getTriple().isX86())
2890 Environment = Simulator;
2891
2892 VersionTuple ZipperedOSVersion;
2893 if (Environment == MacCatalyst)
2894 ZipperedOSVersion = PlatformAndVersion->getZipperedOSVersion();
2895 setTarget(Platform, Environment, Major, Minor, Micro, NativeTargetVersion: ZipperedOSVersion);
2896 TargetVariantTriple = PlatformAndVersion->getTargetVariantTriple();
2897 if (TargetVariantTriple &&
2898 !llvm::Triple::isValidVersionForOS(OSKind: TargetVariantTriple->getOS(),
2899 Version: TargetVariantTriple->getOSVersion())) {
2900 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2901 << TargetVariantTriple->str();
2902 }
2903}
2904
2905bool DarwinClang::HasPlatformPrefix(const llvm::Triple &T) const {
2906 if (SDKInfo)
2907 return !SDKInfo->getPlatformPrefix(Triple: T).empty();
2908 else
2909 return Darwin::HasPlatformPrefix(T);
2910}
2911
2912// For certain platforms/environments almost all resources (e.g., headers) are
2913// located in sub-directories, e.g., for DriverKit they live in
2914// <SYSROOT>/System/DriverKit/usr/include (instead of <SYSROOT>/usr/include).
2915void DarwinClang::AppendPlatformPrefix(SmallString<128> &Path,
2916 const llvm::Triple &T) const {
2917 if (SDKInfo) {
2918 const StringRef PlatformPrefix = SDKInfo->getPlatformPrefix(Triple: T);
2919 if (!PlatformPrefix.empty())
2920 llvm::sys::path::append(path&: Path, a: PlatformPrefix);
2921 } else if (T.isDriverKit()) {
2922 // The first version of DriverKit didn't have SDKSettings.json, manually add
2923 // its prefix.
2924 llvm::sys::path::append(path&: Path, a: "System", b: "DriverKit");
2925 }
2926}
2927
2928// Returns the effective sysroot from either -isysroot or --sysroot, plus the
2929// platform prefix (if any).
2930llvm::SmallString<128>
2931AppleMachO::GetEffectiveSysroot(const llvm::opt::ArgList &DriverArgs) const {
2932 llvm::SmallString<128> Path("/");
2933 if (DriverArgs.hasArg(Ids: options::OPT_isysroot))
2934 Path = DriverArgs.getLastArgValue(Id: options::OPT_isysroot);
2935 else if (!getDriver().SysRoot.empty())
2936 Path = getDriver().SysRoot;
2937
2938 if (hasEffectiveTriple()) {
2939 AppendPlatformPrefix(Path, T: getEffectiveTriple());
2940 }
2941 return Path;
2942}
2943
2944void AppleMachO::AddClangSystemIncludeArgs(
2945 const llvm::opt::ArgList &DriverArgs,
2946 llvm::opt::ArgStringList &CC1Args) const {
2947 const Driver &D = getDriver();
2948
2949 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2950
2951 bool NoStdInc = DriverArgs.hasArg(Ids: options::OPT_nostdinc);
2952 bool NoStdlibInc = DriverArgs.hasArg(Ids: options::OPT_nostdlibinc);
2953 bool NoBuiltinInc = DriverArgs.hasFlag(
2954 Pos: options::OPT_nobuiltininc, Neg: options::OPT_ibuiltininc, /*Default=*/false);
2955 bool ForceBuiltinInc = DriverArgs.hasFlag(
2956 Pos: options::OPT_ibuiltininc, Neg: options::OPT_nobuiltininc, /*Default=*/false);
2957
2958 // Add <sysroot>/usr/local/include
2959 if (!NoStdInc && !NoStdlibInc) {
2960 SmallString<128> P(Sysroot);
2961 llvm::sys::path::append(path&: P, a: "usr", b: "local", c: "include");
2962 addSystemInclude(DriverArgs, CC1Args, Path: P);
2963 }
2964
2965 // Add the Clang builtin headers (<resource>/include)
2966 if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
2967 SmallString<128> P(D.ResourceDir);
2968 llvm::sys::path::append(path&: P, a: "include");
2969 addSystemInclude(DriverArgs, CC1Args, Path: P);
2970 }
2971
2972 if (NoStdInc || NoStdlibInc)
2973 return;
2974
2975 // Check for configure-time C include directories.
2976 llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
2977 if (!CIncludeDirs.empty()) {
2978 llvm::SmallVector<llvm::StringRef, 5> dirs;
2979 CIncludeDirs.split(A&: dirs, Separator: ":");
2980 for (llvm::StringRef dir : dirs) {
2981 llvm::StringRef Prefix =
2982 llvm::sys::path::is_absolute(path: dir) ? "" : llvm::StringRef(Sysroot);
2983 addExternCSystemInclude(DriverArgs, CC1Args, Path: Prefix + dir);
2984 }
2985 } else {
2986 // Otherwise, add <sysroot>/usr/include.
2987 SmallString<128> P(Sysroot);
2988 llvm::sys::path::append(path&: P, a: "usr", b: "include");
2989 addExternCSystemInclude(DriverArgs, CC1Args, Path: P.str());
2990 }
2991}
2992
2993void DarwinClang::AddClangSystemIncludeArgs(
2994 const llvm::opt::ArgList &DriverArgs,
2995 llvm::opt::ArgStringList &CC1Args) const {
2996 AppleMachO::AddClangSystemIncludeArgs(DriverArgs, CC1Args);
2997
2998 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc, Ids: options::OPT_nostdlibinc))
2999 return;
3000
3001 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
3002
3003 // Add <sysroot>/System/Library/Frameworks
3004 // Add <sysroot>/System/Library/SubFrameworks
3005 // Add <sysroot>/Library/Frameworks
3006 SmallString<128> P1(Sysroot), P2(Sysroot), P3(Sysroot);
3007 llvm::sys::path::append(path&: P1, a: "System", b: "Library", c: "Frameworks");
3008 llvm::sys::path::append(path&: P2, a: "System", b: "Library", c: "SubFrameworks");
3009 llvm::sys::path::append(path&: P3, a: "Library", b: "Frameworks");
3010 addSystemFrameworkIncludes(DriverArgs, CC1Args, Paths: {P1, P2, P3});
3011}
3012
3013bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
3014 llvm::opt::ArgStringList &CC1Args,
3015 llvm::SmallString<128> Base,
3016 llvm::StringRef Version,
3017 llvm::StringRef ArchDir,
3018 llvm::StringRef BitDir) const {
3019 llvm::sys::path::append(path&: Base, a: Version);
3020
3021 // Add the base dir
3022 addSystemInclude(DriverArgs, CC1Args, Path: Base);
3023
3024 // Add the multilib dirs
3025 {
3026 llvm::SmallString<128> P = Base;
3027 if (!ArchDir.empty())
3028 llvm::sys::path::append(path&: P, a: ArchDir);
3029 if (!BitDir.empty())
3030 llvm::sys::path::append(path&: P, a: BitDir);
3031 addSystemInclude(DriverArgs, CC1Args, Path: P);
3032 }
3033
3034 // Add the backward dir
3035 {
3036 llvm::SmallString<128> P = Base;
3037 llvm::sys::path::append(path&: P, a: "backward");
3038 addSystemInclude(DriverArgs, CC1Args, Path: P);
3039 }
3040
3041 return getVFS().exists(Path: Base);
3042}
3043
3044void AppleMachO::AddClangCXXStdlibIncludeArgs(
3045 const llvm::opt::ArgList &DriverArgs,
3046 llvm::opt::ArgStringList &CC1Args) const {
3047 // The implementation from a base class will pass through the -stdlib to
3048 // CC1Args.
3049 // FIXME: this should not be necessary, remove usages in the frontend
3050 // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
3051 // Also check whether this is used for setting library search paths.
3052 ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
3053
3054 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc, Ids: options::OPT_nostdlibinc,
3055 Ids: options::OPT_nostdincxx))
3056 return;
3057
3058 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
3059
3060 switch (GetCXXStdlibType(Args: DriverArgs)) {
3061 case ToolChain::CST_Libcxx: {
3062 // On Darwin, libc++ can be installed in one of the following places:
3063 // 1. Alongside the compiler in <clang-executable-folder>/../include/c++/v1
3064 // 2. In a SDK (or a custom sysroot) in <sysroot>/usr/include/c++/v1
3065 //
3066 // The precedence of paths is as listed above, i.e. we take the first path
3067 // that exists. Note that we never include libc++ twice -- we take the first
3068 // path that exists and don't send the other paths to CC1 (otherwise
3069 // include_next could break).
3070
3071 // Check for (1)
3072 // Get from '<install>/bin' to '<install>/include/c++/v1'.
3073 // Note that InstallBin can be relative, so we use '..' instead of
3074 // parent_path.
3075 llvm::SmallString<128> InstallBin(getDriver().Dir); // <install>/bin
3076 llvm::sys::path::append(path&: InstallBin, a: "..", b: "include", c: "c++", d: "v1");
3077 if (getVFS().exists(Path: InstallBin)) {
3078 addSystemInclude(DriverArgs, CC1Args, Path: InstallBin);
3079 return;
3080 } else if (DriverArgs.hasArg(Ids: options::OPT_v)) {
3081 llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
3082 << "\"\n";
3083 }
3084
3085 // Otherwise, check for (2)
3086 llvm::SmallString<128> SysrootUsr = Sysroot;
3087 llvm::sys::path::append(path&: SysrootUsr, a: "usr", b: "include", c: "c++", d: "v1");
3088 if (getVFS().exists(Path: SysrootUsr)) {
3089 addSystemInclude(DriverArgs, CC1Args, Path: SysrootUsr);
3090 return;
3091 } else if (DriverArgs.hasArg(Ids: options::OPT_v)) {
3092 llvm::errs() << "ignoring nonexistent directory \"" << SysrootUsr
3093 << "\"\n";
3094 }
3095
3096 // Otherwise, don't add any path.
3097 break;
3098 }
3099
3100 case ToolChain::CST_Libstdcxx:
3101 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args);
3102 break;
3103 }
3104}
3105
3106void AppleMachO::AddGnuCPlusPlusIncludePaths(
3107 const llvm::opt::ArgList &DriverArgs,
3108 llvm::opt::ArgStringList &CC1Args) const {}
3109
3110void DarwinClang::AddGnuCPlusPlusIncludePaths(
3111 const llvm::opt::ArgList &DriverArgs,
3112 llvm::opt::ArgStringList &CC1Args) const {
3113 llvm::SmallString<128> UsrIncludeCxx = GetEffectiveSysroot(DriverArgs);
3114 llvm::sys::path::append(path&: UsrIncludeCxx, a: "usr", b: "include", c: "c++");
3115
3116 llvm::Triple::ArchType arch = getTriple().getArch();
3117 bool IsBaseFound = true;
3118 switch (arch) {
3119 default:
3120 break;
3121
3122 case llvm::Triple::x86:
3123 case llvm::Triple::x86_64:
3124 IsBaseFound = AddGnuCPlusPlusIncludePaths(
3125 DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.2.1", ArchDir: "i686-apple-darwin10",
3126 BitDir: arch == llvm::Triple::x86_64 ? "x86_64" : "");
3127 IsBaseFound |= AddGnuCPlusPlusIncludePaths(
3128 DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.0.0", ArchDir: "i686-apple-darwin8", BitDir: "");
3129 break;
3130
3131 case llvm::Triple::arm:
3132 case llvm::Triple::thumb:
3133 IsBaseFound =
3134 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.2.1",
3135 ArchDir: "arm-apple-darwin10", BitDir: "v7");
3136 IsBaseFound |=
3137 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.2.1",
3138 ArchDir: "arm-apple-darwin10", BitDir: "v6");
3139 break;
3140
3141 case llvm::Triple::aarch64:
3142 IsBaseFound =
3143 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.2.1",
3144 ArchDir: "arm64-apple-darwin10", BitDir: "");
3145 break;
3146 }
3147
3148 if (!IsBaseFound) {
3149 getDriver().Diag(DiagID: diag::warn_drv_libstdcxx_not_found);
3150 }
3151}
3152
3153void AppleMachO::AddCXXStdlibLibArgs(const ArgList &Args,
3154 ArgStringList &CmdArgs) const {
3155 CXXStdlibType Type = GetCXXStdlibType(Args);
3156
3157 switch (Type) {
3158 case ToolChain::CST_Libcxx:
3159 CmdArgs.push_back(Elt: "-lc++");
3160 if (Args.hasArg(Ids: options::OPT_fexperimental_library))
3161 CmdArgs.push_back(Elt: "-lc++experimental");
3162 break;
3163
3164 case ToolChain::CST_Libstdcxx:
3165 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
3166 // it was previously found in the gcc lib dir. However, for all the Darwin
3167 // platforms we care about it was -lstdc++.6, so we search for that
3168 // explicitly if we can't see an obvious -lstdc++ candidate.
3169
3170 // Check in the sysroot first.
3171 if (const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot)) {
3172 SmallString<128> P(A->getValue());
3173 llvm::sys::path::append(path&: P, a: "usr", b: "lib", c: "libstdc++.dylib");
3174
3175 if (!getVFS().exists(Path: P)) {
3176 llvm::sys::path::remove_filename(path&: P);
3177 llvm::sys::path::append(path&: P, a: "libstdc++.6.dylib");
3178 if (getVFS().exists(Path: P)) {
3179 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
3180 return;
3181 }
3182 }
3183 }
3184
3185 // Otherwise, look in the root.
3186 // FIXME: This should be removed someday when we don't have to care about
3187 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
3188 if (!getVFS().exists(Path: "/usr/lib/libstdc++.dylib") &&
3189 getVFS().exists(Path: "/usr/lib/libstdc++.6.dylib")) {
3190 CmdArgs.push_back(Elt: "/usr/lib/libstdc++.6.dylib");
3191 return;
3192 }
3193
3194 // Otherwise, let the linker search.
3195 CmdArgs.push_back(Elt: "-lstdc++");
3196 break;
3197 }
3198}
3199
3200void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
3201 ArgStringList &CmdArgs) const {
3202 // For Darwin platforms, use the compiler-rt-based support library
3203 // instead of the gcc-provided one (which is also incidentally
3204 // only present in the gcc lib dir, which makes it hard to find).
3205
3206 SmallString<128> P(getDriver().ResourceDir);
3207 llvm::sys::path::append(path&: P, a: "lib", b: "darwin");
3208
3209 // Use the newer cc_kext for iOS ARM after 6.0.
3210 if (isTargetWatchOS()) {
3211 llvm::sys::path::append(path&: P, a: "libclang_rt.cc_kext_watchos.a");
3212 } else if (isTargetTvOS()) {
3213 llvm::sys::path::append(path&: P, a: "libclang_rt.cc_kext_tvos.a");
3214 } else if (isTargetIPhoneOS()) {
3215 llvm::sys::path::append(path&: P, a: "libclang_rt.cc_kext_ios.a");
3216 } else if (isTargetDriverKit()) {
3217 // DriverKit doesn't want extra runtime support.
3218 } else if (isTargetXROSDevice()) {
3219 llvm::sys::path::append(
3220 path&: P, a: llvm::Twine("libclang_rt.cc_kext_") +
3221 llvm::Triple::getOSTypeName(Kind: llvm::Triple::XROS) + ".a");
3222 } else {
3223 llvm::sys::path::append(path&: P, a: "libclang_rt.cc_kext.a");
3224 }
3225
3226 // For now, allow missing resource libraries to support developers who may
3227 // not have compiler-rt checked out or integrated into their build.
3228 if (getVFS().exists(Path: P))
3229 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
3230}
3231
3232DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args, BoundArch BA,
3233 Action::OffloadKind) const {
3234 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3235 const OptTable &Opts = getDriver().getOpts();
3236
3237 // FIXME: We really want to get out of the tool chain level argument
3238 // translation business, as it makes the driver functionality much
3239 // more opaque. For now, we follow gcc closely solely for the
3240 // purpose of easily achieving feature parity & testability. Once we
3241 // have something that works, we should reevaluate each translation
3242 // and try to push it down into tool specific logic.
3243
3244 for (Arg *A : Args) {
3245 // Sob. These is strictly gcc compatible for the time being. Apple
3246 // gcc translates options twice, which means that self-expanding
3247 // options add duplicates.
3248 switch ((options::ID)A->getOption().getID()) {
3249 default:
3250 DAL->append(A);
3251 break;
3252
3253 case options::OPT_mkernel:
3254 case options::OPT_fapple_kext:
3255 DAL->append(A);
3256 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_static));
3257 break;
3258
3259 case options::OPT_dependency_file:
3260 DAL->AddSeparateArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MF), Value: A->getValue());
3261 break;
3262
3263 case options::OPT_gfull:
3264 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_g_Flag));
3265 DAL->AddFlagArg(
3266 BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_fno_eliminate_unused_debug_symbols));
3267 break;
3268
3269 case options::OPT_gused:
3270 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_g_Flag));
3271 DAL->AddFlagArg(
3272 BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_feliminate_unused_debug_symbols));
3273 break;
3274
3275 case options::OPT_shared:
3276 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_dynamiclib));
3277 break;
3278
3279 case options::OPT_fconstant_cfstrings:
3280 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_mconstant_cfstrings));
3281 break;
3282
3283 case options::OPT_fno_constant_cfstrings:
3284 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_mno_constant_cfstrings));
3285 break;
3286
3287 case options::OPT_Wnonportable_cfstrings:
3288 DAL->AddFlagArg(BaseArg: A,
3289 Opt: Opts.getOption(Opt: options::OPT_mwarn_nonportable_cfstrings));
3290 break;
3291
3292 case options::OPT_Wno_nonportable_cfstrings:
3293 DAL->AddFlagArg(
3294 BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_mno_warn_nonportable_cfstrings));
3295 break;
3296 }
3297 }
3298
3299 // Add the arch options based on the particular spelling of -arch, to match
3300 // how the driver works.
3301 if (BA) {
3302 StringRef Name = BA.ArchName;
3303 const Option MCpu = Opts.getOption(Opt: options::OPT_mcpu_EQ);
3304 const Option MArch = Opts.getOption(Opt: options::OPT_march_EQ);
3305
3306 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
3307 // which defines the list of which architectures we accept.
3308 if (Name == "ppc")
3309 ;
3310 else if (Name == "ppc601")
3311 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "601");
3312 else if (Name == "ppc603")
3313 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "603");
3314 else if (Name == "ppc604")
3315 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "604");
3316 else if (Name == "ppc604e")
3317 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "604e");
3318 else if (Name == "ppc750")
3319 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "750");
3320 else if (Name == "ppc7400")
3321 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "7400");
3322 else if (Name == "ppc7450")
3323 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "7450");
3324 else if (Name == "ppc970")
3325 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "970");
3326
3327 else if (Name == "ppc64" || Name == "ppc64le")
3328 DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_m64));
3329
3330 else if (Name == "i386")
3331 ;
3332 else if (Name == "i486")
3333 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "i486");
3334 else if (Name == "i586")
3335 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "i586");
3336 else if (Name == "i686")
3337 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "i686");
3338 else if (Name == "pentium")
3339 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "pentium");
3340 else if (Name == "pentium2")
3341 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "pentium2");
3342 else if (Name == "pentpro")
3343 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "pentiumpro");
3344 else if (Name == "pentIIm3")
3345 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "pentium2");
3346
3347 else if (Name == "x86_64" || Name == "x86_64h")
3348 DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_m64));
3349
3350 else if (Name == "arm")
3351 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv4t");
3352 else if (Name == "armv4t")
3353 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv4t");
3354 else if (Name == "armv5")
3355 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv5tej");
3356 else if (Name == "xscale")
3357 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "xscale");
3358 else if (Name == "armv6")
3359 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv6k");
3360 else if (Name == "armv6m")
3361 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv6m");
3362 else if (Name == "armv7")
3363 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7a");
3364 else if (Name == "armv7em")
3365 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7em");
3366 else if (Name == "armv7k")
3367 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7k");
3368 else if (Name == "armv7m")
3369 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7m");
3370 else if (Name == "armv7s")
3371 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7s");
3372 else if (Name == "armv8-m.base" || Name == "armv8m.base")
3373 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv8m.base");
3374 else if (Name == "armv8-m.main" || Name == "armv8m.main")
3375 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv8m.main");
3376 else if (Name == "armv8.1-m.main" || Name == "armv8.1m.main")
3377 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv8.1m.main");
3378 }
3379
3380 return DAL;
3381}
3382
3383void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
3384 ArgStringList &CmdArgs,
3385 bool ForceLinkBuiltinRT) const {
3386 // Embedded targets are simple at the moment, not supporting sanitizers and
3387 // with different libraries for each member of the product { static, PIC } x
3388 // { hard-float, soft-float }
3389 llvm::SmallString<32> CompilerRT = StringRef("");
3390 CompilerRT +=
3391 (tools::arm::getARMFloatABI(TC: *this, Args) == tools::arm::FloatABI::Hard)
3392 ? "hard"
3393 : "soft";
3394 CompilerRT += Args.hasArg(Ids: options::OPT_fPIC) ? "_pic" : "_static";
3395
3396 AddLinkRuntimeLib(Args, CmdArgs, Component: CompilerRT, Opts: RLO_IsEmbedded);
3397}
3398
3399bool Darwin::isAlignedAllocationUnavailable() const {
3400 llvm::Triple::OSType OS;
3401
3402 if (isTargetMacCatalyst())
3403 return TargetVersion < alignedAllocMinVersion(OS: llvm::Triple::MacOSX);
3404 switch (TargetPlatform) {
3405 case MacOS: // Earlier than 10.13.
3406 OS = llvm::Triple::MacOSX;
3407 break;
3408 case IPhoneOS:
3409 OS = llvm::Triple::IOS;
3410 break;
3411 case TvOS: // Earlier than 11.0.
3412 OS = llvm::Triple::TvOS;
3413 break;
3414 case WatchOS: // Earlier than 4.0.
3415 OS = llvm::Triple::WatchOS;
3416 break;
3417 default: // Always available on newer platforms.
3418 return false;
3419 }
3420
3421 return TargetVersion < alignedAllocMinVersion(OS);
3422}
3423
3424static bool
3425sdkSupportsBuiltinModules(const std::optional<DarwinSDKInfo> &SDKInfo) {
3426 if (!SDKInfo)
3427 // If there is no SDK info, assume this is building against an SDK that
3428 // predates SDKSettings.json. None of those support builtin modules.
3429 return false;
3430
3431 switch (SDKInfo->getEnvironment()) {
3432 case llvm::Triple::UnknownEnvironment:
3433 case llvm::Triple::Simulator:
3434 case llvm::Triple::MacABI:
3435 // Standard xnu/Mach/Darwin based environments depend on the SDK version.
3436 break;
3437
3438 default:
3439 // All other environments support builtin modules from the start.
3440 return true;
3441 }
3442
3443 VersionTuple SDKVersion = SDKInfo->getVersion();
3444 switch (SDKInfo->getOS()) {
3445 // Existing SDKs added support for builtin modules in the fall
3446 // 2024 major releases.
3447 case llvm::Triple::MacOSX:
3448 return SDKVersion >= VersionTuple(15U);
3449 case llvm::Triple::IOS:
3450 return SDKVersion >= VersionTuple(18U);
3451 case llvm::Triple::TvOS:
3452 return SDKVersion >= VersionTuple(18U);
3453 case llvm::Triple::WatchOS:
3454 return SDKVersion >= VersionTuple(11U);
3455 case llvm::Triple::XROS:
3456 return SDKVersion >= VersionTuple(2U);
3457
3458 // New SDKs support builtin modules from the start.
3459 default:
3460 return true;
3461 }
3462}
3463
3464static inline llvm::VersionTuple
3465sizedDeallocMinVersion(llvm::Triple::OSType OS) {
3466 switch (OS) {
3467 default:
3468 break;
3469 case llvm::Triple::Darwin:
3470 case llvm::Triple::MacOSX: // Earliest supporting version is 10.12.
3471 return llvm::VersionTuple(10U, 12U);
3472 case llvm::Triple::IOS:
3473 case llvm::Triple::TvOS: // Earliest supporting version is 10.0.0.
3474 return llvm::VersionTuple(10U);
3475 case llvm::Triple::WatchOS: // Earliest supporting version is 3.0.0.
3476 return llvm::VersionTuple(3U);
3477 }
3478
3479 llvm_unreachable("Unexpected OS");
3480}
3481
3482bool Darwin::isSizedDeallocationUnavailable() const {
3483 llvm::Triple::OSType OS;
3484
3485 if (isTargetMacCatalyst())
3486 return TargetVersion < sizedDeallocMinVersion(OS: llvm::Triple::MacOSX);
3487 switch (TargetPlatform) {
3488 case MacOS: // Earlier than 10.12.
3489 OS = llvm::Triple::MacOSX;
3490 break;
3491 case IPhoneOS:
3492 OS = llvm::Triple::IOS;
3493 break;
3494 case TvOS: // Earlier than 10.0.
3495 OS = llvm::Triple::TvOS;
3496 break;
3497 case WatchOS: // Earlier than 3.0.
3498 OS = llvm::Triple::WatchOS;
3499 break;
3500 default:
3501 // Always available on newer platforms.
3502 return false;
3503 }
3504
3505 return TargetVersion < sizedDeallocMinVersion(OS);
3506}
3507
3508void MachO::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
3509 llvm::opt::ArgStringList &CC1Args,
3510 BoundArch BA,
3511 Action::OffloadKind DeviceOffloadKind) const {
3512
3513 ToolChain::addClangTargetOptions(DriverArgs, CC1Args, BA, DeviceOffloadKind);
3514
3515 // On arm64e, we enable all the features required for the Darwin userspace
3516 // ABI
3517 if (getTriple().isArm64e()) {
3518 // Core platform ABI
3519 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_calls,
3520 Ids: options::OPT_fno_ptrauth_calls))
3521 CC1Args.push_back(Elt: "-fptrauth-calls");
3522 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_returns,
3523 Ids: options::OPT_fno_ptrauth_returns))
3524 CC1Args.push_back(Elt: "-fptrauth-returns");
3525 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_intrinsics,
3526 Ids: options::OPT_fno_ptrauth_intrinsics))
3527 CC1Args.push_back(Elt: "-fptrauth-intrinsics");
3528 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_indirect_gotos,
3529 Ids: options::OPT_fno_ptrauth_indirect_gotos))
3530 CC1Args.push_back(Elt: "-fptrauth-indirect-gotos");
3531 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_auth_traps,
3532 Ids: options::OPT_fno_ptrauth_auth_traps))
3533 CC1Args.push_back(Elt: "-fptrauth-auth-traps");
3534
3535 // C++ v-table ABI
3536 if (!DriverArgs.hasArg(
3537 Ids: options::OPT_fptrauth_vtable_pointer_address_discrimination,
3538 Ids: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
3539 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-address-discrimination");
3540 if (!DriverArgs.hasArg(
3541 Ids: options::OPT_fptrauth_vtable_pointer_type_discrimination,
3542 Ids: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
3543 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-type-discrimination");
3544
3545 // Objective-C ABI
3546 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_objc_isa,
3547 Ids: options::OPT_fno_ptrauth_objc_isa))
3548 CC1Args.push_back(Elt: "-fptrauth-objc-isa");
3549 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_objc_class_ro,
3550 Ids: options::OPT_fno_ptrauth_objc_class_ro))
3551 CC1Args.push_back(Elt: "-fptrauth-objc-class-ro");
3552 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_objc_interface_sel,
3553 Ids: options::OPT_fno_ptrauth_objc_interface_sel))
3554 CC1Args.push_back(Elt: "-fptrauth-objc-interface-sel");
3555 }
3556}
3557
3558void Darwin::addClangTargetOptions(
3559 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3560 BoundArch BA, Action::OffloadKind DeviceOffloadKind) const {
3561
3562 MachO::addClangTargetOptions(DriverArgs, CC1Args, BA, DeviceOffloadKind);
3563
3564 // When compiling device code (e.g. SPIR-V for HIP), skip host-specific
3565 // flags like -faligned-alloc-unavailable and -fno-sized-deallocation
3566 // that depend on the host OS version and are irrelevant to device code.
3567 if (DeviceOffloadKind != Action::OFK_None)
3568 return;
3569
3570 // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
3571 // enabled or disabled aligned allocations.
3572 if (!DriverArgs.hasArgNoClaim(Ids: options::OPT_faligned_allocation,
3573 Ids: options::OPT_fno_aligned_allocation) &&
3574 isAlignedAllocationUnavailable())
3575 CC1Args.push_back(Elt: "-faligned-alloc-unavailable");
3576
3577 // Enable objc_msgSend selector stubs by default if the linker supports it.
3578 // ld64-811.2+ does, for arm64, arm64e, and arm64_32.
3579 if (!DriverArgs.hasArgNoClaim(Ids: options::OPT_fobjc_msgsend_selector_stubs,
3580 Ids: options::OPT_fno_objc_msgsend_selector_stubs) &&
3581 getTriple().isAArch64() &&
3582 (getLinkerVersion(Args: DriverArgs) >= VersionTuple(811, 2)))
3583 CC1Args.push_back(Elt: "-fobjc-msgsend-selector-stubs");
3584
3585 // Enable objc_msgSend class selector stubs by default if the linker supports
3586 // it. ld64-1250+ does, for arm64, arm64e, and arm64_32.
3587 if (!DriverArgs.hasArgNoClaim(
3588 Ids: options::OPT_fobjc_msgsend_class_selector_stubs,
3589 Ids: options::OPT_fno_objc_msgsend_class_selector_stubs) &&
3590 getTriple().isAArch64() &&
3591 (getLinkerVersion(Args: DriverArgs) >= VersionTuple(1250, 0)))
3592 CC1Args.push_back(Elt: "-fobjc-msgsend-class-selector-stubs");
3593
3594 // Pass "-fno-sized-deallocation" only when the user hasn't manually enabled
3595 // or disabled sized deallocations.
3596 if (!DriverArgs.hasArgNoClaim(Ids: options::OPT_fsized_deallocation,
3597 Ids: options::OPT_fno_sized_deallocation) &&
3598 isSizedDeallocationUnavailable())
3599 CC1Args.push_back(Elt: "-fno-sized-deallocation");
3600
3601 addClangCC1ASTargetOptions(Args: DriverArgs, CC1ASArgs&: CC1Args);
3602
3603 if (SDKInfo) {
3604 // Make the SDKSettings.json an explicit dependency for the compiler
3605 // invocation, in case the compiler needs to read it to remap versions.
3606 if (!SDKInfo->getFilePath().empty()) {
3607 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
3608 ExtraDepOpt += SDKInfo->getFilePath();
3609 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: ExtraDepOpt));
3610 }
3611 }
3612
3613 // Enable compatibility mode for NSItemProviderCompletionHandler in
3614 // Foundation/NSItemProvider.h.
3615 CC1Args.push_back(Elt: "-fcompatibility-qualified-id-block-type-checking");
3616
3617 // Give static local variables in inline functions hidden visibility when
3618 // -fvisibility-inlines-hidden is enabled.
3619 if (!DriverArgs.getLastArgNoClaim(
3620 Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
3621 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var))
3622 CC1Args.push_back(Elt: "-fvisibility-inlines-hidden-static-local-var");
3623
3624 // Earlier versions of the darwin SDK have the C standard library headers
3625 // all together in the Darwin module. That leads to module cycles with
3626 // the _Builtin_ modules. e.g. <inttypes.h> on darwin includes <stdint.h>.
3627 // The builtin <stdint.h> include-nexts <stdint.h>. When both of those
3628 // darwin headers are in the Darwin module, there's a module cycle Darwin ->
3629 // _Builtin_stdint -> Darwin (i.e. inttypes.h (darwin) -> stdint.h (builtin) ->
3630 // stdint.h (darwin)). This is fixed in later versions of the darwin SDK,
3631 // but until then, the builtin headers need to join the system modules.
3632 // i.e. when the builtin stdint.h is in the Darwin module too, the cycle
3633 // goes away. Note that -fbuiltin-headers-in-system-modules does nothing
3634 // to fix the same problem with C++ headers, and is generally fragile.
3635 if (!sdkSupportsBuiltinModules(SDKInfo))
3636 CC1Args.push_back(Elt: "-fbuiltin-headers-in-system-modules");
3637
3638 if (!DriverArgs.hasArgNoClaim(Ids: options::OPT_fdefine_target_os_macros,
3639 Ids: options::OPT_fno_define_target_os_macros))
3640 CC1Args.push_back(Elt: "-fdefine-target-os-macros");
3641
3642 // Disable subdirectory modulemap search on sufficiently recent SDKs.
3643 if (SDKInfo &&
3644 !DriverArgs.hasFlag(Pos: options::OPT_fmodulemap_allow_subdirectory_search,
3645 Neg: options::OPT_fno_modulemap_allow_subdirectory_search,
3646 Default: false)) {
3647 bool RequiresSubdirectorySearch;
3648 VersionTuple SDKVersion = SDKInfo->getVersion();
3649 switch (TargetPlatform) {
3650 default:
3651 RequiresSubdirectorySearch = true;
3652 break;
3653 case MacOS:
3654 RequiresSubdirectorySearch = SDKVersion < VersionTuple(15, 0);
3655 break;
3656 case IPhoneOS:
3657 case TvOS:
3658 RequiresSubdirectorySearch = SDKVersion < VersionTuple(18, 0);
3659 break;
3660 case WatchOS:
3661 RequiresSubdirectorySearch = SDKVersion < VersionTuple(11, 0);
3662 break;
3663 case XROS:
3664 RequiresSubdirectorySearch = SDKVersion < VersionTuple(2, 0);
3665 break;
3666 }
3667 if (!RequiresSubdirectorySearch)
3668 CC1Args.push_back(Elt: "-fno-modulemap-allow-subdirectory-search");
3669 }
3670}
3671
3672void Darwin::addClangCC1ASTargetOptions(
3673 const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const {
3674 if (TargetVariantTriple) {
3675 CC1ASArgs.push_back(Elt: "-darwin-target-variant-triple");
3676 CC1ASArgs.push_back(Elt: Args.MakeArgString(Str: TargetVariantTriple->getTriple()));
3677 }
3678
3679 if (SDKInfo) {
3680 /// Pass the SDK version to the compiler when the SDK information is
3681 /// available.
3682 auto EmitTargetSDKVersionArg = [&](const VersionTuple &V) {
3683 std::string Arg;
3684 llvm::raw_string_ostream OS(Arg);
3685 OS << "-target-sdk-version=" << V;
3686 CC1ASArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
3687 };
3688
3689 if (isTargetMacCatalyst()) {
3690 if (const auto *MacOStoMacCatalystMapping = SDKInfo->getVersionMapping(
3691 Kind: DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
3692 std::optional<VersionTuple> SDKVersion = MacOStoMacCatalystMapping->map(
3693 Key: SDKInfo->getVersion(), MinimumValue: minimumMacCatalystDeploymentTarget(),
3694 MaximumValue: std::nullopt);
3695 EmitTargetSDKVersionArg(
3696 SDKVersion ? *SDKVersion : minimumMacCatalystDeploymentTarget());
3697 }
3698 } else {
3699 EmitTargetSDKVersionArg(SDKInfo->getVersion());
3700 }
3701
3702 /// Pass the target variant SDK version to the compiler when the SDK
3703 /// information is available and is required for target variant.
3704 if (TargetVariantTriple) {
3705 if (isTargetMacCatalyst()) {
3706 std::string Arg;
3707 llvm::raw_string_ostream OS(Arg);
3708 OS << "-darwin-target-variant-sdk-version=" << SDKInfo->getVersion();
3709 CC1ASArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
3710 } else if (const auto *MacOStoMacCatalystMapping =
3711 SDKInfo->getVersionMapping(
3712 Kind: DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
3713 if (std::optional<VersionTuple> SDKVersion =
3714 MacOStoMacCatalystMapping->map(
3715 Key: SDKInfo->getVersion(), MinimumValue: minimumMacCatalystDeploymentTarget(),
3716 MaximumValue: std::nullopt)) {
3717 std::string Arg;
3718 llvm::raw_string_ostream OS(Arg);
3719 OS << "-darwin-target-variant-sdk-version=" << *SDKVersion;
3720 CC1ASArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
3721 }
3722 }
3723 }
3724 }
3725}
3726
3727DerivedArgList *
3728Darwin::TranslateArgs(const DerivedArgList &Args, BoundArch BA,
3729 Action::OffloadKind DeviceOffloadKind) const {
3730 // First get the generic Apple args, before moving onto Darwin-specific ones.
3731 DerivedArgList *DAL = MachO::TranslateArgs(Args, BA, DeviceOffloadKind);
3732
3733 // If no architecture is bound, none of the translations here are relevant.
3734 if (!BA)
3735 return DAL;
3736
3737 // Add an explicit version min argument for the deployment target. We do this
3738 // after argument translation because -Xarch_ arguments may add a version min
3739 // argument.
3740 AddDeploymentTarget(Args&: *DAL);
3741
3742 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
3743 // FIXME: It would be far better to avoid inserting those -static arguments,
3744 // but we can't check the deployment target in the translation code until
3745 // it is set here.
3746 if (isTargetWatchOSBased() || isTargetDriverKit() || isTargetXROS() ||
3747 (isTargetIOSBased() && !isIPhoneOSVersionLT(V0: 6, V1: 0))) {
3748 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
3749 Arg *A = *it;
3750 ++it;
3751 if (A->getOption().getID() != options::OPT_mkernel &&
3752 A->getOption().getID() != options::OPT_fapple_kext)
3753 continue;
3754 assert(it != ie && "unexpected argument translation");
3755 A = *it;
3756 assert(A->getOption().getID() == options::OPT_static &&
3757 "missing expected -static argument");
3758 *it = nullptr;
3759 ++it;
3760 }
3761 }
3762
3763 auto Arch = tools::darwin::getArchTypeForMachOArchName(Str: BA.ArchName);
3764 if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
3765 if (Args.hasFlag(Pos: options::OPT_fomit_frame_pointer,
3766 Neg: options::OPT_fno_omit_frame_pointer, Default: false))
3767 getDriver().Diag(DiagID: clang::diag::warn_drv_unsupported_opt_for_target)
3768 << "-fomit-frame-pointer" << BA.ArchName;
3769 }
3770
3771 return DAL;
3772}
3773
3774ToolChain::UnwindTableLevel MachO::getDefaultUnwindTableLevel(const ArgList &Args) const {
3775 // Unwind tables are not emitted if -fno-exceptions is supplied (except when
3776 // targeting x86_64).
3777 if (getArch() == llvm::Triple::x86_64 ||
3778 (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
3779 Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
3780 Default: true)))
3781 return (getArch() == llvm::Triple::aarch64 ||
3782 getArch() == llvm::Triple::aarch64_32)
3783 ? UnwindTableLevel::Synchronous
3784 : UnwindTableLevel::Asynchronous;
3785
3786 return UnwindTableLevel::None;
3787}
3788
3789bool MachO::UseDwarfDebugFlags() const {
3790 if (const char *S = ::getenv(name: "RC_DEBUG_OPTIONS"))
3791 return S[0] != '\0';
3792 return false;
3793}
3794
3795std::string MachO::GetGlobalDebugPathRemapping() const {
3796 if (const char *S = ::getenv(name: "RC_DEBUG_PREFIX_MAP"))
3797 return S;
3798 return {};
3799}
3800
3801llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
3802 // Darwin uses SjLj exceptions on ARM.
3803 if (getTriple().getArch() != llvm::Triple::arm &&
3804 getTriple().getArch() != llvm::Triple::thumb)
3805 return llvm::ExceptionHandling::Default;
3806
3807 // Only watchOS uses the new DWARF/Compact unwinding method.
3808 llvm::Triple Triple(ComputeLLVMTriple(Args));
3809 if (Triple.isWatchABI())
3810 return llvm::ExceptionHandling::DwarfCFI;
3811
3812 return llvm::ExceptionHandling::SjLj;
3813}
3814
3815bool Darwin::SupportsEmbeddedBitcode() const {
3816 assert(TargetInitialized && "Target not initialized!");
3817 if (isTargetIPhoneOS() && isIPhoneOSVersionLT(V0: 6, V1: 0))
3818 return false;
3819 return true;
3820}
3821
3822bool MachO::isPICDefault() const { return true; }
3823
3824bool MachO::isPIEDefault(const llvm::opt::ArgList &Args) const { return false; }
3825
3826bool MachO::isPICDefaultForced() const {
3827 return (getArch() == llvm::Triple::x86_64 ||
3828 getArch() == llvm::Triple::aarch64);
3829}
3830
3831bool MachO::SupportsProfiling() const {
3832 // Profiling instrumentation is only supported on x86.
3833 return getTriple().isX86();
3834}
3835
3836void Darwin::addMinVersionArgs(const ArgList &Args,
3837 ArgStringList &CmdArgs) const {
3838 VersionTuple TargetVersion = getTripleTargetVersion();
3839
3840 assert(!isTargetXROS() && "xrOS always uses -platform-version");
3841
3842 if (isTargetWatchOS())
3843 CmdArgs.push_back(Elt: "-watchos_version_min");
3844 else if (isTargetWatchOSSimulator())
3845 CmdArgs.push_back(Elt: "-watchos_simulator_version_min");
3846 else if (isTargetTvOS())
3847 CmdArgs.push_back(Elt: "-tvos_version_min");
3848 else if (isTargetTvOSSimulator())
3849 CmdArgs.push_back(Elt: "-tvos_simulator_version_min");
3850 else if (isTargetDriverKit())
3851 CmdArgs.push_back(Elt: "-driverkit_version_min");
3852 else if (isTargetIOSSimulator())
3853 CmdArgs.push_back(Elt: "-ios_simulator_version_min");
3854 else if (isTargetIOSBased())
3855 CmdArgs.push_back(Elt: "-iphoneos_version_min");
3856 else if (isTargetMacCatalyst())
3857 CmdArgs.push_back(Elt: "-maccatalyst_version_min");
3858 else {
3859 assert(isTargetMacOS() && "unexpected target");
3860 CmdArgs.push_back(Elt: "-macosx_version_min");
3861 }
3862
3863 VersionTuple MinTgtVers = getEffectiveTriple().getMinimumSupportedOSVersion();
3864 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3865 TargetVersion = MinTgtVers;
3866 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TargetVersion.getAsString()));
3867 if (TargetVariantTriple) {
3868 assert(isTargetMacOSBased() && "unexpected target");
3869 VersionTuple VariantTargetVersion;
3870 if (TargetVariantTriple->isMacOSX()) {
3871 CmdArgs.push_back(Elt: "-macosx_version_min");
3872 TargetVariantTriple->getMacOSXVersion(Version&: VariantTargetVersion);
3873 } else {
3874 assert(TargetVariantTriple->isiOS() &&
3875 TargetVariantTriple->isMacCatalystEnvironment() &&
3876 "unexpected target variant triple");
3877 CmdArgs.push_back(Elt: "-maccatalyst_version_min");
3878 VariantTargetVersion = TargetVariantTriple->getiOSVersion();
3879 }
3880 VersionTuple MinTgtVers =
3881 TargetVariantTriple->getMinimumSupportedOSVersion();
3882 if (MinTgtVers.getMajor() && MinTgtVers > VariantTargetVersion)
3883 VariantTargetVersion = MinTgtVers;
3884 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VariantTargetVersion.getAsString()));
3885 }
3886}
3887
3888static const char *getPlatformName(Darwin::DarwinPlatformKind Platform,
3889 Darwin::DarwinEnvironmentKind Environment) {
3890 switch (Platform) {
3891 case Darwin::MacOS:
3892 return "macos";
3893 case Darwin::IPhoneOS:
3894 if (Environment == Darwin::MacCatalyst)
3895 return "mac catalyst";
3896 return "ios";
3897 case Darwin::TvOS:
3898 return "tvos";
3899 case Darwin::WatchOS:
3900 return "watchos";
3901 case Darwin::XROS:
3902 return "xros";
3903 case Darwin::DriverKit:
3904 return "driverkit";
3905 default:
3906 break;
3907 }
3908 llvm_unreachable("invalid platform");
3909}
3910
3911void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
3912 llvm::opt::ArgStringList &CmdArgs) const {
3913 // Firmware doesn't use -platform_version.
3914 if (TargetPlatform == DarwinPlatformKind::Firmware)
3915 return MachO::addPlatformVersionArgs(Args, CmdArgs);
3916
3917 auto EmitPlatformVersionArg =
3918 [&](const VersionTuple &TV, Darwin::DarwinPlatformKind TargetPlatform,
3919 Darwin::DarwinEnvironmentKind TargetEnvironment,
3920 const llvm::Triple &TT) {
3921 // -platform_version <platform> <target_version> <sdk_version>
3922 // Both the target and SDK version support only up to 3 components.
3923 CmdArgs.push_back(Elt: "-platform_version");
3924 std::string PlatformName =
3925 getPlatformName(Platform: TargetPlatform, Environment: TargetEnvironment);
3926 if (TargetEnvironment == Darwin::Simulator)
3927 PlatformName += "-simulator";
3928 CmdArgs.push_back(Elt: Args.MakeArgString(Str: PlatformName));
3929 VersionTuple TargetVersion = TV.withoutBuild();
3930 if ((TargetPlatform == Darwin::IPhoneOS ||
3931 TargetPlatform == Darwin::TvOS) &&
3932 getTriple().getArchName() == "arm64e" &&
3933 TargetVersion.getMajor() < 14) {
3934 // arm64e slice is supported on iOS/tvOS 14+ only.
3935 TargetVersion = VersionTuple(14, 0);
3936 }
3937 VersionTuple MinTgtVers = TT.getMinimumSupportedOSVersion();
3938 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3939 TargetVersion = MinTgtVers;
3940 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TargetVersion.getAsString()));
3941
3942 if (TargetPlatform == IPhoneOS && TargetEnvironment == MacCatalyst) {
3943 // Mac Catalyst programs must use the appropriate iOS SDK version
3944 // that corresponds to the macOS SDK version used for the compilation.
3945 std::optional<VersionTuple> iOSSDKVersion;
3946 if (SDKInfo) {
3947 if (const auto *MacOStoMacCatalystMapping =
3948 SDKInfo->getVersionMapping(
3949 Kind: DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
3950 iOSSDKVersion = MacOStoMacCatalystMapping->map(
3951 Key: SDKInfo->getVersion().withoutBuild(),
3952 MinimumValue: minimumMacCatalystDeploymentTarget(), MaximumValue: std::nullopt);
3953 }
3954 }
3955 CmdArgs.push_back(Elt: Args.MakeArgString(
3956 Str: (iOSSDKVersion ? *iOSSDKVersion
3957 : minimumMacCatalystDeploymentTarget())
3958 .getAsString()));
3959 return;
3960 }
3961
3962 if (SDKInfo) {
3963 VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
3964 if (!SDKVersion.getMinor())
3965 SDKVersion = VersionTuple(SDKVersion.getMajor(), 0);
3966 CmdArgs.push_back(Elt: Args.MakeArgString(Str: SDKVersion.getAsString()));
3967 } else {
3968 // Use an SDK version that's matching the deployment target if the SDK
3969 // version is missing. This is preferred over an empty SDK version
3970 // (0.0.0) as the system's runtime might expect the linked binary to
3971 // contain a valid SDK version in order for the binary to work
3972 // correctly. It's reasonable to use the deployment target version as
3973 // a proxy for the SDK version because older SDKs don't guarantee
3974 // support for deployment targets newer than the SDK versions, so that
3975 // rules out using some predetermined older SDK version, which leaves
3976 // the deployment target version as the only reasonable choice.
3977 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TargetVersion.getAsString()));
3978 }
3979 };
3980 EmitPlatformVersionArg(getTripleTargetVersion(), TargetPlatform,
3981 TargetEnvironment, getEffectiveTriple());
3982 if (!TargetVariantTriple)
3983 return;
3984 Darwin::DarwinPlatformKind Platform;
3985 Darwin::DarwinEnvironmentKind Environment;
3986 VersionTuple TargetVariantVersion;
3987 if (TargetVariantTriple->isMacOSX()) {
3988 TargetVariantTriple->getMacOSXVersion(Version&: TargetVariantVersion);
3989 Platform = Darwin::MacOS;
3990 Environment = Darwin::NativeEnvironment;
3991 } else {
3992 assert(TargetVariantTriple->isiOS() &&
3993 TargetVariantTriple->isMacCatalystEnvironment() &&
3994 "unexpected target variant triple");
3995 TargetVariantVersion = TargetVariantTriple->getiOSVersion();
3996 Platform = Darwin::IPhoneOS;
3997 Environment = Darwin::MacCatalyst;
3998 }
3999 EmitPlatformVersionArg(TargetVariantVersion, Platform, Environment,
4000 *TargetVariantTriple);
4001}
4002
4003// Add additional link args for the -dynamiclib option.
4004static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args,
4005 ArgStringList &CmdArgs) {
4006 // Derived from darwin_dylib1 spec.
4007 if (D.isTargetIPhoneOS()) {
4008 if (D.isIPhoneOSVersionLT(V0: 3, V1: 1))
4009 CmdArgs.push_back(Elt: "-ldylib1.o");
4010 return;
4011 }
4012
4013 if (!D.isTargetMacOS())
4014 return;
4015 if (D.isMacosxVersionLT(V0: 10, V1: 5))
4016 CmdArgs.push_back(Elt: "-ldylib1.o");
4017 else if (D.isMacosxVersionLT(V0: 10, V1: 6))
4018 CmdArgs.push_back(Elt: "-ldylib1.10.5.o");
4019}
4020
4021// Add additional link args for the -bundle option.
4022static void addBundleLinkArgs(const Darwin &D, const ArgList &Args,
4023 ArgStringList &CmdArgs) {
4024 if (Args.hasArg(Ids: options::OPT_static))
4025 return;
4026 // Derived from darwin_bundle1 spec.
4027 if ((D.isTargetIPhoneOS() && D.isIPhoneOSVersionLT(V0: 3, V1: 1)) ||
4028 (D.isTargetMacOS() && D.isMacosxVersionLT(V0: 10, V1: 6)))
4029 CmdArgs.push_back(Elt: "-lbundle1.o");
4030}
4031
4032// Add additional link args for the -pg option.
4033static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args,
4034 ArgStringList &CmdArgs) {
4035 if (D.isTargetMacOS() && D.isMacosxVersionLT(V0: 10, V1: 9)) {
4036 if (Args.hasArg(Ids: options::OPT_static) || Args.hasArg(Ids: options::OPT_object) ||
4037 Args.hasArg(Ids: options::OPT_preload)) {
4038 CmdArgs.push_back(Elt: "-lgcrt0.o");
4039 } else {
4040 CmdArgs.push_back(Elt: "-lgcrt1.o");
4041
4042 // darwin_crt2 spec is empty.
4043 }
4044 // By default on OS X 10.8 and later, we don't link with a crt1.o
4045 // file and the linker knows to use _main as the entry point. But,
4046 // when compiling with -pg, we need to link with the gcrt1.o file,
4047 // so pass the -no_new_main option to tell the linker to use the
4048 // "start" symbol as the entry point.
4049 if (!D.isMacosxVersionLT(V0: 10, V1: 8))
4050 CmdArgs.push_back(Elt: "-no_new_main");
4051 } else {
4052 D.getDriver().Diag(DiagID: diag::err_drv_clang_unsupported_opt_pg_darwin)
4053 << D.isTargetMacOSBased();
4054 }
4055}
4056
4057static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args,
4058 ArgStringList &CmdArgs) {
4059 // Derived from darwin_crt1 spec.
4060 if (D.isTargetIPhoneOS()) {
4061 if (D.getArch() == llvm::Triple::aarch64)
4062 ; // iOS does not need any crt1 files for arm64
4063 else if (D.isIPhoneOSVersionLT(V0: 3, V1: 1))
4064 CmdArgs.push_back(Elt: "-lcrt1.o");
4065 else if (D.isIPhoneOSVersionLT(V0: 6, V1: 0))
4066 CmdArgs.push_back(Elt: "-lcrt1.3.1.o");
4067 return;
4068 }
4069
4070 if (!D.isTargetMacOS())
4071 return;
4072 if (D.isMacosxVersionLT(V0: 10, V1: 5))
4073 CmdArgs.push_back(Elt: "-lcrt1.o");
4074 else if (D.isMacosxVersionLT(V0: 10, V1: 6))
4075 CmdArgs.push_back(Elt: "-lcrt1.10.5.o");
4076 else if (D.isMacosxVersionLT(V0: 10, V1: 8))
4077 CmdArgs.push_back(Elt: "-lcrt1.10.6.o");
4078 // darwin_crt2 spec is empty.
4079}
4080
4081void Darwin::addStartObjectFileArgs(const ArgList &Args,
4082 ArgStringList &CmdArgs) const {
4083 // Firmware uses the "bare metal" start object file args.
4084 if (isTargetFirmware())
4085 return MachO::addStartObjectFileArgs(Args, CmdArgs);
4086
4087 // Derived from startfile spec.
4088 if (Args.hasArg(Ids: options::OPT_dynamiclib))
4089 addDynamicLibLinkArgs(D: *this, Args, CmdArgs);
4090 else if (Args.hasArg(Ids: options::OPT_bundle))
4091 addBundleLinkArgs(D: *this, Args, CmdArgs);
4092 else if (Args.hasArg(Ids: options::OPT_pg) && SupportsProfiling())
4093 addPgProfilingLinkArgs(D: *this, Args, CmdArgs);
4094 else if (Args.hasArg(Ids: options::OPT_static) ||
4095 Args.hasArg(Ids: options::OPT_object) ||
4096 Args.hasArg(Ids: options::OPT_preload))
4097 CmdArgs.push_back(Elt: "-lcrt0.o");
4098 else
4099 addDefaultCRTLinkArgs(D: *this, Args, CmdArgs);
4100
4101 if (isTargetMacOS() && Args.hasArg(Ids: options::OPT_shared_libgcc) &&
4102 isMacosxVersionLT(V0: 10, V1: 5)) {
4103 const char *Str = Args.MakeArgString(Str: GetFilePath(Name: "crt3.o"));
4104 CmdArgs.push_back(Elt: Str);
4105 }
4106}
4107
4108void Darwin::CheckObjCARC() const {
4109 ensureTargetInitialized();
4110 if (!isTargetInitialized())
4111 return;
4112 if (isTargetIOSBased() || isTargetWatchOSBased() || isTargetXROS() ||
4113 (isTargetMacOSBased() && !isMacosxVersionLT(V0: 10, V1: 6)))
4114 return;
4115 getDriver().Diag(DiagID: diag::err_arc_unsupported_on_toolchain);
4116}
4117
4118SanitizerMask
4119Darwin::getSupportedSanitizers(BoundArch BA,
4120 Action::OffloadKind DeviceOffloadKind) const {
4121 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
4122 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
4123 SanitizerMask Res = ToolChain::getSupportedSanitizers(BA, DeviceOffloadKind);
4124 Res |= SanitizerKind::Address;
4125 Res |= SanitizerKind::PointerCompare;
4126 Res |= SanitizerKind::PointerSubtract;
4127 Res |= SanitizerKind::Realtime;
4128 Res |= SanitizerKind::Leak;
4129 Res |= SanitizerKind::Fuzzer;
4130 Res |= SanitizerKind::FuzzerNoLink;
4131 Res |= SanitizerKind::ObjCCast;
4132
4133 ensureTargetInitialized();
4134 if (!isTargetInitialized())
4135 return Res;
4136 // Prior to 10.9, macOS shipped a version of the C++ standard library without
4137 // C++11 support. The same is true of iOS prior to version 5. These OS'es are
4138 // incompatible with -fsanitize=vptr.
4139 if (!(isTargetMacOSBased() && isMacosxVersionLT(V0: 10, V1: 9)) &&
4140 !(isTargetIPhoneOS() && isIPhoneOSVersionLT(V0: 5, V1: 0)))
4141 Res |= SanitizerKind::Vptr;
4142
4143 if ((IsX86_64 || IsAArch64) &&
4144 (isTargetMacOSBased() || isTargetIOSSimulator() ||
4145 isTargetTvOSSimulator() || isTargetWatchOSSimulator())) {
4146 Res |= SanitizerKind::Thread;
4147 }
4148
4149 if ((IsX86_64 || IsAArch64) && isTargetMacOSBased()) {
4150 Res |= SanitizerKind::Type;
4151 }
4152
4153 if (IsX86_64)
4154 Res |= SanitizerKind::NumericalStability;
4155
4156 return Res;
4157}
4158
4159void AppleMachO::printVerboseInfo(raw_ostream &OS) const {
4160 CudaInstallation->print(OS);
4161 RocmInstallation->print(OS);
4162}
4163