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/Basic/VirtualFileSystem.h"
16 #include "clang/Driver/Compilation.h"
17 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Driver/SanitizerArgs.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Option/ArgList.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/ScopedPrinter.h"
25 #include "llvm/Support/TargetParser.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 /// \brief 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 /// \brief 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   // It seems that the 'e' option is completely ignored for dynamic executables
483   // (the default), and with static executables, the last one wins, as expected.
484   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
485                             options::OPT_Z_Flag, options::OPT_u_Group,
486                             options::OPT_e, options::OPT_r});
487 
488   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
489   // members of static archive libraries which implement Objective-C classes or
490   // categories.
491   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
492     CmdArgs.push_back("-ObjC");
493 
494   CmdArgs.push_back("-o");
495   CmdArgs.push_back(Output.getFilename());
496 
497   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
498     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
499 
500   // SafeStack requires its own runtime libraries
501   // These libraries should be linked first, to make sure the
502   // __safestack_init constructor executes before everything else
503   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
504     getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
505                                           "libclang_rt.safestack_osx.a",
506                                           toolchains::Darwin::RLO_AlwaysLink);
507   }
508 
509   Args.AddAllArgs(CmdArgs, options::OPT_L);
510 
511   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
512   // Build the input file for -filelist (list of linker input files) in case we
513   // need it later
514   for (const auto &II : Inputs) {
515     if (!II.isFilename()) {
516       // This is a linker input argument.
517       // We cannot mix input arguments and file names in a -filelist input, thus
518       // we prematurely stop our list (remaining files shall be passed as
519       // arguments).
520       if (InputFileList.size() > 0)
521         break;
522 
523       continue;
524     }
525 
526     InputFileList.push_back(II.getFilename());
527   }
528 
529   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
530     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
531 
532   if (isObjCRuntimeLinked(Args) &&
533       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
534     // We use arclite library for both ARC and subscripting support.
535     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
536 
537     CmdArgs.push_back("-framework");
538     CmdArgs.push_back("Foundation");
539     // Link libobj.
540     CmdArgs.push_back("-lobjc");
541   }
542 
543   if (LinkingOutput) {
544     CmdArgs.push_back("-arch_multiple");
545     CmdArgs.push_back("-final_output");
546     CmdArgs.push_back(LinkingOutput);
547   }
548 
549   if (Args.hasArg(options::OPT_fnested_functions))
550     CmdArgs.push_back("-allow_stack_execute");
551 
552   getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
553 
554   if (unsigned Parallelism =
555           getLTOParallelism(Args, getToolChain().getDriver())) {
556     CmdArgs.push_back("-mllvm");
557     CmdArgs.push_back(Args.MakeArgString("-threads=" + Twine(Parallelism)));
558   }
559 
560   if (getToolChain().ShouldLinkCXXStdlib(Args))
561     getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
562   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
563     // link_ssp spec is empty.
564 
565     // Let the tool chain choose which runtime library to link.
566     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
567 
568     // No need to do anything for pthreads. Claim argument to avoid warning.
569     Args.ClaimAllArgs(options::OPT_pthread);
570     Args.ClaimAllArgs(options::OPT_pthreads);
571   }
572 
573   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
574     // endfile_spec is empty.
575   }
576 
577   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
578   Args.AddAllArgs(CmdArgs, options::OPT_F);
579 
580   // -iframework should be forwarded as -F.
581   for (const Arg *A : Args.filtered(options::OPT_iframework))
582     CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
583 
584   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
585     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
586       if (A->getValue() == StringRef("Accelerate")) {
587         CmdArgs.push_back("-framework");
588         CmdArgs.push_back("Accelerate");
589       }
590     }
591   }
592 
593   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
594   std::unique_ptr<Command> Cmd =
595       llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
596   Cmd->setInputFileList(std::move(InputFileList));
597   C.addCommand(std::move(Cmd));
598 }
599 
600 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
601                                 const InputInfo &Output,
602                                 const InputInfoList &Inputs,
603                                 const ArgList &Args,
604                                 const char *LinkingOutput) const {
605   ArgStringList CmdArgs;
606 
607   CmdArgs.push_back("-create");
608   assert(Output.isFilename() && "Unexpected lipo output.");
609 
610   CmdArgs.push_back("-output");
611   CmdArgs.push_back(Output.getFilename());
612 
613   for (const auto &II : Inputs) {
614     assert(II.isFilename() && "Unexpected lipo input.");
615     CmdArgs.push_back(II.getFilename());
616   }
617 
618   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
619   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
620 }
621 
622 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
623                                     const InputInfo &Output,
624                                     const InputInfoList &Inputs,
625                                     const ArgList &Args,
626                                     const char *LinkingOutput) const {
627   ArgStringList CmdArgs;
628 
629   CmdArgs.push_back("-o");
630   CmdArgs.push_back(Output.getFilename());
631 
632   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
633   const InputInfo &Input = Inputs[0];
634   assert(Input.isFilename() && "Unexpected dsymutil input.");
635   CmdArgs.push_back(Input.getFilename());
636 
637   const char *Exec =
638       Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
639   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
640 }
641 
642 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
643                                        const InputInfo &Output,
644                                        const InputInfoList &Inputs,
645                                        const ArgList &Args,
646                                        const char *LinkingOutput) const {
647   ArgStringList CmdArgs;
648   CmdArgs.push_back("--verify");
649   CmdArgs.push_back("--debug-info");
650   CmdArgs.push_back("--eh-frame");
651   CmdArgs.push_back("--quiet");
652 
653   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
654   const InputInfo &Input = Inputs[0];
655   assert(Input.isFilename() && "Unexpected verify input");
656 
657   // Grabbing the output of the earlier dsymutil run.
658   CmdArgs.push_back(Input.getFilename());
659 
660   const char *Exec =
661       Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
662   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
663 }
664 
665 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
666     : ToolChain(D, Triple, Args) {
667   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
668   getProgramPaths().push_back(getDriver().getInstalledDir());
669   if (getDriver().getInstalledDir() != getDriver().Dir)
670     getProgramPaths().push_back(getDriver().Dir);
671 }
672 
673 /// Darwin - Darwin tool chain for i386 and x86_64.
674 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
675     : MachO(D, Triple, Args), TargetInitialized(false),
676       CudaInstallation(D, Triple, Args) {}
677 
678 types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
679   types::ID Ty = types::lookupTypeForExtension(Ext);
680 
681   // Darwin always preprocesses assembly files (unless -x is used explicitly).
682   if (Ty == types::TY_PP_Asm)
683     return types::TY_Asm;
684 
685   return Ty;
686 }
687 
688 bool MachO::HasNativeLLVMSupport() const { return true; }
689 
690 ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
691   // Default to use libc++ on OS X 10.9+ and iOS 7+.
692   if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
693        (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
694        isTargetWatchOSBased())
695     return ToolChain::CST_Libcxx;
696 
697   return ToolChain::CST_Libstdcxx;
698 }
699 
700 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
701 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
702   if (isTargetWatchOSBased())
703     return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
704   if (isTargetIOSBased())
705     return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
706   if (isNonFragile)
707     return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
708   return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
709 }
710 
711 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
712 bool Darwin::hasBlocksRuntime() const {
713   if (isTargetWatchOSBased())
714     return true;
715   else if (isTargetIOSBased())
716     return !isIPhoneOSVersionLT(3, 2);
717   else {
718     assert(isTargetMacOS() && "unexpected darwin target");
719     return !isMacosxVersionLT(10, 6);
720   }
721 }
722 
723 void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
724                                 ArgStringList &CC1Args) const {
725   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
726 }
727 
728 // This is just a MachO name translation routine and there's no
729 // way to join this into ARMTargetParser without breaking all
730 // other assumptions. Maybe MachO should consider standardising
731 // their nomenclature.
732 static const char *ArmMachOArchName(StringRef Arch) {
733   return llvm::StringSwitch<const char *>(Arch)
734       .Case("armv6k", "armv6")
735       .Case("armv6m", "armv6m")
736       .Case("armv5tej", "armv5")
737       .Case("xscale", "xscale")
738       .Case("armv4t", "armv4t")
739       .Case("armv7", "armv7")
740       .Cases("armv7a", "armv7-a", "armv7")
741       .Cases("armv7r", "armv7-r", "armv7")
742       .Cases("armv7em", "armv7e-m", "armv7em")
743       .Cases("armv7k", "armv7-k", "armv7k")
744       .Cases("armv7m", "armv7-m", "armv7m")
745       .Cases("armv7s", "armv7-s", "armv7s")
746       .Default(nullptr);
747 }
748 
749 static const char *ArmMachOArchNameCPU(StringRef CPU) {
750   llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
751   if (ArchKind == llvm::ARM::ArchKind::INVALID)
752     return nullptr;
753   StringRef Arch = llvm::ARM::getArchName(ArchKind);
754 
755   // FIXME: Make sure this MachO triple mangling is really necessary.
756   // ARMv5* normalises to ARMv5.
757   if (Arch.startswith("armv5"))
758     Arch = Arch.substr(0, 5);
759   // ARMv6*, except ARMv6M, normalises to ARMv6.
760   else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
761     Arch = Arch.substr(0, 5);
762   // ARMv7A normalises to ARMv7.
763   else if (Arch.endswith("v7a"))
764     Arch = Arch.substr(0, 5);
765   return Arch.data();
766 }
767 
768 StringRef MachO::getMachOArchName(const ArgList &Args) const {
769   switch (getTriple().getArch()) {
770   default:
771     return getDefaultUniversalArchName();
772 
773   case llvm::Triple::aarch64:
774     return "arm64";
775 
776   case llvm::Triple::thumb:
777   case llvm::Triple::arm:
778     if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ))
779       if (const char *Arch = ArmMachOArchName(A->getValue()))
780         return Arch;
781 
782     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
783       if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
784         return Arch;
785 
786     return "arm";
787   }
788 }
789 
790 Darwin::~Darwin() {}
791 
792 MachO::~MachO() {}
793 
794 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
795                                                 types::ID InputType) const {
796   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
797 
798   // If the target isn't initialized (e.g., an unknown Darwin platform, return
799   // the default triple).
800   if (!isTargetInitialized())
801     return Triple.getTriple();
802 
803   SmallString<16> Str;
804   if (isTargetWatchOSBased())
805     Str += "watchos";
806   else if (isTargetTvOSBased())
807     Str += "tvos";
808   else if (isTargetIOSBased())
809     Str += "ios";
810   else
811     Str += "macosx";
812   Str += getTargetVersion().getAsString();
813   Triple.setOSName(Str);
814 
815   return Triple.getTriple();
816 }
817 
818 Tool *MachO::getTool(Action::ActionClass AC) const {
819   switch (AC) {
820   case Action::LipoJobClass:
821     if (!Lipo)
822       Lipo.reset(new tools::darwin::Lipo(*this));
823     return Lipo.get();
824   case Action::DsymutilJobClass:
825     if (!Dsymutil)
826       Dsymutil.reset(new tools::darwin::Dsymutil(*this));
827     return Dsymutil.get();
828   case Action::VerifyDebugInfoJobClass:
829     if (!VerifyDebug)
830       VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
831     return VerifyDebug.get();
832   default:
833     return ToolChain::getTool(AC);
834   }
835 }
836 
837 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
838 
839 Tool *MachO::buildAssembler() const {
840   return new tools::darwin::Assembler(*this);
841 }
842 
843 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
844                          const ArgList &Args)
845     : Darwin(D, Triple, Args) {}
846 
847 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
848   // For modern targets, promote certain warnings to errors.
849   if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
850     // Always enable -Wdeprecated-objc-isa-usage and promote it
851     // to an error.
852     CC1Args.push_back("-Wdeprecated-objc-isa-usage");
853     CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
854 
855     // For iOS and watchOS, also error about implicit function declarations,
856     // as that can impact calling conventions.
857     if (!isTargetMacOS())
858       CC1Args.push_back("-Werror=implicit-function-declaration");
859   }
860 }
861 
862 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
863                                  ArgStringList &CmdArgs) const {
864   // Avoid linking compatibility stubs on i386 mac.
865   if (isTargetMacOS() && getArch() == llvm::Triple::x86)
866     return;
867 
868   ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
869 
870   if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
871       runtime.hasSubscripting())
872     return;
873 
874   CmdArgs.push_back("-force_load");
875   SmallString<128> P(getDriver().ClangExecutable);
876   llvm::sys::path::remove_filename(P); // 'clang'
877   llvm::sys::path::remove_filename(P); // 'bin'
878   llvm::sys::path::append(P, "lib", "arc", "libarclite_");
879   // Mash in the platform.
880   if (isTargetWatchOSSimulator())
881     P += "watchsimulator";
882   else if (isTargetWatchOS())
883     P += "watchos";
884   else if (isTargetTvOSSimulator())
885     P += "appletvsimulator";
886   else if (isTargetTvOS())
887     P += "appletvos";
888   else if (isTargetIOSSimulator())
889     P += "iphonesimulator";
890   else if (isTargetIPhoneOS())
891     P += "iphoneos";
892   else
893     P += "macosx";
894   P += ".a";
895 
896   CmdArgs.push_back(Args.MakeArgString(P));
897 }
898 
899 unsigned DarwinClang::GetDefaultDwarfVersion() const {
900   // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
901   if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) ||
902       (isTargetIOSBased() && isIPhoneOSVersionLT(9)))
903     return 2;
904   return 4;
905 }
906 
907 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
908                               StringRef DarwinLibName,
909                               RuntimeLinkOptions Opts) const {
910   SmallString<128> Dir(getDriver().ResourceDir);
911   llvm::sys::path::append(
912       Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin");
913 
914   SmallString<128> P(Dir);
915   llvm::sys::path::append(P, DarwinLibName);
916 
917   // For now, allow missing resource libraries to support developers who may
918   // not have compiler-rt checked out or integrated into their build (unless
919   // we explicitly force linking with this library).
920   if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) {
921     const char *LibArg = Args.MakeArgString(P);
922     if (Opts & RLO_FirstLink)
923       CmdArgs.insert(CmdArgs.begin(), LibArg);
924     else
925       CmdArgs.push_back(LibArg);
926   }
927 
928   // Adding the rpaths might negatively interact when other rpaths are involved,
929   // so we should make sure we add the rpaths last, after all user-specified
930   // rpaths. This is currently true from this place, but we need to be
931   // careful if this function is ever called before user's rpaths are emitted.
932   if (Opts & RLO_AddRPath) {
933     assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
934 
935     // Add @executable_path to rpath to support having the dylib copied with
936     // the executable.
937     CmdArgs.push_back("-rpath");
938     CmdArgs.push_back("@executable_path");
939 
940     // Add the path to the resource dir to rpath to support using the dylib
941     // from the default location without copying.
942     CmdArgs.push_back("-rpath");
943     CmdArgs.push_back(Args.MakeArgString(Dir));
944   }
945 }
946 
947 StringRef Darwin::getPlatformFamily() const {
948   switch (TargetPlatform) {
949     case DarwinPlatformKind::MacOS:
950       return "MacOSX";
951     case DarwinPlatformKind::IPhoneOS:
952       return "iPhone";
953     case DarwinPlatformKind::TvOS:
954       return "AppleTV";
955     case DarwinPlatformKind::WatchOS:
956       return "Watch";
957   }
958   llvm_unreachable("Unsupported platform");
959 }
960 
961 StringRef Darwin::getSDKName(StringRef isysroot) {
962   // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
963   llvm::sys::path::const_iterator SDKDir;
964   auto BeginSDK = llvm::sys::path::begin(isysroot);
965   auto EndSDK = llvm::sys::path::end(isysroot);
966   for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
967     StringRef SDK = *IT;
968     if (SDK.endswith(".sdk"))
969       return SDK.slice(0, SDK.size() - 4);
970   }
971   return "";
972 }
973 
974 StringRef Darwin::getOSLibraryNameSuffix() const {
975   switch(TargetPlatform) {
976   case DarwinPlatformKind::MacOS:
977     return "osx";
978   case DarwinPlatformKind::IPhoneOS:
979     return TargetEnvironment == NativeEnvironment ? "ios" : "iossim";
980   case DarwinPlatformKind::TvOS:
981     return TargetEnvironment == NativeEnvironment ? "tvos" : "tvossim";
982   case DarwinPlatformKind::WatchOS:
983     return TargetEnvironment == NativeEnvironment ? "watchos" : "watchossim";
984   }
985   llvm_unreachable("Unsupported platform");
986 }
987 
988 /// Check if the link command contains a symbol export directive.
989 static bool hasExportSymbolDirective(const ArgList &Args) {
990   for (Arg *A : Args) {
991     if (A->getOption().matches(options::OPT_exported__symbols__list))
992       return true;
993     if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
994         !A->getOption().matches(options::OPT_Xlinker))
995       continue;
996     if (A->containsValue("-exported_symbols_list") ||
997         A->containsValue("-exported_symbol"))
998       return true;
999   }
1000   return false;
1001 }
1002 
1003 /// Add an export directive for \p Symbol to the link command.
1004 static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
1005   CmdArgs.push_back("-exported_symbol");
1006   CmdArgs.push_back(Symbol);
1007 }
1008 
1009 void Darwin::addProfileRTLibs(const ArgList &Args,
1010                               ArgStringList &CmdArgs) const {
1011   if (!needsProfileRT(Args)) return;
1012 
1013   AddLinkRuntimeLib(
1014       Args, CmdArgs,
1015       (Twine("libclang_rt.profile_") + getOSLibraryNameSuffix() + ".a").str(),
1016       RuntimeLinkOptions(RLO_AlwaysLink | RLO_FirstLink));
1017 
1018   // If we have a symbol export directive and we're linking in the profile
1019   // runtime, automatically export symbols necessary to implement some of the
1020   // runtime's functionality.
1021   if (hasExportSymbolDirective(Args)) {
1022     addExportedSymbol(CmdArgs, "_VPMergeHook");
1023     addExportedSymbol(CmdArgs, "___llvm_profile_filename");
1024     addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
1025     addExportedSymbol(CmdArgs, "_lprofCurFilename");
1026   }
1027 }
1028 
1029 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1030                                           ArgStringList &CmdArgs,
1031                                           StringRef Sanitizer,
1032                                           bool Shared) const {
1033   auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1034   AddLinkRuntimeLib(Args, CmdArgs,
1035                     (Twine("libclang_rt.") + Sanitizer + "_" +
1036                      getOSLibraryNameSuffix() +
1037                      (Shared ? "_dynamic.dylib" : ".a"))
1038                         .str(),
1039                     RLO);
1040 }
1041 
1042 ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
1043     const ArgList &Args) const {
1044   if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1045     StringRef Value = A->getValue();
1046     if (Value != "compiler-rt")
1047       getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1048           << Value << "darwin";
1049   }
1050 
1051   return ToolChain::RLT_CompilerRT;
1052 }
1053 
1054 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1055                                         ArgStringList &CmdArgs) const {
1056   // Call once to ensure diagnostic is printed if wrong value was specified
1057   GetRuntimeLibType(Args);
1058 
1059   // Darwin doesn't support real static executables, don't link any runtime
1060   // libraries with -static.
1061   if (Args.hasArg(options::OPT_static) ||
1062       Args.hasArg(options::OPT_fapple_kext) ||
1063       Args.hasArg(options::OPT_mkernel))
1064     return;
1065 
1066   // Reject -static-libgcc for now, we can deal with this when and if someone
1067   // cares. This is useful in situations where someone wants to statically link
1068   // something like libstdc++, and needs its runtime support routines.
1069   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1070     getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1071     return;
1072   }
1073 
1074   const SanitizerArgs &Sanitize = getSanitizerArgs();
1075   if (Sanitize.needsAsanRt())
1076     AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1077   if (Sanitize.needsLsanRt())
1078     AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
1079   if (Sanitize.needsUbsanRt())
1080     AddLinkSanitizerLibArgs(Args, CmdArgs,
1081                             Sanitize.requiresMinimalRuntime() ? "ubsan_minimal"
1082                                                               : "ubsan",
1083                             Sanitize.needsSharedRt());
1084   if (Sanitize.needsTsanRt())
1085     AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1086   if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
1087     AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
1088 
1089     // Libfuzzer is written in C++ and requires libcxx.
1090     AddCXXStdlibLibArgs(Args, CmdArgs);
1091   }
1092   if (Sanitize.needsStatsRt()) {
1093     StringRef OS = isTargetMacOS() ? "osx" : "iossim";
1094     AddLinkRuntimeLib(Args, CmdArgs,
1095                       (Twine("libclang_rt.stats_client_") + OS + ".a").str(),
1096                       RLO_AlwaysLink);
1097     AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1098   }
1099   if (Sanitize.needsEsanRt())
1100     AddLinkSanitizerLibArgs(Args, CmdArgs, "esan");
1101 
1102   // Otherwise link libSystem, then the dynamic runtime library, and finally any
1103   // target specific static runtime library.
1104   CmdArgs.push_back("-lSystem");
1105 
1106   // Select the dynamic runtime library and the target specific static library.
1107   if (isTargetWatchOSBased()) {
1108     // We currently always need a static runtime library for watchOS.
1109     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.watchos.a");
1110   } else if (isTargetTvOSBased()) {
1111     // We currently always need a static runtime library for tvOS.
1112     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.tvos.a");
1113   } else if (isTargetIOSBased()) {
1114     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
1115     // it never went into the SDK.
1116     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
1117     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
1118         getTriple().getArch() != llvm::Triple::aarch64)
1119       CmdArgs.push_back("-lgcc_s.1");
1120 
1121     // We currently always need a static runtime library for iOS.
1122     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
1123   } else {
1124     assert(isTargetMacOS() && "unexpected non MacOS platform");
1125     // The dynamic runtime library was merged with libSystem for 10.6 and
1126     // beyond; only 10.4 and 10.5 need an additional runtime library.
1127     if (isMacosxVersionLT(10, 5))
1128       CmdArgs.push_back("-lgcc_s.10.4");
1129     else if (isMacosxVersionLT(10, 6))
1130       CmdArgs.push_back("-lgcc_s.10.5");
1131 
1132     // Originally for OS X, we thought we would only need a static runtime
1133     // library when targeting 10.4, to provide versions of the static functions
1134     // which were omitted from 10.4.dylib. This led to the creation of the 10.4
1135     // builtins library.
1136     //
1137     // Unfortunately, that turned out to not be true, because Darwin system
1138     // headers can still use eprintf on i386, and it is not exported from
1139     // libSystem. Therefore, we still must provide a runtime library just for
1140     // the tiny tiny handful of projects that *might* use that symbol.
1141     //
1142     // Then over time, we figured out it was useful to add more things to the
1143     // runtime so we created libclang_rt.osx.a to provide new functions when
1144     // deploying to old OS builds, and for a long time we had both eprintf and
1145     // osx builtin libraries. Which just seems excessive. So with PR 28855, we
1146     // are removing the eprintf library and expecting eprintf to be provided by
1147     // the OS X builtins library.
1148     if (isMacosxVersionLT(10, 5))
1149       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
1150     else
1151       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
1152   }
1153 }
1154 
1155 /// Returns the most appropriate macOS target version for the current process.
1156 ///
1157 /// If the macOS SDK version is the same or earlier than the system version,
1158 /// then the SDK version is returned. Otherwise the system version is returned.
1159 static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1160   unsigned Major, Minor, Micro;
1161   llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1162   if (!SystemTriple.isMacOSX())
1163     return MacOSSDKVersion;
1164   SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1165   VersionTuple SystemVersion(Major, Minor, Micro);
1166   bool HadExtra;
1167   if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
1168                                  HadExtra))
1169     return MacOSSDKVersion;
1170   VersionTuple SDKVersion(Major, Minor, Micro);
1171   if (SDKVersion > SystemVersion)
1172     return SystemVersion.getAsString();
1173   return MacOSSDKVersion;
1174 }
1175 
1176 namespace {
1177 
1178 /// The Darwin OS that was selected or inferred from arguments / environment.
1179 struct DarwinPlatform {
1180   enum SourceKind {
1181     /// The OS was specified using the -target argument.
1182     TargetArg,
1183     /// The OS was specified using the -m<os>-version-min argument.
1184     OSVersionArg,
1185     /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1186     DeploymentTargetEnv,
1187     /// The OS was inferred from the SDK.
1188     InferredFromSDK,
1189     /// The OS was inferred from the -arch.
1190     InferredFromArch
1191   };
1192 
1193   using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1194   using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1195 
1196   DarwinPlatformKind getPlatform() const { return Platform; }
1197 
1198   DarwinEnvironmentKind getEnvironment() const { return Environment; }
1199 
1200   void setEnvironment(DarwinEnvironmentKind Kind) {
1201     Environment = Kind;
1202     InferSimulatorFromArch = false;
1203   }
1204 
1205   StringRef getOSVersion() const {
1206     if (Kind == OSVersionArg)
1207       return Argument->getValue();
1208     return OSVersion;
1209   }
1210 
1211   void setOSVersion(StringRef S) {
1212     assert(Kind == TargetArg && "Unexpected kind!");
1213     OSVersion = S;
1214   }
1215 
1216   bool hasOSVersion() const { return HasOSVersion; }
1217 
1218   /// Returns true if the target OS was explicitly specified.
1219   bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1220 
1221   /// Returns true if the simulator environment can be inferred from the arch.
1222   bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1223 
1224   /// Adds the -m<os>-version-min argument to the compiler invocation.
1225   void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1226     if (Argument)
1227       return;
1228     assert(Kind != TargetArg && Kind != OSVersionArg && "Invalid kind");
1229     options::ID Opt;
1230     switch (Platform) {
1231     case DarwinPlatformKind::MacOS:
1232       Opt = options::OPT_mmacosx_version_min_EQ;
1233       break;
1234     case DarwinPlatformKind::IPhoneOS:
1235       Opt = options::OPT_miphoneos_version_min_EQ;
1236       break;
1237     case DarwinPlatformKind::TvOS:
1238       Opt = options::OPT_mtvos_version_min_EQ;
1239       break;
1240     case DarwinPlatformKind::WatchOS:
1241       Opt = options::OPT_mwatchos_version_min_EQ;
1242       break;
1243     }
1244     Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
1245     Args.append(Argument);
1246   }
1247 
1248   /// Returns the OS version with the argument / environment variable that
1249   /// specified it.
1250   std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1251     switch (Kind) {
1252     case TargetArg:
1253     case OSVersionArg:
1254     case InferredFromSDK:
1255     case InferredFromArch:
1256       assert(Argument && "OS version argument not yet inferred");
1257       return Argument->getAsString(Args);
1258     case DeploymentTargetEnv:
1259       return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
1260     }
1261     llvm_unreachable("Unsupported Darwin Source Kind");
1262   }
1263 
1264   static DarwinPlatform createFromTarget(const llvm::Triple &TT,
1265                                          StringRef OSVersion, Arg *A) {
1266     DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
1267                           A);
1268     switch (TT.getEnvironment()) {
1269     case llvm::Triple::Simulator:
1270       Result.Environment = DarwinEnvironmentKind::Simulator;
1271       break;
1272     default:
1273       break;
1274     }
1275     unsigned Major, Minor, Micro;
1276     TT.getOSVersion(Major, Minor, Micro);
1277     if (Major == 0)
1278       Result.HasOSVersion = false;
1279     return Result;
1280   }
1281   static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform,
1282                                            Arg *A) {
1283     return DarwinPlatform(OSVersionArg, Platform, A);
1284   }
1285   static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
1286                                                   StringRef EnvVarName,
1287                                                   StringRef Value) {
1288     DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
1289     Result.EnvVarName = EnvVarName;
1290     return Result;
1291   }
1292   static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
1293                                       StringRef Value,
1294                                       bool IsSimulator = false) {
1295     DarwinPlatform Result(InferredFromSDK, Platform, Value);
1296     if (IsSimulator)
1297       Result.Environment = DarwinEnvironmentKind::Simulator;
1298     Result.InferSimulatorFromArch = false;
1299     return Result;
1300   }
1301   static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
1302                                        StringRef Value) {
1303     return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
1304   }
1305 
1306 private:
1307   DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
1308       : Kind(Kind), Platform(Platform), Argument(Argument) {}
1309   DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
1310                  Arg *Argument = nullptr)
1311       : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
1312 
1313   static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
1314     switch (OS) {
1315     case llvm::Triple::Darwin:
1316     case llvm::Triple::MacOSX:
1317       return DarwinPlatformKind::MacOS;
1318     case llvm::Triple::IOS:
1319       return DarwinPlatformKind::IPhoneOS;
1320     case llvm::Triple::TvOS:
1321       return DarwinPlatformKind::TvOS;
1322     case llvm::Triple::WatchOS:
1323       return DarwinPlatformKind::WatchOS;
1324     default:
1325       llvm_unreachable("Unable to infer Darwin variant");
1326     }
1327   }
1328 
1329   SourceKind Kind;
1330   DarwinPlatformKind Platform;
1331   DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
1332   std::string OSVersion;
1333   bool HasOSVersion = true, InferSimulatorFromArch = true;
1334   Arg *Argument;
1335   StringRef EnvVarName;
1336 };
1337 
1338 /// Returns the deployment target that's specified using the -m<os>-version-min
1339 /// argument.
1340 Optional<DarwinPlatform>
1341 getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
1342                                     const Driver &TheDriver) {
1343   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
1344   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
1345                                     options::OPT_mios_simulator_version_min_EQ);
1346   Arg *TvOSVersion =
1347       Args.getLastArg(options::OPT_mtvos_version_min_EQ,
1348                       options::OPT_mtvos_simulator_version_min_EQ);
1349   Arg *WatchOSVersion =
1350       Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
1351                       options::OPT_mwatchos_simulator_version_min_EQ);
1352   if (OSXVersion) {
1353     if (iOSVersion || TvOSVersion || WatchOSVersion) {
1354       TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1355           << OSXVersion->getAsString(Args)
1356           << (iOSVersion ? iOSVersion
1357                          : TvOSVersion ? TvOSVersion : WatchOSVersion)
1358                  ->getAsString(Args);
1359     }
1360     return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion);
1361   } else if (iOSVersion) {
1362     if (TvOSVersion || WatchOSVersion) {
1363       TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1364           << iOSVersion->getAsString(Args)
1365           << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1366     }
1367     return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion);
1368   } else if (TvOSVersion) {
1369     if (WatchOSVersion) {
1370       TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1371           << TvOSVersion->getAsString(Args)
1372           << WatchOSVersion->getAsString(Args);
1373     }
1374     return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion);
1375   } else if (WatchOSVersion)
1376     return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion);
1377   return None;
1378 }
1379 
1380 /// Returns the deployment target that's specified using the
1381 /// OS_DEPLOYMENT_TARGET environment variable.
1382 Optional<DarwinPlatform>
1383 getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
1384                                             const llvm::Triple &Triple) {
1385   std::string Targets[Darwin::LastDarwinPlatform + 1];
1386   const char *EnvVars[] = {
1387       "MACOSX_DEPLOYMENT_TARGET",
1388       "IPHONEOS_DEPLOYMENT_TARGET",
1389       "TVOS_DEPLOYMENT_TARGET",
1390       "WATCHOS_DEPLOYMENT_TARGET",
1391   };
1392   static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1,
1393                 "Missing platform");
1394   for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) {
1395     if (char *Env = ::getenv(I.value()))
1396       Targets[I.index()] = Env;
1397   }
1398 
1399   // Do not allow conflicts with the watchOS target.
1400   if (!Targets[Darwin::WatchOS].empty() &&
1401       (!Targets[Darwin::IPhoneOS].empty() || !Targets[Darwin::TvOS].empty())) {
1402     TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1403         << "WATCHOS_DEPLOYMENT_TARGET"
1404         << (!Targets[Darwin::IPhoneOS].empty() ? "IPHONEOS_DEPLOYMENT_TARGET"
1405                                                : "TVOS_DEPLOYMENT_TARGET");
1406   }
1407 
1408   // Do not allow conflicts with the tvOS target.
1409   if (!Targets[Darwin::TvOS].empty() && !Targets[Darwin::IPhoneOS].empty()) {
1410     TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1411         << "TVOS_DEPLOYMENT_TARGET"
1412         << "IPHONEOS_DEPLOYMENT_TARGET";
1413   }
1414 
1415   // Allow conflicts among OSX and iOS for historical reasons, but choose the
1416   // default platform.
1417   if (!Targets[Darwin::MacOS].empty() &&
1418       (!Targets[Darwin::IPhoneOS].empty() ||
1419        !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) {
1420     if (Triple.getArch() == llvm::Triple::arm ||
1421         Triple.getArch() == llvm::Triple::aarch64 ||
1422         Triple.getArch() == llvm::Triple::thumb)
1423       Targets[Darwin::MacOS] = "";
1424     else
1425       Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
1426           Targets[Darwin::TvOS] = "";
1427   }
1428 
1429   for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) {
1430     if (!Target.value().empty())
1431       return DarwinPlatform::createDeploymentTargetEnv(
1432           (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
1433           Target.value());
1434   }
1435   return None;
1436 }
1437 
1438 /// Tries to infer the deployment target from the SDK specified by -isysroot
1439 /// (or SDKROOT).
1440 Optional<DarwinPlatform> inferDeploymentTargetFromSDK(DerivedArgList &Args) {
1441   const Arg *A = Args.getLastArg(options::OPT_isysroot);
1442   if (!A)
1443     return None;
1444   StringRef isysroot = A->getValue();
1445   StringRef SDK = Darwin::getSDKName(isysroot);
1446   if (!SDK.size())
1447     return None;
1448   // Slice the version number out.
1449   // Version number is between the first and the last number.
1450   size_t StartVer = SDK.find_first_of("0123456789");
1451   size_t EndVer = SDK.find_last_of("0123456789");
1452   if (StartVer != StringRef::npos && EndVer > StartVer) {
1453     StringRef Version = SDK.slice(StartVer, EndVer + 1);
1454     if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
1455       return DarwinPlatform::createFromSDK(
1456           Darwin::IPhoneOS, Version,
1457           /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
1458     else if (SDK.startswith("MacOSX"))
1459       return DarwinPlatform::createFromSDK(Darwin::MacOS,
1460                                            getSystemOrSDKMacOSVersion(Version));
1461     else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
1462       return DarwinPlatform::createFromSDK(
1463           Darwin::WatchOS, Version,
1464           /*IsSimulator=*/SDK.startswith("WatchSimulator"));
1465     else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
1466       return DarwinPlatform::createFromSDK(
1467           Darwin::TvOS, Version,
1468           /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
1469   }
1470   return None;
1471 }
1472 
1473 std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
1474                          const Driver &TheDriver) {
1475   unsigned Major, Minor, Micro;
1476   switch (OS) {
1477   case llvm::Triple::Darwin:
1478   case llvm::Triple::MacOSX:
1479     if (!Triple.getMacOSXVersion(Major, Minor, Micro))
1480       TheDriver.Diag(diag::err_drv_invalid_darwin_version)
1481           << Triple.getOSName();
1482     break;
1483   case llvm::Triple::IOS:
1484     Triple.getiOSVersion(Major, Minor, Micro);
1485     break;
1486   case llvm::Triple::TvOS:
1487     Triple.getOSVersion(Major, Minor, Micro);
1488     break;
1489   case llvm::Triple::WatchOS:
1490     Triple.getWatchOSVersion(Major, Minor, Micro);
1491     break;
1492   default:
1493     llvm_unreachable("Unexpected OS type");
1494     break;
1495   }
1496 
1497   std::string OSVersion;
1498   llvm::raw_string_ostream(OSVersion) << Major << '.' << Minor << '.' << Micro;
1499   return OSVersion;
1500 }
1501 
1502 /// Tries to infer the target OS from the -arch.
1503 Optional<DarwinPlatform>
1504 inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
1505                               const llvm::Triple &Triple,
1506                               const Driver &TheDriver) {
1507   llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
1508 
1509   StringRef MachOArchName = Toolchain.getMachOArchName(Args);
1510   if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
1511       MachOArchName == "arm64")
1512     OSTy = llvm::Triple::IOS;
1513   else if (MachOArchName == "armv7k")
1514     OSTy = llvm::Triple::WatchOS;
1515   else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
1516            MachOArchName != "armv7em")
1517     OSTy = llvm::Triple::MacOSX;
1518 
1519   if (OSTy == llvm::Triple::UnknownOS)
1520     return None;
1521   return DarwinPlatform::createFromArch(OSTy,
1522                                         getOSVersion(OSTy, Triple, TheDriver));
1523 }
1524 
1525 /// Returns the deployment target that's specified using the -target option.
1526 Optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
1527     DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver) {
1528   if (!Args.hasArg(options::OPT_target))
1529     return None;
1530   if (Triple.getOS() == llvm::Triple::Darwin ||
1531       Triple.getOS() == llvm::Triple::UnknownOS)
1532     return None;
1533   std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
1534   return DarwinPlatform::createFromTarget(Triple, OSVersion,
1535                                           Args.getLastArg(options::OPT_target));
1536 }
1537 
1538 } // namespace
1539 
1540 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
1541   const OptTable &Opts = getDriver().getOpts();
1542 
1543   // Support allowing the SDKROOT environment variable used by xcrun and other
1544   // Xcode tools to define the default sysroot, by making it the default for
1545   // isysroot.
1546   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1547     // Warn if the path does not exist.
1548     if (!getVFS().exists(A->getValue()))
1549       getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
1550   } else {
1551     if (char *env = ::getenv("SDKROOT")) {
1552       // We only use this value as the default if it is an absolute path,
1553       // exists, and it is not the root path.
1554       if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
1555           StringRef(env) != "/") {
1556         Args.append(Args.MakeSeparateArg(
1557             nullptr, Opts.getOption(options::OPT_isysroot), env));
1558       }
1559     }
1560   }
1561 
1562   // The OS and the version can be specified using the -target argument.
1563   Optional<DarwinPlatform> OSTarget =
1564       getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver());
1565   if (OSTarget) {
1566     Optional<DarwinPlatform> OSVersionArgTarget =
1567         getDeploymentTargetFromOSVersionArg(Args, getDriver());
1568     if (OSVersionArgTarget) {
1569       unsigned TargetMajor, TargetMinor, TargetMicro;
1570       bool TargetExtra;
1571       unsigned ArgMajor, ArgMinor, ArgMicro;
1572       bool ArgExtra;
1573       if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
1574           (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
1575                                      TargetMinor, TargetMicro, TargetExtra) &&
1576            Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
1577                                      ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
1578            (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
1579                 VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
1580             TargetExtra != ArgExtra))) {
1581         // Select the OS version from the -m<os>-version-min argument when
1582         // the -target does not include an OS version.
1583         if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
1584             !OSTarget->hasOSVersion()) {
1585           OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
1586         } else {
1587           // Warn about -m<os>-version-min that doesn't match the OS version
1588           // that's specified in the target.
1589           std::string OSVersionArg =
1590               OSVersionArgTarget->getAsString(Args, Opts);
1591           std::string TargetArg = OSTarget->getAsString(Args, Opts);
1592           getDriver().Diag(clang::diag::warn_drv_overriding_flag_option)
1593               << OSVersionArg << TargetArg;
1594         }
1595       }
1596     }
1597   } else {
1598     // The OS target can be specified using the -m<os>version-min argument.
1599     OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
1600     // If no deployment target was specified on the command line, check for
1601     // environment defines.
1602     if (!OSTarget) {
1603       OSTarget =
1604           getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
1605       if (OSTarget) {
1606         // Don't infer simulator from the arch when the SDK is also specified.
1607         Optional<DarwinPlatform> SDKTarget = inferDeploymentTargetFromSDK(Args);
1608         if (SDKTarget)
1609           OSTarget->setEnvironment(SDKTarget->getEnvironment());
1610       }
1611     }
1612     // If there is no command-line argument to specify the Target version and
1613     // no environment variable defined, see if we can set the default based
1614     // on -isysroot.
1615     if (!OSTarget)
1616       OSTarget = inferDeploymentTargetFromSDK(Args);
1617     // If no OS targets have been specified, try to guess platform from -target
1618     // or arch name and compute the version from the triple.
1619     if (!OSTarget)
1620       OSTarget =
1621           inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
1622   }
1623 
1624   assert(OSTarget && "Unable to infer Darwin variant");
1625   OSTarget->addOSVersionMinArgument(Args, Opts);
1626   DarwinPlatformKind Platform = OSTarget->getPlatform();
1627 
1628   unsigned Major, Minor, Micro;
1629   bool HadExtra;
1630   // Set the tool chain target information.
1631   if (Platform == MacOS) {
1632     if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1633                                    Micro, HadExtra) ||
1634         HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
1635       getDriver().Diag(diag::err_drv_invalid_version_number)
1636           << OSTarget->getAsString(Args, Opts);
1637   } else if (Platform == IPhoneOS) {
1638     if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1639                                    Micro, HadExtra) ||
1640         HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1641       getDriver().Diag(diag::err_drv_invalid_version_number)
1642           << OSTarget->getAsString(Args, Opts);
1643     ;
1644     // For 32-bit targets, the deployment target for iOS has to be earlier than
1645     // iOS 11.
1646     if (getTriple().isArch32Bit() && Major >= 11) {
1647       // If the deployment target is explicitly specified, print a diagnostic.
1648       if (OSTarget->isExplicitlySpecified()) {
1649         getDriver().Diag(diag::warn_invalid_ios_deployment_target)
1650             << OSTarget->getAsString(Args, Opts);
1651         // Otherwise, set it to 10.99.99.
1652       } else {
1653         Major = 10;
1654         Minor = 99;
1655         Micro = 99;
1656       }
1657     }
1658   } else if (Platform == TvOS) {
1659     if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1660                                    Micro, HadExtra) ||
1661         HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1662       getDriver().Diag(diag::err_drv_invalid_version_number)
1663           << OSTarget->getAsString(Args, Opts);
1664   } else if (Platform == WatchOS) {
1665     if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1666                                    Micro, HadExtra) ||
1667         HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
1668       getDriver().Diag(diag::err_drv_invalid_version_number)
1669           << OSTarget->getAsString(Args, Opts);
1670   } else
1671     llvm_unreachable("unknown kind of Darwin platform");
1672 
1673   DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
1674   // Recognize iOS targets with an x86 architecture as the iOS simulator.
1675   if (Environment == NativeEnvironment && Platform != MacOS &&
1676       OSTarget->canInferSimulatorFromArch() &&
1677       (getTriple().getArch() == llvm::Triple::x86 ||
1678        getTriple().getArch() == llvm::Triple::x86_64))
1679     Environment = Simulator;
1680 
1681   setTarget(Platform, Environment, Major, Minor, Micro);
1682 
1683   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1684     StringRef SDK = getSDKName(A->getValue());
1685     if (SDK.size() > 0) {
1686       size_t StartVer = SDK.find_first_of("0123456789");
1687       StringRef SDKName = SDK.slice(0, StartVer);
1688       if (!SDKName.startswith(getPlatformFamily()))
1689         getDriver().Diag(diag::warn_incompatible_sysroot)
1690             << SDKName << getPlatformFamily();
1691     }
1692   }
1693 }
1694 
1695 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
1696                                       ArgStringList &CmdArgs) const {
1697   CXXStdlibType Type = GetCXXStdlibType(Args);
1698 
1699   switch (Type) {
1700   case ToolChain::CST_Libcxx:
1701     CmdArgs.push_back("-lc++");
1702     break;
1703 
1704   case ToolChain::CST_Libstdcxx:
1705     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
1706     // it was previously found in the gcc lib dir. However, for all the Darwin
1707     // platforms we care about it was -lstdc++.6, so we search for that
1708     // explicitly if we can't see an obvious -lstdc++ candidate.
1709 
1710     // Check in the sysroot first.
1711     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1712       SmallString<128> P(A->getValue());
1713       llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
1714 
1715       if (!getVFS().exists(P)) {
1716         llvm::sys::path::remove_filename(P);
1717         llvm::sys::path::append(P, "libstdc++.6.dylib");
1718         if (getVFS().exists(P)) {
1719           CmdArgs.push_back(Args.MakeArgString(P));
1720           return;
1721         }
1722       }
1723     }
1724 
1725     // Otherwise, look in the root.
1726     // FIXME: This should be removed someday when we don't have to care about
1727     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
1728     if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
1729         getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
1730       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
1731       return;
1732     }
1733 
1734     // Otherwise, let the linker search.
1735     CmdArgs.push_back("-lstdc++");
1736     break;
1737   }
1738 }
1739 
1740 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
1741                                    ArgStringList &CmdArgs) const {
1742   // For Darwin platforms, use the compiler-rt-based support library
1743   // instead of the gcc-provided one (which is also incidentally
1744   // only present in the gcc lib dir, which makes it hard to find).
1745 
1746   SmallString<128> P(getDriver().ResourceDir);
1747   llvm::sys::path::append(P, "lib", "darwin");
1748 
1749   // Use the newer cc_kext for iOS ARM after 6.0.
1750   if (isTargetWatchOS()) {
1751     llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
1752   } else if (isTargetTvOS()) {
1753     llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
1754   } else if (isTargetIPhoneOS()) {
1755     llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
1756   } else {
1757     llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
1758   }
1759 
1760   // For now, allow missing resource libraries to support developers who may
1761   // not have compiler-rt checked out or integrated into their build.
1762   if (getVFS().exists(P))
1763     CmdArgs.push_back(Args.MakeArgString(P));
1764 }
1765 
1766 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
1767                                      StringRef BoundArch,
1768                                      Action::OffloadKind) const {
1769   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1770   const OptTable &Opts = getDriver().getOpts();
1771 
1772   // FIXME: We really want to get out of the tool chain level argument
1773   // translation business, as it makes the driver functionality much
1774   // more opaque. For now, we follow gcc closely solely for the
1775   // purpose of easily achieving feature parity & testability. Once we
1776   // have something that works, we should reevaluate each translation
1777   // and try to push it down into tool specific logic.
1778 
1779   for (Arg *A : Args) {
1780     if (A->getOption().matches(options::OPT_Xarch__)) {
1781       // Skip this argument unless the architecture matches either the toolchain
1782       // triple arch, or the arch being bound.
1783       llvm::Triple::ArchType XarchArch =
1784           tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
1785       if (!(XarchArch == getArch() ||
1786             (!BoundArch.empty() &&
1787              XarchArch ==
1788                  tools::darwin::getArchTypeForMachOArchName(BoundArch))))
1789         continue;
1790 
1791       Arg *OriginalArg = A;
1792       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1793       unsigned Prev = Index;
1794       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1795 
1796       // If the argument parsing failed or more than one argument was
1797       // consumed, the -Xarch_ argument's parameter tried to consume
1798       // extra arguments. Emit an error and ignore.
1799       //
1800       // We also want to disallow any options which would alter the
1801       // driver behavior; that isn't going to work in our model. We
1802       // use isDriverOption() as an approximation, although things
1803       // like -O4 are going to slip through.
1804       if (!XarchArg || Index > Prev + 1) {
1805         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1806             << A->getAsString(Args);
1807         continue;
1808       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
1809         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
1810             << A->getAsString(Args);
1811         continue;
1812       }
1813 
1814       XarchArg->setBaseArg(A);
1815 
1816       A = XarchArg.release();
1817       DAL->AddSynthesizedArg(A);
1818 
1819       // Linker input arguments require custom handling. The problem is that we
1820       // have already constructed the phase actions, so we can not treat them as
1821       // "input arguments".
1822       if (A->getOption().hasFlag(options::LinkerInput)) {
1823         // Convert the argument into individual Zlinker_input_args.
1824         for (const char *Value : A->getValues()) {
1825           DAL->AddSeparateArg(
1826               OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
1827         }
1828         continue;
1829       }
1830     }
1831 
1832     // Sob. These is strictly gcc compatible for the time being. Apple
1833     // gcc translates options twice, which means that self-expanding
1834     // options add duplicates.
1835     switch ((options::ID)A->getOption().getID()) {
1836     default:
1837       DAL->append(A);
1838       break;
1839 
1840     case options::OPT_mkernel:
1841     case options::OPT_fapple_kext:
1842       DAL->append(A);
1843       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
1844       break;
1845 
1846     case options::OPT_dependency_file:
1847       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
1848       break;
1849 
1850     case options::OPT_gfull:
1851       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
1852       DAL->AddFlagArg(
1853           A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
1854       break;
1855 
1856     case options::OPT_gused:
1857       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
1858       DAL->AddFlagArg(
1859           A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
1860       break;
1861 
1862     case options::OPT_shared:
1863       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
1864       break;
1865 
1866     case options::OPT_fconstant_cfstrings:
1867       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
1868       break;
1869 
1870     case options::OPT_fno_constant_cfstrings:
1871       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
1872       break;
1873 
1874     case options::OPT_Wnonportable_cfstrings:
1875       DAL->AddFlagArg(A,
1876                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
1877       break;
1878 
1879     case options::OPT_Wno_nonportable_cfstrings:
1880       DAL->AddFlagArg(
1881           A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
1882       break;
1883 
1884     case options::OPT_fpascal_strings:
1885       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
1886       break;
1887 
1888     case options::OPT_fno_pascal_strings:
1889       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
1890       break;
1891     }
1892   }
1893 
1894   if (getTriple().getArch() == llvm::Triple::x86 ||
1895       getTriple().getArch() == llvm::Triple::x86_64)
1896     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
1897       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
1898                         "core2");
1899 
1900   // Add the arch options based on the particular spelling of -arch, to match
1901   // how the driver driver works.
1902   if (!BoundArch.empty()) {
1903     StringRef Name = BoundArch;
1904     const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
1905     const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
1906 
1907     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
1908     // which defines the list of which architectures we accept.
1909     if (Name == "ppc")
1910       ;
1911     else if (Name == "ppc601")
1912       DAL->AddJoinedArg(nullptr, MCpu, "601");
1913     else if (Name == "ppc603")
1914       DAL->AddJoinedArg(nullptr, MCpu, "603");
1915     else if (Name == "ppc604")
1916       DAL->AddJoinedArg(nullptr, MCpu, "604");
1917     else if (Name == "ppc604e")
1918       DAL->AddJoinedArg(nullptr, MCpu, "604e");
1919     else if (Name == "ppc750")
1920       DAL->AddJoinedArg(nullptr, MCpu, "750");
1921     else if (Name == "ppc7400")
1922       DAL->AddJoinedArg(nullptr, MCpu, "7400");
1923     else if (Name == "ppc7450")
1924       DAL->AddJoinedArg(nullptr, MCpu, "7450");
1925     else if (Name == "ppc970")
1926       DAL->AddJoinedArg(nullptr, MCpu, "970");
1927 
1928     else if (Name == "ppc64" || Name == "ppc64le")
1929       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1930 
1931     else if (Name == "i386")
1932       ;
1933     else if (Name == "i486")
1934       DAL->AddJoinedArg(nullptr, MArch, "i486");
1935     else if (Name == "i586")
1936       DAL->AddJoinedArg(nullptr, MArch, "i586");
1937     else if (Name == "i686")
1938       DAL->AddJoinedArg(nullptr, MArch, "i686");
1939     else if (Name == "pentium")
1940       DAL->AddJoinedArg(nullptr, MArch, "pentium");
1941     else if (Name == "pentium2")
1942       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
1943     else if (Name == "pentpro")
1944       DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
1945     else if (Name == "pentIIm3")
1946       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
1947 
1948     else if (Name == "x86_64")
1949       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1950     else if (Name == "x86_64h") {
1951       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1952       DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
1953     }
1954 
1955     else if (Name == "arm")
1956       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
1957     else if (Name == "armv4t")
1958       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
1959     else if (Name == "armv5")
1960       DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
1961     else if (Name == "xscale")
1962       DAL->AddJoinedArg(nullptr, MArch, "xscale");
1963     else if (Name == "armv6")
1964       DAL->AddJoinedArg(nullptr, MArch, "armv6k");
1965     else if (Name == "armv6m")
1966       DAL->AddJoinedArg(nullptr, MArch, "armv6m");
1967     else if (Name == "armv7")
1968       DAL->AddJoinedArg(nullptr, MArch, "armv7a");
1969     else if (Name == "armv7em")
1970       DAL->AddJoinedArg(nullptr, MArch, "armv7em");
1971     else if (Name == "armv7k")
1972       DAL->AddJoinedArg(nullptr, MArch, "armv7k");
1973     else if (Name == "armv7m")
1974       DAL->AddJoinedArg(nullptr, MArch, "armv7m");
1975     else if (Name == "armv7s")
1976       DAL->AddJoinedArg(nullptr, MArch, "armv7s");
1977   }
1978 
1979   return DAL;
1980 }
1981 
1982 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
1983                                   ArgStringList &CmdArgs) const {
1984   // Embedded targets are simple at the moment, not supporting sanitizers and
1985   // with different libraries for each member of the product { static, PIC } x
1986   // { hard-float, soft-float }
1987   llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
1988   CompilerRT +=
1989       (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
1990           ? "hard"
1991           : "soft";
1992   CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
1993 
1994   AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
1995 }
1996 
1997 bool Darwin::isAlignedAllocationUnavailable() const {
1998   llvm::Triple::OSType OS;
1999 
2000   switch (TargetPlatform) {
2001   case MacOS: // Earlier than 10.13.
2002     OS = llvm::Triple::MacOSX;
2003     break;
2004   case IPhoneOS:
2005     OS = llvm::Triple::IOS;
2006     break;
2007   case TvOS: // Earlier than 11.0.
2008     OS = llvm::Triple::TvOS;
2009     break;
2010   case WatchOS: // Earlier than 4.0.
2011     OS = llvm::Triple::WatchOS;
2012     break;
2013   }
2014 
2015   return TargetVersion < alignedAllocMinVersion(OS);
2016 }
2017 
2018 void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
2019                                    llvm::opt::ArgStringList &CC1Args,
2020                                    Action::OffloadKind DeviceOffloadKind) const {
2021   if (isAlignedAllocationUnavailable())
2022     CC1Args.push_back("-faligned-alloc-unavailable");
2023 }
2024 
2025 DerivedArgList *
2026 Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
2027                       Action::OffloadKind DeviceOffloadKind) const {
2028   // First get the generic Apple args, before moving onto Darwin-specific ones.
2029   DerivedArgList *DAL =
2030       MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
2031   const OptTable &Opts = getDriver().getOpts();
2032 
2033   // If no architecture is bound, none of the translations here are relevant.
2034   if (BoundArch.empty())
2035     return DAL;
2036 
2037   // Add an explicit version min argument for the deployment target. We do this
2038   // after argument translation because -Xarch_ arguments may add a version min
2039   // argument.
2040   AddDeploymentTarget(*DAL);
2041 
2042   // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
2043   // FIXME: It would be far better to avoid inserting those -static arguments,
2044   // but we can't check the deployment target in the translation code until
2045   // it is set here.
2046   if (isTargetWatchOSBased() ||
2047       (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
2048     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
2049       Arg *A = *it;
2050       ++it;
2051       if (A->getOption().getID() != options::OPT_mkernel &&
2052           A->getOption().getID() != options::OPT_fapple_kext)
2053         continue;
2054       assert(it != ie && "unexpected argument translation");
2055       A = *it;
2056       assert(A->getOption().getID() == options::OPT_static &&
2057              "missing expected -static argument");
2058       *it = nullptr;
2059       ++it;
2060     }
2061   }
2062 
2063   if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
2064       GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2065     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
2066                       "libc++");
2067 
2068   // Validate the C++ standard library choice.
2069   CXXStdlibType Type = GetCXXStdlibType(*DAL);
2070   if (Type == ToolChain::CST_Libcxx) {
2071     // Check whether the target provides libc++.
2072     StringRef where;
2073 
2074     // Complain about targeting iOS < 5.0 in any way.
2075     if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
2076       where = "iOS 5.0";
2077 
2078     if (where != StringRef()) {
2079       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
2080     }
2081   }
2082 
2083   auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
2084   if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
2085     if (Args.hasFlag(options::OPT_fomit_frame_pointer,
2086                      options::OPT_fno_omit_frame_pointer, false))
2087       getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
2088           << "-fomit-frame-pointer" << BoundArch;
2089   }
2090 
2091   return DAL;
2092 }
2093 
2094 bool MachO::IsUnwindTablesDefault(const ArgList &Args) const {
2095   // Unwind tables are not emitted if -fno-exceptions is supplied (except when
2096   // targeting x86_64).
2097   return getArch() == llvm::Triple::x86_64 ||
2098          (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
2099           Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2100                        true));
2101 }
2102 
2103 bool MachO::UseDwarfDebugFlags() const {
2104   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
2105     return S[0] != '\0';
2106   return false;
2107 }
2108 
2109 llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
2110   // Darwin uses SjLj exceptions on ARM.
2111   if (getTriple().getArch() != llvm::Triple::arm &&
2112       getTriple().getArch() != llvm::Triple::thumb)
2113     return llvm::ExceptionHandling::None;
2114 
2115   // Only watchOS uses the new DWARF/Compact unwinding method.
2116   llvm::Triple Triple(ComputeLLVMTriple(Args));
2117   if(Triple.isWatchABI())
2118     return llvm::ExceptionHandling::DwarfCFI;
2119 
2120   return llvm::ExceptionHandling::SjLj;
2121 }
2122 
2123 bool Darwin::SupportsEmbeddedBitcode() const {
2124   assert(TargetInitialized && "Target not initialized!");
2125   if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
2126     return false;
2127   return true;
2128 }
2129 
2130 bool MachO::isPICDefault() const { return true; }
2131 
2132 bool MachO::isPIEDefault() const { return false; }
2133 
2134 bool MachO::isPICDefaultForced() const {
2135   return (getArch() == llvm::Triple::x86_64 ||
2136           getArch() == llvm::Triple::aarch64);
2137 }
2138 
2139 bool MachO::SupportsProfiling() const {
2140   // Profiling instrumentation is only supported on x86.
2141   return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
2142 }
2143 
2144 void Darwin::addMinVersionArgs(const ArgList &Args,
2145                                ArgStringList &CmdArgs) const {
2146   VersionTuple TargetVersion = getTargetVersion();
2147 
2148   if (isTargetWatchOS())
2149     CmdArgs.push_back("-watchos_version_min");
2150   else if (isTargetWatchOSSimulator())
2151     CmdArgs.push_back("-watchos_simulator_version_min");
2152   else if (isTargetTvOS())
2153     CmdArgs.push_back("-tvos_version_min");
2154   else if (isTargetTvOSSimulator())
2155     CmdArgs.push_back("-tvos_simulator_version_min");
2156   else if (isTargetIOSSimulator())
2157     CmdArgs.push_back("-ios_simulator_version_min");
2158   else if (isTargetIOSBased())
2159     CmdArgs.push_back("-iphoneos_version_min");
2160   else {
2161     assert(isTargetMacOS() && "unexpected target");
2162     CmdArgs.push_back("-macosx_version_min");
2163   }
2164 
2165   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2166 }
2167 
2168 void Darwin::addStartObjectFileArgs(const ArgList &Args,
2169                                     ArgStringList &CmdArgs) const {
2170   // Derived from startfile spec.
2171   if (Args.hasArg(options::OPT_dynamiclib)) {
2172     // Derived from darwin_dylib1 spec.
2173     if (isTargetWatchOSBased()) {
2174       ; // watchOS does not need dylib1.o.
2175     } else if (isTargetIOSSimulator()) {
2176       ; // iOS simulator does not need dylib1.o.
2177     } else if (isTargetIPhoneOS()) {
2178       if (isIPhoneOSVersionLT(3, 1))
2179         CmdArgs.push_back("-ldylib1.o");
2180     } else {
2181       if (isMacosxVersionLT(10, 5))
2182         CmdArgs.push_back("-ldylib1.o");
2183       else if (isMacosxVersionLT(10, 6))
2184         CmdArgs.push_back("-ldylib1.10.5.o");
2185     }
2186   } else {
2187     if (Args.hasArg(options::OPT_bundle)) {
2188       if (!Args.hasArg(options::OPT_static)) {
2189         // Derived from darwin_bundle1 spec.
2190         if (isTargetWatchOSBased()) {
2191           ; // watchOS does not need bundle1.o.
2192         } else if (isTargetIOSSimulator()) {
2193           ; // iOS simulator does not need bundle1.o.
2194         } else if (isTargetIPhoneOS()) {
2195           if (isIPhoneOSVersionLT(3, 1))
2196             CmdArgs.push_back("-lbundle1.o");
2197         } else {
2198           if (isMacosxVersionLT(10, 6))
2199             CmdArgs.push_back("-lbundle1.o");
2200         }
2201       }
2202     } else {
2203       if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
2204         if (Args.hasArg(options::OPT_static) ||
2205             Args.hasArg(options::OPT_object) ||
2206             Args.hasArg(options::OPT_preload)) {
2207           CmdArgs.push_back("-lgcrt0.o");
2208         } else {
2209           CmdArgs.push_back("-lgcrt1.o");
2210 
2211           // darwin_crt2 spec is empty.
2212         }
2213         // By default on OS X 10.8 and later, we don't link with a crt1.o
2214         // file and the linker knows to use _main as the entry point.  But,
2215         // when compiling with -pg, we need to link with the gcrt1.o file,
2216         // so pass the -no_new_main option to tell the linker to use the
2217         // "start" symbol as the entry point.
2218         if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
2219           CmdArgs.push_back("-no_new_main");
2220       } else {
2221         if (Args.hasArg(options::OPT_static) ||
2222             Args.hasArg(options::OPT_object) ||
2223             Args.hasArg(options::OPT_preload)) {
2224           CmdArgs.push_back("-lcrt0.o");
2225         } else {
2226           // Derived from darwin_crt1 spec.
2227           if (isTargetWatchOSBased()) {
2228             ; // watchOS does not need crt1.o.
2229           } else if (isTargetIOSSimulator()) {
2230             ; // iOS simulator does not need crt1.o.
2231           } else if (isTargetIPhoneOS()) {
2232             if (getArch() == llvm::Triple::aarch64)
2233               ; // iOS does not need any crt1 files for arm64
2234             else if (isIPhoneOSVersionLT(3, 1))
2235               CmdArgs.push_back("-lcrt1.o");
2236             else if (isIPhoneOSVersionLT(6, 0))
2237               CmdArgs.push_back("-lcrt1.3.1.o");
2238           } else {
2239             if (isMacosxVersionLT(10, 5))
2240               CmdArgs.push_back("-lcrt1.o");
2241             else if (isMacosxVersionLT(10, 6))
2242               CmdArgs.push_back("-lcrt1.10.5.o");
2243             else if (isMacosxVersionLT(10, 8))
2244               CmdArgs.push_back("-lcrt1.10.6.o");
2245 
2246             // darwin_crt2 spec is empty.
2247           }
2248         }
2249       }
2250     }
2251   }
2252 
2253   if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
2254       !isTargetWatchOS() &&
2255       isMacosxVersionLT(10, 5)) {
2256     const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
2257     CmdArgs.push_back(Str);
2258   }
2259 }
2260 
2261 void Darwin::CheckObjCARC() const {
2262   if (isTargetIOSBased() || isTargetWatchOSBased() ||
2263       (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
2264     return;
2265   getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
2266 }
2267 
2268 SanitizerMask Darwin::getSupportedSanitizers() const {
2269   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
2270   SanitizerMask Res = ToolChain::getSupportedSanitizers();
2271   Res |= SanitizerKind::Address;
2272   Res |= SanitizerKind::Leak;
2273   Res |= SanitizerKind::Fuzzer;
2274   Res |= SanitizerKind::FuzzerNoLink;
2275   Res |= SanitizerKind::Function;
2276   if (isTargetMacOS()) {
2277     if (!isMacosxVersionLT(10, 9))
2278       Res |= SanitizerKind::Vptr;
2279     Res |= SanitizerKind::SafeStack;
2280     if (IsX86_64)
2281       Res |= SanitizerKind::Thread;
2282   } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
2283     if (IsX86_64)
2284       Res |= SanitizerKind::Thread;
2285   }
2286   return Res;
2287 }
2288 
2289 void Darwin::printVerboseInfo(raw_ostream &OS) const {
2290   CudaInstallation.print(OS);
2291 }
2292