ToolChains.cpp 139 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816
  1. //===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "ToolChains.h"
  10. #include "clang/Basic/ObjCRuntime.h"
  11. #include "clang/Basic/Version.h"
  12. #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
  13. #include "clang/Driver/Compilation.h"
  14. #include "clang/Driver/Driver.h"
  15. #include "clang/Driver/DriverDiagnostic.h"
  16. #include "clang/Driver/Options.h"
  17. #include "clang/Driver/SanitizerArgs.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringSwitch.h"
  22. #include "llvm/Option/Arg.h"
  23. #include "llvm/Option/ArgList.h"
  24. #include "llvm/Option/OptTable.h"
  25. #include "llvm/Option/Option.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/FileSystem.h"
  28. #include "llvm/Support/MemoryBuffer.h"
  29. #include "llvm/Support/Path.h"
  30. #include "llvm/Support/Program.h"
  31. #include "llvm/Support/TargetParser.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <cstdlib> // ::getenv
  34. #include <system_error>
  35. using namespace clang::driver;
  36. using namespace clang::driver::toolchains;
  37. using namespace clang;
  38. using namespace llvm::opt;
  39. MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  40. : ToolChain(D, Triple, Args) {
  41. // We expect 'as', 'ld', etc. to be adjacent to our install dir.
  42. getProgramPaths().push_back(getDriver().getInstalledDir());
  43. if (getDriver().getInstalledDir() != getDriver().Dir)
  44. getProgramPaths().push_back(getDriver().Dir);
  45. }
  46. /// Darwin - Darwin tool chain for i386 and x86_64.
  47. Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  48. : MachO(D, Triple, Args), TargetInitialized(false) {}
  49. types::ID MachO::LookupTypeForExtension(const char *Ext) const {
  50. types::ID Ty = types::lookupTypeForExtension(Ext);
  51. // Darwin always preprocesses assembly files (unless -x is used explicitly).
  52. if (Ty == types::TY_PP_Asm)
  53. return types::TY_Asm;
  54. return Ty;
  55. }
  56. bool MachO::HasNativeLLVMSupport() const { return true; }
  57. /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
  58. ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
  59. if (isTargetIOSBased())
  60. return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
  61. if (isNonFragile)
  62. return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
  63. return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
  64. }
  65. /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
  66. bool Darwin::hasBlocksRuntime() const {
  67. if (isTargetIOSBased())
  68. return !isIPhoneOSVersionLT(3, 2);
  69. else {
  70. assert(isTargetMacOS() && "unexpected darwin target");
  71. return !isMacosxVersionLT(10, 6);
  72. }
  73. }
  74. // This is just a MachO name translation routine and there's no
  75. // way to join this into ARMTargetParser without breaking all
  76. // other assumptions. Maybe MachO should consider standardising
  77. // their nomenclature.
  78. static const char *ArmMachOArchName(StringRef Arch) {
  79. return llvm::StringSwitch<const char *>(Arch)
  80. .Case("armv6k", "armv6")
  81. .Case("armv6m", "armv6m")
  82. .Case("armv5tej", "armv5")
  83. .Case("xscale", "xscale")
  84. .Case("armv4t", "armv4t")
  85. .Case("armv7", "armv7")
  86. .Cases("armv7a", "armv7-a", "armv7")
  87. .Cases("armv7r", "armv7-r", "armv7")
  88. .Cases("armv7em", "armv7e-m", "armv7em")
  89. .Cases("armv7k", "armv7-k", "armv7k")
  90. .Cases("armv7m", "armv7-m", "armv7m")
  91. .Cases("armv7s", "armv7-s", "armv7s")
  92. .Default(nullptr);
  93. }
  94. static const char *ArmMachOArchNameCPU(StringRef CPU) {
  95. unsigned ArchKind = llvm::ARMTargetParser::parseCPUArch(CPU);
  96. if (ArchKind == llvm::ARM::AK_INVALID)
  97. return nullptr;
  98. StringRef Arch = llvm::ARMTargetParser::getArchName(ArchKind);
  99. // FIXME: Make sure this MachO triple mangling is really necessary.
  100. // ARMv5* normalises to ARMv5.
  101. if (Arch.startswith("armv5"))
  102. Arch = Arch.substr(0, 5);
  103. // ARMv6*, except ARMv6M, normalises to ARMv6.
  104. else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
  105. Arch = Arch.substr(0, 5);
  106. // ARMv7A normalises to ARMv7.
  107. else if (Arch.endswith("v7a"))
  108. Arch = Arch.substr(0, 5);
  109. return Arch.data();
  110. }
  111. static bool isSoftFloatABI(const ArgList &Args) {
  112. Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  113. options::OPT_mfloat_abi_EQ);
  114. if (!A)
  115. return false;
  116. return A->getOption().matches(options::OPT_msoft_float) ||
  117. (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
  118. A->getValue() == StringRef("soft"));
  119. }
  120. StringRef MachO::getMachOArchName(const ArgList &Args) const {
  121. switch (getTriple().getArch()) {
  122. default:
  123. return getDefaultUniversalArchName();
  124. case llvm::Triple::aarch64:
  125. return "arm64";
  126. case llvm::Triple::thumb:
  127. case llvm::Triple::arm: {
  128. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  129. if (const char *Arch = ArmMachOArchName(A->getValue()))
  130. return Arch;
  131. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  132. if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
  133. return Arch;
  134. return "arm";
  135. }
  136. }
  137. }
  138. Darwin::~Darwin() {}
  139. MachO::~MachO() {}
  140. std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args,
  141. types::ID InputType) const {
  142. llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
  143. return Triple.getTriple();
  144. }
  145. std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
  146. types::ID InputType) const {
  147. llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
  148. // If the target isn't initialized (e.g., an unknown Darwin platform, return
  149. // the default triple).
  150. if (!isTargetInitialized())
  151. return Triple.getTriple();
  152. SmallString<16> Str;
  153. Str += isTargetIOSBased() ? "ios" : "macosx";
  154. Str += getTargetVersion().getAsString();
  155. Triple.setOSName(Str);
  156. return Triple.getTriple();
  157. }
  158. void Generic_ELF::anchor() {}
  159. Tool *MachO::getTool(Action::ActionClass AC) const {
  160. switch (AC) {
  161. case Action::LipoJobClass:
  162. if (!Lipo)
  163. Lipo.reset(new tools::darwin::Lipo(*this));
  164. return Lipo.get();
  165. case Action::DsymutilJobClass:
  166. if (!Dsymutil)
  167. Dsymutil.reset(new tools::darwin::Dsymutil(*this));
  168. return Dsymutil.get();
  169. case Action::VerifyDebugInfoJobClass:
  170. if (!VerifyDebug)
  171. VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
  172. return VerifyDebug.get();
  173. default:
  174. return ToolChain::getTool(AC);
  175. }
  176. }
  177. Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
  178. Tool *MachO::buildAssembler() const {
  179. return new tools::darwin::Assembler(*this);
  180. }
  181. DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
  182. const ArgList &Args)
  183. : Darwin(D, Triple, Args) {}
  184. void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
  185. // For iOS, 64-bit, promote certain warnings to errors.
  186. if (!isTargetMacOS() && getTriple().isArch64Bit()) {
  187. // Always enable -Wdeprecated-objc-isa-usage and promote it
  188. // to an error.
  189. CC1Args.push_back("-Wdeprecated-objc-isa-usage");
  190. CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
  191. // Also error about implicit function declarations, as that
  192. // can impact calling conventions.
  193. CC1Args.push_back("-Werror=implicit-function-declaration");
  194. }
  195. }
  196. /// \brief Determine whether Objective-C automated reference counting is
  197. /// enabled.
  198. static bool isObjCAutoRefCount(const ArgList &Args) {
  199. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  200. }
  201. void DarwinClang::AddLinkARCArgs(const ArgList &Args,
  202. ArgStringList &CmdArgs) const {
  203. // Avoid linking compatibility stubs on i386 mac.
  204. if (isTargetMacOS() && getArch() == llvm::Triple::x86)
  205. return;
  206. ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
  207. if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
  208. runtime.hasSubscripting())
  209. return;
  210. CmdArgs.push_back("-force_load");
  211. SmallString<128> P(getDriver().ClangExecutable);
  212. llvm::sys::path::remove_filename(P); // 'clang'
  213. llvm::sys::path::remove_filename(P); // 'bin'
  214. llvm::sys::path::append(P, "lib", "arc", "libarclite_");
  215. // Mash in the platform.
  216. if (isTargetIOSSimulator())
  217. P += "iphonesimulator";
  218. else if (isTargetIPhoneOS())
  219. P += "iphoneos";
  220. else
  221. P += "macosx";
  222. P += ".a";
  223. CmdArgs.push_back(Args.MakeArgString(P));
  224. }
  225. void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
  226. StringRef DarwinLibName, bool AlwaysLink,
  227. bool IsEmbedded, bool AddRPath) const {
  228. SmallString<128> Dir(getDriver().ResourceDir);
  229. llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
  230. SmallString<128> P(Dir);
  231. llvm::sys::path::append(P, DarwinLibName);
  232. // For now, allow missing resource libraries to support developers who may
  233. // not have compiler-rt checked out or integrated into their build (unless
  234. // we explicitly force linking with this library).
  235. if (AlwaysLink || llvm::sys::fs::exists(P))
  236. CmdArgs.push_back(Args.MakeArgString(P));
  237. // Adding the rpaths might negatively interact when other rpaths are involved,
  238. // so we should make sure we add the rpaths last, after all user-specified
  239. // rpaths. This is currently true from this place, but we need to be
  240. // careful if this function is ever called before user's rpaths are emitted.
  241. if (AddRPath) {
  242. assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
  243. // Add @executable_path to rpath to support having the dylib copied with
  244. // the executable.
  245. CmdArgs.push_back("-rpath");
  246. CmdArgs.push_back("@executable_path");
  247. // Add the path to the resource dir to rpath to support using the dylib
  248. // from the default location without copying.
  249. CmdArgs.push_back("-rpath");
  250. CmdArgs.push_back(Args.MakeArgString(Dir));
  251. }
  252. }
  253. void Darwin::addProfileRTLibs(const ArgList &Args,
  254. ArgStringList &CmdArgs) const {
  255. if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  256. false) ||
  257. Args.hasArg(options::OPT_fprofile_generate) ||
  258. Args.hasArg(options::OPT_fprofile_generate_EQ) ||
  259. Args.hasArg(options::OPT_fprofile_instr_generate) ||
  260. Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
  261. Args.hasArg(options::OPT_fcreate_profile) ||
  262. Args.hasArg(options::OPT_coverage)))
  263. return;
  264. // Select the appropriate runtime library for the target.
  265. if (isTargetIOSBased())
  266. AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a",
  267. /*AlwaysLink*/ true);
  268. else
  269. AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a",
  270. /*AlwaysLink*/ true);
  271. }
  272. void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
  273. ArgStringList &CmdArgs,
  274. StringRef Sanitizer) const {
  275. if (!Args.hasArg(options::OPT_dynamiclib) &&
  276. !Args.hasArg(options::OPT_bundle)) {
  277. // Sanitizer runtime libraries requires C++.
  278. AddCXXStdlibLibArgs(Args, CmdArgs);
  279. }
  280. assert(isTargetMacOS() || isTargetIOSSimulator());
  281. StringRef OS = isTargetMacOS() ? "osx" : "iossim";
  282. AddLinkRuntimeLib(
  283. Args, CmdArgs,
  284. (Twine("libclang_rt.") + Sanitizer + "_" + OS + "_dynamic.dylib").str(),
  285. /*AlwaysLink*/ true, /*IsEmbedded*/ false,
  286. /*AddRPath*/ true);
  287. if (GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) {
  288. // Add explicit dependcy on -lc++abi, as -lc++ doesn't re-export
  289. // all RTTI-related symbols that UBSan uses.
  290. CmdArgs.push_back("-lc++abi");
  291. }
  292. }
  293. void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
  294. ArgStringList &CmdArgs) const {
  295. // Darwin only supports the compiler-rt based runtime libraries.
  296. switch (GetRuntimeLibType(Args)) {
  297. case ToolChain::RLT_CompilerRT:
  298. break;
  299. default:
  300. getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
  301. << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
  302. return;
  303. }
  304. // Darwin doesn't support real static executables, don't link any runtime
  305. // libraries with -static.
  306. if (Args.hasArg(options::OPT_static) ||
  307. Args.hasArg(options::OPT_fapple_kext) ||
  308. Args.hasArg(options::OPT_mkernel))
  309. return;
  310. // Reject -static-libgcc for now, we can deal with this when and if someone
  311. // cares. This is useful in situations where someone wants to statically link
  312. // something like libstdc++, and needs its runtime support routines.
  313. if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
  314. getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
  315. return;
  316. }
  317. const SanitizerArgs &Sanitize = getSanitizerArgs();
  318. if (Sanitize.needsAsanRt())
  319. AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
  320. if (Sanitize.needsUbsanRt())
  321. AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
  322. // Otherwise link libSystem, then the dynamic runtime library, and finally any
  323. // target specific static runtime library.
  324. CmdArgs.push_back("-lSystem");
  325. // Select the dynamic runtime library and the target specific static library.
  326. if (isTargetIOSBased()) {
  327. // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
  328. // it never went into the SDK.
  329. // Linking against libgcc_s.1 isn't needed for iOS 5.0+
  330. if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
  331. getTriple().getArch() != llvm::Triple::aarch64)
  332. CmdArgs.push_back("-lgcc_s.1");
  333. // We currently always need a static runtime library for iOS.
  334. AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
  335. } else {
  336. assert(isTargetMacOS() && "unexpected non MacOS platform");
  337. // The dynamic runtime library was merged with libSystem for 10.6 and
  338. // beyond; only 10.4 and 10.5 need an additional runtime library.
  339. if (isMacosxVersionLT(10, 5))
  340. CmdArgs.push_back("-lgcc_s.10.4");
  341. else if (isMacosxVersionLT(10, 6))
  342. CmdArgs.push_back("-lgcc_s.10.5");
  343. // For OS X, we thought we would only need a static runtime library when
  344. // targeting 10.4, to provide versions of the static functions which were
  345. // omitted from 10.4.dylib.
  346. //
  347. // Unfortunately, that turned out to not be true, because Darwin system
  348. // headers can still use eprintf on i386, and it is not exported from
  349. // libSystem. Therefore, we still must provide a runtime library just for
  350. // the tiny tiny handful of projects that *might* use that symbol.
  351. if (isMacosxVersionLT(10, 5)) {
  352. AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
  353. } else {
  354. if (getTriple().getArch() == llvm::Triple::x86)
  355. AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
  356. AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
  357. }
  358. }
  359. }
  360. void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
  361. const OptTable &Opts = getDriver().getOpts();
  362. // Support allowing the SDKROOT environment variable used by xcrun and other
  363. // Xcode tools to define the default sysroot, by making it the default for
  364. // isysroot.
  365. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  366. // Warn if the path does not exist.
  367. if (!llvm::sys::fs::exists(A->getValue()))
  368. getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
  369. } else {
  370. if (char *env = ::getenv("SDKROOT")) {
  371. // We only use this value as the default if it is an absolute path,
  372. // exists, and it is not the root path.
  373. if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
  374. StringRef(env) != "/") {
  375. Args.append(Args.MakeSeparateArg(
  376. nullptr, Opts.getOption(options::OPT_isysroot), env));
  377. }
  378. }
  379. }
  380. Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
  381. Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
  382. if (OSXVersion && iOSVersion) {
  383. getDriver().Diag(diag::err_drv_argument_not_allowed_with)
  384. << OSXVersion->getAsString(Args) << iOSVersion->getAsString(Args);
  385. iOSVersion = nullptr;
  386. } else if (!OSXVersion && !iOSVersion) {
  387. // If no deployment target was specified on the command line, check for
  388. // environment defines.
  389. std::string OSXTarget;
  390. std::string iOSTarget;
  391. if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
  392. OSXTarget = env;
  393. if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
  394. iOSTarget = env;
  395. // If there is no command-line argument to specify the Target version and
  396. // no environment variable defined, see if we can set the default based
  397. // on -isysroot.
  398. if (iOSTarget.empty() && OSXTarget.empty() &&
  399. Args.hasArg(options::OPT_isysroot)) {
  400. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  401. StringRef isysroot = A->getValue();
  402. // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
  403. size_t BeginSDK = isysroot.rfind("SDKs/");
  404. size_t EndSDK = isysroot.rfind(".sdk");
  405. if (BeginSDK != StringRef::npos && EndSDK != StringRef::npos) {
  406. StringRef SDK = isysroot.slice(BeginSDK + 5, EndSDK);
  407. // Slice the version number out.
  408. // Version number is between the first and the last number.
  409. size_t StartVer = SDK.find_first_of("0123456789");
  410. size_t EndVer = SDK.find_last_of("0123456789");
  411. if (StartVer != StringRef::npos && EndVer > StartVer) {
  412. StringRef Version = SDK.slice(StartVer, EndVer + 1);
  413. if (SDK.startswith("iPhoneOS") ||
  414. SDK.startswith("iPhoneSimulator"))
  415. iOSTarget = Version;
  416. else if (SDK.startswith("MacOSX"))
  417. OSXTarget = Version;
  418. }
  419. }
  420. }
  421. }
  422. // If no OSX or iOS target has been specified, try to guess platform
  423. // from arch name and compute the version from the triple.
  424. if (OSXTarget.empty() && iOSTarget.empty()) {
  425. StringRef MachOArchName = getMachOArchName(Args);
  426. unsigned Major, Minor, Micro;
  427. if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
  428. MachOArchName == "arm64") {
  429. getTriple().getiOSVersion(Major, Minor, Micro);
  430. llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
  431. << Micro;
  432. } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
  433. MachOArchName != "armv7em") {
  434. if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
  435. getDriver().Diag(diag::err_drv_invalid_darwin_version)
  436. << getTriple().getOSName();
  437. }
  438. llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
  439. << Micro;
  440. }
  441. }
  442. // Allow conflicts among OSX and iOS for historical reasons, but choose the
  443. // default platform.
  444. if (!OSXTarget.empty() && !iOSTarget.empty()) {
  445. if (getTriple().getArch() == llvm::Triple::arm ||
  446. getTriple().getArch() == llvm::Triple::aarch64 ||
  447. getTriple().getArch() == llvm::Triple::thumb)
  448. OSXTarget = "";
  449. else
  450. iOSTarget = "";
  451. }
  452. if (!OSXTarget.empty()) {
  453. const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
  454. OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
  455. Args.append(OSXVersion);
  456. } else if (!iOSTarget.empty()) {
  457. const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
  458. iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
  459. Args.append(iOSVersion);
  460. }
  461. }
  462. DarwinPlatformKind Platform;
  463. if (OSXVersion)
  464. Platform = MacOS;
  465. else if (iOSVersion)
  466. Platform = IPhoneOS;
  467. else
  468. llvm_unreachable("Unable to infer Darwin variant");
  469. // Set the tool chain target information.
  470. unsigned Major, Minor, Micro;
  471. bool HadExtra;
  472. if (Platform == MacOS) {
  473. assert(!iOSVersion && "Unknown target platform!");
  474. if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro,
  475. HadExtra) ||
  476. HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
  477. getDriver().Diag(diag::err_drv_invalid_version_number)
  478. << OSXVersion->getAsString(Args);
  479. } else if (Platform == IPhoneOS) {
  480. assert(iOSVersion && "Unknown target platform!");
  481. if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro,
  482. HadExtra) ||
  483. HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
  484. getDriver().Diag(diag::err_drv_invalid_version_number)
  485. << iOSVersion->getAsString(Args);
  486. } else
  487. llvm_unreachable("unknown kind of Darwin platform");
  488. // Recognize iOS targets with an x86 architecture as the iOS simulator.
  489. if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
  490. getTriple().getArch() == llvm::Triple::x86_64))
  491. Platform = IPhoneOSSimulator;
  492. setTarget(Platform, Major, Minor, Micro);
  493. }
  494. void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
  495. ArgStringList &CmdArgs) const {
  496. CXXStdlibType Type = GetCXXStdlibType(Args);
  497. switch (Type) {
  498. case ToolChain::CST_Libcxx:
  499. CmdArgs.push_back("-lc++");
  500. break;
  501. case ToolChain::CST_Libstdcxx: {
  502. // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
  503. // it was previously found in the gcc lib dir. However, for all the Darwin
  504. // platforms we care about it was -lstdc++.6, so we search for that
  505. // explicitly if we can't see an obvious -lstdc++ candidate.
  506. // Check in the sysroot first.
  507. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  508. SmallString<128> P(A->getValue());
  509. llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
  510. if (!llvm::sys::fs::exists(P)) {
  511. llvm::sys::path::remove_filename(P);
  512. llvm::sys::path::append(P, "libstdc++.6.dylib");
  513. if (llvm::sys::fs::exists(P)) {
  514. CmdArgs.push_back(Args.MakeArgString(P));
  515. return;
  516. }
  517. }
  518. }
  519. // Otherwise, look in the root.
  520. // FIXME: This should be removed someday when we don't have to care about
  521. // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
  522. if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
  523. llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
  524. CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
  525. return;
  526. }
  527. // Otherwise, let the linker search.
  528. CmdArgs.push_back("-lstdc++");
  529. break;
  530. }
  531. }
  532. }
  533. void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
  534. ArgStringList &CmdArgs) const {
  535. // For Darwin platforms, use the compiler-rt-based support library
  536. // instead of the gcc-provided one (which is also incidentally
  537. // only present in the gcc lib dir, which makes it hard to find).
  538. SmallString<128> P(getDriver().ResourceDir);
  539. llvm::sys::path::append(P, "lib", "darwin");
  540. // Use the newer cc_kext for iOS ARM after 6.0.
  541. if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
  542. getTriple().getArch() == llvm::Triple::aarch64 ||
  543. !isIPhoneOSVersionLT(6, 0)) {
  544. llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
  545. } else {
  546. llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
  547. }
  548. // For now, allow missing resource libraries to support developers who may
  549. // not have compiler-rt checked out or integrated into their build.
  550. if (llvm::sys::fs::exists(P))
  551. CmdArgs.push_back(Args.MakeArgString(P));
  552. }
  553. DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
  554. const char *BoundArch) const {
  555. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  556. const OptTable &Opts = getDriver().getOpts();
  557. // FIXME: We really want to get out of the tool chain level argument
  558. // translation business, as it makes the driver functionality much
  559. // more opaque. For now, we follow gcc closely solely for the
  560. // purpose of easily achieving feature parity & testability. Once we
  561. // have something that works, we should reevaluate each translation
  562. // and try to push it down into tool specific logic.
  563. for (Arg *A : Args) {
  564. if (A->getOption().matches(options::OPT_Xarch__)) {
  565. // Skip this argument unless the architecture matches either the toolchain
  566. // triple arch, or the arch being bound.
  567. llvm::Triple::ArchType XarchArch =
  568. tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
  569. if (!(XarchArch == getArch() ||
  570. (BoundArch &&
  571. XarchArch ==
  572. tools::darwin::getArchTypeForMachOArchName(BoundArch))))
  573. continue;
  574. Arg *OriginalArg = A;
  575. unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
  576. unsigned Prev = Index;
  577. std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
  578. // If the argument parsing failed or more than one argument was
  579. // consumed, the -Xarch_ argument's parameter tried to consume
  580. // extra arguments. Emit an error and ignore.
  581. //
  582. // We also want to disallow any options which would alter the
  583. // driver behavior; that isn't going to work in our model. We
  584. // use isDriverOption() as an approximation, although things
  585. // like -O4 are going to slip through.
  586. if (!XarchArg || Index > Prev + 1) {
  587. getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
  588. << A->getAsString(Args);
  589. continue;
  590. } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
  591. getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
  592. << A->getAsString(Args);
  593. continue;
  594. }
  595. XarchArg->setBaseArg(A);
  596. A = XarchArg.release();
  597. DAL->AddSynthesizedArg(A);
  598. // Linker input arguments require custom handling. The problem is that we
  599. // have already constructed the phase actions, so we can not treat them as
  600. // "input arguments".
  601. if (A->getOption().hasFlag(options::LinkerInput)) {
  602. // Convert the argument into individual Zlinker_input_args.
  603. for (const char *Value : A->getValues()) {
  604. DAL->AddSeparateArg(
  605. OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
  606. }
  607. continue;
  608. }
  609. }
  610. // Sob. These is strictly gcc compatible for the time being. Apple
  611. // gcc translates options twice, which means that self-expanding
  612. // options add duplicates.
  613. switch ((options::ID)A->getOption().getID()) {
  614. default:
  615. DAL->append(A);
  616. break;
  617. case options::OPT_mkernel:
  618. case options::OPT_fapple_kext:
  619. DAL->append(A);
  620. DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
  621. break;
  622. case options::OPT_dependency_file:
  623. DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
  624. break;
  625. case options::OPT_gfull:
  626. DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
  627. DAL->AddFlagArg(
  628. A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
  629. break;
  630. case options::OPT_gused:
  631. DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
  632. DAL->AddFlagArg(
  633. A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
  634. break;
  635. case options::OPT_shared:
  636. DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
  637. break;
  638. case options::OPT_fconstant_cfstrings:
  639. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
  640. break;
  641. case options::OPT_fno_constant_cfstrings:
  642. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
  643. break;
  644. case options::OPT_Wnonportable_cfstrings:
  645. DAL->AddFlagArg(A,
  646. Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
  647. break;
  648. case options::OPT_Wno_nonportable_cfstrings:
  649. DAL->AddFlagArg(
  650. A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
  651. break;
  652. case options::OPT_fpascal_strings:
  653. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
  654. break;
  655. case options::OPT_fno_pascal_strings:
  656. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
  657. break;
  658. }
  659. }
  660. if (getTriple().getArch() == llvm::Triple::x86 ||
  661. getTriple().getArch() == llvm::Triple::x86_64)
  662. if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
  663. DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
  664. "core2");
  665. // Add the arch options based on the particular spelling of -arch, to match
  666. // how the driver driver works.
  667. if (BoundArch) {
  668. StringRef Name = BoundArch;
  669. const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
  670. const Option MArch = Opts.getOption(options::OPT_march_EQ);
  671. // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
  672. // which defines the list of which architectures we accept.
  673. if (Name == "ppc")
  674. ;
  675. else if (Name == "ppc601")
  676. DAL->AddJoinedArg(nullptr, MCpu, "601");
  677. else if (Name == "ppc603")
  678. DAL->AddJoinedArg(nullptr, MCpu, "603");
  679. else if (Name == "ppc604")
  680. DAL->AddJoinedArg(nullptr, MCpu, "604");
  681. else if (Name == "ppc604e")
  682. DAL->AddJoinedArg(nullptr, MCpu, "604e");
  683. else if (Name == "ppc750")
  684. DAL->AddJoinedArg(nullptr, MCpu, "750");
  685. else if (Name == "ppc7400")
  686. DAL->AddJoinedArg(nullptr, MCpu, "7400");
  687. else if (Name == "ppc7450")
  688. DAL->AddJoinedArg(nullptr, MCpu, "7450");
  689. else if (Name == "ppc970")
  690. DAL->AddJoinedArg(nullptr, MCpu, "970");
  691. else if (Name == "ppc64" || Name == "ppc64le")
  692. DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
  693. else if (Name == "i386")
  694. ;
  695. else if (Name == "i486")
  696. DAL->AddJoinedArg(nullptr, MArch, "i486");
  697. else if (Name == "i586")
  698. DAL->AddJoinedArg(nullptr, MArch, "i586");
  699. else if (Name == "i686")
  700. DAL->AddJoinedArg(nullptr, MArch, "i686");
  701. else if (Name == "pentium")
  702. DAL->AddJoinedArg(nullptr, MArch, "pentium");
  703. else if (Name == "pentium2")
  704. DAL->AddJoinedArg(nullptr, MArch, "pentium2");
  705. else if (Name == "pentpro")
  706. DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
  707. else if (Name == "pentIIm3")
  708. DAL->AddJoinedArg(nullptr, MArch, "pentium2");
  709. else if (Name == "x86_64")
  710. DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
  711. else if (Name == "x86_64h") {
  712. DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
  713. DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
  714. }
  715. else if (Name == "arm")
  716. DAL->AddJoinedArg(nullptr, MArch, "armv4t");
  717. else if (Name == "armv4t")
  718. DAL->AddJoinedArg(nullptr, MArch, "armv4t");
  719. else if (Name == "armv5")
  720. DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
  721. else if (Name == "xscale")
  722. DAL->AddJoinedArg(nullptr, MArch, "xscale");
  723. else if (Name == "armv6")
  724. DAL->AddJoinedArg(nullptr, MArch, "armv6k");
  725. else if (Name == "armv6m")
  726. DAL->AddJoinedArg(nullptr, MArch, "armv6m");
  727. else if (Name == "armv7")
  728. DAL->AddJoinedArg(nullptr, MArch, "armv7a");
  729. else if (Name == "armv7em")
  730. DAL->AddJoinedArg(nullptr, MArch, "armv7em");
  731. else if (Name == "armv7k")
  732. DAL->AddJoinedArg(nullptr, MArch, "armv7k");
  733. else if (Name == "armv7m")
  734. DAL->AddJoinedArg(nullptr, MArch, "armv7m");
  735. else if (Name == "armv7s")
  736. DAL->AddJoinedArg(nullptr, MArch, "armv7s");
  737. }
  738. return DAL;
  739. }
  740. void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
  741. ArgStringList &CmdArgs) const {
  742. // Embedded targets are simple at the moment, not supporting sanitizers and
  743. // with different libraries for each member of the product { static, PIC } x
  744. // { hard-float, soft-float }
  745. llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
  746. CompilerRT +=
  747. tools::arm::getARMFloatABI(getDriver(), Args, getTriple()) == "hard"
  748. ? "hard"
  749. : "soft";
  750. CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
  751. AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
  752. }
  753. DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
  754. const char *BoundArch) const {
  755. // First get the generic Apple args, before moving onto Darwin-specific ones.
  756. DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
  757. const OptTable &Opts = getDriver().getOpts();
  758. // If no architecture is bound, none of the translations here are relevant.
  759. if (!BoundArch)
  760. return DAL;
  761. // Add an explicit version min argument for the deployment target. We do this
  762. // after argument translation because -Xarch_ arguments may add a version min
  763. // argument.
  764. AddDeploymentTarget(*DAL);
  765. // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
  766. // FIXME: It would be far better to avoid inserting those -static arguments,
  767. // but we can't check the deployment target in the translation code until
  768. // it is set here.
  769. if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0)) {
  770. for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie;) {
  771. Arg *A = *it;
  772. ++it;
  773. if (A->getOption().getID() != options::OPT_mkernel &&
  774. A->getOption().getID() != options::OPT_fapple_kext)
  775. continue;
  776. assert(it != ie && "unexpected argument translation");
  777. A = *it;
  778. assert(A->getOption().getID() == options::OPT_static &&
  779. "missing expected -static argument");
  780. it = DAL->getArgs().erase(it);
  781. }
  782. }
  783. // Default to use libc++ on OS X 10.9+ and iOS 7+.
  784. if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
  785. (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0))) &&
  786. !Args.getLastArg(options::OPT_stdlib_EQ))
  787. DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
  788. "libc++");
  789. // Validate the C++ standard library choice.
  790. CXXStdlibType Type = GetCXXStdlibType(*DAL);
  791. if (Type == ToolChain::CST_Libcxx) {
  792. // Check whether the target provides libc++.
  793. StringRef where;
  794. // Complain about targeting iOS < 5.0 in any way.
  795. if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
  796. where = "iOS 5.0";
  797. if (where != StringRef()) {
  798. getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
  799. }
  800. }
  801. return DAL;
  802. }
  803. bool MachO::IsUnwindTablesDefault() const {
  804. return getArch() == llvm::Triple::x86_64;
  805. }
  806. bool MachO::UseDwarfDebugFlags() const {
  807. if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
  808. return S[0] != '\0';
  809. return false;
  810. }
  811. bool Darwin::UseSjLjExceptions() const {
  812. // Darwin uses SjLj exceptions on ARM.
  813. return (getTriple().getArch() == llvm::Triple::arm ||
  814. getTriple().getArch() == llvm::Triple::thumb);
  815. }
  816. bool MachO::isPICDefault() const { return true; }
  817. bool MachO::isPIEDefault() const { return false; }
  818. bool MachO::isPICDefaultForced() const {
  819. return (getArch() == llvm::Triple::x86_64 ||
  820. getArch() == llvm::Triple::aarch64);
  821. }
  822. bool MachO::SupportsProfiling() const {
  823. // Profiling instrumentation is only supported on x86.
  824. return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
  825. }
  826. void Darwin::addMinVersionArgs(const ArgList &Args,
  827. ArgStringList &CmdArgs) const {
  828. VersionTuple TargetVersion = getTargetVersion();
  829. if (isTargetIOSSimulator())
  830. CmdArgs.push_back("-ios_simulator_version_min");
  831. else if (isTargetIOSBased())
  832. CmdArgs.push_back("-iphoneos_version_min");
  833. else {
  834. assert(isTargetMacOS() && "unexpected target");
  835. CmdArgs.push_back("-macosx_version_min");
  836. }
  837. CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
  838. }
  839. void Darwin::addStartObjectFileArgs(const ArgList &Args,
  840. ArgStringList &CmdArgs) const {
  841. // Derived from startfile spec.
  842. if (Args.hasArg(options::OPT_dynamiclib)) {
  843. // Derived from darwin_dylib1 spec.
  844. if (isTargetIOSSimulator()) {
  845. ; // iOS simulator does not need dylib1.o.
  846. } else if (isTargetIPhoneOS()) {
  847. if (isIPhoneOSVersionLT(3, 1))
  848. CmdArgs.push_back("-ldylib1.o");
  849. } else {
  850. if (isMacosxVersionLT(10, 5))
  851. CmdArgs.push_back("-ldylib1.o");
  852. else if (isMacosxVersionLT(10, 6))
  853. CmdArgs.push_back("-ldylib1.10.5.o");
  854. }
  855. } else {
  856. if (Args.hasArg(options::OPT_bundle)) {
  857. if (!Args.hasArg(options::OPT_static)) {
  858. // Derived from darwin_bundle1 spec.
  859. if (isTargetIOSSimulator()) {
  860. ; // iOS simulator does not need bundle1.o.
  861. } else if (isTargetIPhoneOS()) {
  862. if (isIPhoneOSVersionLT(3, 1))
  863. CmdArgs.push_back("-lbundle1.o");
  864. } else {
  865. if (isMacosxVersionLT(10, 6))
  866. CmdArgs.push_back("-lbundle1.o");
  867. }
  868. }
  869. } else {
  870. if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
  871. if (Args.hasArg(options::OPT_static) ||
  872. Args.hasArg(options::OPT_object) ||
  873. Args.hasArg(options::OPT_preload)) {
  874. CmdArgs.push_back("-lgcrt0.o");
  875. } else {
  876. CmdArgs.push_back("-lgcrt1.o");
  877. // darwin_crt2 spec is empty.
  878. }
  879. // By default on OS X 10.8 and later, we don't link with a crt1.o
  880. // file and the linker knows to use _main as the entry point. But,
  881. // when compiling with -pg, we need to link with the gcrt1.o file,
  882. // so pass the -no_new_main option to tell the linker to use the
  883. // "start" symbol as the entry point.
  884. if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
  885. CmdArgs.push_back("-no_new_main");
  886. } else {
  887. if (Args.hasArg(options::OPT_static) ||
  888. Args.hasArg(options::OPT_object) ||
  889. Args.hasArg(options::OPT_preload)) {
  890. CmdArgs.push_back("-lcrt0.o");
  891. } else {
  892. // Derived from darwin_crt1 spec.
  893. if (isTargetIOSSimulator()) {
  894. ; // iOS simulator does not need crt1.o.
  895. } else if (isTargetIPhoneOS()) {
  896. if (getArch() == llvm::Triple::aarch64)
  897. ; // iOS does not need any crt1 files for arm64
  898. else if (isIPhoneOSVersionLT(3, 1))
  899. CmdArgs.push_back("-lcrt1.o");
  900. else if (isIPhoneOSVersionLT(6, 0))
  901. CmdArgs.push_back("-lcrt1.3.1.o");
  902. } else {
  903. if (isMacosxVersionLT(10, 5))
  904. CmdArgs.push_back("-lcrt1.o");
  905. else if (isMacosxVersionLT(10, 6))
  906. CmdArgs.push_back("-lcrt1.10.5.o");
  907. else if (isMacosxVersionLT(10, 8))
  908. CmdArgs.push_back("-lcrt1.10.6.o");
  909. // darwin_crt2 spec is empty.
  910. }
  911. }
  912. }
  913. }
  914. }
  915. if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
  916. isMacosxVersionLT(10, 5)) {
  917. const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
  918. CmdArgs.push_back(Str);
  919. }
  920. }
  921. bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); }
  922. void Darwin::CheckObjCARC() const {
  923. if (isTargetIOSBased() || (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
  924. return;
  925. getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
  926. }
  927. SanitizerMask Darwin::getSupportedSanitizers() const {
  928. SanitizerMask Res = ToolChain::getSupportedSanitizers();
  929. if (isTargetMacOS() || isTargetIOSSimulator())
  930. Res |= SanitizerKind::Address;
  931. if (isTargetMacOS()) {
  932. if (!isMacosxVersionLT(10, 9))
  933. Res |= SanitizerKind::Vptr;
  934. Res |= SanitizerKind::SafeStack;
  935. }
  936. return Res;
  937. }
  938. /// Generic_GCC - A tool chain using the 'gcc' command to perform
  939. /// all subcommands; this relies on gcc translating the majority of
  940. /// command line options.
  941. /// \brief Parse a GCCVersion object out of a string of text.
  942. ///
  943. /// This is the primary means of forming GCCVersion objects.
  944. /*static*/
  945. Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
  946. const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
  947. std::pair<StringRef, StringRef> First = VersionText.split('.');
  948. std::pair<StringRef, StringRef> Second = First.second.split('.');
  949. GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
  950. if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
  951. return BadVersion;
  952. GoodVersion.MajorStr = First.first.str();
  953. if (Second.first.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
  954. return BadVersion;
  955. GoodVersion.MinorStr = Second.first.str();
  956. // First look for a number prefix and parse that if present. Otherwise just
  957. // stash the entire patch string in the suffix, and leave the number
  958. // unspecified. This covers versions strings such as:
  959. // 4.4
  960. // 4.4.0
  961. // 4.4.x
  962. // 4.4.2-rc4
  963. // 4.4.x-patched
  964. // And retains any patch number it finds.
  965. StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
  966. if (!PatchText.empty()) {
  967. if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
  968. // Try to parse the number and any suffix.
  969. if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
  970. GoodVersion.Patch < 0)
  971. return BadVersion;
  972. GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
  973. }
  974. }
  975. return GoodVersion;
  976. }
  977. /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
  978. bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
  979. int RHSPatch,
  980. StringRef RHSPatchSuffix) const {
  981. if (Major != RHSMajor)
  982. return Major < RHSMajor;
  983. if (Minor != RHSMinor)
  984. return Minor < RHSMinor;
  985. if (Patch != RHSPatch) {
  986. // Note that versions without a specified patch sort higher than those with
  987. // a patch.
  988. if (RHSPatch == -1)
  989. return true;
  990. if (Patch == -1)
  991. return false;
  992. // Otherwise just sort on the patch itself.
  993. return Patch < RHSPatch;
  994. }
  995. if (PatchSuffix != RHSPatchSuffix) {
  996. // Sort empty suffixes higher.
  997. if (RHSPatchSuffix.empty())
  998. return true;
  999. if (PatchSuffix.empty())
  1000. return false;
  1001. // Provide a lexicographic sort to make this a total ordering.
  1002. return PatchSuffix < RHSPatchSuffix;
  1003. }
  1004. // The versions are equal.
  1005. return false;
  1006. }
  1007. static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
  1008. const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
  1009. if (A)
  1010. return A->getValue();
  1011. return GCC_INSTALL_PREFIX;
  1012. }
  1013. /// \brief Initialize a GCCInstallationDetector from the driver.
  1014. ///
  1015. /// This performs all of the autodetection and sets up the various paths.
  1016. /// Once constructed, a GCCInstallationDetector is essentially immutable.
  1017. ///
  1018. /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
  1019. /// should instead pull the target out of the driver. This is currently
  1020. /// necessary because the driver doesn't store the final version of the target
  1021. /// triple.
  1022. void Generic_GCC::GCCInstallationDetector::init(
  1023. const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args) {
  1024. llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
  1025. ? TargetTriple.get64BitArchVariant()
  1026. : TargetTriple.get32BitArchVariant();
  1027. // The library directories which may contain GCC installations.
  1028. SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
  1029. // The compatible GCC triples for this particular architecture.
  1030. SmallVector<StringRef, 16> CandidateTripleAliases;
  1031. SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
  1032. CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
  1033. CandidateTripleAliases, CandidateBiarchLibDirs,
  1034. CandidateBiarchTripleAliases);
  1035. // Compute the set of prefixes for our search.
  1036. SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
  1037. D.PrefixDirs.end());
  1038. StringRef GCCToolchainDir = getGCCToolchainDir(Args);
  1039. if (GCCToolchainDir != "") {
  1040. if (GCCToolchainDir.back() == '/')
  1041. GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
  1042. Prefixes.push_back(GCCToolchainDir);
  1043. } else {
  1044. // If we have a SysRoot, try that first.
  1045. if (!D.SysRoot.empty()) {
  1046. Prefixes.push_back(D.SysRoot);
  1047. Prefixes.push_back(D.SysRoot + "/usr");
  1048. }
  1049. // Then look for gcc installed alongside clang.
  1050. Prefixes.push_back(D.InstalledDir + "/..");
  1051. // And finally in /usr.
  1052. if (D.SysRoot.empty())
  1053. Prefixes.push_back("/usr");
  1054. }
  1055. // Loop over the various components which exist and select the best GCC
  1056. // installation available. GCC installs are ranked by version number.
  1057. Version = GCCVersion::Parse("0.0.0");
  1058. for (const std::string &Prefix : Prefixes) {
  1059. if (!llvm::sys::fs::exists(Prefix))
  1060. continue;
  1061. for (const StringRef Suffix : CandidateLibDirs) {
  1062. const std::string LibDir = Prefix + Suffix.str();
  1063. if (!llvm::sys::fs::exists(LibDir))
  1064. continue;
  1065. for (const StringRef Candidate : CandidateTripleAliases)
  1066. ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
  1067. }
  1068. for (const StringRef Suffix : CandidateBiarchLibDirs) {
  1069. const std::string LibDir = Prefix + Suffix.str();
  1070. if (!llvm::sys::fs::exists(LibDir))
  1071. continue;
  1072. for (const StringRef Candidate : CandidateBiarchTripleAliases)
  1073. ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
  1074. /*NeedsBiarchSuffix=*/ true);
  1075. }
  1076. }
  1077. }
  1078. void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
  1079. for (const auto &InstallPath : CandidateGCCInstallPaths)
  1080. OS << "Found candidate GCC installation: " << InstallPath << "\n";
  1081. if (!GCCInstallPath.empty())
  1082. OS << "Selected GCC installation: " << GCCInstallPath << "\n";
  1083. for (const auto &Multilib : Multilibs)
  1084. OS << "Candidate multilib: " << Multilib << "\n";
  1085. if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
  1086. OS << "Selected multilib: " << SelectedMultilib << "\n";
  1087. }
  1088. bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
  1089. if (BiarchSibling.hasValue()) {
  1090. M = BiarchSibling.getValue();
  1091. return true;
  1092. }
  1093. return false;
  1094. }
  1095. /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
  1096. const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
  1097. SmallVectorImpl<StringRef> &LibDirs,
  1098. SmallVectorImpl<StringRef> &TripleAliases,
  1099. SmallVectorImpl<StringRef> &BiarchLibDirs,
  1100. SmallVectorImpl<StringRef> &BiarchTripleAliases) {
  1101. // Declare a bunch of static data sets that we'll select between below. These
  1102. // are specifically designed to always refer to string literals to avoid any
  1103. // lifetime or initialization issues.
  1104. static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
  1105. static const char *const AArch64Triples[] = {
  1106. "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android",
  1107. "aarch64-redhat-linux"};
  1108. static const char *const AArch64beLibDirs[] = {"/lib"};
  1109. static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
  1110. "aarch64_be-linux-gnu"};
  1111. static const char *const ARMLibDirs[] = {"/lib"};
  1112. static const char *const ARMTriples[] = {"arm-linux-gnueabi",
  1113. "arm-linux-androideabi"};
  1114. static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
  1115. "armv7hl-redhat-linux-gnueabi"};
  1116. static const char *const ARMebLibDirs[] = {"/lib"};
  1117. static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
  1118. "armeb-linux-androideabi"};
  1119. static const char *const ARMebHFTriples[] = {
  1120. "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
  1121. static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
  1122. static const char *const X86_64Triples[] = {
  1123. "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
  1124. "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
  1125. "x86_64-redhat-linux", "x86_64-suse-linux",
  1126. "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
  1127. "x86_64-slackware-linux", "x86_64-linux-android",
  1128. "x86_64-unknown-linux"};
  1129. static const char *const X32LibDirs[] = {"/libx32"};
  1130. static const char *const X86LibDirs[] = {"/lib32", "/lib"};
  1131. static const char *const X86Triples[] = {
  1132. "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu",
  1133. "i386-linux-gnu", "i386-redhat-linux6E", "i686-redhat-linux",
  1134. "i586-redhat-linux", "i386-redhat-linux", "i586-suse-linux",
  1135. "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
  1136. "i586-linux-gnu"};
  1137. static const char *const MIPSLibDirs[] = {"/lib"};
  1138. static const char *const MIPSTriples[] = {
  1139. "mips-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu"};
  1140. static const char *const MIPSELLibDirs[] = {"/lib"};
  1141. static const char *const MIPSELTriples[] = {
  1142. "mipsel-linux-gnu", "mipsel-linux-android", "mips-img-linux-gnu"};
  1143. static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
  1144. static const char *const MIPS64Triples[] = {
  1145. "mips64-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
  1146. "mips64-linux-gnuabi64"};
  1147. static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
  1148. static const char *const MIPS64ELTriples[] = {
  1149. "mips64el-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
  1150. "mips64el-linux-android", "mips64el-linux-gnuabi64"};
  1151. static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
  1152. static const char *const PPCTriples[] = {
  1153. "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
  1154. "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
  1155. static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
  1156. static const char *const PPC64Triples[] = {
  1157. "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
  1158. "powerpc64-suse-linux", "ppc64-redhat-linux"};
  1159. static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
  1160. static const char *const PPC64LETriples[] = {
  1161. "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
  1162. "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
  1163. static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
  1164. static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
  1165. "sparcv8-linux-gnu"};
  1166. static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
  1167. static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
  1168. "sparcv9-linux-gnu"};
  1169. static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
  1170. static const char *const SystemZTriples[] = {
  1171. "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
  1172. "s390x-suse-linux", "s390x-redhat-linux"};
  1173. using std::begin;
  1174. using std::end;
  1175. switch (TargetTriple.getArch()) {
  1176. case llvm::Triple::aarch64:
  1177. LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
  1178. TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
  1179. BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
  1180. BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
  1181. break;
  1182. case llvm::Triple::aarch64_be:
  1183. LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
  1184. TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
  1185. BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
  1186. BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
  1187. break;
  1188. case llvm::Triple::arm:
  1189. case llvm::Triple::thumb:
  1190. LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
  1191. if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
  1192. TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
  1193. } else {
  1194. TripleAliases.append(begin(ARMTriples), end(ARMTriples));
  1195. }
  1196. break;
  1197. case llvm::Triple::armeb:
  1198. case llvm::Triple::thumbeb:
  1199. LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
  1200. if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
  1201. TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
  1202. } else {
  1203. TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
  1204. }
  1205. break;
  1206. case llvm::Triple::x86_64:
  1207. LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
  1208. TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
  1209. // x32 is always available when x86_64 is available, so adding it as
  1210. // secondary arch with x86_64 triples
  1211. if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
  1212. BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
  1213. BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
  1214. } else {
  1215. BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
  1216. BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
  1217. }
  1218. break;
  1219. case llvm::Triple::x86:
  1220. LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
  1221. TripleAliases.append(begin(X86Triples), end(X86Triples));
  1222. BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
  1223. BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
  1224. break;
  1225. case llvm::Triple::mips:
  1226. LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
  1227. TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
  1228. BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
  1229. BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
  1230. break;
  1231. case llvm::Triple::mipsel:
  1232. LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
  1233. TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
  1234. TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
  1235. BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
  1236. BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
  1237. break;
  1238. case llvm::Triple::mips64:
  1239. LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
  1240. TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
  1241. BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
  1242. BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
  1243. break;
  1244. case llvm::Triple::mips64el:
  1245. LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
  1246. TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
  1247. BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
  1248. BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
  1249. BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
  1250. break;
  1251. case llvm::Triple::ppc:
  1252. LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
  1253. TripleAliases.append(begin(PPCTriples), end(PPCTriples));
  1254. BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
  1255. BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
  1256. break;
  1257. case llvm::Triple::ppc64:
  1258. LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
  1259. TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
  1260. BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
  1261. BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
  1262. break;
  1263. case llvm::Triple::ppc64le:
  1264. LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
  1265. TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
  1266. break;
  1267. case llvm::Triple::sparc:
  1268. LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
  1269. TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
  1270. BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
  1271. BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
  1272. break;
  1273. case llvm::Triple::sparcv9:
  1274. LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
  1275. TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
  1276. BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
  1277. BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
  1278. break;
  1279. case llvm::Triple::systemz:
  1280. LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
  1281. TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
  1282. break;
  1283. default:
  1284. // By default, just rely on the standard lib directories and the original
  1285. // triple.
  1286. break;
  1287. }
  1288. // Always append the drivers target triple to the end, in case it doesn't
  1289. // match any of our aliases.
  1290. TripleAliases.push_back(TargetTriple.str());
  1291. // Also include the multiarch variant if it's different.
  1292. if (TargetTriple.str() != BiarchTriple.str())
  1293. BiarchTripleAliases.push_back(BiarchTriple.str());
  1294. }
  1295. namespace {
  1296. // Filter to remove Multilibs that don't exist as a suffix to Path
  1297. class FilterNonExistent {
  1298. StringRef Base;
  1299. public:
  1300. FilterNonExistent(StringRef Base) : Base(Base) {}
  1301. bool operator()(const Multilib &M) {
  1302. return !llvm::sys::fs::exists(Base + M.gccSuffix() + "/crtbegin.o");
  1303. }
  1304. };
  1305. } // end anonymous namespace
  1306. static void addMultilibFlag(bool Enabled, const char *const Flag,
  1307. std::vector<std::string> &Flags) {
  1308. if (Enabled)
  1309. Flags.push_back(std::string("+") + Flag);
  1310. else
  1311. Flags.push_back(std::string("-") + Flag);
  1312. }
  1313. static bool isMipsArch(llvm::Triple::ArchType Arch) {
  1314. return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
  1315. Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
  1316. }
  1317. static bool isMips32(llvm::Triple::ArchType Arch) {
  1318. return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
  1319. }
  1320. static bool isMips64(llvm::Triple::ArchType Arch) {
  1321. return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
  1322. }
  1323. static bool isMipsEL(llvm::Triple::ArchType Arch) {
  1324. return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
  1325. }
  1326. static bool isMips16(const ArgList &Args) {
  1327. Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
  1328. return A && A->getOption().matches(options::OPT_mips16);
  1329. }
  1330. static bool isMicroMips(const ArgList &Args) {
  1331. Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
  1332. return A && A->getOption().matches(options::OPT_mmicromips);
  1333. }
  1334. struct DetectedMultilibs {
  1335. /// The set of multilibs that the detected installation supports.
  1336. MultilibSet Multilibs;
  1337. /// The primary multilib appropriate for the given flags.
  1338. Multilib SelectedMultilib;
  1339. /// On Biarch systems, this corresponds to the default multilib when
  1340. /// targeting the non-default multilib. Otherwise, it is empty.
  1341. llvm::Optional<Multilib> BiarchSibling;
  1342. };
  1343. static Multilib makeMultilib(StringRef commonSuffix) {
  1344. return Multilib(commonSuffix, commonSuffix, commonSuffix);
  1345. }
  1346. static bool findMIPSMultilibs(const llvm::Triple &TargetTriple, StringRef Path,
  1347. const ArgList &Args, DetectedMultilibs &Result) {
  1348. // Some MIPS toolchains put libraries and object files compiled
  1349. // using different options in to the sub-directoris which names
  1350. // reflects the flags used for compilation. For example sysroot
  1351. // directory might looks like the following examples:
  1352. //
  1353. // /usr
  1354. // /lib <= crt*.o files compiled with '-mips32'
  1355. // /mips16
  1356. // /usr
  1357. // /lib <= crt*.o files compiled with '-mips16'
  1358. // /el
  1359. // /usr
  1360. // /lib <= crt*.o files compiled with '-mips16 -EL'
  1361. //
  1362. // or
  1363. //
  1364. // /usr
  1365. // /lib <= crt*.o files compiled with '-mips32r2'
  1366. // /mips16
  1367. // /usr
  1368. // /lib <= crt*.o files compiled with '-mips32r2 -mips16'
  1369. // /mips32
  1370. // /usr
  1371. // /lib <= crt*.o files compiled with '-mips32'
  1372. FilterNonExistent NonExistent(Path);
  1373. // Check for FSF toolchain multilibs
  1374. MultilibSet FSFMipsMultilibs;
  1375. {
  1376. auto MArchMips32 = makeMultilib("/mips32")
  1377. .flag("+m32")
  1378. .flag("-m64")
  1379. .flag("-mmicromips")
  1380. .flag("+march=mips32");
  1381. auto MArchMicroMips = makeMultilib("/micromips")
  1382. .flag("+m32")
  1383. .flag("-m64")
  1384. .flag("+mmicromips");
  1385. auto MArchMips64r2 = makeMultilib("/mips64r2")
  1386. .flag("-m32")
  1387. .flag("+m64")
  1388. .flag("+march=mips64r2");
  1389. auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
  1390. "-march=mips64r2");
  1391. auto MArchDefault = makeMultilib("")
  1392. .flag("+m32")
  1393. .flag("-m64")
  1394. .flag("-mmicromips")
  1395. .flag("+march=mips32r2");
  1396. auto Mips16 = makeMultilib("/mips16").flag("+mips16");
  1397. auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
  1398. auto MAbi64 =
  1399. makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
  1400. auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
  1401. auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
  1402. auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
  1403. auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
  1404. FSFMipsMultilibs =
  1405. MultilibSet()
  1406. .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
  1407. MArchDefault)
  1408. .Maybe(UCLibc)
  1409. .Maybe(Mips16)
  1410. .FilterOut("/mips64/mips16")
  1411. .FilterOut("/mips64r2/mips16")
  1412. .FilterOut("/micromips/mips16")
  1413. .Maybe(MAbi64)
  1414. .FilterOut("/micromips/64")
  1415. .FilterOut("/mips32/64")
  1416. .FilterOut("^/64")
  1417. .FilterOut("/mips16/64")
  1418. .Either(BigEndian, LittleEndian)
  1419. .Maybe(SoftFloat)
  1420. .Maybe(Nan2008)
  1421. .FilterOut(".*sof/nan2008")
  1422. .FilterOut(NonExistent)
  1423. .setIncludeDirsCallback([](StringRef InstallDir,
  1424. StringRef TripleStr, const Multilib &M) {
  1425. std::vector<std::string> Dirs;
  1426. Dirs.push_back((InstallDir + "/include").str());
  1427. std::string SysRootInc =
  1428. InstallDir.str() + "/../../../../sysroot";
  1429. if (StringRef(M.includeSuffix()).startswith("/uclibc"))
  1430. Dirs.push_back(SysRootInc + "/uclibc/usr/include");
  1431. else
  1432. Dirs.push_back(SysRootInc + "/usr/include");
  1433. return Dirs;
  1434. });
  1435. }
  1436. // Check for Code Sourcery toolchain multilibs
  1437. MultilibSet CSMipsMultilibs;
  1438. {
  1439. auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
  1440. auto MArchMicroMips =
  1441. makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
  1442. auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
  1443. auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
  1444. auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
  1445. auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
  1446. auto DefaultFloat =
  1447. makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
  1448. auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
  1449. auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
  1450. // Note that this one's osSuffix is ""
  1451. auto MAbi64 = makeMultilib("")
  1452. .gccSuffix("/64")
  1453. .includeSuffix("/64")
  1454. .flag("+mabi=n64")
  1455. .flag("-mabi=n32")
  1456. .flag("-m32");
  1457. CSMipsMultilibs =
  1458. MultilibSet()
  1459. .Either(MArchMips16, MArchMicroMips, MArchDefault)
  1460. .Maybe(UCLibc)
  1461. .Either(SoftFloat, Nan2008, DefaultFloat)
  1462. .FilterOut("/micromips/nan2008")
  1463. .FilterOut("/mips16/nan2008")
  1464. .Either(BigEndian, LittleEndian)
  1465. .Maybe(MAbi64)
  1466. .FilterOut("/mips16.*/64")
  1467. .FilterOut("/micromips.*/64")
  1468. .FilterOut(NonExistent)
  1469. .setIncludeDirsCallback([](StringRef InstallDir,
  1470. StringRef TripleStr, const Multilib &M) {
  1471. std::vector<std::string> Dirs;
  1472. Dirs.push_back((InstallDir + "/include").str());
  1473. std::string SysRootInc =
  1474. InstallDir.str() + "/../../../../" + TripleStr.str();
  1475. if (StringRef(M.includeSuffix()).startswith("/uclibc"))
  1476. Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
  1477. else
  1478. Dirs.push_back(SysRootInc + "/libc/usr/include");
  1479. return Dirs;
  1480. });
  1481. }
  1482. MultilibSet AndroidMipsMultilibs =
  1483. MultilibSet()
  1484. .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
  1485. .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
  1486. .FilterOut(NonExistent);
  1487. MultilibSet DebianMipsMultilibs;
  1488. {
  1489. Multilib MAbiN32 =
  1490. Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
  1491. Multilib M64 = Multilib()
  1492. .gccSuffix("/64")
  1493. .includeSuffix("/64")
  1494. .flag("+m64")
  1495. .flag("-m32")
  1496. .flag("-mabi=n32");
  1497. Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
  1498. DebianMipsMultilibs =
  1499. MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
  1500. }
  1501. MultilibSet ImgMultilibs;
  1502. {
  1503. auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
  1504. auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
  1505. auto MAbi64 =
  1506. makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
  1507. ImgMultilibs =
  1508. MultilibSet()
  1509. .Maybe(Mips64r6)
  1510. .Maybe(MAbi64)
  1511. .Maybe(LittleEndian)
  1512. .FilterOut(NonExistent)
  1513. .setIncludeDirsCallback([](StringRef InstallDir,
  1514. StringRef TripleStr, const Multilib &M) {
  1515. std::vector<std::string> Dirs;
  1516. Dirs.push_back((InstallDir + "/include").str());
  1517. Dirs.push_back(
  1518. (InstallDir + "/../../../../sysroot/usr/include").str());
  1519. return Dirs;
  1520. });
  1521. }
  1522. StringRef CPUName;
  1523. StringRef ABIName;
  1524. tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
  1525. llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
  1526. Multilib::flags_list Flags;
  1527. addMultilibFlag(isMips32(TargetArch), "m32", Flags);
  1528. addMultilibFlag(isMips64(TargetArch), "m64", Flags);
  1529. addMultilibFlag(isMips16(Args), "mips16", Flags);
  1530. addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
  1531. addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
  1532. CPUName == "mips32r5",
  1533. "march=mips32r2", Flags);
  1534. addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
  1535. addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
  1536. addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
  1537. CPUName == "mips64r5" || CPUName == "octeon",
  1538. "march=mips64r2", Flags);
  1539. addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
  1540. addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
  1541. addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
  1542. Flags);
  1543. addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
  1544. addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
  1545. addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
  1546. addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
  1547. addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
  1548. addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
  1549. if (TargetTriple.getEnvironment() == llvm::Triple::Android) {
  1550. // Select Android toolchain. It's the only choice in that case.
  1551. if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
  1552. Result.Multilibs = AndroidMipsMultilibs;
  1553. return true;
  1554. }
  1555. return false;
  1556. }
  1557. if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  1558. TargetTriple.getOS() == llvm::Triple::Linux &&
  1559. TargetTriple.getEnvironment() == llvm::Triple::GNU) {
  1560. // Select mips-img-linux-gnu toolchain.
  1561. if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
  1562. Result.Multilibs = ImgMultilibs;
  1563. return true;
  1564. }
  1565. return false;
  1566. }
  1567. // Sort candidates. Toolchain that best meets the directories goes first.
  1568. // Then select the first toolchains matches command line flags.
  1569. MultilibSet *candidates[] = {&DebianMipsMultilibs, &FSFMipsMultilibs,
  1570. &CSMipsMultilibs};
  1571. std::sort(
  1572. std::begin(candidates), std::end(candidates),
  1573. [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
  1574. for (const auto &candidate : candidates) {
  1575. if (candidate->select(Flags, Result.SelectedMultilib)) {
  1576. if (candidate == &DebianMipsMultilibs)
  1577. Result.BiarchSibling = Multilib();
  1578. Result.Multilibs = *candidate;
  1579. return true;
  1580. }
  1581. }
  1582. {
  1583. // Fallback to the regular toolchain-tree structure.
  1584. Multilib Default;
  1585. Result.Multilibs.push_back(Default);
  1586. Result.Multilibs.FilterOut(NonExistent);
  1587. if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
  1588. Result.BiarchSibling = Multilib();
  1589. return true;
  1590. }
  1591. }
  1592. return false;
  1593. }
  1594. static bool findBiarchMultilibs(const llvm::Triple &TargetTriple,
  1595. StringRef Path, const ArgList &Args,
  1596. bool NeedsBiarchSuffix,
  1597. DetectedMultilibs &Result) {
  1598. // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
  1599. // in what would normally be GCCInstallPath and put the 64-bit
  1600. // libs in a subdirectory named 64. The simple logic we follow is that
  1601. // *if* there is a subdirectory of the right name with crtbegin.o in it,
  1602. // we use that. If not, and if not a biarch triple alias, we look for
  1603. // crtbegin.o without the subdirectory.
  1604. Multilib Default;
  1605. Multilib Alt64 = Multilib()
  1606. .gccSuffix("/64")
  1607. .includeSuffix("/64")
  1608. .flag("-m32")
  1609. .flag("+m64")
  1610. .flag("-mx32");
  1611. Multilib Alt32 = Multilib()
  1612. .gccSuffix("/32")
  1613. .includeSuffix("/32")
  1614. .flag("+m32")
  1615. .flag("-m64")
  1616. .flag("-mx32");
  1617. Multilib Altx32 = Multilib()
  1618. .gccSuffix("/x32")
  1619. .includeSuffix("/x32")
  1620. .flag("-m32")
  1621. .flag("-m64")
  1622. .flag("+mx32");
  1623. FilterNonExistent NonExistent(Path);
  1624. // Determine default multilib from: 32, 64, x32
  1625. // Also handle cases such as 64 on 32, 32 on 64, etc.
  1626. enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
  1627. const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
  1628. if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
  1629. Want = WANT64;
  1630. else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
  1631. Want = WANT64;
  1632. else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
  1633. Want = WANT32;
  1634. else {
  1635. if (TargetTriple.isArch32Bit())
  1636. Want = NeedsBiarchSuffix ? WANT64 : WANT32;
  1637. else if (IsX32)
  1638. Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
  1639. else
  1640. Want = NeedsBiarchSuffix ? WANT32 : WANT64;
  1641. }
  1642. if (Want == WANT32)
  1643. Default.flag("+m32").flag("-m64").flag("-mx32");
  1644. else if (Want == WANT64)
  1645. Default.flag("-m32").flag("+m64").flag("-mx32");
  1646. else if (Want == WANTX32)
  1647. Default.flag("-m32").flag("-m64").flag("+mx32");
  1648. else
  1649. return false;
  1650. Result.Multilibs.push_back(Default);
  1651. Result.Multilibs.push_back(Alt64);
  1652. Result.Multilibs.push_back(Alt32);
  1653. Result.Multilibs.push_back(Altx32);
  1654. Result.Multilibs.FilterOut(NonExistent);
  1655. Multilib::flags_list Flags;
  1656. addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
  1657. addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
  1658. addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
  1659. if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
  1660. return false;
  1661. if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
  1662. Result.SelectedMultilib == Altx32)
  1663. Result.BiarchSibling = Default;
  1664. return true;
  1665. }
  1666. void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
  1667. const llvm::Triple &TargetTriple, const ArgList &Args,
  1668. const std::string &LibDir, StringRef CandidateTriple,
  1669. bool NeedsBiarchSuffix) {
  1670. llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
  1671. // There are various different suffixes involving the triple we
  1672. // check for. We also record what is necessary to walk from each back
  1673. // up to the lib directory.
  1674. const std::string LibSuffixes[] = {
  1675. "/gcc/" + CandidateTriple.str(),
  1676. // Debian puts cross-compilers in gcc-cross
  1677. "/gcc-cross/" + CandidateTriple.str(),
  1678. "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
  1679. // The Freescale PPC SDK has the gcc libraries in
  1680. // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
  1681. "/" + CandidateTriple.str(),
  1682. // Ubuntu has a strange mis-matched pair of triples that this happens to
  1683. // match.
  1684. // FIXME: It may be worthwhile to generalize this and look for a second
  1685. // triple.
  1686. "/i386-linux-gnu/gcc/" + CandidateTriple.str()};
  1687. const std::string InstallSuffixes[] = {
  1688. "/../../..", // gcc/
  1689. "/../../..", // gcc-cross/
  1690. "/../../../..", // <triple>/gcc/
  1691. "/../..", // <triple>/
  1692. "/../../../.." // i386-linux-gnu/gcc/<triple>/
  1693. };
  1694. // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
  1695. const unsigned NumLibSuffixes =
  1696. (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
  1697. for (unsigned i = 0; i < NumLibSuffixes; ++i) {
  1698. StringRef LibSuffix = LibSuffixes[i];
  1699. std::error_code EC;
  1700. for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
  1701. !EC && LI != LE; LI = LI.increment(EC)) {
  1702. StringRef VersionText = llvm::sys::path::filename(LI->path());
  1703. GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
  1704. if (CandidateVersion.Major != -1) // Filter obviously bad entries.
  1705. if (!CandidateGCCInstallPaths.insert(LI->path()).second)
  1706. continue; // Saw this path before; no need to look at it again.
  1707. if (CandidateVersion.isOlderThan(4, 1, 1))
  1708. continue;
  1709. if (CandidateVersion <= Version)
  1710. continue;
  1711. DetectedMultilibs Detected;
  1712. // Debian mips multilibs behave more like the rest of the biarch ones,
  1713. // so handle them there
  1714. if (isMipsArch(TargetArch)) {
  1715. if (!findMIPSMultilibs(TargetTriple, LI->path(), Args, Detected))
  1716. continue;
  1717. } else if (!findBiarchMultilibs(TargetTriple, LI->path(), Args,
  1718. NeedsBiarchSuffix, Detected)) {
  1719. continue;
  1720. }
  1721. Multilibs = Detected.Multilibs;
  1722. SelectedMultilib = Detected.SelectedMultilib;
  1723. BiarchSibling = Detected.BiarchSibling;
  1724. Version = CandidateVersion;
  1725. GCCTriple.setTriple(CandidateTriple);
  1726. // FIXME: We hack together the directory name here instead of
  1727. // using LI to ensure stable path separators across Windows and
  1728. // Linux.
  1729. GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
  1730. GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
  1731. IsValid = true;
  1732. }
  1733. }
  1734. }
  1735. Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
  1736. const ArgList &Args)
  1737. : ToolChain(D, Triple, Args), GCCInstallation() {
  1738. getProgramPaths().push_back(getDriver().getInstalledDir());
  1739. if (getDriver().getInstalledDir() != getDriver().Dir)
  1740. getProgramPaths().push_back(getDriver().Dir);
  1741. }
  1742. Generic_GCC::~Generic_GCC() {}
  1743. Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
  1744. switch (AC) {
  1745. case Action::PreprocessJobClass:
  1746. if (!Preprocess)
  1747. Preprocess.reset(new tools::gcc::Preprocessor(*this));
  1748. return Preprocess.get();
  1749. case Action::CompileJobClass:
  1750. if (!Compile)
  1751. Compile.reset(new tools::gcc::Compiler(*this));
  1752. return Compile.get();
  1753. default:
  1754. return ToolChain::getTool(AC);
  1755. }
  1756. }
  1757. Tool *Generic_GCC::buildAssembler() const {
  1758. return new tools::gnutools::Assembler(*this);
  1759. }
  1760. Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
  1761. void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
  1762. // Print the information about how we detected the GCC installation.
  1763. GCCInstallation.print(OS);
  1764. }
  1765. bool Generic_GCC::IsUnwindTablesDefault() const {
  1766. return getArch() == llvm::Triple::x86_64;
  1767. }
  1768. bool Generic_GCC::isPICDefault() const {
  1769. return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
  1770. }
  1771. bool Generic_GCC::isPIEDefault() const { return false; }
  1772. bool Generic_GCC::isPICDefaultForced() const {
  1773. return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
  1774. }
  1775. bool Generic_GCC::IsIntegratedAssemblerDefault() const {
  1776. switch (getTriple().getArch()) {
  1777. case llvm::Triple::x86:
  1778. case llvm::Triple::x86_64:
  1779. case llvm::Triple::aarch64:
  1780. case llvm::Triple::aarch64_be:
  1781. case llvm::Triple::arm:
  1782. case llvm::Triple::armeb:
  1783. case llvm::Triple::bpfel:
  1784. case llvm::Triple::bpfeb:
  1785. case llvm::Triple::thumb:
  1786. case llvm::Triple::thumbeb:
  1787. case llvm::Triple::ppc:
  1788. case llvm::Triple::ppc64:
  1789. case llvm::Triple::ppc64le:
  1790. case llvm::Triple::sparc:
  1791. case llvm::Triple::sparcel:
  1792. case llvm::Triple::sparcv9:
  1793. case llvm::Triple::systemz:
  1794. return true;
  1795. default:
  1796. return false;
  1797. }
  1798. }
  1799. void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
  1800. ArgStringList &CC1Args) const {
  1801. const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
  1802. bool UseInitArrayDefault =
  1803. getTriple().getArch() == llvm::Triple::aarch64 ||
  1804. getTriple().getArch() == llvm::Triple::aarch64_be ||
  1805. (getTriple().getOS() == llvm::Triple::Linux &&
  1806. (!V.isOlderThan(4, 7, 0) ||
  1807. getTriple().getEnvironment() == llvm::Triple::Android)) ||
  1808. getTriple().getOS() == llvm::Triple::NaCl;
  1809. if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
  1810. options::OPT_fno_use_init_array, UseInitArrayDefault))
  1811. CC1Args.push_back("-fuse-init-array");
  1812. }
  1813. /// Hexagon Toolchain
  1814. std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir,
  1815. const ArgList &Args) {
  1816. // Locate the rest of the toolchain ...
  1817. std::string GccToolchain = getGCCToolchainDir(Args);
  1818. if (!GccToolchain.empty())
  1819. return GccToolchain;
  1820. std::string InstallRelDir = InstalledDir + "/../../gnu";
  1821. if (llvm::sys::fs::exists(InstallRelDir))
  1822. return InstallRelDir;
  1823. std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
  1824. if (llvm::sys::fs::exists(PrefixRelDir))
  1825. return PrefixRelDir;
  1826. return InstallRelDir;
  1827. }
  1828. const char *Hexagon_TC::GetSmallDataThreshold(const ArgList &Args) {
  1829. Arg *A;
  1830. A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ,
  1831. options::OPT_msmall_data_threshold_EQ);
  1832. if (A)
  1833. return A->getValue();
  1834. A = Args.getLastArg(options::OPT_shared, options::OPT_fpic,
  1835. options::OPT_fPIC);
  1836. if (A)
  1837. return "0";
  1838. return 0;
  1839. }
  1840. bool Hexagon_TC::UsesG0(const char *smallDataThreshold) {
  1841. return smallDataThreshold && smallDataThreshold[0] == '0';
  1842. }
  1843. static void GetHexagonLibraryPaths(const ArgList &Args, const std::string &Ver,
  1844. const std::string &MarchString,
  1845. const std::string &InstalledDir,
  1846. ToolChain::path_list *LibPaths) {
  1847. bool buildingLib = Args.hasArg(options::OPT_shared);
  1848. //----------------------------------------------------------------------------
  1849. // -L Args
  1850. //----------------------------------------------------------------------------
  1851. for (Arg *A : Args.filtered(options::OPT_L))
  1852. for (const char *Value : A->getValues())
  1853. LibPaths->push_back(Value);
  1854. //----------------------------------------------------------------------------
  1855. // Other standard paths
  1856. //----------------------------------------------------------------------------
  1857. const std::string MarchSuffix = "/" + MarchString;
  1858. const std::string G0Suffix = "/G0";
  1859. const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
  1860. const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir, Args) + "/";
  1861. // lib/gcc/hexagon/...
  1862. std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
  1863. if (buildingLib) {
  1864. LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
  1865. LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
  1866. }
  1867. LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
  1868. LibPaths->push_back(LibGCCHexagonDir + Ver);
  1869. // lib/gcc/...
  1870. LibPaths->push_back(RootDir + "lib/gcc");
  1871. // hexagon/lib/...
  1872. std::string HexagonLibDir = RootDir + "hexagon/lib";
  1873. if (buildingLib) {
  1874. LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
  1875. LibPaths->push_back(HexagonLibDir + G0Suffix);
  1876. }
  1877. LibPaths->push_back(HexagonLibDir + MarchSuffix);
  1878. LibPaths->push_back(HexagonLibDir);
  1879. }
  1880. Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
  1881. const ArgList &Args)
  1882. : Linux(D, Triple, Args) {
  1883. const std::string InstalledDir(getDriver().getInstalledDir());
  1884. const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir, Args);
  1885. // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
  1886. // program paths
  1887. const std::string BinDir(GnuDir + "/bin");
  1888. if (llvm::sys::fs::exists(BinDir))
  1889. getProgramPaths().push_back(BinDir);
  1890. // Determine version of GCC libraries and headers to use.
  1891. const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
  1892. std::error_code ec;
  1893. GCCVersion MaxVersion = GCCVersion::Parse("0.0.0");
  1894. for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
  1895. !ec && di != de; di = di.increment(ec)) {
  1896. GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
  1897. if (MaxVersion < cv)
  1898. MaxVersion = cv;
  1899. }
  1900. GCCLibAndIncVersion = MaxVersion;
  1901. ToolChain::path_list *LibPaths = &getFilePaths();
  1902. // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
  1903. // 'elf' OS type, so the Linux paths are not appropriate. When we actually
  1904. // support 'linux' we'll need to fix this up
  1905. LibPaths->clear();
  1906. GetHexagonLibraryPaths(Args, GetGCCLibAndIncVersion(), GetTargetCPU(Args),
  1907. InstalledDir, LibPaths);
  1908. }
  1909. Hexagon_TC::~Hexagon_TC() {}
  1910. Tool *Hexagon_TC::buildAssembler() const {
  1911. return new tools::hexagon::Assembler(*this);
  1912. }
  1913. Tool *Hexagon_TC::buildLinker() const {
  1914. return new tools::hexagon::Linker(*this);
  1915. }
  1916. void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  1917. ArgStringList &CC1Args) const {
  1918. const Driver &D = getDriver();
  1919. if (DriverArgs.hasArg(options::OPT_nostdinc) ||
  1920. DriverArgs.hasArg(options::OPT_nostdlibinc))
  1921. return;
  1922. std::string Ver(GetGCCLibAndIncVersion());
  1923. std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs);
  1924. std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
  1925. addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
  1926. addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
  1927. addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
  1928. }
  1929. void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  1930. ArgStringList &CC1Args) const {
  1931. if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
  1932. DriverArgs.hasArg(options::OPT_nostdincxx))
  1933. return;
  1934. const Driver &D = getDriver();
  1935. std::string Ver(GetGCCLibAndIncVersion());
  1936. SmallString<128> IncludeDir(
  1937. Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs));
  1938. llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
  1939. llvm::sys::path::append(IncludeDir, Ver);
  1940. addSystemInclude(DriverArgs, CC1Args, IncludeDir);
  1941. }
  1942. ToolChain::CXXStdlibType
  1943. Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
  1944. Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
  1945. if (!A)
  1946. return ToolChain::CST_Libstdcxx;
  1947. StringRef Value = A->getValue();
  1948. if (Value != "libstdc++") {
  1949. getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
  1950. }
  1951. return ToolChain::CST_Libstdcxx;
  1952. }
  1953. static int getHexagonVersion(const ArgList &Args) {
  1954. Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ);
  1955. // Select the default CPU (v4) if none was given.
  1956. if (!A)
  1957. return 4;
  1958. // FIXME: produce errors if we cannot parse the version.
  1959. StringRef WhichHexagon = A->getValue();
  1960. if (WhichHexagon.startswith("hexagonv")) {
  1961. int Val;
  1962. if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val))
  1963. return Val;
  1964. }
  1965. if (WhichHexagon.startswith("v")) {
  1966. int Val;
  1967. if (!WhichHexagon.substr(1).getAsInteger(10, Val))
  1968. return Val;
  1969. }
  1970. // FIXME: should probably be an error.
  1971. return 4;
  1972. }
  1973. StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args) {
  1974. int V = getHexagonVersion(Args);
  1975. // FIXME: We don't support versions < 4. We should error on them.
  1976. switch (V) {
  1977. default:
  1978. llvm_unreachable("Unexpected version");
  1979. case 5:
  1980. return "v5";
  1981. case 4:
  1982. return "v4";
  1983. case 3:
  1984. return "v3";
  1985. case 2:
  1986. return "v2";
  1987. case 1:
  1988. return "v1";
  1989. }
  1990. }
  1991. // End Hexagon
  1992. /// NaCl Toolchain
  1993. NaCl_TC::NaCl_TC(const Driver &D, const llvm::Triple &Triple,
  1994. const ArgList &Args)
  1995. : Generic_ELF(D, Triple, Args) {
  1996. // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the
  1997. // default paths, and must instead only use the paths provided
  1998. // with this toolchain based on architecture.
  1999. path_list &file_paths = getFilePaths();
  2000. path_list &prog_paths = getProgramPaths();
  2001. file_paths.clear();
  2002. prog_paths.clear();
  2003. // Path for library files (libc.a, ...)
  2004. std::string FilePath(getDriver().Dir + "/../");
  2005. // Path for tools (clang, ld, etc..)
  2006. std::string ProgPath(getDriver().Dir + "/../");
  2007. // Path for toolchain libraries (libgcc.a, ...)
  2008. std::string ToolPath(getDriver().ResourceDir + "/lib/");
  2009. switch (Triple.getArch()) {
  2010. case llvm::Triple::x86: {
  2011. file_paths.push_back(FilePath + "x86_64-nacl/lib32");
  2012. file_paths.push_back(FilePath + "x86_64-nacl/usr/lib32");
  2013. prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
  2014. file_paths.push_back(ToolPath + "i686-nacl");
  2015. break;
  2016. }
  2017. case llvm::Triple::x86_64: {
  2018. file_paths.push_back(FilePath + "x86_64-nacl/lib");
  2019. file_paths.push_back(FilePath + "x86_64-nacl/usr/lib");
  2020. prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
  2021. file_paths.push_back(ToolPath + "x86_64-nacl");
  2022. break;
  2023. }
  2024. case llvm::Triple::arm: {
  2025. file_paths.push_back(FilePath + "arm-nacl/lib");
  2026. file_paths.push_back(FilePath + "arm-nacl/usr/lib");
  2027. prog_paths.push_back(ProgPath + "arm-nacl/bin");
  2028. file_paths.push_back(ToolPath + "arm-nacl");
  2029. break;
  2030. }
  2031. case llvm::Triple::mipsel: {
  2032. file_paths.push_back(FilePath + "mipsel-nacl/lib");
  2033. file_paths.push_back(FilePath + "mipsel-nacl/usr/lib");
  2034. prog_paths.push_back(ProgPath + "bin");
  2035. file_paths.push_back(ToolPath + "mipsel-nacl");
  2036. break;
  2037. }
  2038. default:
  2039. break;
  2040. }
  2041. // Use provided linker, not system linker
  2042. Linker = GetProgramPath("ld");
  2043. NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s");
  2044. }
  2045. void NaCl_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  2046. ArgStringList &CC1Args) const {
  2047. const Driver &D = getDriver();
  2048. if (DriverArgs.hasArg(options::OPT_nostdinc))
  2049. return;
  2050. if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
  2051. SmallString<128> P(D.ResourceDir);
  2052. llvm::sys::path::append(P, "include");
  2053. addSystemInclude(DriverArgs, CC1Args, P.str());
  2054. }
  2055. if (DriverArgs.hasArg(options::OPT_nostdlibinc))
  2056. return;
  2057. SmallString<128> P(D.Dir + "/../");
  2058. switch (getTriple().getArch()) {
  2059. case llvm::Triple::arm:
  2060. llvm::sys::path::append(P, "arm-nacl/usr/include");
  2061. break;
  2062. case llvm::Triple::x86:
  2063. llvm::sys::path::append(P, "x86_64-nacl/usr/include");
  2064. break;
  2065. case llvm::Triple::x86_64:
  2066. llvm::sys::path::append(P, "x86_64-nacl/usr/include");
  2067. break;
  2068. case llvm::Triple::mipsel:
  2069. llvm::sys::path::append(P, "mipsel-nacl/usr/include");
  2070. break;
  2071. default:
  2072. return;
  2073. }
  2074. addSystemInclude(DriverArgs, CC1Args, P.str());
  2075. llvm::sys::path::remove_filename(P);
  2076. llvm::sys::path::remove_filename(P);
  2077. llvm::sys::path::append(P, "include");
  2078. addSystemInclude(DriverArgs, CC1Args, P.str());
  2079. }
  2080. void NaCl_TC::AddCXXStdlibLibArgs(const ArgList &Args,
  2081. ArgStringList &CmdArgs) const {
  2082. // Check for -stdlib= flags. We only support libc++ but this consumes the arg
  2083. // if the value is libc++, and emits an error for other values.
  2084. GetCXXStdlibType(Args);
  2085. CmdArgs.push_back("-lc++");
  2086. }
  2087. void NaCl_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  2088. ArgStringList &CC1Args) const {
  2089. const Driver &D = getDriver();
  2090. if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
  2091. DriverArgs.hasArg(options::OPT_nostdincxx))
  2092. return;
  2093. // Check for -stdlib= flags. We only support libc++ but this consumes the arg
  2094. // if the value is libc++, and emits an error for other values.
  2095. GetCXXStdlibType(DriverArgs);
  2096. SmallString<128> P(D.Dir + "/../");
  2097. switch (getTriple().getArch()) {
  2098. case llvm::Triple::arm:
  2099. llvm::sys::path::append(P, "arm-nacl/include/c++/v1");
  2100. addSystemInclude(DriverArgs, CC1Args, P.str());
  2101. break;
  2102. case llvm::Triple::x86:
  2103. llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
  2104. addSystemInclude(DriverArgs, CC1Args, P.str());
  2105. break;
  2106. case llvm::Triple::x86_64:
  2107. llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
  2108. addSystemInclude(DriverArgs, CC1Args, P.str());
  2109. break;
  2110. case llvm::Triple::mipsel:
  2111. llvm::sys::path::append(P, "mipsel-nacl/include/c++/v1");
  2112. addSystemInclude(DriverArgs, CC1Args, P.str());
  2113. break;
  2114. default:
  2115. break;
  2116. }
  2117. }
  2118. ToolChain::CXXStdlibType NaCl_TC::GetCXXStdlibType(const ArgList &Args) const {
  2119. if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
  2120. StringRef Value = A->getValue();
  2121. if (Value == "libc++")
  2122. return ToolChain::CST_Libcxx;
  2123. getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
  2124. }
  2125. return ToolChain::CST_Libcxx;
  2126. }
  2127. std::string NaCl_TC::ComputeEffectiveClangTriple(const ArgList &Args,
  2128. types::ID InputType) const {
  2129. llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType));
  2130. if (TheTriple.getArch() == llvm::Triple::arm &&
  2131. TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
  2132. TheTriple.setEnvironment(llvm::Triple::GNUEABIHF);
  2133. return TheTriple.getTriple();
  2134. }
  2135. Tool *NaCl_TC::buildLinker() const {
  2136. return new tools::nacltools::Linker(*this);
  2137. }
  2138. Tool *NaCl_TC::buildAssembler() const {
  2139. if (getTriple().getArch() == llvm::Triple::arm)
  2140. return new tools::nacltools::AssemblerARM(*this);
  2141. return new tools::gnutools::Assembler(*this);
  2142. }
  2143. // End NaCl
  2144. /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
  2145. /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
  2146. /// Currently does not support anything else but compilation.
  2147. TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple,
  2148. const ArgList &Args)
  2149. : ToolChain(D, Triple, Args) {
  2150. // Path mangling to find libexec
  2151. std::string Path(getDriver().Dir);
  2152. Path += "/../libexec";
  2153. getProgramPaths().push_back(Path);
  2154. }
  2155. TCEToolChain::~TCEToolChain() {}
  2156. bool TCEToolChain::IsMathErrnoDefault() const { return true; }
  2157. bool TCEToolChain::isPICDefault() const { return false; }
  2158. bool TCEToolChain::isPIEDefault() const { return false; }
  2159. bool TCEToolChain::isPICDefaultForced() const { return false; }
  2160. // CloudABI - CloudABI tool chain which can call ld(1) directly.
  2161. CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple,
  2162. const ArgList &Args)
  2163. : Generic_ELF(D, Triple, Args) {
  2164. SmallString<128> P(getDriver().Dir);
  2165. llvm::sys::path::append(P, "..", getTriple().str(), "lib");
  2166. getFilePaths().push_back(P.str());
  2167. }
  2168. void CloudABI::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  2169. ArgStringList &CC1Args) const {
  2170. if (DriverArgs.hasArg(options::OPT_nostdlibinc) &&
  2171. DriverArgs.hasArg(options::OPT_nostdincxx))
  2172. return;
  2173. SmallString<128> P(getDriver().Dir);
  2174. llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1");
  2175. addSystemInclude(DriverArgs, CC1Args, P.str());
  2176. }
  2177. void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args,
  2178. ArgStringList &CmdArgs) const {
  2179. CmdArgs.push_back("-lc++");
  2180. CmdArgs.push_back("-lc++abi");
  2181. CmdArgs.push_back("-lunwind");
  2182. }
  2183. Tool *CloudABI::buildLinker() const {
  2184. return new tools::cloudabi::Linker(*this);
  2185. }
  2186. /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
  2187. OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
  2188. const ArgList &Args)
  2189. : Generic_ELF(D, Triple, Args) {
  2190. getFilePaths().push_back(getDriver().Dir + "/../lib");
  2191. getFilePaths().push_back("/usr/lib");
  2192. }
  2193. Tool *OpenBSD::buildAssembler() const {
  2194. return new tools::openbsd::Assembler(*this);
  2195. }
  2196. Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
  2197. /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
  2198. Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  2199. : Generic_ELF(D, Triple, Args) {
  2200. getFilePaths().push_back(getDriver().Dir + "/../lib");
  2201. getFilePaths().push_back("/usr/lib");
  2202. }
  2203. Tool *Bitrig::buildAssembler() const {
  2204. return new tools::bitrig::Assembler(*this);
  2205. }
  2206. Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); }
  2207. ToolChain::CXXStdlibType Bitrig::GetCXXStdlibType(const ArgList &Args) const {
  2208. if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
  2209. StringRef Value = A->getValue();
  2210. if (Value == "libstdc++")
  2211. return ToolChain::CST_Libstdcxx;
  2212. if (Value == "libc++")
  2213. return ToolChain::CST_Libcxx;
  2214. getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
  2215. }
  2216. return ToolChain::CST_Libcxx;
  2217. }
  2218. void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  2219. ArgStringList &CC1Args) const {
  2220. if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
  2221. DriverArgs.hasArg(options::OPT_nostdincxx))
  2222. return;
  2223. switch (GetCXXStdlibType(DriverArgs)) {
  2224. case ToolChain::CST_Libcxx:
  2225. addSystemInclude(DriverArgs, CC1Args,
  2226. getDriver().SysRoot + "/usr/include/c++/v1");
  2227. break;
  2228. case ToolChain::CST_Libstdcxx:
  2229. addSystemInclude(DriverArgs, CC1Args,
  2230. getDriver().SysRoot + "/usr/include/c++/stdc++");
  2231. addSystemInclude(DriverArgs, CC1Args,
  2232. getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
  2233. StringRef Triple = getTriple().str();
  2234. if (Triple.startswith("amd64"))
  2235. addSystemInclude(DriverArgs, CC1Args,
  2236. getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
  2237. Triple.substr(5));
  2238. else
  2239. addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot +
  2240. "/usr/include/c++/stdc++/" +
  2241. Triple);
  2242. break;
  2243. }
  2244. }
  2245. void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
  2246. ArgStringList &CmdArgs) const {
  2247. switch (GetCXXStdlibType(Args)) {
  2248. case ToolChain::CST_Libcxx:
  2249. CmdArgs.push_back("-lc++");
  2250. CmdArgs.push_back("-lc++abi");
  2251. CmdArgs.push_back("-lpthread");
  2252. break;
  2253. case ToolChain::CST_Libstdcxx:
  2254. CmdArgs.push_back("-lstdc++");
  2255. break;
  2256. }
  2257. }
  2258. /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
  2259. FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
  2260. const ArgList &Args)
  2261. : Generic_ELF(D, Triple, Args) {
  2262. // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
  2263. // back to '/usr/lib' if it doesn't exist.
  2264. if ((Triple.getArch() == llvm::Triple::x86 ||
  2265. Triple.getArch() == llvm::Triple::ppc) &&
  2266. llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
  2267. getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
  2268. else
  2269. getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
  2270. }
  2271. ToolChain::CXXStdlibType FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
  2272. if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
  2273. StringRef Value = A->getValue();
  2274. if (Value == "libstdc++")
  2275. return ToolChain::CST_Libstdcxx;
  2276. if (Value == "libc++")
  2277. return ToolChain::CST_Libcxx;
  2278. getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
  2279. }
  2280. if (getTriple().getOSMajorVersion() >= 10)
  2281. return ToolChain::CST_Libcxx;
  2282. return ToolChain::CST_Libstdcxx;
  2283. }
  2284. void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  2285. ArgStringList &CC1Args) const {
  2286. if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
  2287. DriverArgs.hasArg(options::OPT_nostdincxx))
  2288. return;
  2289. switch (GetCXXStdlibType(DriverArgs)) {
  2290. case ToolChain::CST_Libcxx:
  2291. addSystemInclude(DriverArgs, CC1Args,
  2292. getDriver().SysRoot + "/usr/include/c++/v1");
  2293. break;
  2294. case ToolChain::CST_Libstdcxx:
  2295. addSystemInclude(DriverArgs, CC1Args,
  2296. getDriver().SysRoot + "/usr/include/c++/4.2");
  2297. addSystemInclude(DriverArgs, CC1Args,
  2298. getDriver().SysRoot + "/usr/include/c++/4.2/backward");
  2299. break;
  2300. }
  2301. }
  2302. Tool *FreeBSD::buildAssembler() const {
  2303. return new tools::freebsd::Assembler(*this);
  2304. }
  2305. Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
  2306. bool FreeBSD::UseSjLjExceptions() const {
  2307. // FreeBSD uses SjLj exceptions on ARM oabi.
  2308. switch (getTriple().getEnvironment()) {
  2309. case llvm::Triple::GNUEABIHF:
  2310. case llvm::Triple::GNUEABI:
  2311. case llvm::Triple::EABI:
  2312. return false;
  2313. default:
  2314. return (getTriple().getArch() == llvm::Triple::arm ||
  2315. getTriple().getArch() == llvm::Triple::thumb);
  2316. }
  2317. }
  2318. bool FreeBSD::HasNativeLLVMSupport() const { return true; }
  2319. bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
  2320. SanitizerMask FreeBSD::getSupportedSanitizers() const {
  2321. const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
  2322. const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
  2323. const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
  2324. getTriple().getArch() == llvm::Triple::mips64el;
  2325. SanitizerMask Res = ToolChain::getSupportedSanitizers();
  2326. Res |= SanitizerKind::Address;
  2327. Res |= SanitizerKind::Vptr;
  2328. if (IsX86_64 || IsMIPS64) {
  2329. Res |= SanitizerKind::Leak;
  2330. Res |= SanitizerKind::Thread;
  2331. }
  2332. if (IsX86 || IsX86_64) {
  2333. Res |= SanitizerKind::SafeStack;
  2334. }
  2335. return Res;
  2336. }
  2337. /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
  2338. NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  2339. : Generic_ELF(D, Triple, Args) {
  2340. if (getDriver().UseStdLib) {
  2341. // When targeting a 32-bit platform, try the special directory used on
  2342. // 64-bit hosts, and only fall back to the main library directory if that
  2343. // doesn't work.
  2344. // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
  2345. // what all logic is needed to emulate the '=' prefix here.
  2346. switch (Triple.getArch()) {
  2347. case llvm::Triple::x86:
  2348. getFilePaths().push_back("=/usr/lib/i386");
  2349. break;
  2350. case llvm::Triple::arm:
  2351. case llvm::Triple::armeb:
  2352. case llvm::Triple::thumb:
  2353. case llvm::Triple::thumbeb:
  2354. switch (Triple.getEnvironment()) {
  2355. case llvm::Triple::EABI:
  2356. case llvm::Triple::GNUEABI:
  2357. getFilePaths().push_back("=/usr/lib/eabi");
  2358. break;
  2359. case llvm::Triple::EABIHF:
  2360. case llvm::Triple::GNUEABIHF:
  2361. getFilePaths().push_back("=/usr/lib/eabihf");
  2362. break;
  2363. default:
  2364. getFilePaths().push_back("=/usr/lib/oabi");
  2365. break;
  2366. }
  2367. break;
  2368. case llvm::Triple::mips64:
  2369. case llvm::Triple::mips64el:
  2370. if (tools::mips::hasMipsAbiArg(Args, "o32"))
  2371. getFilePaths().push_back("=/usr/lib/o32");
  2372. else if (tools::mips::hasMipsAbiArg(Args, "64"))
  2373. getFilePaths().push_back("=/usr/lib/64");
  2374. break;
  2375. case llvm::Triple::ppc:
  2376. getFilePaths().push_back("=/usr/lib/powerpc");
  2377. break;
  2378. case llvm::Triple::sparc:
  2379. getFilePaths().push_back("=/usr/lib/sparc");
  2380. break;
  2381. default:
  2382. break;
  2383. }
  2384. getFilePaths().push_back("=/usr/lib");
  2385. }
  2386. }
  2387. Tool *NetBSD::buildAssembler() const {
  2388. return new tools::netbsd::Assembler(*this);
  2389. }
  2390. Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); }
  2391. ToolChain::CXXStdlibType NetBSD::GetCXXStdlibType(const ArgList &Args) const {
  2392. if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
  2393. StringRef Value = A->getValue();
  2394. if (Value == "libstdc++")
  2395. return ToolChain::CST_Libstdcxx;
  2396. if (Value == "libc++")
  2397. return ToolChain::CST_Libcxx;
  2398. getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
  2399. }
  2400. unsigned Major, Minor, Micro;
  2401. getTriple().getOSVersion(Major, Minor, Micro);
  2402. if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
  2403. switch (getArch()) {
  2404. case llvm::Triple::aarch64:
  2405. case llvm::Triple::arm:
  2406. case llvm::Triple::armeb:
  2407. case llvm::Triple::thumb:
  2408. case llvm::Triple::thumbeb:
  2409. case llvm::Triple::ppc:
  2410. case llvm::Triple::ppc64:
  2411. case llvm::Triple::ppc64le:
  2412. case llvm::Triple::x86:
  2413. case llvm::Triple::x86_64:
  2414. return ToolChain::CST_Libcxx;
  2415. default:
  2416. break;
  2417. }
  2418. }
  2419. return ToolChain::CST_Libstdcxx;
  2420. }
  2421. void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  2422. ArgStringList &CC1Args) const {
  2423. if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
  2424. DriverArgs.hasArg(options::OPT_nostdincxx))
  2425. return;
  2426. switch (GetCXXStdlibType(DriverArgs)) {
  2427. case ToolChain::CST_Libcxx:
  2428. addSystemInclude(DriverArgs, CC1Args,
  2429. getDriver().SysRoot + "/usr/include/c++/");
  2430. break;
  2431. case ToolChain::CST_Libstdcxx:
  2432. addSystemInclude(DriverArgs, CC1Args,
  2433. getDriver().SysRoot + "/usr/include/g++");
  2434. addSystemInclude(DriverArgs, CC1Args,
  2435. getDriver().SysRoot + "/usr/include/g++/backward");
  2436. break;
  2437. }
  2438. }
  2439. /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
  2440. Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  2441. : Generic_ELF(D, Triple, Args) {
  2442. getFilePaths().push_back(getDriver().Dir + "/../lib");
  2443. getFilePaths().push_back("/usr/lib");
  2444. }
  2445. Tool *Minix::buildAssembler() const {
  2446. return new tools::minix::Assembler(*this);
  2447. }
  2448. Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); }
  2449. /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
  2450. Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
  2451. const ArgList &Args)
  2452. : Generic_GCC(D, Triple, Args) {
  2453. getProgramPaths().push_back(getDriver().getInstalledDir());
  2454. if (getDriver().getInstalledDir() != getDriver().Dir)
  2455. getProgramPaths().push_back(getDriver().Dir);
  2456. getFilePaths().push_back(getDriver().Dir + "/../lib");
  2457. getFilePaths().push_back("/usr/lib");
  2458. }
  2459. Tool *Solaris::buildAssembler() const {
  2460. return new tools::solaris::Assembler(*this);
  2461. }
  2462. Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
  2463. /// Distribution (very bare-bones at the moment).
  2464. enum Distro {
  2465. // NB: Releases of a particular Linux distro should be kept together
  2466. // in this enum, because some tests are done by integer comparison against
  2467. // the first and last known member in the family, e.g. IsRedHat().
  2468. ArchLinux,
  2469. DebianLenny,
  2470. DebianSqueeze,
  2471. DebianWheezy,
  2472. DebianJessie,
  2473. DebianStretch,
  2474. Exherbo,
  2475. RHEL4,
  2476. RHEL5,
  2477. RHEL6,
  2478. RHEL7,
  2479. Fedora,
  2480. OpenSUSE,
  2481. UbuntuHardy,
  2482. UbuntuIntrepid,
  2483. UbuntuJaunty,
  2484. UbuntuKarmic,
  2485. UbuntuLucid,
  2486. UbuntuMaverick,
  2487. UbuntuNatty,
  2488. UbuntuOneiric,
  2489. UbuntuPrecise,
  2490. UbuntuQuantal,
  2491. UbuntuRaring,
  2492. UbuntuSaucy,
  2493. UbuntuTrusty,
  2494. UbuntuUtopic,
  2495. UbuntuVivid,
  2496. UbuntuWily,
  2497. UnknownDistro
  2498. };
  2499. static bool IsRedhat(enum Distro Distro) {
  2500. return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL7);
  2501. }
  2502. static bool IsOpenSUSE(enum Distro Distro) { return Distro == OpenSUSE; }
  2503. static bool IsDebian(enum Distro Distro) {
  2504. return Distro >= DebianLenny && Distro <= DebianStretch;
  2505. }
  2506. static bool IsUbuntu(enum Distro Distro) {
  2507. return Distro >= UbuntuHardy && Distro <= UbuntuWily;
  2508. }
  2509. static Distro DetectDistro(llvm::Triple::ArchType Arch) {
  2510. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
  2511. llvm::MemoryBuffer::getFile("/etc/lsb-release");
  2512. if (File) {
  2513. StringRef Data = File.get()->getBuffer();
  2514. SmallVector<StringRef, 16> Lines;
  2515. Data.split(Lines, "\n");
  2516. Distro Version = UnknownDistro;
  2517. for (const StringRef Line : Lines)
  2518. if (Version == UnknownDistro && Line.startswith("DISTRIB_CODENAME="))
  2519. Version = llvm::StringSwitch<Distro>(Line.substr(17))
  2520. .Case("hardy", UbuntuHardy)
  2521. .Case("intrepid", UbuntuIntrepid)
  2522. .Case("jaunty", UbuntuJaunty)
  2523. .Case("karmic", UbuntuKarmic)
  2524. .Case("lucid", UbuntuLucid)
  2525. .Case("maverick", UbuntuMaverick)
  2526. .Case("natty", UbuntuNatty)
  2527. .Case("oneiric", UbuntuOneiric)
  2528. .Case("precise", UbuntuPrecise)
  2529. .Case("quantal", UbuntuQuantal)
  2530. .Case("raring", UbuntuRaring)
  2531. .Case("saucy", UbuntuSaucy)
  2532. .Case("trusty", UbuntuTrusty)
  2533. .Case("utopic", UbuntuUtopic)
  2534. .Case("vivid", UbuntuVivid)
  2535. .Case("wily", UbuntuWily)
  2536. .Default(UnknownDistro);
  2537. return Version;
  2538. }
  2539. File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
  2540. if (File) {
  2541. StringRef Data = File.get()->getBuffer();
  2542. if (Data.startswith("Fedora release"))
  2543. return Fedora;
  2544. if (Data.startswith("Red Hat Enterprise Linux") ||
  2545. Data.startswith("CentOS")) {
  2546. if (Data.find("release 7") != StringRef::npos)
  2547. return RHEL7;
  2548. else if (Data.find("release 6") != StringRef::npos)
  2549. return RHEL6;
  2550. else if (Data.find("release 5") != StringRef::npos)
  2551. return RHEL5;
  2552. else if (Data.find("release 4") != StringRef::npos)
  2553. return RHEL4;
  2554. }
  2555. return UnknownDistro;
  2556. }
  2557. File = llvm::MemoryBuffer::getFile("/etc/debian_version");
  2558. if (File) {
  2559. StringRef Data = File.get()->getBuffer();
  2560. if (Data[0] == '5')
  2561. return DebianLenny;
  2562. else if (Data.startswith("squeeze/sid") || Data[0] == '6')
  2563. return DebianSqueeze;
  2564. else if (Data.startswith("wheezy/sid") || Data[0] == '7')
  2565. return DebianWheezy;
  2566. else if (Data.startswith("jessie/sid") || Data[0] == '8')
  2567. return DebianJessie;
  2568. else if (Data.startswith("stretch/sid") || Data[0] == '9')
  2569. return DebianStretch;
  2570. return UnknownDistro;
  2571. }
  2572. if (llvm::sys::fs::exists("/etc/SuSE-release"))
  2573. return OpenSUSE;
  2574. if (llvm::sys::fs::exists("/etc/exherbo-release"))
  2575. return Exherbo;
  2576. if (llvm::sys::fs::exists("/etc/arch-release"))
  2577. return ArchLinux;
  2578. return UnknownDistro;
  2579. }
  2580. /// \brief Get our best guess at the multiarch triple for a target.
  2581. ///
  2582. /// Debian-based systems are starting to use a multiarch setup where they use
  2583. /// a target-triple directory in the library and header search paths.
  2584. /// Unfortunately, this triple does not align with the vanilla target triple,
  2585. /// so we provide a rough mapping here.
  2586. static std::string getMultiarchTriple(const llvm::Triple &TargetTriple,
  2587. StringRef SysRoot) {
  2588. llvm::Triple::EnvironmentType TargetEnvironment = TargetTriple.getEnvironment();
  2589. // For most architectures, just use whatever we have rather than trying to be
  2590. // clever.
  2591. switch (TargetTriple.getArch()) {
  2592. default:
  2593. break;
  2594. // We use the existence of '/lib/<triple>' as a directory to detect some
  2595. // common linux triples that don't quite match the Clang triple for both
  2596. // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
  2597. // regardless of what the actual target triple is.
  2598. case llvm::Triple::arm:
  2599. case llvm::Triple::thumb:
  2600. if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
  2601. if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
  2602. return "arm-linux-gnueabihf";
  2603. } else {
  2604. if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
  2605. return "arm-linux-gnueabi";
  2606. }
  2607. break;
  2608. case llvm::Triple::armeb:
  2609. case llvm::Triple::thumbeb:
  2610. if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
  2611. if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
  2612. return "armeb-linux-gnueabihf";
  2613. } else {
  2614. if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabi"))
  2615. return "armeb-linux-gnueabi";
  2616. }
  2617. break;
  2618. case llvm::Triple::x86:
  2619. if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
  2620. return "i386-linux-gnu";
  2621. break;
  2622. case llvm::Triple::x86_64:
  2623. // We don't want this for x32, otherwise it will match x86_64 libs
  2624. if (TargetEnvironment != llvm::Triple::GNUX32 &&
  2625. llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
  2626. return "x86_64-linux-gnu";
  2627. break;
  2628. case llvm::Triple::aarch64:
  2629. if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
  2630. return "aarch64-linux-gnu";
  2631. break;
  2632. case llvm::Triple::aarch64_be:
  2633. if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
  2634. return "aarch64_be-linux-gnu";
  2635. break;
  2636. case llvm::Triple::mips:
  2637. if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
  2638. return "mips-linux-gnu";
  2639. break;
  2640. case llvm::Triple::mipsel:
  2641. if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
  2642. return "mipsel-linux-gnu";
  2643. break;
  2644. case llvm::Triple::mips64:
  2645. if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnu"))
  2646. return "mips64-linux-gnu";
  2647. if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
  2648. return "mips64-linux-gnuabi64";
  2649. break;
  2650. case llvm::Triple::mips64el:
  2651. if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnu"))
  2652. return "mips64el-linux-gnu";
  2653. if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
  2654. return "mips64el-linux-gnuabi64";
  2655. break;
  2656. case llvm::Triple::ppc:
  2657. if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
  2658. return "powerpc-linux-gnuspe";
  2659. if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
  2660. return "powerpc-linux-gnu";
  2661. break;
  2662. case llvm::Triple::ppc64:
  2663. if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
  2664. return "powerpc64-linux-gnu";
  2665. break;
  2666. case llvm::Triple::ppc64le:
  2667. if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
  2668. return "powerpc64le-linux-gnu";
  2669. break;
  2670. case llvm::Triple::sparc:
  2671. if (llvm::sys::fs::exists(SysRoot + "/lib/sparc-linux-gnu"))
  2672. return "sparc-linux-gnu";
  2673. break;
  2674. case llvm::Triple::sparcv9:
  2675. if (llvm::sys::fs::exists(SysRoot + "/lib/sparc64-linux-gnu"))
  2676. return "sparc64-linux-gnu";
  2677. break;
  2678. }
  2679. return TargetTriple.str();
  2680. }
  2681. static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
  2682. if (llvm::sys::fs::exists(Path))
  2683. Paths.push_back(Path.str());
  2684. }
  2685. static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
  2686. if (isMipsArch(Triple.getArch())) {
  2687. // lib32 directory has a special meaning on MIPS targets.
  2688. // It contains N32 ABI binaries. Use this folder if produce
  2689. // code for N32 ABI only.
  2690. if (tools::mips::hasMipsAbiArg(Args, "n32"))
  2691. return "lib32";
  2692. return Triple.isArch32Bit() ? "lib" : "lib64";
  2693. }
  2694. // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
  2695. // using that variant while targeting other architectures causes problems
  2696. // because the libraries are laid out in shared system roots that can't cope
  2697. // with a 'lib32' library search path being considered. So we only enable
  2698. // them when we know we may need it.
  2699. //
  2700. // FIXME: This is a bit of a hack. We should really unify this code for
  2701. // reasoning about oslibdir spellings with the lib dir spellings in the
  2702. // GCCInstallationDetector, but that is a more significant refactoring.
  2703. if (Triple.getArch() == llvm::Triple::x86 ||
  2704. Triple.getArch() == llvm::Triple::ppc)
  2705. return "lib32";
  2706. if (Triple.getArch() == llvm::Triple::x86_64 &&
  2707. Triple.getEnvironment() == llvm::Triple::GNUX32)
  2708. return "libx32";
  2709. return Triple.isArch32Bit() ? "lib" : "lib64";
  2710. }
  2711. Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  2712. : Generic_ELF(D, Triple, Args) {
  2713. GCCInstallation.init(D, Triple, Args);
  2714. Multilibs = GCCInstallation.getMultilibs();
  2715. llvm::Triple::ArchType Arch = Triple.getArch();
  2716. std::string SysRoot = computeSysRoot();
  2717. // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
  2718. // least) put various tools in a triple-prefixed directory off of the parent
  2719. // of the GCC installation. We use the GCC triple here to ensure that we end
  2720. // up with tools that support the same amount of cross compiling as the
  2721. // detected GCC installation. For example, if we find a GCC installation
  2722. // targeting x86_64, but it is a bi-arch GCC installation, it can also be
  2723. // used to target i386.
  2724. // FIXME: This seems unlikely to be Linux-specific.
  2725. ToolChain::path_list &PPaths = getProgramPaths();
  2726. PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
  2727. GCCInstallation.getTriple().str() + "/bin")
  2728. .str());
  2729. Linker = GetLinkerPath();
  2730. Distro Distro = DetectDistro(Arch);
  2731. if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
  2732. ExtraOpts.push_back("-z");
  2733. ExtraOpts.push_back("relro");
  2734. }
  2735. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
  2736. ExtraOpts.push_back("-X");
  2737. const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
  2738. const bool IsMips = isMipsArch(Arch);
  2739. if (IsMips && !SysRoot.empty())
  2740. ExtraOpts.push_back("--sysroot=" + SysRoot);
  2741. // Do not use 'gnu' hash style for Mips targets because .gnu.hash
  2742. // and the MIPS ABI require .dynsym to be sorted in different ways.
  2743. // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
  2744. // ABI requires a mapping between the GOT and the symbol table.
  2745. // Android loader does not support .gnu.hash.
  2746. if (!IsMips && !IsAndroid) {
  2747. if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
  2748. (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
  2749. ExtraOpts.push_back("--hash-style=gnu");
  2750. if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
  2751. Distro == UbuntuJaunty || Distro == UbuntuKarmic)
  2752. ExtraOpts.push_back("--hash-style=both");
  2753. }
  2754. if (IsRedhat(Distro))
  2755. ExtraOpts.push_back("--no-add-needed");
  2756. if ((IsDebian(Distro) && Distro >= DebianSqueeze) || IsOpenSUSE(Distro) ||
  2757. (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
  2758. (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
  2759. ExtraOpts.push_back("--build-id");
  2760. if (IsOpenSUSE(Distro))
  2761. ExtraOpts.push_back("--enable-new-dtags");
  2762. // The selection of paths to try here is designed to match the patterns which
  2763. // the GCC driver itself uses, as this is part of the GCC-compatible driver.
  2764. // This was determined by running GCC in a fake filesystem, creating all
  2765. // possible permutations of these directories, and seeing which ones it added
  2766. // to the link paths.
  2767. path_list &Paths = getFilePaths();
  2768. const std::string OSLibDir = getOSLibDir(Triple, Args);
  2769. const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
  2770. // Add the multilib suffixed paths where they are available.
  2771. if (GCCInstallation.isValid()) {
  2772. const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
  2773. const std::string &LibPath = GCCInstallation.getParentLibPath();
  2774. const Multilib &Multilib = GCCInstallation.getMultilib();
  2775. // Sourcery CodeBench MIPS toolchain holds some libraries under
  2776. // a biarch-like suffix of the GCC installation.
  2777. addPathIfExists((GCCInstallation.getInstallPath() + Multilib.gccSuffix()),
  2778. Paths);
  2779. // GCC cross compiling toolchains will install target libraries which ship
  2780. // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
  2781. // any part of the GCC installation in
  2782. // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
  2783. // debatable, but is the reality today. We need to search this tree even
  2784. // when we have a sysroot somewhere else. It is the responsibility of
  2785. // whomever is doing the cross build targeting a sysroot using a GCC
  2786. // installation that is *not* within the system root to ensure two things:
  2787. //
  2788. // 1) Any DSOs that are linked in from this tree or from the install path
  2789. // above must be present on the system root and found via an
  2790. // appropriate rpath.
  2791. // 2) There must not be libraries installed into
  2792. // <prefix>/<triple>/<libdir> unless they should be preferred over
  2793. // those within the system root.
  2794. //
  2795. // Note that this matches the GCC behavior. See the below comment for where
  2796. // Clang diverges from GCC's behavior.
  2797. addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
  2798. Multilib.osSuffix(),
  2799. Paths);
  2800. // If the GCC installation we found is inside of the sysroot, we want to
  2801. // prefer libraries installed in the parent prefix of the GCC installation.
  2802. // It is important to *not* use these paths when the GCC installation is
  2803. // outside of the system root as that can pick up unintended libraries.
  2804. // This usually happens when there is an external cross compiler on the
  2805. // host system, and a more minimal sysroot available that is the target of
  2806. // the cross. Note that GCC does include some of these directories in some
  2807. // configurations but this seems somewhere between questionable and simply
  2808. // a bug.
  2809. if (StringRef(LibPath).startswith(SysRoot)) {
  2810. addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
  2811. addPathIfExists(LibPath + "/../" + OSLibDir, Paths);
  2812. }
  2813. }
  2814. // Similar to the logic for GCC above, if we currently running Clang inside
  2815. // of the requested system root, add its parent library paths to
  2816. // those searched.
  2817. // FIXME: It's not clear whether we should use the driver's installed
  2818. // directory ('Dir' below) or the ResourceDir.
  2819. if (StringRef(D.Dir).startswith(SysRoot)) {
  2820. addPathIfExists(D.Dir + "/../lib/" + MultiarchTriple, Paths);
  2821. addPathIfExists(D.Dir + "/../" + OSLibDir, Paths);
  2822. }
  2823. addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
  2824. addPathIfExists(SysRoot + "/lib/../" + OSLibDir, Paths);
  2825. addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
  2826. addPathIfExists(SysRoot + "/usr/lib/../" + OSLibDir, Paths);
  2827. // Try walking via the GCC triple path in case of biarch or multiarch GCC
  2828. // installations with strange symlinks.
  2829. if (GCCInstallation.isValid()) {
  2830. addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
  2831. "/../../" + OSLibDir,
  2832. Paths);
  2833. // Add the 'other' biarch variant path
  2834. Multilib BiarchSibling;
  2835. if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
  2836. addPathIfExists(
  2837. GCCInstallation.getInstallPath() + BiarchSibling.gccSuffix(), Paths);
  2838. }
  2839. // See comments above on the multilib variant for details of why this is
  2840. // included even from outside the sysroot.
  2841. const std::string &LibPath = GCCInstallation.getParentLibPath();
  2842. const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
  2843. const Multilib &Multilib = GCCInstallation.getMultilib();
  2844. addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib" +
  2845. Multilib.osSuffix(),
  2846. Paths);
  2847. // See comments above on the multilib variant for details of why this is
  2848. // only included from within the sysroot.
  2849. if (StringRef(LibPath).startswith(SysRoot))
  2850. addPathIfExists(LibPath, Paths);
  2851. }
  2852. // Similar to the logic for GCC above, if we are currently running Clang
  2853. // inside of the requested system root, add its parent library path to those
  2854. // searched.
  2855. // FIXME: It's not clear whether we should use the driver's installed
  2856. // directory ('Dir' below) or the ResourceDir.
  2857. if (StringRef(D.Dir).startswith(SysRoot))
  2858. addPathIfExists(D.Dir + "/../lib", Paths);
  2859. addPathIfExists(SysRoot + "/lib", Paths);
  2860. addPathIfExists(SysRoot + "/usr/lib", Paths);
  2861. }
  2862. bool Linux::HasNativeLLVMSupport() const { return true; }
  2863. Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
  2864. Tool *Linux::buildAssembler() const {
  2865. return new tools::gnutools::Assembler(*this);
  2866. }
  2867. std::string Linux::computeSysRoot() const {
  2868. if (!getDriver().SysRoot.empty())
  2869. return getDriver().SysRoot;
  2870. if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
  2871. return std::string();
  2872. // Standalone MIPS toolchains use different names for sysroot folder
  2873. // and put it into different places. Here we try to check some known
  2874. // variants.
  2875. const StringRef InstallDir = GCCInstallation.getInstallPath();
  2876. const StringRef TripleStr = GCCInstallation.getTriple().str();
  2877. const Multilib &Multilib = GCCInstallation.getMultilib();
  2878. std::string Path =
  2879. (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
  2880. .str();
  2881. if (llvm::sys::fs::exists(Path))
  2882. return Path;
  2883. Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
  2884. if (llvm::sys::fs::exists(Path))
  2885. return Path;
  2886. return std::string();
  2887. }
  2888. void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  2889. ArgStringList &CC1Args) const {
  2890. const Driver &D = getDriver();
  2891. std::string SysRoot = computeSysRoot();
  2892. if (DriverArgs.hasArg(options::OPT_nostdinc))
  2893. return;
  2894. if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
  2895. addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
  2896. if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
  2897. SmallString<128> P(D.ResourceDir);
  2898. llvm::sys::path::append(P, "include");
  2899. addSystemInclude(DriverArgs, CC1Args, P);
  2900. }
  2901. if (DriverArgs.hasArg(options::OPT_nostdlibinc))
  2902. return;
  2903. // Check for configure-time C include directories.
  2904. StringRef CIncludeDirs(C_INCLUDE_DIRS);
  2905. if (CIncludeDirs != "") {
  2906. SmallVector<StringRef, 5> dirs;
  2907. CIncludeDirs.split(dirs, ":");
  2908. for (StringRef dir : dirs) {
  2909. StringRef Prefix =
  2910. llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
  2911. addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
  2912. }
  2913. return;
  2914. }
  2915. // Lacking those, try to detect the correct set of system includes for the
  2916. // target triple.
  2917. // Add include directories specific to the selected multilib set and multilib.
  2918. if (GCCInstallation.isValid()) {
  2919. const auto &Callback = Multilibs.includeDirsCallback();
  2920. if (Callback) {
  2921. const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
  2922. GCCInstallation.getTriple().str(),
  2923. GCCInstallation.getMultilib());
  2924. for (const auto &Path : IncludePaths)
  2925. addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
  2926. }
  2927. }
  2928. // Implement generic Debian multiarch support.
  2929. const StringRef X86_64MultiarchIncludeDirs[] = {
  2930. "/usr/include/x86_64-linux-gnu",
  2931. // FIXME: These are older forms of multiarch. It's not clear that they're
  2932. // in use in any released version of Debian, so we should consider
  2933. // removing them.
  2934. "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
  2935. const StringRef X86MultiarchIncludeDirs[] = {
  2936. "/usr/include/i386-linux-gnu",
  2937. // FIXME: These are older forms of multiarch. It's not clear that they're
  2938. // in use in any released version of Debian, so we should consider
  2939. // removing them.
  2940. "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
  2941. "/usr/include/i486-linux-gnu"};
  2942. const StringRef AArch64MultiarchIncludeDirs[] = {
  2943. "/usr/include/aarch64-linux-gnu"};
  2944. const StringRef ARMMultiarchIncludeDirs[] = {
  2945. "/usr/include/arm-linux-gnueabi"};
  2946. const StringRef ARMHFMultiarchIncludeDirs[] = {
  2947. "/usr/include/arm-linux-gnueabihf"};
  2948. const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
  2949. const StringRef MIPSELMultiarchIncludeDirs[] = {
  2950. "/usr/include/mipsel-linux-gnu"};
  2951. const StringRef MIPS64MultiarchIncludeDirs[] = {
  2952. "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
  2953. const StringRef MIPS64ELMultiarchIncludeDirs[] = {
  2954. "/usr/include/mips64el-linux-gnu",
  2955. "/usr/include/mips64el-linux-gnuabi64"};
  2956. const StringRef PPCMultiarchIncludeDirs[] = {
  2957. "/usr/include/powerpc-linux-gnu"};
  2958. const StringRef PPC64MultiarchIncludeDirs[] = {
  2959. "/usr/include/powerpc64-linux-gnu"};
  2960. const StringRef PPC64LEMultiarchIncludeDirs[] = {
  2961. "/usr/include/powerpc64le-linux-gnu"};
  2962. const StringRef SparcMultiarchIncludeDirs[] = {
  2963. "/usr/include/sparc-linux-gnu"};
  2964. const StringRef Sparc64MultiarchIncludeDirs[] = {
  2965. "/usr/include/sparc64-linux-gnu"};
  2966. ArrayRef<StringRef> MultiarchIncludeDirs;
  2967. switch (getTriple().getArch()) {
  2968. case llvm::Triple::x86_64:
  2969. MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
  2970. break;
  2971. case llvm::Triple::x86:
  2972. MultiarchIncludeDirs = X86MultiarchIncludeDirs;
  2973. break;
  2974. case llvm::Triple::aarch64:
  2975. case llvm::Triple::aarch64_be:
  2976. MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
  2977. break;
  2978. case llvm::Triple::arm:
  2979. if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
  2980. MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
  2981. else
  2982. MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
  2983. break;
  2984. case llvm::Triple::mips:
  2985. MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
  2986. break;
  2987. case llvm::Triple::mipsel:
  2988. MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
  2989. break;
  2990. case llvm::Triple::mips64:
  2991. MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
  2992. break;
  2993. case llvm::Triple::mips64el:
  2994. MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
  2995. break;
  2996. case llvm::Triple::ppc:
  2997. MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
  2998. break;
  2999. case llvm::Triple::ppc64:
  3000. MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
  3001. break;
  3002. case llvm::Triple::ppc64le:
  3003. MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
  3004. break;
  3005. case llvm::Triple::sparc:
  3006. MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
  3007. break;
  3008. case llvm::Triple::sparcv9:
  3009. MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
  3010. break;
  3011. default:
  3012. break;
  3013. }
  3014. for (StringRef Dir : MultiarchIncludeDirs) {
  3015. if (llvm::sys::fs::exists(SysRoot + Dir)) {
  3016. addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
  3017. break;
  3018. }
  3019. }
  3020. if (getTriple().getOS() == llvm::Triple::RTEMS)
  3021. return;
  3022. // Add an include of '/include' directly. This isn't provided by default by
  3023. // system GCCs, but is often used with cross-compiling GCCs, and harmless to
  3024. // add even when Clang is acting as-if it were a system compiler.
  3025. addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
  3026. addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
  3027. }
  3028. /// \brief Helper to add the variant paths of a libstdc++ installation.
  3029. /*static*/ bool Linux::addLibStdCXXIncludePaths(
  3030. Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
  3031. StringRef TargetMultiarchTriple, Twine IncludeSuffix,
  3032. const ArgList &DriverArgs, ArgStringList &CC1Args) {
  3033. if (!llvm::sys::fs::exists(Base + Suffix))
  3034. return false;
  3035. addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
  3036. // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
  3037. // that path exists or we have neither a GCC nor target multiarch triple, use
  3038. // this vanilla search path.
  3039. if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
  3040. llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
  3041. addSystemInclude(DriverArgs, CC1Args,
  3042. Base + Suffix + "/" + GCCTriple + IncludeSuffix);
  3043. } else {
  3044. // Otherwise try to use multiarch naming schemes which have normalized the
  3045. // triples and put the triple before the suffix.
  3046. //
  3047. // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
  3048. // the target triple, so we support that here.
  3049. addSystemInclude(DriverArgs, CC1Args,
  3050. Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
  3051. addSystemInclude(DriverArgs, CC1Args,
  3052. Base + "/" + TargetMultiarchTriple + Suffix);
  3053. }
  3054. addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
  3055. return true;
  3056. }
  3057. void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  3058. ArgStringList &CC1Args) const {
  3059. if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
  3060. DriverArgs.hasArg(options::OPT_nostdincxx))
  3061. return;
  3062. // Check if libc++ has been enabled and provide its include paths if so.
  3063. if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
  3064. const std::string LibCXXIncludePathCandidates[] = {
  3065. // The primary location is within the Clang installation.
  3066. // FIXME: We shouldn't hard code 'v1' here to make Clang future proof to
  3067. // newer ABI versions.
  3068. getDriver().Dir + "/../include/c++/v1",
  3069. // We also check the system as for a long time this is the only place
  3070. // Clang looked.
  3071. // FIXME: We should really remove this. It doesn't make any sense.
  3072. getDriver().SysRoot + "/usr/include/c++/v1"};
  3073. for (const auto &IncludePath : LibCXXIncludePathCandidates) {
  3074. if (!llvm::sys::fs::exists(IncludePath))
  3075. continue;
  3076. // Add the first candidate that exists.
  3077. addSystemInclude(DriverArgs, CC1Args, IncludePath);
  3078. break;
  3079. }
  3080. return;
  3081. }
  3082. // We need a detected GCC installation on Linux to provide libstdc++'s
  3083. // headers. We handled the libc++ case above.
  3084. if (!GCCInstallation.isValid())
  3085. return;
  3086. // By default, look for the C++ headers in an include directory adjacent to
  3087. // the lib directory of the GCC installation. Note that this is expect to be
  3088. // equivalent to '/usr/include/c++/X.Y' in almost all cases.
  3089. StringRef LibDir = GCCInstallation.getParentLibPath();
  3090. StringRef InstallDir = GCCInstallation.getInstallPath();
  3091. StringRef TripleStr = GCCInstallation.getTriple().str();
  3092. const Multilib &Multilib = GCCInstallation.getMultilib();
  3093. const std::string GCCMultiarchTriple =
  3094. getMultiarchTriple(GCCInstallation.getTriple(), getDriver().SysRoot);
  3095. const std::string TargetMultiarchTriple =
  3096. getMultiarchTriple(getTriple(), getDriver().SysRoot);
  3097. const GCCVersion &Version = GCCInstallation.getVersion();
  3098. // The primary search for libstdc++ supports multiarch variants.
  3099. if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
  3100. "/c++/" + Version.Text, TripleStr,
  3101. GCCMultiarchTriple, TargetMultiarchTriple,
  3102. Multilib.includeSuffix(), DriverArgs, CC1Args))
  3103. return;
  3104. // Otherwise, fall back on a bunch of options which don't use multiarch
  3105. // layouts for simplicity.
  3106. const std::string LibStdCXXIncludePathCandidates[] = {
  3107. // Gentoo is weird and places its headers inside the GCC install,
  3108. // so if the first attempt to find the headers fails, try these patterns.
  3109. InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
  3110. Version.MinorStr,
  3111. InstallDir.str() + "/include/g++-v" + Version.MajorStr,
  3112. // Android standalone toolchain has C++ headers in yet another place.
  3113. LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
  3114. // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
  3115. // without a subdirectory corresponding to the gcc version.
  3116. LibDir.str() + "/../include/c++",
  3117. };
  3118. for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
  3119. if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
  3120. /*GCCMultiarchTriple*/ "",
  3121. /*TargetMultiarchTriple*/ "",
  3122. Multilib.includeSuffix(), DriverArgs, CC1Args))
  3123. break;
  3124. }
  3125. }
  3126. bool Linux::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
  3127. SanitizerMask Linux::getSupportedSanitizers() const {
  3128. const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
  3129. const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
  3130. const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
  3131. getTriple().getArch() == llvm::Triple::mips64el;
  3132. const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
  3133. getTriple().getArch() == llvm::Triple::ppc64le;
  3134. SanitizerMask Res = ToolChain::getSupportedSanitizers();
  3135. Res |= SanitizerKind::Address;
  3136. Res |= SanitizerKind::KernelAddress;
  3137. Res |= SanitizerKind::Vptr;
  3138. if (IsX86_64 || IsMIPS64) {
  3139. Res |= SanitizerKind::DataFlow;
  3140. Res |= SanitizerKind::Leak;
  3141. Res |= SanitizerKind::Thread;
  3142. }
  3143. if (IsX86_64 || IsMIPS64 || IsPowerPC64)
  3144. Res |= SanitizerKind::Memory;
  3145. if (IsX86 || IsX86_64) {
  3146. Res |= SanitizerKind::Function;
  3147. Res |= SanitizerKind::SafeStack;
  3148. }
  3149. return Res;
  3150. }
  3151. /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
  3152. DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple,
  3153. const ArgList &Args)
  3154. : Generic_ELF(D, Triple, Args) {
  3155. // Path mangling to find libexec
  3156. getProgramPaths().push_back(getDriver().getInstalledDir());
  3157. if (getDriver().getInstalledDir() != getDriver().Dir)
  3158. getProgramPaths().push_back(getDriver().Dir);
  3159. getFilePaths().push_back(getDriver().Dir + "/../lib");
  3160. getFilePaths().push_back("/usr/lib");
  3161. if (llvm::sys::fs::exists("/usr/lib/gcc47"))
  3162. getFilePaths().push_back("/usr/lib/gcc47");
  3163. else
  3164. getFilePaths().push_back("/usr/lib/gcc44");
  3165. }
  3166. Tool *DragonFly::buildAssembler() const {
  3167. return new tools::dragonfly::Assembler(*this);
  3168. }
  3169. Tool *DragonFly::buildLinker() const {
  3170. return new tools::dragonfly::Linker(*this);
  3171. }
  3172. /// Stub for CUDA toolchain. At the moment we don't have assembler or
  3173. /// linker and need toolchain mainly to propagate device-side options
  3174. /// to CC1.
  3175. CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
  3176. const ArgList &Args)
  3177. : Linux(D, Triple, Args) {}
  3178. void
  3179. CudaToolChain::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
  3180. llvm::opt::ArgStringList &CC1Args) const {
  3181. Linux::addClangTargetOptions(DriverArgs, CC1Args);
  3182. CC1Args.push_back("-fcuda-is-device");
  3183. }
  3184. llvm::opt::DerivedArgList *
  3185. CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
  3186. const char *BoundArch) const {
  3187. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  3188. const OptTable &Opts = getDriver().getOpts();
  3189. for (Arg *A : Args) {
  3190. if (A->getOption().matches(options::OPT_Xarch__)) {
  3191. // Skip this argument unless the architecture matches BoundArch
  3192. if (A->getValue(0) != StringRef(BoundArch))
  3193. continue;
  3194. unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
  3195. unsigned Prev = Index;
  3196. std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
  3197. // If the argument parsing failed or more than one argument was
  3198. // consumed, the -Xarch_ argument's parameter tried to consume
  3199. // extra arguments. Emit an error and ignore.
  3200. //
  3201. // We also want to disallow any options which would alter the
  3202. // driver behavior; that isn't going to work in our model. We
  3203. // use isDriverOption() as an approximation, although things
  3204. // like -O4 are going to slip through.
  3205. if (!XarchArg || Index > Prev + 1) {
  3206. getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
  3207. << A->getAsString(Args);
  3208. continue;
  3209. } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
  3210. getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
  3211. << A->getAsString(Args);
  3212. continue;
  3213. }
  3214. XarchArg->setBaseArg(A);
  3215. A = XarchArg.release();
  3216. DAL->AddSynthesizedArg(A);
  3217. }
  3218. DAL->append(A);
  3219. }
  3220. DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
  3221. return DAL;
  3222. }
  3223. /// XCore tool chain
  3224. XCore::XCore(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  3225. : ToolChain(D, Triple, Args) {
  3226. // ProgramPaths are found via 'PATH' environment variable.
  3227. }
  3228. Tool *XCore::buildAssembler() const {
  3229. return new tools::XCore::Assembler(*this);
  3230. }
  3231. Tool *XCore::buildLinker() const { return new tools::XCore::Linker(*this); }
  3232. bool XCore::isPICDefault() const { return false; }
  3233. bool XCore::isPIEDefault() const { return false; }
  3234. bool XCore::isPICDefaultForced() const { return false; }
  3235. bool XCore::SupportsProfiling() const { return false; }
  3236. bool XCore::hasBlocksRuntime() const { return false; }
  3237. void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  3238. ArgStringList &CC1Args) const {
  3239. if (DriverArgs.hasArg(options::OPT_nostdinc) ||
  3240. DriverArgs.hasArg(options::OPT_nostdlibinc))
  3241. return;
  3242. if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
  3243. SmallVector<StringRef, 4> Dirs;
  3244. const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
  3245. StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
  3246. ArrayRef<StringRef> DirVec(Dirs);
  3247. addSystemIncludes(DriverArgs, CC1Args, DirVec);
  3248. }
  3249. }
  3250. void XCore::addClangTargetOptions(const ArgList &DriverArgs,
  3251. ArgStringList &CC1Args) const {
  3252. CC1Args.push_back("-nostdsysteminc");
  3253. }
  3254. void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  3255. ArgStringList &CC1Args) const {
  3256. if (DriverArgs.hasArg(options::OPT_nostdinc) ||
  3257. DriverArgs.hasArg(options::OPT_nostdlibinc) ||
  3258. DriverArgs.hasArg(options::OPT_nostdincxx))
  3259. return;
  3260. if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
  3261. SmallVector<StringRef, 4> Dirs;
  3262. const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
  3263. StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
  3264. ArrayRef<StringRef> DirVec(Dirs);
  3265. addSystemIncludes(DriverArgs, CC1Args, DirVec);
  3266. }
  3267. }
  3268. void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
  3269. ArgStringList &CmdArgs) const {
  3270. // We don't output any lib args. This is handled by xcc.
  3271. }
  3272. // SHAVEToolChain does not call Clang's C compiler.
  3273. // We override SelectTool to avoid testing ShouldUseClangCompiler().
  3274. Tool *SHAVEToolChain::SelectTool(const JobAction &JA) const {
  3275. switch (JA.getKind()) {
  3276. case Action::CompileJobClass:
  3277. if (!Compiler)
  3278. Compiler.reset(new tools::SHAVE::Compiler(*this));
  3279. return Compiler.get();
  3280. case Action::AssembleJobClass:
  3281. if (!Assembler)
  3282. Assembler.reset(new tools::SHAVE::Assembler(*this));
  3283. return Assembler.get();
  3284. default:
  3285. return ToolChain::getTool(JA.getKind());
  3286. }
  3287. }
  3288. SHAVEToolChain::SHAVEToolChain(const Driver &D, const llvm::Triple &Triple,
  3289. const ArgList &Args)
  3290. : Generic_GCC(D, Triple, Args) {}
  3291. SHAVEToolChain::~SHAVEToolChain() {}
  3292. /// Following are methods necessary to avoid having moviClang be an abstract
  3293. /// class.
  3294. Tool *SHAVEToolChain::getTool(Action::ActionClass AC) const {
  3295. // SelectTool() must find a tool using the method in the superclass.
  3296. // There's nothing we can do if that fails.
  3297. llvm_unreachable("SHAVEToolChain can't getTool");
  3298. }
  3299. Tool *SHAVEToolChain::buildLinker() const {
  3300. // SHAVEToolChain executables can not be linked except by the vendor tools.
  3301. llvm_unreachable("SHAVEToolChain can't buildLinker");
  3302. }
  3303. Tool *SHAVEToolChain::buildAssembler() const {
  3304. // This one you'd think should be reachable since we expose an
  3305. // assembler to the driver, except not the way it expects.
  3306. llvm_unreachable("SHAVEToolChain can't buildAssembler");
  3307. }