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