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