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