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