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
969AppleMachO::AppleMachO(const Driver &D, const llvm::Triple &Triple,
970 const ArgList &Args)
971 : MachO(D, Triple, Args), CudaInstallation(D, Triple, Args),
972 RocmInstallation(D, Triple, Args), SYCLInstallation(D, Triple, Args) {}
973
974/// Darwin - Darwin tool chain for i386 and x86_64.
975Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
976 : AppleMachO(D, Triple, Args), TargetInitialized(false) {}
977
980
981 // Darwin always preprocesses assembly files (unless -x is used explicitly).
982 if (Ty == types::TY_PP_Asm)
983 return types::TY_Asm;
984
985 return Ty;
986}
987
988bool MachO::HasNativeLLVMSupport() const { return true; }
989
991 // Always use libc++ by default
993}
994
995/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
999 if (isTargetIOSBased())
1001 if (isTargetXROS()) {
1002 // XROS uses the iOS runtime.
1003 auto T = llvm::Triple(Twine("arm64-apple-") +
1004 llvm::Triple::getOSTypeName(llvm::Triple::XROS) +
1005 TargetVersion.getAsString());
1006 return ObjCRuntime(ObjCRuntime::iOS, T.getiOSVersion());
1007 }
1008 if (isNonFragile)
1011}
1012
1013/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
1016 return true;
1017 else if (isTargetIOSBased())
1018 return !isIPhoneOSVersionLT(3, 2);
1019 else {
1020 assert(isTargetMacOSBased() && "unexpected darwin target");
1021 return !isMacosxVersionLT(10, 6);
1022 }
1023}
1024
1025void AppleMachO::AddCudaIncludeArgs(const ArgList &DriverArgs,
1026 ArgStringList &CC1Args) const {
1027 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
1028}
1029
1030void AppleMachO::AddHIPIncludeArgs(const ArgList &DriverArgs,
1031 ArgStringList &CC1Args) const {
1032 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
1033}
1034
1035void AppleMachO::addSYCLIncludeArgs(const ArgList &DriverArgs,
1036 ArgStringList &CC1Args) const {
1037 SYCLInstallation->addSYCLIncludeArgs(DriverArgs, CC1Args);
1038}
1039
1040// This is just a MachO name translation routine and there's no
1041// way to join this into ARMTargetParser without breaking all
1042// other assumptions. Maybe MachO should consider standardising
1043// their nomenclature.
1044static const char *ArmMachOArchName(StringRef Arch) {
1045 return llvm::StringSwitch<const char *>(Arch)
1046 .Case("armv6k", "armv6")
1047 .Case("armv6m", "armv6m")
1048 .Case("armv5tej", "armv5")
1049 .Case("xscale", "xscale")
1050 .Case("armv4t", "armv4t")
1051 .Case("armv7", "armv7")
1052 .Cases("armv7a", "armv7-a", "armv7")
1053 .Cases("armv7r", "armv7-r", "armv7")
1054 .Cases("armv7em", "armv7e-m", "armv7em")
1055 .Cases("armv7k", "armv7-k", "armv7k")
1056 .Cases("armv7m", "armv7-m", "armv7m")
1057 .Cases("armv7s", "armv7-s", "armv7s")
1058 .Default(nullptr);
1059}
1060
1061static const char *ArmMachOArchNameCPU(StringRef CPU) {
1062 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
1063 if (ArchKind == llvm::ARM::ArchKind::INVALID)
1064 return nullptr;
1065 StringRef Arch = llvm::ARM::getArchName(ArchKind);
1066
1067 // FIXME: Make sure this MachO triple mangling is really necessary.
1068 // ARMv5* normalises to ARMv5.
1069 if (Arch.starts_with("armv5"))
1070 Arch = Arch.substr(0, 5);
1071 // ARMv6*, except ARMv6M, normalises to ARMv6.
1072 else if (Arch.starts_with("armv6") && !Arch.ends_with("6m"))
1073 Arch = Arch.substr(0, 5);
1074 // ARMv7A normalises to ARMv7.
1075 else if (Arch.ends_with("v7a"))
1076 Arch = Arch.substr(0, 5);
1077 return Arch.data();
1078}
1079
1080StringRef MachO::getMachOArchName(const ArgList &Args) const {
1081 switch (getTriple().getArch()) {
1082 default:
1084
1085 case llvm::Triple::aarch64_32:
1086 return "arm64_32";
1087
1088 case llvm::Triple::aarch64: {
1089 if (getTriple().isArm64e())
1090 return "arm64e";
1091 return "arm64";
1092 }
1093
1094 case llvm::Triple::thumb:
1095 case llvm::Triple::arm:
1096 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ))
1097 if (const char *Arch = ArmMachOArchName(A->getValue()))
1098 return Arch;
1099
1100 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1101 if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
1102 return Arch;
1103
1104 return "arm";
1105 }
1106}
1107
1108VersionTuple MachO::getLinkerVersion(const llvm::opt::ArgList &Args) const {
1109 if (LinkerVersion) {
1110#ifndef NDEBUG
1111 VersionTuple NewLinkerVersion;
1112 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ))
1113 (void)NewLinkerVersion.tryParse(A->getValue());
1114 assert(NewLinkerVersion == LinkerVersion);
1115#endif
1116 return *LinkerVersion;
1117 }
1118
1119 VersionTuple NewLinkerVersion;
1120 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ))
1121 if (NewLinkerVersion.tryParse(A->getValue()))
1122 getDriver().Diag(diag::err_drv_invalid_version_number)
1123 << A->getAsString(Args);
1124
1125 LinkerVersion = NewLinkerVersion;
1126 return *LinkerVersion;
1127}
1128
1130
1132
1134
1135std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
1136 types::ID InputType) const {
1137 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
1138
1139 // If the target isn't initialized (e.g., an unknown Darwin platform, return
1140 // the default triple).
1141 if (!isTargetInitialized())
1142 return Triple.getTriple();
1143
1144 SmallString<16> Str;
1146 Str += "watchos";
1147 else if (isTargetTvOSBased())
1148 Str += "tvos";
1149 else if (isTargetDriverKit())
1150 Str += "driverkit";
1151 else if (isTargetIOSBased() || isTargetMacCatalyst())
1152 Str += "ios";
1153 else if (isTargetXROS())
1154 Str += llvm::Triple::getOSTypeName(llvm::Triple::XROS);
1155 else
1156 Str += "macosx";
1157 Str += getTripleTargetVersion().getAsString();
1158 Triple.setOSName(Str);
1159
1160 return Triple.getTriple();
1161}
1162
1164 switch (AC) {
1166 if (!Lipo)
1167 Lipo.reset(new tools::darwin::Lipo(*this));
1168 return Lipo.get();
1170 if (!Dsymutil)
1171 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
1172 return Dsymutil.get();
1174 if (!VerifyDebug)
1175 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
1176 return VerifyDebug.get();
1177 default:
1178 return ToolChain::getTool(AC);
1179 }
1180}
1181
1182Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
1183
1185 return new tools::darwin::StaticLibTool(*this);
1186}
1187
1189 return new tools::darwin::Assembler(*this);
1190}
1191
1192DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
1193 const ArgList &Args)
1194 : Darwin(D, Triple, Args) {}
1195
1196void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
1197 // Always error about undefined 'TARGET_OS_*' macros.
1198 CC1Args.push_back("-Wundef-prefix=TARGET_OS_");
1199 CC1Args.push_back("-Werror=undef-prefix");
1200
1201 // For modern targets, promote certain warnings to errors.
1202 if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
1203 // Always enable -Wdeprecated-objc-isa-usage and promote it
1204 // to an error.
1205 CC1Args.push_back("-Wdeprecated-objc-isa-usage");
1206 CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
1207
1208 // For iOS and watchOS, also error about implicit function declarations,
1209 // as that can impact calling conventions.
1210 if (!isTargetMacOS())
1211 CC1Args.push_back("-Werror=implicit-function-declaration");
1212 }
1213}
1214
1215/// Take a path that speculatively points into Xcode and return the
1216/// `XCODE/Contents/Developer` path if it is an Xcode path, or an empty path
1217/// otherwise.
1218static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode) {
1219 static constexpr llvm::StringLiteral XcodeAppSuffix(
1220 ".app/Contents/Developer");
1221 size_t Index = PathIntoXcode.find(XcodeAppSuffix);
1222 if (Index == StringRef::npos)
1223 return "";
1224 return PathIntoXcode.take_front(Index + XcodeAppSuffix.size());
1225}
1226
1227void DarwinClang::AddLinkARCArgs(const ArgList &Args,
1228 ArgStringList &CmdArgs) const {
1229 // Avoid linking compatibility stubs on i386 mac.
1230 if (isTargetMacOSBased() && getArch() == llvm::Triple::x86)
1231 return;
1233 return;
1234 // ARC runtime is supported everywhere on arm64e.
1235 if (getTriple().isArm64e())
1236 return;
1237 if (isTargetXROS())
1238 return;
1239
1240 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
1241
1242 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
1243 runtime.hasSubscripting())
1244 return;
1245
1246 SmallString<128> P(getDriver().ClangExecutable);
1247 llvm::sys::path::remove_filename(P); // 'clang'
1248 llvm::sys::path::remove_filename(P); // 'bin'
1249 llvm::sys::path::append(P, "lib", "arc");
1250
1251 // 'libarclite' usually lives in the same toolchain as 'clang'. However, the
1252 // Swift open source toolchains for macOS distribute Clang without libarclite.
1253 // In that case, to allow the linker to find 'libarclite', we point to the
1254 // 'libarclite' in the XcodeDefault toolchain instead.
1255 if (!getVFS().exists(P)) {
1256 auto updatePath = [&](const Arg *A) {
1257 // Try to infer the path to 'libarclite' in the toolchain from the
1258 // specified SDK path.
1259 StringRef XcodePathForSDK = getXcodeDeveloperPath(A->getValue());
1260 if (XcodePathForSDK.empty())
1261 return false;
1262
1263 P = XcodePathForSDK;
1264 llvm::sys::path::append(P, "Toolchains/XcodeDefault.xctoolchain/usr",
1265 "lib", "arc");
1266 return getVFS().exists(P);
1267 };
1268
1269 bool updated = false;
1270 if (const Arg *A = Args.getLastArg(options::OPT_isysroot))
1271 updated = updatePath(A);
1272
1273 if (!updated) {
1274 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1275 updatePath(A);
1276 }
1277 }
1278
1279 CmdArgs.push_back("-force_load");
1280 llvm::sys::path::append(P, "libarclite_");
1281 // Mash in the platform.
1283 P += "watchsimulator";
1284 else if (isTargetWatchOS())
1285 P += "watchos";
1286 else if (isTargetTvOSSimulator())
1287 P += "appletvsimulator";
1288 else if (isTargetTvOS())
1289 P += "appletvos";
1290 else if (isTargetIOSSimulator())
1291 P += "iphonesimulator";
1292 else if (isTargetIPhoneOS())
1293 P += "iphoneos";
1294 else
1295 P += "macosx";
1296 P += ".a";
1297
1298 if (!getVFS().exists(P))
1299 getDriver().Diag(clang::diag::err_drv_darwin_sdk_missing_arclite) << P;
1300
1301 CmdArgs.push_back(Args.MakeArgString(P));
1302}
1303
1305 // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
1306 if ((isTargetMacOSBased() && isMacosxVersionLT(10, 11)) ||
1308 return 2;
1309 // Default to use DWARF 4 on OS X 10.11 - macOS 14 / iOS 9 - iOS 17.
1310 if ((isTargetMacOSBased() && isMacosxVersionLT(15)) ||
1312 (isTargetWatchOSBased() && TargetVersion < llvm::VersionTuple(11)) ||
1313 (isTargetXROS() && TargetVersion < llvm::VersionTuple(2)) ||
1314 (isTargetDriverKit() && TargetVersion < llvm::VersionTuple(24)) ||
1315 (isTargetMacOSBased() &&
1316 TargetVersion.empty())) // apple-darwin, no version.
1317 return 4;
1318 return 5;
1319}
1320
1321void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
1322 StringRef Component, RuntimeLinkOptions Opts,
1323 bool IsShared) const {
1324 std::string P = getCompilerRT(
1325 Args, Component, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static);
1326
1327 // For now, allow missing resource libraries to support developers who may
1328 // not have compiler-rt checked out or integrated into their build (unless
1329 // we explicitly force linking with this library).
1330 if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) {
1331 const char *LibArg = Args.MakeArgString(P);
1332 CmdArgs.push_back(LibArg);
1333 }
1334
1335 // Adding the rpaths might negatively interact when other rpaths are involved,
1336 // so we should make sure we add the rpaths last, after all user-specified
1337 // rpaths. This is currently true from this place, but we need to be
1338 // careful if this function is ever called before user's rpaths are emitted.
1339 if (Opts & RLO_AddRPath) {
1340 assert(StringRef(P).ends_with(".dylib") && "must be a dynamic library");
1341
1342 // Add @executable_path to rpath to support having the dylib copied with
1343 // the executable.
1344 CmdArgs.push_back("-rpath");
1345 CmdArgs.push_back("@executable_path");
1346
1347 // Add the compiler-rt library's directory to rpath to support using the
1348 // dylib from the default location without copying.
1349 CmdArgs.push_back("-rpath");
1350 CmdArgs.push_back(Args.MakeArgString(llvm::sys::path::parent_path(P)));
1351 }
1352}
1353
1354std::string MachO::getCompilerRT(const ArgList &, StringRef Component,
1355 FileType Type) const {
1356 assert(Type != ToolChain::FT_Object &&
1357 "it doesn't make sense to ask for the compiler-rt library name as an "
1358 "object file");
1359 SmallString<64> MachOLibName = StringRef("libclang_rt");
1360 // On MachO, the builtins component is not in the library name
1361 if (Component != "builtins") {
1362 MachOLibName += '.';
1363 MachOLibName += Component;
1364 }
1365 MachOLibName += Type == ToolChain::FT_Shared ? "_dynamic.dylib" : ".a";
1366
1367 SmallString<128> FullPath(getDriver().ResourceDir);
1368 llvm::sys::path::append(FullPath, "lib", "darwin", "macho_embedded",
1369 MachOLibName);
1370 return std::string(FullPath);
1371}
1372
1373std::string Darwin::getCompilerRT(const ArgList &, StringRef Component,
1374 FileType Type) const {
1375 assert(Type != ToolChain::FT_Object &&
1376 "it doesn't make sense to ask for the compiler-rt library name as an "
1377 "object file");
1378 SmallString<64> DarwinLibName = StringRef("libclang_rt.");
1379 // On Darwin, the builtins component is not in the library name
1380 if (Component != "builtins") {
1381 DarwinLibName += Component;
1382 DarwinLibName += '_';
1383 }
1384 DarwinLibName += getOSLibraryNameSuffix();
1385 DarwinLibName += Type == ToolChain::FT_Shared ? "_dynamic.dylib" : ".a";
1386
1387 SmallString<128> FullPath(getDriver().ResourceDir);
1388 llvm::sys::path::append(FullPath, "lib", "darwin", DarwinLibName);
1389 return std::string(FullPath);
1390}
1391
1392StringRef Darwin::getPlatformFamily() const {
1393 switch (TargetPlatform) {
1395 return "MacOSX";
1398 return "MacOSX";
1399 return "iPhone";
1401 return "AppleTV";
1403 return "Watch";
1405 return "DriverKit";
1407 return "XR";
1408 }
1409 llvm_unreachable("Unsupported platform");
1410}
1411
1412StringRef Darwin::getSDKName(StringRef isysroot) {
1413 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
1414 auto BeginSDK = llvm::sys::path::rbegin(isysroot);
1415 auto EndSDK = llvm::sys::path::rend(isysroot);
1416 for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
1417 StringRef SDK = *IT;
1418 if (SDK.ends_with(".sdk"))
1419 return SDK.slice(0, SDK.size() - 4);
1420 }
1421 return "";
1422}
1423
1424StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
1425 switch (TargetPlatform) {
1427 return "osx";
1430 return "osx";
1431 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
1432 : "iossim";
1434 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
1435 : "tvossim";
1437 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
1438 : "watchossim";
1440 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "xros"
1441 : "xrossim";
1443 return "driverkit";
1444 }
1445 llvm_unreachable("Unsupported platform");
1446}
1447
1448/// Check if the link command contains a symbol export directive.
1449static bool hasExportSymbolDirective(const ArgList &Args) {
1450 for (Arg *A : Args) {
1451 if (A->getOption().matches(options::OPT_exported__symbols__list))
1452 return true;
1453 if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
1454 !A->getOption().matches(options::OPT_Xlinker))
1455 continue;
1456 if (A->containsValue("-exported_symbols_list") ||
1457 A->containsValue("-exported_symbol"))
1458 return true;
1459 }
1460 return false;
1461}
1462
1463/// Add an export directive for \p Symbol to the link command.
1464static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
1465 CmdArgs.push_back("-exported_symbol");
1466 CmdArgs.push_back(Symbol);
1467}
1468
1469/// Add a sectalign directive for \p Segment and \p Section to the maximum
1470/// expected page size for Darwin.
1471///
1472/// On iPhone 6+ the max supported page size is 16K. On macOS, the max is 4K.
1473/// Use a common alignment constant (16K) for now, and reduce the alignment on
1474/// macOS if it proves important.
1475static void addSectalignToPage(const ArgList &Args, ArgStringList &CmdArgs,
1476 StringRef Segment, StringRef Section) {
1477 for (const char *A : {"-sectalign", Args.MakeArgString(Segment),
1478 Args.MakeArgString(Section), "0x4000"})
1479 CmdArgs.push_back(A);
1480}
1481
1482void Darwin::addProfileRTLibs(const ArgList &Args,
1483 ArgStringList &CmdArgs) const {
1484 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1485 return;
1486
1487 AddLinkRuntimeLib(Args, CmdArgs, "profile",
1489
1490 bool ForGCOV = needsGCovInstrumentation(Args);
1491
1492 // If we have a symbol export directive and we're linking in the profile
1493 // runtime, automatically export symbols necessary to implement some of the
1494 // runtime's functionality.
1495 if (hasExportSymbolDirective(Args) && ForGCOV) {
1496 addExportedSymbol(CmdArgs, "___gcov_dump");
1497 addExportedSymbol(CmdArgs, "___gcov_reset");
1498 addExportedSymbol(CmdArgs, "_writeout_fn_list");
1499 addExportedSymbol(CmdArgs, "_reset_fn_list");
1500 }
1501
1502 // Align __llvm_prf_{cnts,bits,data} sections to the maximum expected page
1503 // alignment. This allows profile counters to be mmap()'d to disk. Note that
1504 // it's not enough to just page-align __llvm_prf_cnts: the following section
1505 // must also be page-aligned so that its data is not clobbered by mmap().
1506 //
1507 // The section alignment is only needed when continuous profile sync is
1508 // enabled, but this is expected to be the default in Xcode. Specifying the
1509 // extra alignment also allows the same binary to be used with/without sync
1510 // enabled.
1511 if (!ForGCOV) {
1512 for (auto IPSK : {llvm::IPSK_cnts, llvm::IPSK_bitmap, llvm::IPSK_data}) {
1514 Args, CmdArgs, "__DATA",
1515 llvm::getInstrProfSectionName(IPSK, llvm::Triple::MachO,
1516 /*AddSegmentInfo=*/false));
1517 }
1518 }
1519}
1520
1521void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1522 ArgStringList &CmdArgs,
1523 StringRef Sanitizer,
1524 bool Shared) const {
1525 auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1526 AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
1527}
1528
1530 const ArgList &Args) const {
1531 if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1532 StringRef Value = A->getValue();
1533 if (Value != "compiler-rt" && Value != "platform")
1534 getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1535 << Value << "darwin";
1536 }
1537
1539}
1540
1541void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1542 ArgStringList &CmdArgs,
1543 bool ForceLinkBuiltinRT) const {
1544 // Call once to ensure diagnostic is printed if wrong value was specified
1545 GetRuntimeLibType(Args);
1546
1547 // Darwin doesn't support real static executables, don't link any runtime
1548 // libraries with -static.
1549 if (Args.hasArg(options::OPT_static) ||
1550 Args.hasArg(options::OPT_fapple_kext) ||
1551 Args.hasArg(options::OPT_mkernel)) {
1552 if (ForceLinkBuiltinRT)
1553 AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1554 return;
1555 }
1556
1557 // Reject -static-libgcc for now, we can deal with this when and if someone
1558 // cares. This is useful in situations where someone wants to statically link
1559 // something like libstdc++, and needs its runtime support routines.
1560 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1561 getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1562 return;
1563 }
1564
1565 const SanitizerArgs &Sanitize = getSanitizerArgs(Args);
1566
1567 if (!Sanitize.needsSharedRt()) {
1568 const char *sanitizer = nullptr;
1569 if (Sanitize.needsUbsanRt()) {
1570 sanitizer = "UndefinedBehaviorSanitizer";
1571 } else if (Sanitize.needsRtsanRt()) {
1572 sanitizer = "RealtimeSanitizer";
1573 } else if (Sanitize.needsAsanRt()) {
1574 sanitizer = "AddressSanitizer";
1575 } else if (Sanitize.needsTsanRt()) {
1576 sanitizer = "ThreadSanitizer";
1577 }
1578 if (sanitizer) {
1579 getDriver().Diag(diag::err_drv_unsupported_static_sanitizer_darwin)
1580 << sanitizer;
1581 return;
1582 }
1583 }
1584
1585 if (Sanitize.linkRuntimes()) {
1586 if (Sanitize.needsAsanRt()) {
1587 if (Sanitize.needsStableAbi()) {
1588 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan_abi", /*shared=*/false);
1589 } else {
1590 assert(Sanitize.needsSharedRt() &&
1591 "Static sanitizer runtimes not supported");
1592 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1593 }
1594 }
1595 if (Sanitize.needsRtsanRt()) {
1596 assert(Sanitize.needsSharedRt() &&
1597 "Static sanitizer runtimes not supported");
1598 AddLinkSanitizerLibArgs(Args, CmdArgs, "rtsan");
1599 }
1600 if (Sanitize.needsLsanRt())
1601 AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
1602 if (Sanitize.needsUbsanRt()) {
1603 assert(Sanitize.needsSharedRt() &&
1604 "Static sanitizer runtimes not supported");
1605 AddLinkSanitizerLibArgs(
1606 Args, CmdArgs,
1607 Sanitize.requiresMinimalRuntime() ? "ubsan_minimal" : "ubsan");
1608 }
1609 if (Sanitize.needsTsanRt()) {
1610 assert(Sanitize.needsSharedRt() &&
1611 "Static sanitizer runtimes not supported");
1612 AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1613 }
1614 if (Sanitize.needsTysanRt())
1615 AddLinkSanitizerLibArgs(Args, CmdArgs, "tysan");
1616 if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
1617 AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
1618
1619 // Libfuzzer is written in C++ and requires libcxx.
1620 AddCXXStdlibLibArgs(Args, CmdArgs);
1621 }
1622 if (Sanitize.needsStatsRt()) {
1623 AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
1624 AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1625 }
1626 }
1627
1628 const XRayArgs &XRay = getXRayArgs();
1629 if (XRay.needsXRayRt()) {
1630 AddLinkRuntimeLib(Args, CmdArgs, "xray");
1631 AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
1632 AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
1633 }
1634
1635 if (isTargetDriverKit() && !Args.hasArg(options::OPT_nodriverkitlib)) {
1636 CmdArgs.push_back("-framework");
1637 CmdArgs.push_back("DriverKit");
1638 }
1639
1640 // Otherwise link libSystem, then the dynamic runtime library, and finally any
1641 // target specific static runtime library.
1642 if (!isTargetDriverKit())
1643 CmdArgs.push_back("-lSystem");
1644
1645 // Select the dynamic runtime library and the target specific static library.
1646 if (isTargetIOSBased()) {
1647 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
1648 // it never went into the SDK.
1649 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
1650 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
1651 getTriple().getArch() != llvm::Triple::aarch64)
1652 CmdArgs.push_back("-lgcc_s.1");
1653 }
1654 AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1655}
1656
1657/// Returns the most appropriate macOS target version for the current process.
1658///
1659/// If the macOS SDK version is the same or earlier than the system version,
1660/// then the SDK version is returned. Otherwise the system version is returned.
1661static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1662 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1663 if (!SystemTriple.isMacOSX())
1664 return std::string(MacOSSDKVersion);
1665 VersionTuple SystemVersion;
1666 SystemTriple.getMacOSXVersion(SystemVersion);
1667
1668 unsigned Major, Minor, Micro;
1669 bool HadExtra;
1670 if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
1671 HadExtra))
1672 return std::string(MacOSSDKVersion);
1673 VersionTuple SDKVersion(Major, Minor, Micro);
1674
1675 if (SDKVersion > SystemVersion)
1676 return SystemVersion.getAsString();
1677 return std::string(MacOSSDKVersion);
1678}
1679
1680namespace {
1681
1682/// The Darwin OS that was selected or inferred from arguments / environment.
1683struct DarwinPlatform {
1684 enum SourceKind {
1685 /// The OS was specified using the -target argument.
1686 TargetArg,
1687 /// The OS was specified using the -mtargetos= argument.
1688 MTargetOSArg,
1689 /// The OS was specified using the -m<os>-version-min argument.
1690 OSVersionArg,
1691 /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1692 DeploymentTargetEnv,
1693 /// The OS was inferred from the SDK.
1694 InferredFromSDK,
1695 /// The OS was inferred from the -arch.
1696 InferredFromArch
1697 };
1698
1699 using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1700 using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1701
1702 DarwinPlatformKind getPlatform() const { return Platform; }
1703
1704 DarwinEnvironmentKind getEnvironment() const { return Environment; }
1705
1706 void setEnvironment(DarwinEnvironmentKind Kind) {
1707 Environment = Kind;
1708 InferSimulatorFromArch = false;
1709 }
1710
1711 StringRef getOSVersion() const {
1712 if (Kind == OSVersionArg)
1713 return Argument->getValue();
1714 return OSVersion;
1715 }
1716
1717 void setOSVersion(StringRef S) {
1718 assert(Kind == TargetArg && "Unexpected kind!");
1719 OSVersion = std::string(S);
1720 }
1721
1722 bool hasOSVersion() const { return HasOSVersion; }
1723
1724 VersionTuple getNativeTargetVersion() const {
1725 assert(Environment == DarwinEnvironmentKind::MacCatalyst &&
1726 "native target version is specified only for Mac Catalyst");
1727 return NativeTargetVersion;
1728 }
1729
1730 /// Returns true if the target OS was explicitly specified.
1731 bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1732
1733 /// Returns true if the simulator environment can be inferred from the arch.
1734 bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1735
1736 const std::optional<llvm::Triple> &getTargetVariantTriple() const {
1737 return TargetVariantTriple;
1738 }
1739
1740 /// Adds the -m<os>-version-min argument to the compiler invocation.
1741 void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1742 if (Argument)
1743 return;
1744 assert(Kind != TargetArg && Kind != MTargetOSArg && Kind != OSVersionArg &&
1745 "Invalid kind");
1746 options::ID Opt;
1747 switch (Platform) {
1748 case DarwinPlatformKind::MacOS:
1749 Opt = options::OPT_mmacos_version_min_EQ;
1750 break;
1751 case DarwinPlatformKind::IPhoneOS:
1752 Opt = options::OPT_mios_version_min_EQ;
1753 break;
1754 case DarwinPlatformKind::TvOS:
1755 Opt = options::OPT_mtvos_version_min_EQ;
1756 break;
1757 case DarwinPlatformKind::WatchOS:
1758 Opt = options::OPT_mwatchos_version_min_EQ;
1759 break;
1760 case DarwinPlatformKind::XROS:
1761 // xrOS always explicitly provides a version in the triple.
1762 return;
1763 case DarwinPlatformKind::DriverKit:
1764 // DriverKit always explicitly provides a version in the triple.
1765 return;
1766 }
1767 Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
1768 Args.append(Argument);
1769 }
1770
1771 /// Returns the OS version with the argument / environment variable that
1772 /// specified it.
1773 std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1774 switch (Kind) {
1775 case TargetArg:
1776 case MTargetOSArg:
1777 case OSVersionArg:
1778 case InferredFromSDK:
1779 case InferredFromArch:
1780 assert(Argument && "OS version argument not yet inferred");
1781 return Argument->getAsString(Args);
1782 case DeploymentTargetEnv:
1783 return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
1784 }
1785 llvm_unreachable("Unsupported Darwin Source Kind");
1786 }
1787
1788 void setEnvironment(llvm::Triple::EnvironmentType EnvType,
1789 const VersionTuple &OSVersion,
1790 const std::optional<DarwinSDKInfo> &SDKInfo) {
1791 switch (EnvType) {
1792 case llvm::Triple::Simulator:
1793 Environment = DarwinEnvironmentKind::Simulator;
1794 break;
1795 case llvm::Triple::MacABI: {
1796 Environment = DarwinEnvironmentKind::MacCatalyst;
1797 // The minimum native macOS target for MacCatalyst is macOS 10.15.
1798 NativeTargetVersion = VersionTuple(10, 15);
1799 if (HasOSVersion && SDKInfo) {
1800 if (const auto *MacCatalystToMacOSMapping = SDKInfo->getVersionMapping(
1802 if (auto MacOSVersion = MacCatalystToMacOSMapping->map(
1803 OSVersion, NativeTargetVersion, std::nullopt)) {
1804 NativeTargetVersion = *MacOSVersion;
1805 }
1806 }
1807 }
1808 // In a zippered build, we could be building for a macOS target that's
1809 // lower than the version that's implied by the OS version. In that case
1810 // we need to use the minimum version as the native target version.
1811 if (TargetVariantTriple) {
1812 auto TargetVariantVersion = TargetVariantTriple->getOSVersion();
1813 if (TargetVariantVersion.getMajor()) {
1814 if (TargetVariantVersion < NativeTargetVersion)
1815 NativeTargetVersion = TargetVariantVersion;
1816 }
1817 }
1818 break;
1819 }
1820 default:
1821 break;
1822 }
1823 }
1824
1825 static DarwinPlatform
1826 createFromTarget(const llvm::Triple &TT, StringRef OSVersion, Arg *A,
1827 std::optional<llvm::Triple> TargetVariantTriple,
1828 const std::optional<DarwinSDKInfo> &SDKInfo) {
1829 DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
1830 A);
1831 VersionTuple OsVersion = TT.getOSVersion();
1832 if (OsVersion.getMajor() == 0)
1833 Result.HasOSVersion = false;
1834 Result.TargetVariantTriple = TargetVariantTriple;
1835 Result.setEnvironment(TT.getEnvironment(), OsVersion, SDKInfo);
1836 return Result;
1837 }
1838 static DarwinPlatform
1839 createFromMTargetOS(llvm::Triple::OSType OS, VersionTuple OSVersion,
1840 llvm::Triple::EnvironmentType Environment, Arg *A,
1841 const std::optional<DarwinSDKInfo> &SDKInfo) {
1842 DarwinPlatform Result(MTargetOSArg, getPlatformFromOS(OS),
1843 OSVersion.getAsString(), A);
1844 Result.InferSimulatorFromArch = false;
1845 Result.setEnvironment(Environment, OSVersion, SDKInfo);
1846 return Result;
1847 }
1848 static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform, Arg *A,
1849 bool IsSimulator) {
1850 DarwinPlatform Result{OSVersionArg, Platform, A};
1851 if (IsSimulator)
1852 Result.Environment = DarwinEnvironmentKind::Simulator;
1853 return Result;
1854 }
1855 static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
1856 StringRef EnvVarName,
1857 StringRef Value) {
1858 DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
1859 Result.EnvVarName = EnvVarName;
1860 return Result;
1861 }
1862 static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
1863 StringRef Value,
1864 bool IsSimulator = false) {
1865 DarwinPlatform Result(InferredFromSDK, Platform, Value);
1866 if (IsSimulator)
1867 Result.Environment = DarwinEnvironmentKind::Simulator;
1868 Result.InferSimulatorFromArch = false;
1869 return Result;
1870 }
1871 static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
1872 StringRef Value) {
1873 return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
1874 }
1875
1876 /// Constructs an inferred SDKInfo value based on the version inferred from
1877 /// the SDK path itself. Only works for values that were created by inferring
1878 /// the platform from the SDKPath.
1879 DarwinSDKInfo inferSDKInfo() {
1880 assert(Kind == InferredFromSDK && "can infer SDK info only");
1881 llvm::VersionTuple Version;
1882 bool IsValid = !Version.tryParse(OSVersion);
1883 (void)IsValid;
1884 assert(IsValid && "invalid SDK version");
1885 return DarwinSDKInfo(
1886 Version,
1887 /*MaximumDeploymentTarget=*/VersionTuple(Version.getMajor(), 0, 99));
1888 }
1889
1890private:
1891 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
1892 : Kind(Kind), Platform(Platform), Argument(Argument) {}
1893 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
1894 Arg *Argument = nullptr)
1895 : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
1896
1897 static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
1898 switch (OS) {
1899 case llvm::Triple::Darwin:
1900 case llvm::Triple::MacOSX:
1901 return DarwinPlatformKind::MacOS;
1902 case llvm::Triple::IOS:
1903 return DarwinPlatformKind::IPhoneOS;
1904 case llvm::Triple::TvOS:
1905 return DarwinPlatformKind::TvOS;
1906 case llvm::Triple::WatchOS:
1907 return DarwinPlatformKind::WatchOS;
1908 case llvm::Triple::XROS:
1909 return DarwinPlatformKind::XROS;
1910 case llvm::Triple::DriverKit:
1911 return DarwinPlatformKind::DriverKit;
1912 default:
1913 llvm_unreachable("Unable to infer Darwin variant");
1914 }
1915 }
1916
1917 SourceKind Kind;
1918 DarwinPlatformKind Platform;
1919 DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
1920 VersionTuple NativeTargetVersion;
1921 std::string OSVersion;
1922 bool HasOSVersion = true, InferSimulatorFromArch = true;
1923 Arg *Argument;
1924 StringRef EnvVarName;
1925 std::optional<llvm::Triple> TargetVariantTriple;
1926};
1927
1928/// Returns the deployment target that's specified using the -m<os>-version-min
1929/// argument.
1930std::optional<DarwinPlatform>
1931getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
1932 const Driver &TheDriver) {
1933 Arg *macOSVersion = Args.getLastArg(options::OPT_mmacos_version_min_EQ);
1934 Arg *iOSVersion = Args.getLastArg(options::OPT_mios_version_min_EQ,
1935 options::OPT_mios_simulator_version_min_EQ);
1936 Arg *TvOSVersion =
1937 Args.getLastArg(options::OPT_mtvos_version_min_EQ,
1938 options::OPT_mtvos_simulator_version_min_EQ);
1939 Arg *WatchOSVersion =
1940 Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
1941 options::OPT_mwatchos_simulator_version_min_EQ);
1942 if (macOSVersion) {
1943 if (iOSVersion || TvOSVersion || WatchOSVersion) {
1944 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1945 << macOSVersion->getAsString(Args)
1946 << (iOSVersion ? iOSVersion
1947 : TvOSVersion ? TvOSVersion : WatchOSVersion)
1948 ->getAsString(Args);
1949 }
1950 return DarwinPlatform::createOSVersionArg(Darwin::MacOS, macOSVersion,
1951 /*IsSimulator=*/false);
1952 } else if (iOSVersion) {
1953 if (TvOSVersion || WatchOSVersion) {
1954 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1955 << iOSVersion->getAsString(Args)
1956 << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1957 }
1958 return DarwinPlatform::createOSVersionArg(
1959 Darwin::IPhoneOS, iOSVersion,
1960 iOSVersion->getOption().getID() ==
1961 options::OPT_mios_simulator_version_min_EQ);
1962 } else if (TvOSVersion) {
1963 if (WatchOSVersion) {
1964 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1965 << TvOSVersion->getAsString(Args)
1966 << WatchOSVersion->getAsString(Args);
1967 }
1968 return DarwinPlatform::createOSVersionArg(
1969 Darwin::TvOS, TvOSVersion,
1970 TvOSVersion->getOption().getID() ==
1971 options::OPT_mtvos_simulator_version_min_EQ);
1972 } else if (WatchOSVersion)
1973 return DarwinPlatform::createOSVersionArg(
1974 Darwin::WatchOS, WatchOSVersion,
1975 WatchOSVersion->getOption().getID() ==
1976 options::OPT_mwatchos_simulator_version_min_EQ);
1977 return std::nullopt;
1978}
1979
1980/// Returns the deployment target that's specified using the
1981/// OS_DEPLOYMENT_TARGET environment variable.
1982std::optional<DarwinPlatform>
1983getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
1984 const llvm::Triple &Triple) {
1985 std::string Targets[Darwin::LastDarwinPlatform + 1];
1986 const char *EnvVars[] = {
1987 "MACOSX_DEPLOYMENT_TARGET",
1988 "IPHONEOS_DEPLOYMENT_TARGET",
1989 "TVOS_DEPLOYMENT_TARGET",
1990 "WATCHOS_DEPLOYMENT_TARGET",
1991 "DRIVERKIT_DEPLOYMENT_TARGET",
1992 "XROS_DEPLOYMENT_TARGET"
1993 };
1994 static_assert(std::size(EnvVars) == Darwin::LastDarwinPlatform + 1,
1995 "Missing platform");
1996 for (const auto &I : llvm::enumerate(llvm::ArrayRef(EnvVars))) {
1997 if (char *Env = ::getenv(I.value()))
1998 Targets[I.index()] = Env;
1999 }
2000
2001 // Allow conflicts among OSX and iOS for historical reasons, but choose the
2002 // default platform.
2003 if (!Targets[Darwin::MacOS].empty() &&
2004 (!Targets[Darwin::IPhoneOS].empty() ||
2005 !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty() ||
2006 !Targets[Darwin::XROS].empty())) {
2007 if (Triple.getArch() == llvm::Triple::arm ||
2008 Triple.getArch() == llvm::Triple::aarch64 ||
2009 Triple.getArch() == llvm::Triple::thumb)
2010 Targets[Darwin::MacOS] = "";
2011 else
2012 Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
2013 Targets[Darwin::TvOS] = Targets[Darwin::XROS] = "";
2014 } else {
2015 // Don't allow conflicts in any other platform.
2016 unsigned FirstTarget = std::size(Targets);
2017 for (unsigned I = 0; I != std::size(Targets); ++I) {
2018 if (Targets[I].empty())
2019 continue;
2020 if (FirstTarget == std::size(Targets))
2021 FirstTarget = I;
2022 else
2023 TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
2024 << Targets[FirstTarget] << Targets[I];
2025 }
2026 }
2027
2028 for (const auto &Target : llvm::enumerate(llvm::ArrayRef(Targets))) {
2029 if (!Target.value().empty())
2030 return DarwinPlatform::createDeploymentTargetEnv(
2031 (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
2032 Target.value());
2033 }
2034 return std::nullopt;
2035}
2036
2037/// Returns the SDK name without the optional prefix that ends with a '.' or an
2038/// empty string otherwise.
2039static StringRef dropSDKNamePrefix(StringRef SDKName) {
2040 size_t PrefixPos = SDKName.find('.');
2041 if (PrefixPos == StringRef::npos)
2042 return "";
2043 return SDKName.substr(PrefixPos + 1);
2044}
2045
2046/// Tries to infer the deployment target from the SDK specified by -isysroot
2047/// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
2048/// it's available.
2049std::optional<DarwinPlatform>
2050inferDeploymentTargetFromSDK(DerivedArgList &Args,
2051 const std::optional<DarwinSDKInfo> &SDKInfo) {
2052 const Arg *A = Args.getLastArg(options::OPT_isysroot);
2053 if (!A)
2054 return std::nullopt;
2055 StringRef isysroot = A->getValue();
2056 StringRef SDK = Darwin::getSDKName(isysroot);
2057 if (!SDK.size())
2058 return std::nullopt;
2059
2060 std::string Version;
2061 if (SDKInfo) {
2062 // Get the version from the SDKSettings.json if it's available.
2063 Version = SDKInfo->getVersion().getAsString();
2064 } else {
2065 // Slice the version number out.
2066 // Version number is between the first and the last number.
2067 size_t StartVer = SDK.find_first_of("0123456789");
2068 size_t EndVer = SDK.find_last_of("0123456789");
2069 if (StartVer != StringRef::npos && EndVer > StartVer)
2070 Version = std::string(SDK.slice(StartVer, EndVer + 1));
2071 }
2072 if (Version.empty())
2073 return std::nullopt;
2074
2075 auto CreatePlatformFromSDKName =
2076 [&](StringRef SDK) -> std::optional<DarwinPlatform> {
2077 if (SDK.starts_with("iPhoneOS") || SDK.starts_with("iPhoneSimulator"))
2078 return DarwinPlatform::createFromSDK(
2079 Darwin::IPhoneOS, Version,
2080 /*IsSimulator=*/SDK.starts_with("iPhoneSimulator"));
2081 else if (SDK.starts_with("MacOSX"))
2082 return DarwinPlatform::createFromSDK(Darwin::MacOS,
2084 else if (SDK.starts_with("WatchOS") || SDK.starts_with("WatchSimulator"))
2085 return DarwinPlatform::createFromSDK(
2086 Darwin::WatchOS, Version,
2087 /*IsSimulator=*/SDK.starts_with("WatchSimulator"));
2088 else if (SDK.starts_with("AppleTVOS") ||
2089 SDK.starts_with("AppleTVSimulator"))
2090 return DarwinPlatform::createFromSDK(
2091 Darwin::TvOS, Version,
2092 /*IsSimulator=*/SDK.starts_with("AppleTVSimulator"));
2093 else if (SDK.starts_with("XR"))
2094 return DarwinPlatform::createFromSDK(
2095 Darwin::XROS, Version,
2096 /*IsSimulator=*/SDK.contains("Simulator"));
2097 else if (SDK.starts_with("DriverKit"))
2098 return DarwinPlatform::createFromSDK(Darwin::DriverKit, Version);
2099 return std::nullopt;
2100 };
2101 if (auto Result = CreatePlatformFromSDKName(SDK))
2102 return Result;
2103 // The SDK can be an SDK variant with a name like `<prefix>.<platform>`.
2104 return CreatePlatformFromSDKName(dropSDKNamePrefix(SDK));
2105}
2106
2107std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
2108 const Driver &TheDriver) {
2109 VersionTuple OsVersion;
2110 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
2111 switch (OS) {
2112 case llvm::Triple::Darwin:
2113 case llvm::Triple::MacOSX:
2114 // If there is no version specified on triple, and both host and target are
2115 // macos, use the host triple to infer OS version.
2116 if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
2117 !Triple.getOSMajorVersion())
2118 SystemTriple.getMacOSXVersion(OsVersion);
2119 else if (!Triple.getMacOSXVersion(OsVersion))
2120 TheDriver.Diag(diag::err_drv_invalid_darwin_version)
2121 << Triple.getOSName();
2122 break;
2123 case llvm::Triple::IOS:
2124 if (Triple.isMacCatalystEnvironment() && !Triple.getOSMajorVersion()) {
2125 OsVersion = VersionTuple(13, 1);
2126 } else
2127 OsVersion = Triple.getiOSVersion();
2128 break;
2129 case llvm::Triple::TvOS:
2130 OsVersion = Triple.getOSVersion();
2131 break;
2132 case llvm::Triple::WatchOS:
2133 OsVersion = Triple.getWatchOSVersion();
2134 break;
2135 case llvm::Triple::XROS:
2136 OsVersion = Triple.getOSVersion();
2137 if (!OsVersion.getMajor())
2138 OsVersion = OsVersion.withMajorReplaced(1);
2139 break;
2140 case llvm::Triple::DriverKit:
2141 OsVersion = Triple.getDriverKitVersion();
2142 break;
2143 default:
2144 llvm_unreachable("Unexpected OS type");
2145 break;
2146 }
2147
2148 std::string OSVersion;
2149 llvm::raw_string_ostream(OSVersion)
2150 << OsVersion.getMajor() << '.' << OsVersion.getMinor().value_or(0) << '.'
2151 << OsVersion.getSubminor().value_or(0);
2152 return OSVersion;
2153}
2154
2155/// Tries to infer the target OS from the -arch.
2156std::optional<DarwinPlatform>
2157inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
2158 const llvm::Triple &Triple,
2159 const Driver &TheDriver) {
2160 llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
2161
2162 StringRef MachOArchName = Toolchain.getMachOArchName(Args);
2163 if (MachOArchName == "arm64" || MachOArchName == "arm64e")
2164 OSTy = llvm::Triple::MacOSX;
2165 else if (MachOArchName == "armv7" || MachOArchName == "armv7s")
2166 OSTy = llvm::Triple::IOS;
2167 else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
2168 OSTy = llvm::Triple::WatchOS;
2169 else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
2170 MachOArchName != "armv7em")
2171 OSTy = llvm::Triple::MacOSX;
2172 if (OSTy == llvm::Triple::UnknownOS)
2173 return std::nullopt;
2174 return DarwinPlatform::createFromArch(OSTy,
2175 getOSVersion(OSTy, Triple, TheDriver));
2176}
2177
2178/// Returns the deployment target that's specified using the -target option.
2179std::optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
2180 DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver,
2181 const std::optional<DarwinSDKInfo> &SDKInfo) {
2182 if (!Args.hasArg(options::OPT_target))
2183 return std::nullopt;
2184 if (Triple.getOS() == llvm::Triple::Darwin ||
2185 Triple.getOS() == llvm::Triple::UnknownOS)
2186 return std::nullopt;
2187 std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
2188 std::optional<llvm::Triple> TargetVariantTriple;
2189 for (const Arg *A : Args.filtered(options::OPT_darwin_target_variant)) {
2190 llvm::Triple TVT(A->getValue());
2191 // Find a matching <arch>-<vendor> target variant triple that can be used.
2192 if ((Triple.getArch() == llvm::Triple::aarch64 ||
2193 TVT.getArchName() == Triple.getArchName()) &&
2194 TVT.getArch() == Triple.getArch() &&
2195 TVT.getSubArch() == Triple.getSubArch() &&
2196 TVT.getVendor() == Triple.getVendor()) {
2197 if (TargetVariantTriple)
2198 continue;
2199 A->claim();
2200 // Accept a -target-variant triple when compiling code that may run on
2201 // macOS or Mac Catalyst.
2202 if ((Triple.isMacOSX() && TVT.getOS() == llvm::Triple::IOS &&
2203 TVT.isMacCatalystEnvironment()) ||
2204 (TVT.isMacOSX() && Triple.getOS() == llvm::Triple::IOS &&
2205 Triple.isMacCatalystEnvironment())) {
2206 TargetVariantTriple = TVT;
2207 continue;
2208 }
2209 TheDriver.Diag(diag::err_drv_target_variant_invalid)
2210 << A->getSpelling() << A->getValue();
2211 }
2212 }
2213 return DarwinPlatform::createFromTarget(Triple, OSVersion,
2214 Args.getLastArg(options::OPT_target),
2215 TargetVariantTriple, SDKInfo);
2216}
2217
2218/// Returns the deployment target that's specified using the -mtargetos option.
2219std::optional<DarwinPlatform> getDeploymentTargetFromMTargetOSArg(
2220 DerivedArgList &Args, const Driver &TheDriver,
2221 const std::optional<DarwinSDKInfo> &SDKInfo) {
2222 auto *A = Args.getLastArg(options::OPT_mtargetos_EQ);
2223 if (!A)
2224 return std::nullopt;
2225 llvm::Triple TT(llvm::Twine("unknown-apple-") + A->getValue());
2226 switch (TT.getOS()) {
2227 case llvm::Triple::MacOSX:
2228 case llvm::Triple::IOS:
2229 case llvm::Triple::TvOS:
2230 case llvm::Triple::WatchOS:
2231 case llvm::Triple::XROS:
2232 break;
2233 default:
2234 TheDriver.Diag(diag::err_drv_invalid_os_in_arg)
2235 << TT.getOSName() << A->getAsString(Args);
2236 return std::nullopt;
2237 }
2238
2239 VersionTuple Version = TT.getOSVersion();
2240 if (!Version.getMajor()) {
2241 TheDriver.Diag(diag::err_drv_invalid_version_number)
2242 << A->getAsString(Args);
2243 return std::nullopt;
2244 }
2245 return DarwinPlatform::createFromMTargetOS(TT.getOS(), Version,
2246 TT.getEnvironment(), A, SDKInfo);
2247}
2248
2249std::optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
2250 const ArgList &Args,
2251 const Driver &TheDriver) {
2252 const Arg *A = Args.getLastArg(options::OPT_isysroot);
2253 if (!A)
2254 return std::nullopt;
2255 StringRef isysroot = A->getValue();
2256 auto SDKInfoOrErr = parseDarwinSDKInfo(VFS, isysroot);
2257 if (!SDKInfoOrErr) {
2258 llvm::consumeError(SDKInfoOrErr.takeError());
2259 TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
2260 return std::nullopt;
2261 }
2262 return *SDKInfoOrErr;
2263}
2264
2265} // namespace
2266
2267void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
2268 const OptTable &Opts = getDriver().getOpts();
2269
2270 // Support allowing the SDKROOT environment variable used by xcrun and other
2271 // Xcode tools to define the default sysroot, by making it the default for
2272 // isysroot.
2273 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2274 // Warn if the path does not exist.
2275 if (!getVFS().exists(A->getValue()))
2276 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
2277 } else {
2278 if (char *env = ::getenv("SDKROOT")) {
2279 // We only use this value as the default if it is an absolute path,
2280 // exists, and it is not the root path.
2281 if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
2282 StringRef(env) != "/") {
2283 Args.append(Args.MakeSeparateArg(
2284 nullptr, Opts.getOption(options::OPT_isysroot), env));
2285 }
2286 }
2287 }
2288
2289 // Read the SDKSettings.json file for more information, like the SDK version
2290 // that we can pass down to the compiler.
2291 SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
2292
2293 // The OS and the version can be specified using the -target argument.
2294 std::optional<DarwinPlatform> OSTarget =
2295 getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver(), SDKInfo);
2296 if (OSTarget) {
2297 // Disallow mixing -target and -mtargetos=.
2298 if (const auto *MTargetOSArg = Args.getLastArg(options::OPT_mtargetos_EQ)) {
2299 std::string TargetArgStr = OSTarget->getAsString(Args, Opts);
2300 std::string MTargetOSArgStr = MTargetOSArg->getAsString(Args);
2301 getDriver().Diag(diag::err_drv_cannot_mix_options)
2302 << TargetArgStr << MTargetOSArgStr;
2303 }
2304 std::optional<DarwinPlatform> OSVersionArgTarget =
2305 getDeploymentTargetFromOSVersionArg(Args, getDriver());
2306 if (OSVersionArgTarget) {
2307 unsigned TargetMajor, TargetMinor, TargetMicro;
2308 bool TargetExtra;
2309 unsigned ArgMajor, ArgMinor, ArgMicro;
2310 bool ArgExtra;
2311 if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
2312 (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
2313 TargetMinor, TargetMicro, TargetExtra) &&
2314 Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
2315 ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
2316 (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
2317 VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
2318 TargetExtra != ArgExtra))) {
2319 // Select the OS version from the -m<os>-version-min argument when
2320 // the -target does not include an OS version.
2321 if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
2322 !OSTarget->hasOSVersion()) {
2323 OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
2324 } else {
2325 // Warn about -m<os>-version-min that doesn't match the OS version
2326 // that's specified in the target.
2327 std::string OSVersionArg =
2328 OSVersionArgTarget->getAsString(Args, Opts);
2329 std::string TargetArg = OSTarget->getAsString(Args, Opts);
2330 getDriver().Diag(clang::diag::warn_drv_overriding_option)
2331 << OSVersionArg << TargetArg;
2332 }
2333 }
2334 }
2335 } else if ((OSTarget = getDeploymentTargetFromMTargetOSArg(Args, getDriver(),
2336 SDKInfo))) {
2337 // The OS target can be specified using the -mtargetos= argument.
2338 // Disallow mixing -mtargetos= and -m<os>version-min=.
2339 std::optional<DarwinPlatform> OSVersionArgTarget =
2340 getDeploymentTargetFromOSVersionArg(Args, getDriver());
2341 if (OSVersionArgTarget) {
2342 std::string MTargetOSArgStr = OSTarget->getAsString(Args, Opts);
2343 std::string OSVersionArgStr = OSVersionArgTarget->getAsString(Args, Opts);
2344 getDriver().Diag(diag::err_drv_cannot_mix_options)
2345 << MTargetOSArgStr << OSVersionArgStr;
2346 }
2347 } else {
2348 // The OS target can be specified using the -m<os>version-min argument.
2349 OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
2350 // If no deployment target was specified on the command line, check for
2351 // environment defines.
2352 if (!OSTarget) {
2353 OSTarget =
2354 getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
2355 if (OSTarget) {
2356 // Don't infer simulator from the arch when the SDK is also specified.
2357 std::optional<DarwinPlatform> SDKTarget =
2358 inferDeploymentTargetFromSDK(Args, SDKInfo);
2359 if (SDKTarget)
2360 OSTarget->setEnvironment(SDKTarget->getEnvironment());
2361 }
2362 }
2363 // If there is no command-line argument to specify the Target version and
2364 // no environment variable defined, see if we can set the default based
2365 // on -isysroot using SDKSettings.json if it exists.
2366 if (!OSTarget) {
2367 OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo);
2368 /// If the target was successfully constructed from the SDK path, try to
2369 /// infer the SDK info if the SDK doesn't have it.
2370 if (OSTarget && !SDKInfo)
2371 SDKInfo = OSTarget->inferSDKInfo();
2372 }
2373 // If no OS targets have been specified, try to guess platform from -target
2374 // or arch name and compute the version from the triple.
2375 if (!OSTarget)
2376 OSTarget =
2377 inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
2378 }
2379
2380 assert(OSTarget && "Unable to infer Darwin variant");
2381 OSTarget->addOSVersionMinArgument(Args, Opts);
2382 DarwinPlatformKind Platform = OSTarget->getPlatform();
2383
2384 unsigned Major, Minor, Micro;
2385 bool HadExtra;
2386 // The major version should not be over this number.
2387 const unsigned MajorVersionLimit = 1000;
2388 // Set the tool chain target information.
2389 if (Platform == MacOS) {
2390 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2391 Micro, HadExtra) ||
2392 HadExtra || Major < 10 || Major >= MajorVersionLimit || Minor >= 100 ||
2393 Micro >= 100)
2394 getDriver().Diag(diag::err_drv_invalid_version_number)
2395 << OSTarget->getAsString(Args, Opts);
2396 } else if (Platform == IPhoneOS) {
2397 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2398 Micro, HadExtra) ||
2399 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2400 getDriver().Diag(diag::err_drv_invalid_version_number)
2401 << OSTarget->getAsString(Args, Opts);
2402 ;
2403 if (OSTarget->getEnvironment() == MacCatalyst &&
2404 (Major < 13 || (Major == 13 && Minor < 1))) {
2405 getDriver().Diag(diag::err_drv_invalid_version_number)
2406 << OSTarget->getAsString(Args, Opts);
2407 Major = 13;
2408 Minor = 1;
2409 Micro = 0;
2410 }
2411 // For 32-bit targets, the deployment target for iOS has to be earlier than
2412 // iOS 11.
2413 if (getTriple().isArch32Bit() && Major >= 11) {
2414 // If the deployment target is explicitly specified, print a diagnostic.
2415 if (OSTarget->isExplicitlySpecified()) {
2416 if (OSTarget->getEnvironment() == MacCatalyst)
2417 getDriver().Diag(diag::err_invalid_macos_32bit_deployment_target);
2418 else
2419 getDriver().Diag(diag::warn_invalid_ios_deployment_target)
2420 << OSTarget->getAsString(Args, Opts);
2421 // Otherwise, set it to 10.99.99.
2422 } else {
2423 Major = 10;
2424 Minor = 99;
2425 Micro = 99;
2426 }
2427 }
2428 } else if (Platform == TvOS) {
2429 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2430 Micro, HadExtra) ||
2431 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2432 getDriver().Diag(diag::err_drv_invalid_version_number)
2433 << OSTarget->getAsString(Args, Opts);
2434 } else if (Platform == WatchOS) {
2435 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2436 Micro, HadExtra) ||
2437 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2438 getDriver().Diag(diag::err_drv_invalid_version_number)
2439 << OSTarget->getAsString(Args, Opts);
2440 } else if (Platform == DriverKit) {
2441 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2442 Micro, HadExtra) ||
2443 HadExtra || Major < 19 || Major >= MajorVersionLimit || Minor >= 100 ||
2444 Micro >= 100)
2445 getDriver().Diag(diag::err_drv_invalid_version_number)
2446 << OSTarget->getAsString(Args, Opts);
2447 } else if (Platform == XROS) {
2448 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
2449 Micro, HadExtra) ||
2450 HadExtra || Major < 1 || Major >= MajorVersionLimit || Minor >= 100 ||
2451 Micro >= 100)
2452 getDriver().Diag(diag::err_drv_invalid_version_number)
2453 << OSTarget->getAsString(Args, Opts);
2454 } else
2455 llvm_unreachable("unknown kind of Darwin platform");
2456
2457 DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
2458 // Recognize iOS targets with an x86 architecture as the iOS simulator.
2459 if (Environment == NativeEnvironment && Platform != MacOS &&
2460 Platform != DriverKit && OSTarget->canInferSimulatorFromArch() &&
2461 getTriple().isX86())
2462 Environment = Simulator;
2463
2464 VersionTuple NativeTargetVersion;
2465 if (Environment == MacCatalyst)
2466 NativeTargetVersion = OSTarget->getNativeTargetVersion();
2467 setTarget(Platform, Environment, Major, Minor, Micro, NativeTargetVersion);
2468 TargetVariantTriple = OSTarget->getTargetVariantTriple();
2469
2470 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2471 StringRef SDK = getSDKName(A->getValue());
2472 if (SDK.size() > 0) {
2473 size_t StartVer = SDK.find_first_of("0123456789");
2474 StringRef SDKName = SDK.slice(0, StartVer);
2475 if (!SDKName.starts_with(getPlatformFamily()) &&
2476 !dropSDKNamePrefix(SDKName).starts_with(getPlatformFamily()))
2477 getDriver().Diag(diag::warn_incompatible_sysroot)
2478 << SDKName << getPlatformFamily();
2479 }
2480 }
2481}
2482
2483// For certain platforms/environments almost all resources (e.g., headers) are
2484// located in sub-directories, e.g., for DriverKit they live in
2485// <SYSROOT>/System/DriverKit/usr/include (instead of <SYSROOT>/usr/include).
2487 const llvm::Triple &T) {
2488 if (T.isDriverKit()) {
2489 llvm::sys::path::append(Path, "System", "DriverKit");
2490 }
2491}
2492
2493// Returns the effective sysroot from either -isysroot or --sysroot, plus the
2494// platform prefix (if any).
2496AppleMachO::GetEffectiveSysroot(const llvm::opt::ArgList &DriverArgs) const {
2498 if (DriverArgs.hasArg(options::OPT_isysroot))
2499 Path = DriverArgs.getLastArgValue(options::OPT_isysroot);
2500 else if (!getDriver().SysRoot.empty())
2502
2503 if (hasEffectiveTriple()) {
2505 }
2506 return Path;
2507}
2508
2510 const llvm::opt::ArgList &DriverArgs,
2511 llvm::opt::ArgStringList &CC1Args) const {
2512 const Driver &D = getDriver();
2513
2514 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2515
2516 bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
2517 bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
2518 bool NoBuiltinInc = DriverArgs.hasFlag(
2519 options::OPT_nobuiltininc, options::OPT_ibuiltininc, /*Default=*/false);
2520 bool ForceBuiltinInc = DriverArgs.hasFlag(
2521 options::OPT_ibuiltininc, options::OPT_nobuiltininc, /*Default=*/false);
2522
2523 // Add <sysroot>/usr/local/include
2524 if (!NoStdInc && !NoStdlibInc) {
2525 SmallString<128> P(Sysroot);
2526 llvm::sys::path::append(P, "usr", "local", "include");
2527 addSystemInclude(DriverArgs, CC1Args, P);
2528 }
2529
2530 // Add the Clang builtin headers (<resource>/include)
2531 if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
2532 SmallString<128> P(D.ResourceDir);
2533 llvm::sys::path::append(P, "include");
2534 addSystemInclude(DriverArgs, CC1Args, P);
2535 }
2536
2537 if (NoStdInc || NoStdlibInc)
2538 return;
2539
2540 // Check for configure-time C include directories.
2541 llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
2542 if (!CIncludeDirs.empty()) {
2544 CIncludeDirs.split(dirs, ":");
2545 for (llvm::StringRef dir : dirs) {
2546 llvm::StringRef Prefix =
2547 llvm::sys::path::is_absolute(dir) ? "" : llvm::StringRef(Sysroot);
2548 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
2549 }
2550 } else {
2551 // Otherwise, add <sysroot>/usr/include.
2552 SmallString<128> P(Sysroot);
2553 llvm::sys::path::append(P, "usr", "include");
2554 addExternCSystemInclude(DriverArgs, CC1Args, P.str());
2555 }
2556}
2557
2558bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
2559 llvm::opt::ArgStringList &CC1Args,
2561 llvm::StringRef Version,
2562 llvm::StringRef ArchDir,
2563 llvm::StringRef BitDir) const {
2564 llvm::sys::path::append(Base, Version);
2565
2566 // Add the base dir
2567 addSystemInclude(DriverArgs, CC1Args, Base);
2568
2569 // Add the multilib dirs
2570 {
2572 if (!ArchDir.empty())
2573 llvm::sys::path::append(P, ArchDir);
2574 if (!BitDir.empty())
2575 llvm::sys::path::append(P, BitDir);
2576 addSystemInclude(DriverArgs, CC1Args, P);
2577 }
2578
2579 // Add the backward dir
2580 {
2582 llvm::sys::path::append(P, "backward");
2583 addSystemInclude(DriverArgs, CC1Args, P);
2584 }
2585
2586 return getVFS().exists(Base);
2587}
2588
2590 const llvm::opt::ArgList &DriverArgs,
2591 llvm::opt::ArgStringList &CC1Args) const {
2592 // The implementation from a base class will pass through the -stdlib to
2593 // CC1Args.
2594 // FIXME: this should not be necessary, remove usages in the frontend
2595 // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
2596 // Also check whether this is used for setting library search paths.
2597 ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
2598
2599 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
2600 options::OPT_nostdincxx))
2601 return;
2602
2603 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2604
2605 switch (GetCXXStdlibType(DriverArgs)) {
2606 case ToolChain::CST_Libcxx: {
2607 // On Darwin, libc++ can be installed in one of the following places:
2608 // 1. Alongside the compiler in <clang-executable-folder>/../include/c++/v1
2609 // 2. In a SDK (or a custom sysroot) in <sysroot>/usr/include/c++/v1
2610 //
2611 // The precedence of paths is as listed above, i.e. we take the first path
2612 // that exists. Note that we never include libc++ twice -- we take the first
2613 // path that exists and don't send the other paths to CC1 (otherwise
2614 // include_next could break).
2615
2616 // Check for (1)
2617 // Get from '<install>/bin' to '<install>/include/c++/v1'.
2618 // Note that InstallBin can be relative, so we use '..' instead of
2619 // parent_path.
2620 llvm::SmallString<128> InstallBin(getDriver().Dir); // <install>/bin
2621 llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
2622 if (getVFS().exists(InstallBin)) {
2623 addSystemInclude(DriverArgs, CC1Args, InstallBin);
2624 return;
2625 } else if (DriverArgs.hasArg(options::OPT_v)) {
2626 llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
2627 << "\"\n";
2628 }
2629
2630 // Otherwise, check for (2)
2631 llvm::SmallString<128> SysrootUsr = Sysroot;
2632 llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");
2633 if (getVFS().exists(SysrootUsr)) {
2634 addSystemInclude(DriverArgs, CC1Args, SysrootUsr);
2635 return;
2636 } else if (DriverArgs.hasArg(options::OPT_v)) {
2637 llvm::errs() << "ignoring nonexistent directory \"" << SysrootUsr
2638 << "\"\n";
2639 }
2640
2641 // Otherwise, don't add any path.
2642 break;
2643 }
2644
2646 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args);
2647 break;
2648 }
2649}
2650
2651void AppleMachO::AddGnuCPlusPlusIncludePaths(
2652 const llvm::opt::ArgList &DriverArgs,
2653 llvm::opt::ArgStringList &CC1Args) const {}
2654
2655void DarwinClang::AddGnuCPlusPlusIncludePaths(
2656 const llvm::opt::ArgList &DriverArgs,
2657 llvm::opt::ArgStringList &CC1Args) const {
2658 llvm::SmallString<128> UsrIncludeCxx = GetEffectiveSysroot(DriverArgs);
2659 llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
2660
2661 llvm::Triple::ArchType arch = getTriple().getArch();
2662 bool IsBaseFound = true;
2663 switch (arch) {
2664 default:
2665 break;
2666
2667 case llvm::Triple::x86:
2668 case llvm::Triple::x86_64:
2669 IsBaseFound = AddGnuCPlusPlusIncludePaths(
2670 DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1", "i686-apple-darwin10",
2671 arch == llvm::Triple::x86_64 ? "x86_64" : "");
2672 IsBaseFound |= AddGnuCPlusPlusIncludePaths(
2673 DriverArgs, CC1Args, UsrIncludeCxx, "4.0.0", "i686-apple-darwin8", "");
2674 break;
2675
2676 case llvm::Triple::arm:
2677 case llvm::Triple::thumb:
2678 IsBaseFound =
2679 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1",
2680 "arm-apple-darwin10", "v7");
2681 IsBaseFound |=
2682 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1",
2683 "arm-apple-darwin10", "v6");
2684 break;
2685
2686 case llvm::Triple::aarch64:
2687 IsBaseFound =
2688 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1",
2689 "arm64-apple-darwin10", "");
2690 break;
2691 }
2692
2693 if (!IsBaseFound) {
2694 getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
2695 }
2696}
2697
2698void AppleMachO::AddCXXStdlibLibArgs(const ArgList &Args,
2699 ArgStringList &CmdArgs) const {
2701
2702 switch (Type) {
2704 CmdArgs.push_back("-lc++");
2705 if (Args.hasArg(options::OPT_fexperimental_library))
2706 CmdArgs.push_back("-lc++experimental");
2707 break;
2708
2710 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
2711 // it was previously found in the gcc lib dir. However, for all the Darwin
2712 // platforms we care about it was -lstdc++.6, so we search for that
2713 // explicitly if we can't see an obvious -lstdc++ candidate.
2714
2715 // Check in the sysroot first.
2716 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2717 SmallString<128> P(A->getValue());
2718 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
2719
2720 if (!getVFS().exists(P)) {
2721 llvm::sys::path::remove_filename(P);
2722 llvm::sys::path::append(P, "libstdc++.6.dylib");
2723 if (getVFS().exists(P)) {
2724 CmdArgs.push_back(Args.MakeArgString(P));
2725 return;
2726 }
2727 }
2728 }
2729
2730 // Otherwise, look in the root.
2731 // FIXME: This should be removed someday when we don't have to care about
2732 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
2733 if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
2734 getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
2735 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
2736 return;
2737 }
2738
2739 // Otherwise, let the linker search.
2740 CmdArgs.push_back("-lstdc++");
2741 break;
2742 }
2743}
2744
2745void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
2746 ArgStringList &CmdArgs) const {
2747 // For Darwin platforms, use the compiler-rt-based support library
2748 // instead of the gcc-provided one (which is also incidentally
2749 // only present in the gcc lib dir, which makes it hard to find).
2750
2751 SmallString<128> P(getDriver().ResourceDir);
2752 llvm::sys::path::append(P, "lib", "darwin");
2753
2754 // Use the newer cc_kext for iOS ARM after 6.0.
2755 if (isTargetWatchOS()) {
2756 llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
2757 } else if (isTargetTvOS()) {
2758 llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
2759 } else if (isTargetIPhoneOS()) {
2760 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
2761 } else if (isTargetDriverKit()) {
2762 // DriverKit doesn't want extra runtime support.
2763 } else if (isTargetXROSDevice()) {
2764 llvm::sys::path::append(
2765 P, llvm::Twine("libclang_rt.cc_kext_") +
2766 llvm::Triple::getOSTypeName(llvm::Triple::XROS) + ".a");
2767 } else {
2768 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
2769 }
2770
2771 // For now, allow missing resource libraries to support developers who may
2772 // not have compiler-rt checked out or integrated into their build.
2773 if (getVFS().exists(P))
2774 CmdArgs.push_back(Args.MakeArgString(P));
2775}
2776
2777DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
2778 StringRef BoundArch,
2779 Action::OffloadKind) const {
2780 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2781 const OptTable &Opts = getDriver().getOpts();
2782
2783 // FIXME: We really want to get out of the tool chain level argument
2784 // translation business, as it makes the driver functionality much
2785 // more opaque. For now, we follow gcc closely solely for the
2786 // purpose of easily achieving feature parity & testability. Once we
2787 // have something that works, we should reevaluate each translation
2788 // and try to push it down into tool specific logic.
2789
2790 for (Arg *A : Args) {
2791 if (A->getOption().matches(options::OPT_Xarch__)) {
2792 // Skip this argument unless the architecture matches either the toolchain
2793 // triple arch, or the arch being bound.
2794 StringRef XarchArch = A->getValue(0);
2795 if (!(XarchArch == getArchName() ||
2796 (!BoundArch.empty() && XarchArch == BoundArch)))
2797 continue;
2798
2799 Arg *OriginalArg = A;
2800 TranslateXarchArgs(Args, A, DAL);
2801
2802 // Linker input arguments require custom handling. The problem is that we
2803 // have already constructed the phase actions, so we can not treat them as
2804 // "input arguments".
2805 if (A->getOption().hasFlag(options::LinkerInput)) {
2806 // Convert the argument into individual Zlinker_input_args.
2807 for (const char *Value : A->getValues()) {
2808 DAL->AddSeparateArg(
2809 OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
2810 }
2811 continue;
2812 }
2813 }
2814
2815 // Sob. These is strictly gcc compatible for the time being. Apple
2816 // gcc translates options twice, which means that self-expanding
2817 // options add duplicates.
2818 switch ((options::ID)A->getOption().getID()) {
2819 default:
2820 DAL->append(A);
2821 break;
2822
2823 case options::OPT_mkernel:
2824 case options::OPT_fapple_kext:
2825 DAL->append(A);
2826 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
2827 break;
2828
2829 case options::OPT_dependency_file:
2830 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
2831 break;
2832
2833 case options::OPT_gfull:
2834 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2835 DAL->AddFlagArg(
2836 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
2837 break;
2838
2839 case options::OPT_gused:
2840 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2841 DAL->AddFlagArg(
2842 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
2843 break;
2844
2845 case options::OPT_shared:
2846 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
2847 break;
2848
2849 case options::OPT_fconstant_cfstrings:
2850 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
2851 break;
2852
2853 case options::OPT_fno_constant_cfstrings:
2854 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
2855 break;
2856
2857 case options::OPT_Wnonportable_cfstrings:
2858 DAL->AddFlagArg(A,
2859 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
2860 break;
2861
2862 case options::OPT_Wno_nonportable_cfstrings:
2863 DAL->AddFlagArg(
2864 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
2865 break;
2866 }
2867 }
2868
2869 // Add the arch options based on the particular spelling of -arch, to match
2870 // how the driver works.
2871 if (!BoundArch.empty()) {
2872 StringRef Name = BoundArch;
2873 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
2874 const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
2875
2876 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
2877 // which defines the list of which architectures we accept.
2878 if (Name == "ppc")
2879 ;
2880 else if (Name == "ppc601")
2881 DAL->AddJoinedArg(nullptr, MCpu, "601");
2882 else if (Name == "ppc603")
2883 DAL->AddJoinedArg(nullptr, MCpu, "603");
2884 else if (Name == "ppc604")
2885 DAL->AddJoinedArg(nullptr, MCpu, "604");
2886 else if (Name == "ppc604e")
2887 DAL->AddJoinedArg(nullptr, MCpu, "604e");
2888 else if (Name == "ppc750")
2889 DAL->AddJoinedArg(nullptr, MCpu, "750");
2890 else if (Name == "ppc7400")
2891 DAL->AddJoinedArg(nullptr, MCpu, "7400");
2892 else if (Name == "ppc7450")
2893 DAL->AddJoinedArg(nullptr, MCpu, "7450");
2894 else if (Name == "ppc970")
2895 DAL->AddJoinedArg(nullptr, MCpu, "970");
2896
2897 else if (Name == "ppc64" || Name == "ppc64le")
2898 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2899
2900 else if (Name == "i386")
2901 ;
2902 else if (Name == "i486")
2903 DAL->AddJoinedArg(nullptr, MArch, "i486");
2904 else if (Name == "i586")
2905 DAL->AddJoinedArg(nullptr, MArch, "i586");
2906 else if (Name == "i686")
2907 DAL->AddJoinedArg(nullptr, MArch, "i686");
2908 else if (Name == "pentium")
2909 DAL->AddJoinedArg(nullptr, MArch, "pentium");
2910 else if (Name == "pentium2")
2911 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2912 else if (Name == "pentpro")
2913 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
2914 else if (Name == "pentIIm3")
2915 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2916
2917 else if (Name == "x86_64" || Name == "x86_64h")
2918 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2919
2920 else if (Name == "arm")
2921 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2922 else if (Name == "armv4t")
2923 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2924 else if (Name == "armv5")
2925 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
2926 else if (Name == "xscale")
2927 DAL->AddJoinedArg(nullptr, MArch, "xscale");
2928 else if (Name == "armv6")
2929 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
2930 else if (Name == "armv6m")
2931 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
2932 else if (Name == "armv7")
2933 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
2934 else if (Name == "armv7em")
2935 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
2936 else if (Name == "armv7k")
2937 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
2938 else if (Name == "armv7m")
2939 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
2940 else if (Name == "armv7s")
2941 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
2942 }
2943
2944 return DAL;
2945}
2946
2947void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
2948 ArgStringList &CmdArgs,
2949 bool ForceLinkBuiltinRT) const {
2950 // Embedded targets are simple at the moment, not supporting sanitizers and
2951 // with different libraries for each member of the product { static, PIC } x
2952 // { hard-float, soft-float }
2953 llvm::SmallString<32> CompilerRT = StringRef("");
2954 CompilerRT +=
2956 ? "hard"
2957 : "soft";
2958 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
2959
2960 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
2961}
2962
2964 llvm::Triple::OSType OS;
2965
2966 if (isTargetMacCatalyst())
2967 return TargetVersion < alignedAllocMinVersion(llvm::Triple::MacOSX);
2968 switch (TargetPlatform) {
2969 case MacOS: // Earlier than 10.13.
2970 OS = llvm::Triple::MacOSX;
2971 break;
2972 case IPhoneOS:
2973 OS = llvm::Triple::IOS;
2974 break;
2975 case TvOS: // Earlier than 11.0.
2976 OS = llvm::Triple::TvOS;
2977 break;
2978 case WatchOS: // Earlier than 4.0.
2979 OS = llvm::Triple::WatchOS;
2980 break;
2981 case XROS: // Always available.
2982 return false;
2983 case DriverKit: // Always available.
2984 return false;
2985 }
2986
2988}
2989
2991 const Darwin::DarwinPlatformKind &TargetPlatform,
2992 const Darwin::DarwinEnvironmentKind &TargetEnvironment,
2993 const std::optional<DarwinSDKInfo> &SDKInfo) {
2994 if (TargetEnvironment == Darwin::NativeEnvironment ||
2995 TargetEnvironment == Darwin::Simulator ||
2996 TargetEnvironment == Darwin::MacCatalyst) {
2997 // Standard xnu/Mach/Darwin based environments
2998 // depend on the SDK version.
2999 } else {
3000 // All other environments support builtin modules from the start.
3001 return true;
3002 }
3003
3004 if (!SDKInfo)
3005 // If there is no SDK info, assume this is building against a
3006 // pre-SDK version of macOS (i.e. before Mac OS X 10.4). Those
3007 // don't support modules anyway, but the headers definitely
3008 // don't support builtin modules either. It might also be some
3009 // kind of degenerate build environment, err on the side of
3010 // the old behavior which is to not use builtin modules.
3011 return false;
3012
3013 VersionTuple SDKVersion = SDKInfo->getVersion();
3014 switch (TargetPlatform) {
3015 // Existing SDKs added support for builtin modules in the fall
3016 // 2024 major releases.
3017 case Darwin::MacOS:
3018 return SDKVersion >= VersionTuple(15U);
3019 case Darwin::IPhoneOS:
3020 switch (TargetEnvironment) {
3022 // Mac Catalyst uses `-target arm64-apple-ios18.0-macabi` so the platform
3023 // is iOS, but it builds with the macOS SDK, so it's the macOS SDK version
3024 // that's relevant.
3025 return SDKVersion >= VersionTuple(15U);
3026 default:
3027 return SDKVersion >= VersionTuple(18U);
3028 }
3029 case Darwin::TvOS:
3030 return SDKVersion >= VersionTuple(18U);
3031 case Darwin::WatchOS:
3032 return SDKVersion >= VersionTuple(11U);
3033 case Darwin::XROS:
3034 return SDKVersion >= VersionTuple(2U);
3035
3036 // New SDKs support builtin modules from the start.
3037 default:
3038 return true;
3039 }
3040}
3041
3042static inline llvm::VersionTuple
3043sizedDeallocMinVersion(llvm::Triple::OSType OS) {
3044 switch (OS) {
3045 default:
3046 break;
3047 case llvm::Triple::Darwin:
3048 case llvm::Triple::MacOSX: // Earliest supporting version is 10.12.
3049 return llvm::VersionTuple(10U, 12U);
3050 case llvm::Triple::IOS:
3051 case llvm::Triple::TvOS: // Earliest supporting version is 10.0.0.
3052 return llvm::VersionTuple(10U);
3053 case llvm::Triple::WatchOS: // Earliest supporting version is 3.0.0.
3054 return llvm::VersionTuple(3U);
3055 }
3056
3057 llvm_unreachable("Unexpected OS");
3058}
3059
3061 llvm::Triple::OSType OS;
3062
3063 if (isTargetMacCatalyst())
3064 return TargetVersion < sizedDeallocMinVersion(llvm::Triple::MacOSX);
3065 switch (TargetPlatform) {
3066 case MacOS: // Earlier than 10.12.
3067 OS = llvm::Triple::MacOSX;
3068 break;
3069 case IPhoneOS:
3070 OS = llvm::Triple::IOS;
3071 break;
3072 case TvOS: // Earlier than 10.0.
3073 OS = llvm::Triple::TvOS;
3074 break;
3075 case WatchOS: // Earlier than 3.0.
3076 OS = llvm::Triple::WatchOS;
3077 break;
3078 case DriverKit:
3079 case XROS:
3080 // Always available.
3081 return false;
3082 }
3083
3085}
3086
3088 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3089 Action::OffloadKind DeviceOffloadKind) const {
3090 // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
3091 // enabled or disabled aligned allocations.
3092 if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
3093 options::OPT_fno_aligned_allocation) &&
3095 CC1Args.push_back("-faligned-alloc-unavailable");
3096
3097 // Pass "-fno-sized-deallocation" only when the user hasn't manually enabled
3098 // or disabled sized deallocations.
3099 if (!DriverArgs.hasArgNoClaim(options::OPT_fsized_deallocation,
3100 options::OPT_fno_sized_deallocation) &&
3102 CC1Args.push_back("-fno-sized-deallocation");
3103
3104 addClangCC1ASTargetOptions(DriverArgs, CC1Args);
3105
3106 // Enable compatibility mode for NSItemProviderCompletionHandler in
3107 // Foundation/NSItemProvider.h.
3108 CC1Args.push_back("-fcompatibility-qualified-id-block-type-checking");
3109
3110 // Give static local variables in inline functions hidden visibility when
3111 // -fvisibility-inlines-hidden is enabled.
3112 if (!DriverArgs.getLastArgNoClaim(
3113 options::OPT_fvisibility_inlines_hidden_static_local_var,
3114 options::OPT_fno_visibility_inlines_hidden_static_local_var))
3115 CC1Args.push_back("-fvisibility-inlines-hidden-static-local-var");
3116
3117 // Earlier versions of the darwin SDK have the C standard library headers
3118 // all together in the Darwin module. That leads to module cycles with
3119 // the _Builtin_ modules. e.g. <inttypes.h> on darwin includes <stdint.h>.
3120 // The builtin <stdint.h> include-nexts <stdint.h>. When both of those
3121 // darwin headers are in the Darwin module, there's a module cycle Darwin ->
3122 // _Builtin_stdint -> Darwin (i.e. inttypes.h (darwin) -> stdint.h (builtin) ->
3123 // stdint.h (darwin)). This is fixed in later versions of the darwin SDK,
3124 // but until then, the builtin headers need to join the system modules.
3125 // i.e. when the builtin stdint.h is in the Darwin module too, the cycle
3126 // goes away. Note that -fbuiltin-headers-in-system-modules does nothing
3127 // to fix the same problem with C++ headers, and is generally fragile.
3129 CC1Args.push_back("-fbuiltin-headers-in-system-modules");
3130
3131 if (!DriverArgs.hasArgNoClaim(options::OPT_fdefine_target_os_macros,
3132 options::OPT_fno_define_target_os_macros))
3133 CC1Args.push_back("-fdefine-target-os-macros");
3134
3135 // Disable subdirectory modulemap search on sufficiently recent SDKs.
3136 if (SDKInfo &&
3137 !DriverArgs.hasFlag(options::OPT_fmodulemap_allow_subdirectory_search,
3138 options::OPT_fno_modulemap_allow_subdirectory_search,
3139 false)) {
3140 bool RequiresSubdirectorySearch;
3141 VersionTuple SDKVersion = SDKInfo->getVersion();
3142 switch (TargetPlatform) {
3143 default:
3144 RequiresSubdirectorySearch = true;
3145 break;
3146 case MacOS:
3147 RequiresSubdirectorySearch = SDKVersion < VersionTuple(15, 0);
3148 break;
3149 case IPhoneOS:
3150 case TvOS:
3151 RequiresSubdirectorySearch = SDKVersion < VersionTuple(18, 0);
3152 break;
3153 case WatchOS:
3154 RequiresSubdirectorySearch = SDKVersion < VersionTuple(11, 0);
3155 break;
3156 case XROS:
3157 RequiresSubdirectorySearch = SDKVersion < VersionTuple(2, 0);
3158 break;
3159 }
3160 if (!RequiresSubdirectorySearch)
3161 CC1Args.push_back("-fno-modulemap-allow-subdirectory-search");
3162 }
3163}
3164
3166 const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const {
3167 if (TargetVariantTriple) {
3168 CC1ASArgs.push_back("-darwin-target-variant-triple");
3169 CC1ASArgs.push_back(Args.MakeArgString(TargetVariantTriple->getTriple()));
3170 }
3171
3172 if (SDKInfo) {
3173 /// Pass the SDK version to the compiler when the SDK information is
3174 /// available.
3175 auto EmitTargetSDKVersionArg = [&](const VersionTuple &V) {
3176 std::string Arg;
3177 llvm::raw_string_ostream OS(Arg);
3178 OS << "-target-sdk-version=" << V;
3179 CC1ASArgs.push_back(Args.MakeArgString(Arg));
3180 };
3181
3182 if (isTargetMacCatalyst()) {
3183 if (const auto *MacOStoMacCatalystMapping = SDKInfo->getVersionMapping(
3185 std::optional<VersionTuple> SDKVersion = MacOStoMacCatalystMapping->map(
3187 std::nullopt);
3188 EmitTargetSDKVersionArg(
3189 SDKVersion ? *SDKVersion : minimumMacCatalystDeploymentTarget());
3190 }
3191 } else {
3192 EmitTargetSDKVersionArg(SDKInfo->getVersion());
3193 }
3194
3195 /// Pass the target variant SDK version to the compiler when the SDK
3196 /// information is available and is required for target variant.
3197 if (TargetVariantTriple) {
3198 if (isTargetMacCatalyst()) {
3199 std::string Arg;
3200 llvm::raw_string_ostream OS(Arg);
3201 OS << "-darwin-target-variant-sdk-version=" << SDKInfo->getVersion();
3202 CC1ASArgs.push_back(Args.MakeArgString(Arg));
3203 } else if (const auto *MacOStoMacCatalystMapping =
3204 SDKInfo->getVersionMapping(
3206 if (std::optional<VersionTuple> SDKVersion =
3207 MacOStoMacCatalystMapping->map(
3209 std::nullopt)) {
3210 std::string Arg;
3211 llvm::raw_string_ostream OS(Arg);
3212 OS << "-darwin-target-variant-sdk-version=" << *SDKVersion;
3213 CC1ASArgs.push_back(Args.MakeArgString(Arg));
3214 }
3215 }
3216 }
3217 }
3218}
3219
3220DerivedArgList *
3221Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
3222 Action::OffloadKind DeviceOffloadKind) const {
3223 // First get the generic Apple args, before moving onto Darwin-specific ones.
3224 DerivedArgList *DAL =
3225 MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
3226
3227 // If no architecture is bound, none of the translations here are relevant.
3228 if (BoundArch.empty())
3229 return DAL;
3230
3231 // Add an explicit version min argument for the deployment target. We do this
3232 // after argument translation because -Xarch_ arguments may add a version min
3233 // argument.
3234 AddDeploymentTarget(*DAL);
3235
3236 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
3237 // FIXME: It would be far better to avoid inserting those -static arguments,
3238 // but we can't check the deployment target in the translation code until
3239 // it is set here.
3241 (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
3242 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
3243 Arg *A = *it;
3244 ++it;
3245 if (A->getOption().getID() != options::OPT_mkernel &&
3246 A->getOption().getID() != options::OPT_fapple_kext)
3247 continue;
3248 assert(it != ie && "unexpected argument translation");
3249 A = *it;
3250 assert(A->getOption().getID() == options::OPT_static &&
3251 "missing expected -static argument");
3252 *it = nullptr;
3253 ++it;
3254 }
3255 }
3256
3257 auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
3258 if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
3259 if (Args.hasFlag(options::OPT_fomit_frame_pointer,
3260 options::OPT_fno_omit_frame_pointer, false))
3261 getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
3262 << "-fomit-frame-pointer" << BoundArch;
3263 }
3264
3265 return DAL;
3266}
3267
3269 // Unwind tables are not emitted if -fno-exceptions is supplied (except when
3270 // targeting x86_64).
3271 if (getArch() == llvm::Triple::x86_64 ||
3272 (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
3273 Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
3274 true)))
3275 return (getArch() == llvm::Triple::aarch64 ||
3276 getArch() == llvm::Triple::aarch64_32)
3279
3281}
3282
3284 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
3285 return S[0] != '\0';
3286 return false;
3287}
3288
3290 if (const char *S = ::getenv("RC_DEBUG_PREFIX_MAP"))
3291 return S;
3292 return {};
3293}
3294
3295llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
3296 // Darwin uses SjLj exceptions on ARM.
3297 if (getTriple().getArch() != llvm::Triple::arm &&
3298 getTriple().getArch() != llvm::Triple::thumb)
3299 return llvm::ExceptionHandling::None;
3300
3301 // Only watchOS uses the new DWARF/Compact unwinding method.
3302 llvm::Triple Triple(ComputeLLVMTriple(Args));
3303 if (Triple.isWatchABI())
3304 return llvm::ExceptionHandling::DwarfCFI;
3305
3306 return llvm::ExceptionHandling::SjLj;
3307}
3308
3310 assert(TargetInitialized && "Target not initialized!");
3312 return false;
3313 return true;
3314}
3315
3316bool MachO::isPICDefault() const { return true; }
3317
3318bool MachO::isPIEDefault(const llvm::opt::ArgList &Args) const { return false; }
3319
3321 return (getArch() == llvm::Triple::x86_64 ||
3322 getArch() == llvm::Triple::aarch64);
3323}
3324
3326 // Profiling instrumentation is only supported on x86.
3327 return getTriple().isX86();
3328}
3329
3330void Darwin::addMinVersionArgs(const ArgList &Args,
3331 ArgStringList &CmdArgs) const {
3332 VersionTuple TargetVersion = getTripleTargetVersion();
3333
3334 assert(!isTargetXROS() && "xrOS always uses -platform-version");
3335
3336 if (isTargetWatchOS())
3337 CmdArgs.push_back("-watchos_version_min");
3338 else if (isTargetWatchOSSimulator())
3339 CmdArgs.push_back("-watchos_simulator_version_min");
3340 else if (isTargetTvOS())
3341 CmdArgs.push_back("-tvos_version_min");
3342 else if (isTargetTvOSSimulator())
3343 CmdArgs.push_back("-tvos_simulator_version_min");
3344 else if (isTargetDriverKit())
3345 CmdArgs.push_back("-driverkit_version_min");
3346 else if (isTargetIOSSimulator())
3347 CmdArgs.push_back("-ios_simulator_version_min");
3348 else if (isTargetIOSBased())
3349 CmdArgs.push_back("-iphoneos_version_min");
3350 else if (isTargetMacCatalyst())
3351 CmdArgs.push_back("-maccatalyst_version_min");
3352 else {
3353 assert(isTargetMacOS() && "unexpected target");
3354 CmdArgs.push_back("-macosx_version_min");
3355 }
3356
3357 VersionTuple MinTgtVers = getEffectiveTriple().getMinimumSupportedOSVersion();
3358 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3359 TargetVersion = MinTgtVers;
3360 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3361 if (TargetVariantTriple) {
3362 assert(isTargetMacOSBased() && "unexpected target");
3363 VersionTuple VariantTargetVersion;
3364 if (TargetVariantTriple->isMacOSX()) {
3365 CmdArgs.push_back("-macosx_version_min");
3366 TargetVariantTriple->getMacOSXVersion(VariantTargetVersion);
3367 } else {
3368 assert(TargetVariantTriple->isiOS() &&
3369 TargetVariantTriple->isMacCatalystEnvironment() &&
3370 "unexpected target variant triple");
3371 CmdArgs.push_back("-maccatalyst_version_min");
3372 VariantTargetVersion = TargetVariantTriple->getiOSVersion();
3373 }
3374 VersionTuple MinTgtVers =
3375 TargetVariantTriple->getMinimumSupportedOSVersion();
3376 if (MinTgtVers.getMajor() && MinTgtVers > VariantTargetVersion)
3377 VariantTargetVersion = MinTgtVers;
3378 CmdArgs.push_back(Args.MakeArgString(VariantTargetVersion.getAsString()));
3379 }
3380}
3381
3383 Darwin::DarwinEnvironmentKind Environment) {
3384 switch (Platform) {
3385 case Darwin::MacOS:
3386 return "macos";
3387 case Darwin::IPhoneOS:
3388 if (Environment == Darwin::MacCatalyst)
3389 return "mac catalyst";
3390 return "ios";
3391 case Darwin::TvOS:
3392 return "tvos";
3393 case Darwin::WatchOS:
3394 return "watchos";
3395 case Darwin::XROS:
3396 return "xros";
3397 case Darwin::DriverKit:
3398 return "driverkit";
3399 }
3400 llvm_unreachable("invalid platform");
3401}
3402
3403void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
3404 llvm::opt::ArgStringList &CmdArgs) const {
3405 auto EmitPlatformVersionArg =
3406 [&](const VersionTuple &TV, Darwin::DarwinPlatformKind TargetPlatform,
3408 const llvm::Triple &TT) {
3409 // -platform_version <platform> <target_version> <sdk_version>
3410 // Both the target and SDK version support only up to 3 components.
3411 CmdArgs.push_back("-platform_version");
3412 std::string PlatformName =
3415 PlatformName += "-simulator";
3416 CmdArgs.push_back(Args.MakeArgString(PlatformName));
3417 VersionTuple TargetVersion = TV.withoutBuild();
3420 getTriple().getArchName() == "arm64e" &&
3421 TargetVersion.getMajor() < 14) {
3422 // arm64e slice is supported on iOS/tvOS 14+ only.
3423 TargetVersion = VersionTuple(14, 0);
3424 }
3425 VersionTuple MinTgtVers = TT.getMinimumSupportedOSVersion();
3426 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3427 TargetVersion = MinTgtVers;
3428 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3429
3431 // Mac Catalyst programs must use the appropriate iOS SDK version
3432 // that corresponds to the macOS SDK version used for the compilation.
3433 std::optional<VersionTuple> iOSSDKVersion;
3434 if (SDKInfo) {
3435 if (const auto *MacOStoMacCatalystMapping =
3436 SDKInfo->getVersionMapping(
3438 iOSSDKVersion = MacOStoMacCatalystMapping->map(
3439 SDKInfo->getVersion().withoutBuild(),
3440 minimumMacCatalystDeploymentTarget(), std::nullopt);
3441 }
3442 }
3443 CmdArgs.push_back(Args.MakeArgString(
3444 (iOSSDKVersion ? *iOSSDKVersion
3446 .getAsString()));
3447 return;
3448 }
3449
3450 if (SDKInfo) {
3451 VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
3452 if (!SDKVersion.getMinor())
3453 SDKVersion = VersionTuple(SDKVersion.getMajor(), 0);
3454 CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
3455 } else {
3456 // Use an SDK version that's matching the deployment target if the SDK
3457 // version is missing. This is preferred over an empty SDK version
3458 // (0.0.0) as the system's runtime might expect the linked binary to
3459 // contain a valid SDK version in order for the binary to work
3460 // correctly. It's reasonable to use the deployment target version as
3461 // a proxy for the SDK version because older SDKs don't guarantee
3462 // support for deployment targets newer than the SDK versions, so that
3463 // rules out using some predetermined older SDK version, which leaves
3464 // the deployment target version as the only reasonable choice.
3465 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3466 }
3467 };
3468 EmitPlatformVersionArg(getTripleTargetVersion(), TargetPlatform,
3471 return;
3474 VersionTuple TargetVariantVersion;
3475 if (TargetVariantTriple->isMacOSX()) {
3476 TargetVariantTriple->getMacOSXVersion(TargetVariantVersion);
3477 Platform = Darwin::MacOS;
3478 Environment = Darwin::NativeEnvironment;
3479 } else {
3480 assert(TargetVariantTriple->isiOS() &&
3481 TargetVariantTriple->isMacCatalystEnvironment() &&
3482 "unexpected target variant triple");
3483 TargetVariantVersion = TargetVariantTriple->getiOSVersion();
3484 Platform = Darwin::IPhoneOS;
3485 Environment = Darwin::MacCatalyst;
3486 }
3487 EmitPlatformVersionArg(TargetVariantVersion, Platform, Environment,
3489}
3490
3491// Add additional link args for the -dynamiclib option.
3492static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args,
3493 ArgStringList &CmdArgs) {
3494 // Derived from darwin_dylib1 spec.
3495 if (D.isTargetIPhoneOS()) {
3496 if (D.isIPhoneOSVersionLT(3, 1))
3497 CmdArgs.push_back("-ldylib1.o");
3498 return;
3499 }
3500
3501 if (!D.isTargetMacOS())
3502 return;
3503 if (D.isMacosxVersionLT(10, 5))
3504 CmdArgs.push_back("-ldylib1.o");
3505 else if (D.isMacosxVersionLT(10, 6))
3506 CmdArgs.push_back("-ldylib1.10.5.o");
3507}
3508
3509// Add additional link args for the -bundle option.
3510static void addBundleLinkArgs(const Darwin &D, const ArgList &Args,
3511 ArgStringList &CmdArgs) {
3512 if (Args.hasArg(options::OPT_static))
3513 return;
3514 // Derived from darwin_bundle1 spec.
3515 if ((D.isTargetIPhoneOS() && D.isIPhoneOSVersionLT(3, 1)) ||
3516 (D.isTargetMacOS() && D.isMacosxVersionLT(10, 6)))
3517 CmdArgs.push_back("-lbundle1.o");
3518}
3519
3520// Add additional link args for the -pg option.
3521static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args,
3522 ArgStringList &CmdArgs) {
3523 if (D.isTargetMacOS() && D.isMacosxVersionLT(10, 9)) {
3524 if (Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_object) ||
3525 Args.hasArg(options::OPT_preload)) {
3526 CmdArgs.push_back("-lgcrt0.o");
3527 } else {
3528 CmdArgs.push_back("-lgcrt1.o");
3529
3530 // darwin_crt2 spec is empty.
3531 }
3532 // By default on OS X 10.8 and later, we don't link with a crt1.o
3533 // file and the linker knows to use _main as the entry point. But,
3534 // when compiling with -pg, we need to link with the gcrt1.o file,
3535 // so pass the -no_new_main option to tell the linker to use the
3536 // "start" symbol as the entry point.
3537 if (!D.isMacosxVersionLT(10, 8))
3538 CmdArgs.push_back("-no_new_main");
3539 } else {
3540 D.getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
3541 << D.isTargetMacOSBased();
3542 }
3543}
3544
3545static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args,
3546 ArgStringList &CmdArgs) {
3547 // Derived from darwin_crt1 spec.
3548 if (D.isTargetIPhoneOS()) {
3549 if (D.getArch() == llvm::Triple::aarch64)
3550 ; // iOS does not need any crt1 files for arm64
3551 else if (D.isIPhoneOSVersionLT(3, 1))
3552 CmdArgs.push_back("-lcrt1.o");
3553 else if (D.isIPhoneOSVersionLT(6, 0))
3554 CmdArgs.push_back("-lcrt1.3.1.o");
3555 return;
3556 }
3557
3558 if (!D.isTargetMacOS())
3559 return;
3560 if (D.isMacosxVersionLT(10, 5))
3561 CmdArgs.push_back("-lcrt1.o");
3562 else if (D.isMacosxVersionLT(10, 6))
3563 CmdArgs.push_back("-lcrt1.10.5.o");
3564 else if (D.isMacosxVersionLT(10, 8))
3565 CmdArgs.push_back("-lcrt1.10.6.o");
3566 // darwin_crt2 spec is empty.
3567}
3568
3569void Darwin::addStartObjectFileArgs(const ArgList &Args,
3570 ArgStringList &CmdArgs) const {
3571 // Derived from startfile spec.
3572 if (Args.hasArg(options::OPT_dynamiclib))
3573 addDynamicLibLinkArgs(*this, Args, CmdArgs);
3574 else if (Args.hasArg(options::OPT_bundle))
3575 addBundleLinkArgs(*this, Args, CmdArgs);
3576 else if (Args.hasArg(options::OPT_pg) && SupportsProfiling())
3577 addPgProfilingLinkArgs(*this, Args, CmdArgs);
3578 else if (Args.hasArg(options::OPT_static) ||
3579 Args.hasArg(options::OPT_object) ||
3580 Args.hasArg(options::OPT_preload))
3581 CmdArgs.push_back("-lcrt0.o");
3582 else
3583 addDefaultCRTLinkArgs(*this, Args, CmdArgs);
3584
3585 if (isTargetMacOS() && Args.hasArg(options::OPT_shared_libgcc) &&
3586 isMacosxVersionLT(10, 5)) {
3587 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
3588 CmdArgs.push_back(Str);
3589 }
3590}
3591
3595 return;
3596 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
3597}
3598
3600 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3601 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
3603 Res |= SanitizerKind::Address;
3604 Res |= SanitizerKind::PointerCompare;
3605 Res |= SanitizerKind::PointerSubtract;
3606 Res |= SanitizerKind::Realtime;
3607 Res |= SanitizerKind::Leak;
3608 Res |= SanitizerKind::Fuzzer;
3609 Res |= SanitizerKind::FuzzerNoLink;
3610 Res |= SanitizerKind::ObjCCast;
3611
3612 // Prior to 10.9, macOS shipped a version of the C++ standard library without
3613 // C++11 support. The same is true of iOS prior to version 5. These OS'es are
3614 // incompatible with -fsanitize=vptr.
3615 if (!(isTargetMacOSBased() && isMacosxVersionLT(10, 9)) &&
3617 Res |= SanitizerKind::Vptr;
3618
3619 if ((IsX86_64 || IsAArch64) &&
3622 Res |= SanitizerKind::Thread;
3623 }
3624
3625 if ((IsX86_64 || IsAArch64) && isTargetMacOSBased()) {
3626 Res |= SanitizerKind::Type;
3627 }
3628
3629 if (IsX86_64)
3630 Res |= SanitizerKind::NumericalStability;
3631
3632 return Res;
3633}
3634
3635void AppleMachO::printVerboseInfo(raw_ostream &OS) const {
3636 CudaInstallation->print(OS);
3637 RocmInstallation->print(OS);
3638}
#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
enum clang::sema::@1724::IndirectLocalPathEntry::EntryKind Kind
IndirectLocalPath & Path
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition: Clang.cpp:1366
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition: Clang.cpp:1377
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition: Clang.cpp:1393
static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Darwin.cpp:3521
static const char * ArmMachOArchName(StringRef Arch)
Definition: Darwin.cpp:1044
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:1449
static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Darwin.cpp:3545
static void addBundleLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Darwin.cpp:3510
static llvm::VersionTuple sizedDeallocMinVersion(llvm::Triple::OSType OS)
Definition: Darwin.cpp:3043
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:1661
static bool sdkSupportsBuiltinModules(const Darwin::DarwinPlatformKind &TargetPlatform, const Darwin::DarwinEnvironmentKind &TargetEnvironment, const std::optional< DarwinSDKInfo > &SDKInfo)
Definition: Darwin.cpp:2990
static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Darwin.cpp:3492
static void AppendPlatformPrefix(SmallString< 128 > &Path, const llvm::Triple &T)
Definition: Darwin.cpp:2486
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:3382
static const char * ArmMachOArchNameCPU(StringRef CPU)
Definition: Darwin.cpp:1061
static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol)
Add an export directive for Symbol to the link command.
Definition: Darwin.cpp:1464
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:1218
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:1475
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:149
ActionClass getKind() const
Definition: Action.h:148
ActionList & getInputs()
Definition: Action.h:151
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:6782
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:1630
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
Apple specific MachO extensions.
Definition: Darwin.h:295
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:2698
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific CUDA includes.
Definition: Darwin.cpp:1025
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific HIP includes.
Definition: Darwin.cpp:1030
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition: Darwin.cpp:3635
llvm::SmallString< 128 > GetEffectiveSysroot(const llvm::opt::ArgList &DriverArgs) const
Definition: Darwin.cpp:2496
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:2509
LazyDetector< RocmInstallationDetector > RocmInstallation
Definition: Darwin.h:325
LazyDetector< SYCLInstallationDetector > SYCLInstallation
Definition: Darwin.h:326
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:2589
LazyDetector< CudaInstallationDetector > CudaInstallation
}
Definition: Darwin.h:324
AppleMachO(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: Darwin.cpp:969
void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific SYCL includes.
Definition: Darwin.cpp:1035
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Add warning options that need to be passed to cc1 for this target.
Definition: Darwin.cpp:1196
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:2745
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:1541
RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const override
Definition: Darwin.cpp:1529
DarwinClang(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: Darwin.cpp:1192
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:1227
unsigned GetDefaultDwarfVersion() const override
Definition: Darwin.cpp:1304
Darwin - The base Darwin tool chain.
Definition: Darwin.h:339
VersionTuple TargetVersion
The native OS version we are targeting.
Definition: Darwin.h:367
void addPlatformVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition: Darwin.cpp:3403
bool TargetInitialized
Whether the information on the target has been initialized.
Definition: Darwin.h:346
bool isIPhoneOSVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const
Definition: Darwin.h:539
bool SupportsEmbeddedBitcode() const override
SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
Definition: Darwin.cpp:3309
void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Add any profiling runtime libraries that are needed.
Definition: Darwin.cpp:1482
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:975
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Definition: Darwin.cpp:3599
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:3087
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:1135
void CheckObjCARC() const override
Complain if this tool chain doesn't support Objective-C ARC.
Definition: Darwin.cpp:3592
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition: Darwin.cpp:3295
std::optional< DarwinSDKInfo > SDKInfo
The information about the darwin SDK that was used.
Definition: Darwin.h:372
StringRef getPlatformFamily() const
Definition: Darwin.cpp:1392
bool isSizedDeallocationUnavailable() const
Return true if c++14 sized deallocation functions are not implemented in the c++ standard library of ...
Definition: Darwin.cpp:3060
ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const override
Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
Definition: Darwin.cpp:996
bool hasBlocksRuntime() const override
Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
Definition: Darwin.cpp:1014
std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const override
Definition: Darwin.cpp:1373
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:549
bool isTargetInitialized() const
Definition: Darwin.h:528
bool isTargetAppleSiliconMac() const
Definition: Darwin.h:523
static StringRef getSDKName(StringRef isysroot)
Definition: Darwin.cpp:1412
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:3221
bool isTargetTvOSSimulator() const
Definition: Darwin.h:479
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:3165
void setTarget(DarwinPlatformKind Platform, DarwinEnvironmentKind Environment, unsigned Major, unsigned Minor, unsigned Micro, VersionTuple NativeTargetVersion) const
Definition: Darwin.h:421
bool isTargetMacCatalyst() const
Definition: Darwin.h:509
CXXStdlibType GetDefaultCXXStdlibType() const override
Definition: Darwin.cpp:990
bool isTargetWatchOSSimulator() const
Definition: Darwin.h:494
DarwinPlatformKind TargetPlatform
Definition: Darwin.h:363
StringRef getOSLibraryNameSuffix(bool IgnoreSim=false) const override
Definition: Darwin.cpp:1424
void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition: Darwin.cpp:3330
void addStartObjectFileArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition: Darwin.cpp:3569
bool isTargetWatchOSBased() const
Definition: Darwin.h:499
std::optional< llvm::Triple > TargetVariantTriple
The target variant triple that was specified (if any).
Definition: Darwin.h:375
VersionTuple getTripleTargetVersion() const
The version of the OS that's used by the OS specified in the target triple.
Definition: Darwin.h:534
bool isAlignedAllocationUnavailable() const
Return true if c++17 aligned allocation/deallocation functions are not implemented in the c++ standar...
Definition: Darwin.cpp:2963
bool isTargetIOSSimulator() const
Definition: Darwin.h:453
DarwinEnvironmentKind TargetEnvironment
Definition: Darwin.h:364
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:1108
std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const override
Definition: Darwin.cpp:1354
Tool * buildLinker() const override
Definition: Darwin.cpp:1182
Tool * buildStaticLibTool() const override
Definition: Darwin.cpp:1184
bool isTargetIOSBased() const
Is the target either iOS or an iOS simulator?
Definition: Darwin.h:200
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition: Darwin.cpp:3316
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition: Darwin.cpp:3320
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition: Darwin.h:280
Tool * getTool(Action::ActionClass AC) const override
Definition: Darwin.cpp:1163
types::ID LookupTypeForExtension(StringRef Ext) const override
LookupTypeForExtension - Return the default language type to use for the given extension.
Definition: Darwin.cpp:978
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:1321
virtual void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Darwin.h:188
virtual void addPlatformVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Darwin.h:191
UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override
How detailed should the unwind tables be by default.
Definition: Darwin.cpp:3268
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: Darwin.cpp:988
std::string GetGlobalDebugPathRemapping() const override
Add an additional -fdebug-prefix-map entry.
Definition: Darwin.cpp:3289
bool SupportsProfiling() const override
SupportsProfiling - Does this tool chain support -pg.
Definition: Darwin.cpp:3325
RuntimeLinkOptions
Options to control how a runtime library is linked.
Definition: Darwin.h:203
@ RLO_IsEmbedded
Use the embedded runtime from the macho_embedded directory.
Definition: Darwin.h:208
@ RLO_AddRPath
Emit rpaths for @executable_path as well as the resource directory.
Definition: Darwin.h:211
@ RLO_AlwaysLink
Link the library in even if it can't be found in the VFS.
Definition: Darwin.h:205
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:2947
StringRef getMachOArchName(const llvm::opt::ArgList &Args) const
Get the "MachO" arch name for a particular compiler invocation.
Definition: Darwin.cpp:1080
Tool * buildAssembler() const override
Definition: Darwin.cpp:1188
bool isPIEDefault(const llvm::opt::ArgList &Args) const override
Test whether this toolchain defaults to PIE.
Definition: Darwin.cpp:3318
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:2777
bool UseDwarfDebugFlags() const override
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition: Darwin.cpp:3283
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:43
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