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