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

source code of clang/lib/Driver/ToolChains/Darwin.cpp