Darwin.cpp 99 KB

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