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