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