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