Gnu.cpp 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072
  1. //===--- Gnu.cpp - Gnu Tool and ToolChain Implementations -------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "Gnu.h"
  9. #include "Arch/ARM.h"
  10. #include "Arch/Mips.h"
  11. #include "Arch/PPC.h"
  12. #include "Arch/RISCV.h"
  13. #include "Arch/Sparc.h"
  14. #include "Arch/SystemZ.h"
  15. #include "CommonArgs.h"
  16. #include "Linux.h"
  17. #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
  18. #include "clang/Driver/Compilation.h"
  19. #include "clang/Driver/Driver.h"
  20. #include "clang/Driver/DriverDiagnostic.h"
  21. #include "clang/Driver/Options.h"
  22. #include "clang/Driver/Tool.h"
  23. #include "clang/Driver/ToolChain.h"
  24. #include "llvm/Option/ArgList.h"
  25. #include "llvm/Support/CodeGen.h"
  26. #include "llvm/Support/Path.h"
  27. #include "llvm/Support/TargetParser.h"
  28. #include "llvm/Support/VirtualFileSystem.h"
  29. #include <system_error>
  30. using namespace clang::driver;
  31. using namespace clang::driver::toolchains;
  32. using namespace clang;
  33. using namespace llvm::opt;
  34. using tools::addMultilibFlag;
  35. using tools::addPathIfExists;
  36. static bool forwardToGCC(const Option &O) {
  37. // LinkerInput options have been forwarded. Don't duplicate.
  38. if (O.hasFlag(options::LinkerInput))
  39. return false;
  40. return O.matches(options::OPT_Link_Group) || O.hasFlag(options::LinkOption);
  41. }
  42. // Switch CPU names not recognized by GNU assembler to a close CPU that it does
  43. // recognize, instead of a lower march from being picked in the absence of a cpu
  44. // flag.
  45. static void normalizeCPUNamesForAssembler(const ArgList &Args,
  46. ArgStringList &CmdArgs) {
  47. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  48. StringRef CPUArg(A->getValue());
  49. if (CPUArg.equals_insensitive("krait"))
  50. CmdArgs.push_back("-mcpu=cortex-a15");
  51. else if (CPUArg.equals_insensitive("kryo"))
  52. CmdArgs.push_back("-mcpu=cortex-a57");
  53. else
  54. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  55. }
  56. }
  57. void tools::gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  58. const InputInfo &Output,
  59. const InputInfoList &Inputs,
  60. const ArgList &Args,
  61. const char *LinkingOutput) const {
  62. const Driver &D = getToolChain().getDriver();
  63. ArgStringList CmdArgs;
  64. for (const auto &A : Args) {
  65. if (forwardToGCC(A->getOption())) {
  66. // It is unfortunate that we have to claim here, as this means
  67. // we will basically never report anything interesting for
  68. // platforms using a generic gcc, even if we are just using gcc
  69. // to get to the assembler.
  70. A->claim();
  71. A->render(Args, CmdArgs);
  72. }
  73. }
  74. RenderExtraToolArgs(JA, CmdArgs);
  75. // If using a driver driver, force the arch.
  76. if (getToolChain().getTriple().isOSDarwin()) {
  77. CmdArgs.push_back("-arch");
  78. CmdArgs.push_back(
  79. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  80. }
  81. // Try to force gcc to match the tool chain we want, if we recognize
  82. // the arch.
  83. //
  84. // FIXME: The triple class should directly provide the information we want
  85. // here.
  86. switch (getToolChain().getArch()) {
  87. default:
  88. break;
  89. case llvm::Triple::x86:
  90. case llvm::Triple::ppc:
  91. case llvm::Triple::ppcle:
  92. CmdArgs.push_back("-m32");
  93. break;
  94. case llvm::Triple::x86_64:
  95. case llvm::Triple::ppc64:
  96. case llvm::Triple::ppc64le:
  97. CmdArgs.push_back("-m64");
  98. break;
  99. case llvm::Triple::sparcel:
  100. CmdArgs.push_back("-EL");
  101. break;
  102. }
  103. if (Output.isFilename()) {
  104. CmdArgs.push_back("-o");
  105. CmdArgs.push_back(Output.getFilename());
  106. } else {
  107. assert(Output.isNothing() && "Unexpected output");
  108. CmdArgs.push_back("-fsyntax-only");
  109. }
  110. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  111. // Only pass -x if gcc will understand it; otherwise hope gcc
  112. // understands the suffix correctly. The main use case this would go
  113. // wrong in is for linker inputs if they happened to have an odd
  114. // suffix; really the only way to get this to happen is a command
  115. // like '-x foobar a.c' which will treat a.c like a linker input.
  116. //
  117. // FIXME: For the linker case specifically, can we safely convert
  118. // inputs into '-Wl,' options?
  119. for (const auto &II : Inputs) {
  120. // Don't try to pass LLVM or AST inputs to a generic gcc.
  121. if (types::isLLVMIR(II.getType()))
  122. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  123. << getToolChain().getTripleString();
  124. else if (II.getType() == types::TY_AST)
  125. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  126. else if (II.getType() == types::TY_ModuleFile)
  127. D.Diag(diag::err_drv_no_module_support)
  128. << getToolChain().getTripleString();
  129. if (types::canTypeBeUserSpecified(II.getType())) {
  130. CmdArgs.push_back("-x");
  131. CmdArgs.push_back(types::getTypeName(II.getType()));
  132. }
  133. if (II.isFilename())
  134. CmdArgs.push_back(II.getFilename());
  135. else {
  136. const Arg &A = II.getInputArg();
  137. // Reverse translate some rewritten options.
  138. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  139. CmdArgs.push_back("-lstdc++");
  140. continue;
  141. }
  142. // Don't render as input, we need gcc to do the translations.
  143. A.render(Args, CmdArgs);
  144. }
  145. }
  146. const std::string &customGCCName = D.getCCCGenericGCCName();
  147. const char *GCCName;
  148. if (!customGCCName.empty())
  149. GCCName = customGCCName.c_str();
  150. else if (D.CCCIsCXX()) {
  151. GCCName = "g++";
  152. } else
  153. GCCName = "gcc";
  154. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  155. C.addCommand(std::make_unique<Command>(JA, *this,
  156. ResponseFileSupport::AtFileCurCP(),
  157. Exec, CmdArgs, Inputs, Output));
  158. }
  159. void tools::gcc::Preprocessor::RenderExtraToolArgs(
  160. const JobAction &JA, ArgStringList &CmdArgs) const {
  161. CmdArgs.push_back("-E");
  162. }
  163. void tools::gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  164. ArgStringList &CmdArgs) const {
  165. const Driver &D = getToolChain().getDriver();
  166. switch (JA.getType()) {
  167. // If -flto, etc. are present then make sure not to force assembly output.
  168. case types::TY_LLVM_IR:
  169. case types::TY_LTO_IR:
  170. case types::TY_LLVM_BC:
  171. case types::TY_LTO_BC:
  172. CmdArgs.push_back("-c");
  173. break;
  174. // We assume we've got an "integrated" assembler in that gcc will produce an
  175. // object file itself.
  176. case types::TY_Object:
  177. CmdArgs.push_back("-c");
  178. break;
  179. case types::TY_PP_Asm:
  180. CmdArgs.push_back("-S");
  181. break;
  182. case types::TY_Nothing:
  183. CmdArgs.push_back("-fsyntax-only");
  184. break;
  185. default:
  186. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  187. }
  188. }
  189. void tools::gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  190. ArgStringList &CmdArgs) const {
  191. // The types are (hopefully) good enough.
  192. }
  193. // On Arm the endianness of the output file is determined by the target and
  194. // can be overridden by the pseudo-target flags '-mlittle-endian'/'-EL' and
  195. // '-mbig-endian'/'-EB'. Unlike other targets the flag does not result in a
  196. // normalized triple so we must handle the flag here.
  197. static bool isArmBigEndian(const llvm::Triple &Triple,
  198. const ArgList &Args) {
  199. bool IsBigEndian = false;
  200. switch (Triple.getArch()) {
  201. case llvm::Triple::armeb:
  202. case llvm::Triple::thumbeb:
  203. IsBigEndian = true;
  204. LLVM_FALLTHROUGH;
  205. case llvm::Triple::arm:
  206. case llvm::Triple::thumb:
  207. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  208. options::OPT_mbig_endian))
  209. IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
  210. break;
  211. default:
  212. break;
  213. }
  214. return IsBigEndian;
  215. }
  216. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  217. switch (T.getArch()) {
  218. case llvm::Triple::x86:
  219. if (T.isOSIAMCU())
  220. return "elf_iamcu";
  221. return "elf_i386";
  222. case llvm::Triple::aarch64:
  223. return "aarch64linux";
  224. case llvm::Triple::aarch64_be:
  225. return "aarch64linuxb";
  226. case llvm::Triple::arm:
  227. case llvm::Triple::thumb:
  228. case llvm::Triple::armeb:
  229. case llvm::Triple::thumbeb:
  230. return isArmBigEndian(T, Args) ? "armelfb_linux_eabi" : "armelf_linux_eabi";
  231. case llvm::Triple::m68k:
  232. return "m68kelf";
  233. case llvm::Triple::ppc:
  234. if (T.isOSLinux())
  235. return "elf32ppclinux";
  236. return "elf32ppc";
  237. case llvm::Triple::ppcle:
  238. if (T.isOSLinux())
  239. return "elf32lppclinux";
  240. return "elf32lppc";
  241. case llvm::Triple::ppc64:
  242. return "elf64ppc";
  243. case llvm::Triple::ppc64le:
  244. return "elf64lppc";
  245. case llvm::Triple::riscv32:
  246. return "elf32lriscv";
  247. case llvm::Triple::riscv64:
  248. return "elf64lriscv";
  249. case llvm::Triple::sparc:
  250. case llvm::Triple::sparcel:
  251. return "elf32_sparc";
  252. case llvm::Triple::sparcv9:
  253. return "elf64_sparc";
  254. case llvm::Triple::mips:
  255. return "elf32btsmip";
  256. case llvm::Triple::mipsel:
  257. return "elf32ltsmip";
  258. case llvm::Triple::mips64:
  259. if (tools::mips::hasMipsAbiArg(Args, "n32") ||
  260. T.getEnvironment() == llvm::Triple::GNUABIN32)
  261. return "elf32btsmipn32";
  262. return "elf64btsmip";
  263. case llvm::Triple::mips64el:
  264. if (tools::mips::hasMipsAbiArg(Args, "n32") ||
  265. T.getEnvironment() == llvm::Triple::GNUABIN32)
  266. return "elf32ltsmipn32";
  267. return "elf64ltsmip";
  268. case llvm::Triple::systemz:
  269. return "elf64_s390";
  270. case llvm::Triple::x86_64:
  271. if (T.isX32())
  272. return "elf32_x86_64";
  273. return "elf_x86_64";
  274. case llvm::Triple::ve:
  275. return "elf64ve";
  276. default:
  277. return nullptr;
  278. }
  279. }
  280. static bool getPIE(const ArgList &Args, const ToolChain &TC) {
  281. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
  282. Args.hasArg(options::OPT_r) || Args.hasArg(options::OPT_static_pie))
  283. return false;
  284. Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,
  285. options::OPT_nopie);
  286. if (!A)
  287. return TC.isPIEDefault(Args);
  288. return A->getOption().matches(options::OPT_pie);
  289. }
  290. static bool getStaticPIE(const ArgList &Args, const ToolChain &TC) {
  291. bool HasStaticPIE = Args.hasArg(options::OPT_static_pie);
  292. // -no-pie is an alias for -nopie. So, handling -nopie takes care of
  293. // -no-pie as well.
  294. if (HasStaticPIE && Args.hasArg(options::OPT_nopie)) {
  295. const Driver &D = TC.getDriver();
  296. const llvm::opt::OptTable &Opts = D.getOpts();
  297. const char *StaticPIEName = Opts.getOptionName(options::OPT_static_pie);
  298. const char *NoPIEName = Opts.getOptionName(options::OPT_nopie);
  299. D.Diag(diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName;
  300. }
  301. return HasStaticPIE;
  302. }
  303. static bool getStatic(const ArgList &Args) {
  304. return Args.hasArg(options::OPT_static) &&
  305. !Args.hasArg(options::OPT_static_pie);
  306. }
  307. void tools::gnutools::StaticLibTool::ConstructJob(
  308. Compilation &C, const JobAction &JA, const InputInfo &Output,
  309. const InputInfoList &Inputs, const ArgList &Args,
  310. const char *LinkingOutput) const {
  311. const Driver &D = getToolChain().getDriver();
  312. // Silence warning for "clang -g foo.o -o foo"
  313. Args.ClaimAllArgs(options::OPT_g_Group);
  314. // and "clang -emit-llvm foo.o -o foo"
  315. Args.ClaimAllArgs(options::OPT_emit_llvm);
  316. // and for "clang -w foo.o -o foo". Other warning options are already
  317. // handled somewhere else.
  318. Args.ClaimAllArgs(options::OPT_w);
  319. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  320. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  321. // ar tool command "llvm-ar <options> <output_file> <input_files>".
  322. ArgStringList CmdArgs;
  323. // Create and insert file members with a deterministic index.
  324. CmdArgs.push_back("rcsD");
  325. CmdArgs.push_back(Output.getFilename());
  326. for (const auto &II : Inputs) {
  327. if (II.isFilename()) {
  328. CmdArgs.push_back(II.getFilename());
  329. }
  330. }
  331. // Delete old output archive file if it already exists before generating a new
  332. // archive file.
  333. auto OutputFileName = Output.getFilename();
  334. if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) {
  335. if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) {
  336. D.Diag(diag::err_drv_unable_to_remove_file) << EC.message();
  337. return;
  338. }
  339. }
  340. const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
  341. C.addCommand(std::make_unique<Command>(JA, *this,
  342. ResponseFileSupport::AtFileCurCP(),
  343. Exec, CmdArgs, Inputs, Output));
  344. }
  345. void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  346. const InputInfo &Output,
  347. const InputInfoList &Inputs,
  348. const ArgList &Args,
  349. const char *LinkingOutput) const {
  350. // FIXME: The Linker class constructor takes a ToolChain and not a
  351. // Generic_ELF, so the static_cast might return a reference to a invalid
  352. // instance (see PR45061). Ideally, the Linker constructor needs to take a
  353. // Generic_ELF instead.
  354. const toolchains::Generic_ELF &ToolChain =
  355. static_cast<const toolchains::Generic_ELF &>(getToolChain());
  356. const Driver &D = ToolChain.getDriver();
  357. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  358. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  359. const bool isAndroid = ToolChain.getTriple().isAndroid();
  360. const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
  361. const bool IsVE = ToolChain.getTriple().isVE();
  362. const bool IsPIE = getPIE(Args, ToolChain);
  363. const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
  364. const bool IsStatic = getStatic(Args);
  365. const bool HasCRTBeginEndFiles =
  366. ToolChain.getTriple().hasEnvironment() ||
  367. (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
  368. ArgStringList CmdArgs;
  369. // Silence warning for "clang -g foo.o -o foo"
  370. Args.ClaimAllArgs(options::OPT_g_Group);
  371. // and "clang -emit-llvm foo.o -o foo"
  372. Args.ClaimAllArgs(options::OPT_emit_llvm);
  373. // and for "clang -w foo.o -o foo". Other warning options are already
  374. // handled somewhere else.
  375. Args.ClaimAllArgs(options::OPT_w);
  376. if (!D.SysRoot.empty())
  377. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  378. if (IsPIE)
  379. CmdArgs.push_back("-pie");
  380. if (IsStaticPIE) {
  381. CmdArgs.push_back("-static");
  382. CmdArgs.push_back("-pie");
  383. CmdArgs.push_back("--no-dynamic-linker");
  384. CmdArgs.push_back("-z");
  385. CmdArgs.push_back("text");
  386. }
  387. if (Args.hasArg(options::OPT_rdynamic))
  388. CmdArgs.push_back("-export-dynamic");
  389. if (Args.hasArg(options::OPT_s))
  390. CmdArgs.push_back("-s");
  391. if (Triple.isARM() || Triple.isThumb() || Triple.isAArch64()) {
  392. bool IsBigEndian = isArmBigEndian(Triple, Args);
  393. if (IsBigEndian)
  394. arm::appendBE8LinkFlag(Args, CmdArgs, Triple);
  395. IsBigEndian = IsBigEndian || Arch == llvm::Triple::aarch64_be;
  396. CmdArgs.push_back(IsBigEndian ? "-EB" : "-EL");
  397. }
  398. // Most Android ARM64 targets should enable the linker fix for erratum
  399. // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
  400. if (Arch == llvm::Triple::aarch64 && isAndroid) {
  401. std::string CPU = getCPUName(D, Args, Triple);
  402. if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
  403. CmdArgs.push_back("--fix-cortex-a53-843419");
  404. }
  405. // Android does not allow shared text relocations. Emit a warning if the
  406. // user's code contains any.
  407. if (isAndroid)
  408. CmdArgs.push_back("--warn-shared-textrel");
  409. ToolChain.addExtraOpts(CmdArgs);
  410. CmdArgs.push_back("--eh-frame-hdr");
  411. if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
  412. CmdArgs.push_back("-m");
  413. CmdArgs.push_back(LDMOption);
  414. } else {
  415. D.Diag(diag::err_target_unknown_triple) << Triple.str();
  416. return;
  417. }
  418. if (Args.hasArg(options::OPT_shared))
  419. CmdArgs.push_back("-shared");
  420. if (IsStatic) {
  421. CmdArgs.push_back("-static");
  422. } else {
  423. if (Args.hasArg(options::OPT_rdynamic))
  424. CmdArgs.push_back("-export-dynamic");
  425. if (!Args.hasArg(options::OPT_shared) && !IsStaticPIE) {
  426. CmdArgs.push_back("-dynamic-linker");
  427. CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) +
  428. ToolChain.getDynamicLinker(Args)));
  429. }
  430. }
  431. CmdArgs.push_back("-o");
  432. CmdArgs.push_back(Output.getFilename());
  433. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
  434. options::OPT_r)) {
  435. if (!isAndroid && !IsIAMCU) {
  436. const char *crt1 = nullptr;
  437. if (!Args.hasArg(options::OPT_shared)) {
  438. if (Args.hasArg(options::OPT_pg))
  439. crt1 = "gcrt1.o";
  440. else if (IsPIE)
  441. crt1 = "Scrt1.o";
  442. else if (IsStaticPIE)
  443. crt1 = "rcrt1.o";
  444. else
  445. crt1 = "crt1.o";
  446. }
  447. if (crt1)
  448. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  449. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  450. }
  451. if (IsVE) {
  452. CmdArgs.push_back("-z");
  453. CmdArgs.push_back("max-page-size=0x4000000");
  454. }
  455. if (IsIAMCU)
  456. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  457. else if (HasCRTBeginEndFiles) {
  458. std::string P;
  459. if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
  460. !isAndroid) {
  461. std::string crtbegin = ToolChain.getCompilerRT(Args, "crtbegin",
  462. ToolChain::FT_Object);
  463. if (ToolChain.getVFS().exists(crtbegin))
  464. P = crtbegin;
  465. }
  466. if (P.empty()) {
  467. const char *crtbegin;
  468. if (Args.hasArg(options::OPT_shared))
  469. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  470. else if (IsStatic)
  471. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  472. else if (IsPIE || IsStaticPIE)
  473. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  474. else
  475. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  476. P = ToolChain.GetFilePath(crtbegin);
  477. }
  478. CmdArgs.push_back(Args.MakeArgString(P));
  479. }
  480. // Add crtfastmath.o if available and fast math is enabled.
  481. ToolChain.addFastMathRuntimeIfAvailable(Args, CmdArgs);
  482. }
  483. Args.AddAllArgs(CmdArgs, options::OPT_L);
  484. Args.AddAllArgs(CmdArgs, options::OPT_u);
  485. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  486. if (D.isUsingLTO()) {
  487. assert(!Inputs.empty() && "Must have at least one input.");
  488. addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
  489. D.getLTOMode() == LTOK_Thin);
  490. }
  491. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  492. CmdArgs.push_back("--no-demangle");
  493. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  494. bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
  495. addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs);
  496. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
  497. // The profile runtime also needs access to system libraries.
  498. getToolChain().addProfileRTLibs(Args, CmdArgs);
  499. if (D.CCCIsCXX() &&
  500. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
  501. options::OPT_r)) {
  502. if (ToolChain.ShouldLinkCXXStdlib(Args)) {
  503. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  504. !Args.hasArg(options::OPT_static);
  505. if (OnlyLibstdcxxStatic)
  506. CmdArgs.push_back("-Bstatic");
  507. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  508. if (OnlyLibstdcxxStatic)
  509. CmdArgs.push_back("-Bdynamic");
  510. }
  511. CmdArgs.push_back("-lm");
  512. }
  513. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  514. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  515. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_r)) {
  516. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  517. if (IsStatic || IsStaticPIE)
  518. CmdArgs.push_back("--start-group");
  519. if (NeedsSanitizerDeps)
  520. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  521. if (NeedsXRayDeps)
  522. linkXRayRuntimeDeps(ToolChain, CmdArgs);
  523. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  524. Args.hasArg(options::OPT_pthreads);
  525. // Use the static OpenMP runtime with -static-openmp
  526. bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
  527. !Args.hasArg(options::OPT_static);
  528. // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
  529. // require librt. Most modern Linux platforms do, but some may not.
  530. if (addOpenMPRuntime(CmdArgs, ToolChain, Args, StaticOpenMP,
  531. JA.isHostOffloading(Action::OFK_OpenMP),
  532. /* GompNeedsRT= */ true))
  533. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  534. // FIXME: Does this really make sense for all GNU toolchains?
  535. WantPthread = true;
  536. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  537. if (WantPthread && !isAndroid)
  538. CmdArgs.push_back("-lpthread");
  539. if (Args.hasArg(options::OPT_fsplit_stack))
  540. CmdArgs.push_back("--wrap=pthread_create");
  541. if (!Args.hasArg(options::OPT_nolibc))
  542. CmdArgs.push_back("-lc");
  543. // Add IAMCU specific libs, if needed.
  544. if (IsIAMCU)
  545. CmdArgs.push_back("-lgloss");
  546. if (IsStatic || IsStaticPIE)
  547. CmdArgs.push_back("--end-group");
  548. else
  549. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  550. // Add IAMCU specific libs (outside the group), if needed.
  551. if (IsIAMCU) {
  552. CmdArgs.push_back("--as-needed");
  553. CmdArgs.push_back("-lsoftfp");
  554. CmdArgs.push_back("--no-as-needed");
  555. }
  556. }
  557. if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
  558. if (HasCRTBeginEndFiles) {
  559. std::string P;
  560. if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
  561. !isAndroid) {
  562. std::string crtend = ToolChain.getCompilerRT(Args, "crtend",
  563. ToolChain::FT_Object);
  564. if (ToolChain.getVFS().exists(crtend))
  565. P = crtend;
  566. }
  567. if (P.empty()) {
  568. const char *crtend;
  569. if (Args.hasArg(options::OPT_shared))
  570. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  571. else if (IsPIE || IsStaticPIE)
  572. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  573. else
  574. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  575. P = ToolChain.GetFilePath(crtend);
  576. }
  577. CmdArgs.push_back(Args.MakeArgString(P));
  578. }
  579. if (!isAndroid)
  580. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  581. }
  582. }
  583. Args.AddAllArgs(CmdArgs, options::OPT_T);
  584. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  585. C.addCommand(std::make_unique<Command>(JA, *this,
  586. ResponseFileSupport::AtFileCurCP(),
  587. Exec, CmdArgs, Inputs, Output));
  588. }
  589. void tools::gnutools::Assembler::ConstructJob(Compilation &C,
  590. const JobAction &JA,
  591. const InputInfo &Output,
  592. const InputInfoList &Inputs,
  593. const ArgList &Args,
  594. const char *LinkingOutput) const {
  595. const auto &D = getToolChain().getDriver();
  596. claimNoWarnArgs(Args);
  597. ArgStringList CmdArgs;
  598. llvm::Reloc::Model RelocationModel;
  599. unsigned PICLevel;
  600. bool IsPIE;
  601. const char *DefaultAssembler = "as";
  602. std::tie(RelocationModel, PICLevel, IsPIE) =
  603. ParsePICArgs(getToolChain(), Args);
  604. if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) {
  605. if (A->getOption().getID() == options::OPT_gz) {
  606. CmdArgs.push_back("--compress-debug-sections");
  607. } else {
  608. StringRef Value = A->getValue();
  609. if (Value == "none" || Value == "zlib") {
  610. CmdArgs.push_back(
  611. Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
  612. } else {
  613. D.Diag(diag::err_drv_unsupported_option_argument)
  614. << A->getOption().getName() << Value;
  615. }
  616. }
  617. }
  618. switch (getToolChain().getArch()) {
  619. default:
  620. break;
  621. // Add --32/--64 to make sure we get the format we want.
  622. // This is incomplete
  623. case llvm::Triple::x86:
  624. CmdArgs.push_back("--32");
  625. break;
  626. case llvm::Triple::x86_64:
  627. if (getToolChain().getTriple().isX32())
  628. CmdArgs.push_back("--x32");
  629. else
  630. CmdArgs.push_back("--64");
  631. break;
  632. case llvm::Triple::ppc: {
  633. CmdArgs.push_back("-a32");
  634. CmdArgs.push_back("-mppc");
  635. CmdArgs.push_back("-mbig-endian");
  636. CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
  637. getCPUName(D, Args, getToolChain().getTriple())));
  638. break;
  639. }
  640. case llvm::Triple::ppcle: {
  641. CmdArgs.push_back("-a32");
  642. CmdArgs.push_back("-mppc");
  643. CmdArgs.push_back("-mlittle-endian");
  644. CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
  645. getCPUName(D, Args, getToolChain().getTriple())));
  646. break;
  647. }
  648. case llvm::Triple::ppc64: {
  649. CmdArgs.push_back("-a64");
  650. CmdArgs.push_back("-mppc64");
  651. CmdArgs.push_back("-mbig-endian");
  652. CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
  653. getCPUName(D, Args, getToolChain().getTriple())));
  654. break;
  655. }
  656. case llvm::Triple::ppc64le: {
  657. CmdArgs.push_back("-a64");
  658. CmdArgs.push_back("-mppc64");
  659. CmdArgs.push_back("-mlittle-endian");
  660. CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
  661. getCPUName(D, Args, getToolChain().getTriple())));
  662. break;
  663. }
  664. case llvm::Triple::riscv32:
  665. case llvm::Triple::riscv64: {
  666. StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
  667. CmdArgs.push_back("-mabi");
  668. CmdArgs.push_back(ABIName.data());
  669. StringRef MArchName = riscv::getRISCVArch(Args, getToolChain().getTriple());
  670. CmdArgs.push_back("-march");
  671. CmdArgs.push_back(MArchName.data());
  672. break;
  673. }
  674. case llvm::Triple::sparc:
  675. case llvm::Triple::sparcel: {
  676. CmdArgs.push_back("-32");
  677. std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
  678. CmdArgs.push_back(
  679. sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  680. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  681. break;
  682. }
  683. case llvm::Triple::sparcv9: {
  684. CmdArgs.push_back("-64");
  685. std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
  686. CmdArgs.push_back(
  687. sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  688. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  689. break;
  690. }
  691. case llvm::Triple::arm:
  692. case llvm::Triple::armeb:
  693. case llvm::Triple::thumb:
  694. case llvm::Triple::thumbeb: {
  695. const llvm::Triple &Triple2 = getToolChain().getTriple();
  696. CmdArgs.push_back(isArmBigEndian(Triple2, Args) ? "-EB" : "-EL");
  697. switch (Triple2.getSubArch()) {
  698. case llvm::Triple::ARMSubArch_v7:
  699. CmdArgs.push_back("-mfpu=neon");
  700. break;
  701. case llvm::Triple::ARMSubArch_v8:
  702. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  703. break;
  704. default:
  705. break;
  706. }
  707. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  708. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  709. case arm::FloatABI::Soft:
  710. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  711. break;
  712. case arm::FloatABI::SoftFP:
  713. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  714. break;
  715. case arm::FloatABI::Hard:
  716. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  717. break;
  718. }
  719. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  720. normalizeCPUNamesForAssembler(Args, CmdArgs);
  721. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  722. break;
  723. }
  724. case llvm::Triple::aarch64:
  725. case llvm::Triple::aarch64_be: {
  726. CmdArgs.push_back(
  727. getToolChain().getArch() == llvm::Triple::aarch64_be ? "-EB" : "-EL");
  728. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  729. normalizeCPUNamesForAssembler(Args, CmdArgs);
  730. break;
  731. }
  732. case llvm::Triple::mips:
  733. case llvm::Triple::mipsel:
  734. case llvm::Triple::mips64:
  735. case llvm::Triple::mips64el: {
  736. StringRef CPUName;
  737. StringRef ABIName;
  738. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  739. ABIName = mips::getGnuCompatibleMipsABIName(ABIName);
  740. CmdArgs.push_back("-march");
  741. CmdArgs.push_back(CPUName.data());
  742. CmdArgs.push_back("-mabi");
  743. CmdArgs.push_back(ABIName.data());
  744. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  745. // or -mshared (not implemented) is in effect.
  746. if (RelocationModel == llvm::Reloc::Static)
  747. CmdArgs.push_back("-mno-shared");
  748. // LLVM doesn't support -mplt yet and acts as if it is always given.
  749. // However, -mplt has no effect with the N64 ABI.
  750. if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls))
  751. CmdArgs.push_back("-call_nonpic");
  752. if (getToolChain().getTriple().isLittleEndian())
  753. CmdArgs.push_back("-EL");
  754. else
  755. CmdArgs.push_back("-EB");
  756. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  757. if (StringRef(A->getValue()) == "2008")
  758. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  759. }
  760. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  761. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  762. options::OPT_mfp64)) {
  763. A->claim();
  764. A->render(Args, CmdArgs);
  765. } else if (mips::shouldUseFPXX(
  766. Args, getToolChain().getTriple(), CPUName, ABIName,
  767. mips::getMipsFloatABI(getToolChain().getDriver(), Args,
  768. getToolChain().getTriple())))
  769. CmdArgs.push_back("-mfpxx");
  770. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  771. // -mno-mips16 is actually -no-mips16.
  772. if (Arg *A =
  773. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  774. if (A->getOption().matches(options::OPT_mips16)) {
  775. A->claim();
  776. A->render(Args, CmdArgs);
  777. } else {
  778. A->claim();
  779. CmdArgs.push_back("-no-mips16");
  780. }
  781. }
  782. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  783. options::OPT_mno_micromips);
  784. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  785. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  786. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  787. // Do not use AddLastArg because not all versions of MIPS assembler
  788. // support -mmsa / -mno-msa options.
  789. if (A->getOption().matches(options::OPT_mmsa))
  790. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  791. }
  792. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  793. options::OPT_msoft_float);
  794. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  795. options::OPT_msingle_float);
  796. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  797. options::OPT_mno_odd_spreg);
  798. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  799. break;
  800. }
  801. case llvm::Triple::systemz: {
  802. // Always pass an -march option, since our default of z10 is later
  803. // than the GNU assembler's default.
  804. std::string CPUName = systemz::getSystemZTargetCPU(Args);
  805. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  806. break;
  807. }
  808. case llvm::Triple::ve:
  809. DefaultAssembler = "nas";
  810. }
  811. for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
  812. options::OPT_fdebug_prefix_map_EQ)) {
  813. StringRef Map = A->getValue();
  814. if (!Map.contains('='))
  815. D.Diag(diag::err_drv_invalid_argument_to_option)
  816. << Map << A->getOption().getName();
  817. else {
  818. CmdArgs.push_back(Args.MakeArgString("--debug-prefix-map"));
  819. CmdArgs.push_back(Args.MakeArgString(Map));
  820. }
  821. A->claim();
  822. }
  823. Args.AddAllArgs(CmdArgs, options::OPT_I);
  824. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  825. CmdArgs.push_back("-o");
  826. CmdArgs.push_back(Output.getFilename());
  827. for (const auto &II : Inputs)
  828. CmdArgs.push_back(II.getFilename());
  829. const char *Exec =
  830. Args.MakeArgString(getToolChain().GetProgramPath(DefaultAssembler));
  831. C.addCommand(std::make_unique<Command>(JA, *this,
  832. ResponseFileSupport::AtFileCurCP(),
  833. Exec, CmdArgs, Inputs, Output));
  834. // Handle the debug info splitting at object creation time if we're
  835. // creating an object.
  836. // TODO: Currently only works on linux with newer objcopy.
  837. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  838. getToolChain().getTriple().isOSLinux())
  839. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  840. SplitDebugName(JA, Args, Inputs[0], Output));
  841. }
  842. namespace {
  843. // Filter to remove Multilibs that don't exist as a suffix to Path
  844. class FilterNonExistent {
  845. StringRef Base, File;
  846. llvm::vfs::FileSystem &VFS;
  847. public:
  848. FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS)
  849. : Base(Base), File(File), VFS(VFS) {}
  850. bool operator()(const Multilib &M) {
  851. return !VFS.exists(Base + M.gccSuffix() + File);
  852. }
  853. };
  854. } // end anonymous namespace
  855. static bool isSoftFloatABI(const ArgList &Args) {
  856. Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  857. options::OPT_mfloat_abi_EQ);
  858. if (!A)
  859. return false;
  860. return A->getOption().matches(options::OPT_msoft_float) ||
  861. (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
  862. A->getValue() == StringRef("soft"));
  863. }
  864. static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
  865. return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
  866. }
  867. static bool isMipsEL(llvm::Triple::ArchType Arch) {
  868. return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
  869. }
  870. static bool isMips16(const ArgList &Args) {
  871. Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
  872. return A && A->getOption().matches(options::OPT_mips16);
  873. }
  874. static bool isMicroMips(const ArgList &Args) {
  875. Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
  876. return A && A->getOption().matches(options::OPT_mmicromips);
  877. }
  878. static bool isMSP430(llvm::Triple::ArchType Arch) {
  879. return Arch == llvm::Triple::msp430;
  880. }
  881. static Multilib makeMultilib(StringRef commonSuffix) {
  882. return Multilib(commonSuffix, commonSuffix, commonSuffix);
  883. }
  884. static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
  885. FilterNonExistent &NonExistent,
  886. DetectedMultilibs &Result) {
  887. // Check for Code Sourcery toolchain multilibs
  888. MultilibSet CSMipsMultilibs;
  889. {
  890. auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
  891. auto MArchMicroMips =
  892. makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
  893. auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
  894. auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
  895. auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
  896. auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
  897. auto DefaultFloat =
  898. makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
  899. auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
  900. auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
  901. // Note that this one's osSuffix is ""
  902. auto MAbi64 = makeMultilib("")
  903. .gccSuffix("/64")
  904. .includeSuffix("/64")
  905. .flag("+mabi=n64")
  906. .flag("-mabi=n32")
  907. .flag("-m32");
  908. CSMipsMultilibs =
  909. MultilibSet()
  910. .Either(MArchMips16, MArchMicroMips, MArchDefault)
  911. .Maybe(UCLibc)
  912. .Either(SoftFloat, Nan2008, DefaultFloat)
  913. .FilterOut("/micromips/nan2008")
  914. .FilterOut("/mips16/nan2008")
  915. .Either(BigEndian, LittleEndian)
  916. .Maybe(MAbi64)
  917. .FilterOut("/mips16.*/64")
  918. .FilterOut("/micromips.*/64")
  919. .FilterOut(NonExistent)
  920. .setIncludeDirsCallback([](const Multilib &M) {
  921. std::vector<std::string> Dirs({"/include"});
  922. if (StringRef(M.includeSuffix()).startswith("/uclibc"))
  923. Dirs.push_back(
  924. "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
  925. else
  926. Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
  927. return Dirs;
  928. });
  929. }
  930. MultilibSet DebianMipsMultilibs;
  931. {
  932. Multilib MAbiN32 =
  933. Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
  934. Multilib M64 = Multilib()
  935. .gccSuffix("/64")
  936. .includeSuffix("/64")
  937. .flag("+m64")
  938. .flag("-m32")
  939. .flag("-mabi=n32");
  940. Multilib M32 =
  941. Multilib().gccSuffix("/32").flag("-m64").flag("+m32").flag("-mabi=n32");
  942. DebianMipsMultilibs =
  943. MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
  944. }
  945. // Sort candidates. Toolchain that best meets the directories tree goes first.
  946. // Then select the first toolchains matches command line flags.
  947. MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
  948. if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
  949. std::iter_swap(Candidates, Candidates + 1);
  950. for (const MultilibSet *Candidate : Candidates) {
  951. if (Candidate->select(Flags, Result.SelectedMultilib)) {
  952. if (Candidate == &DebianMipsMultilibs)
  953. Result.BiarchSibling = Multilib();
  954. Result.Multilibs = *Candidate;
  955. return true;
  956. }
  957. }
  958. return false;
  959. }
  960. static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path,
  961. const Multilib::flags_list &Flags,
  962. FilterNonExistent &NonExistent,
  963. DetectedMultilibs &Result) {
  964. MultilibSet AndroidMipsMultilibs =
  965. MultilibSet()
  966. .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
  967. .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
  968. .FilterOut(NonExistent);
  969. MultilibSet AndroidMipselMultilibs =
  970. MultilibSet()
  971. .Either(Multilib().flag("+march=mips32"),
  972. Multilib("/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
  973. Multilib("/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
  974. .FilterOut(NonExistent);
  975. MultilibSet AndroidMips64elMultilibs =
  976. MultilibSet()
  977. .Either(
  978. Multilib().flag("+march=mips64r6"),
  979. Multilib("/32/mips-r1", "", "/mips-r1").flag("+march=mips32"),
  980. Multilib("/32/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
  981. Multilib("/32/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
  982. .FilterOut(NonExistent);
  983. MultilibSet *MS = &AndroidMipsMultilibs;
  984. if (VFS.exists(Path + "/mips-r6"))
  985. MS = &AndroidMipselMultilibs;
  986. else if (VFS.exists(Path + "/32"))
  987. MS = &AndroidMips64elMultilibs;
  988. if (MS->select(Flags, Result.SelectedMultilib)) {
  989. Result.Multilibs = *MS;
  990. return true;
  991. }
  992. return false;
  993. }
  994. static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags,
  995. FilterNonExistent &NonExistent,
  996. DetectedMultilibs &Result) {
  997. // Musl toolchain multilibs
  998. MultilibSet MuslMipsMultilibs;
  999. {
  1000. auto MArchMipsR2 = makeMultilib("")
  1001. .osSuffix("/mips-r2-hard-musl")
  1002. .flag("+EB")
  1003. .flag("-EL")
  1004. .flag("+march=mips32r2");
  1005. auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
  1006. .flag("-EB")
  1007. .flag("+EL")
  1008. .flag("+march=mips32r2");
  1009. MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
  1010. // Specify the callback that computes the include directories.
  1011. MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
  1012. return std::vector<std::string>(
  1013. {"/../sysroot" + M.osSuffix() + "/usr/include"});
  1014. });
  1015. }
  1016. if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
  1017. Result.Multilibs = MuslMipsMultilibs;
  1018. return true;
  1019. }
  1020. return false;
  1021. }
  1022. static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags,
  1023. FilterNonExistent &NonExistent,
  1024. DetectedMultilibs &Result) {
  1025. // CodeScape MTI toolchain v1.2 and early.
  1026. MultilibSet MtiMipsMultilibsV1;
  1027. {
  1028. auto MArchMips32 = makeMultilib("/mips32")
  1029. .flag("+m32")
  1030. .flag("-m64")
  1031. .flag("-mmicromips")
  1032. .flag("+march=mips32");
  1033. auto MArchMicroMips = makeMultilib("/micromips")
  1034. .flag("+m32")
  1035. .flag("-m64")
  1036. .flag("+mmicromips");
  1037. auto MArchMips64r2 = makeMultilib("/mips64r2")
  1038. .flag("-m32")
  1039. .flag("+m64")
  1040. .flag("+march=mips64r2");
  1041. auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
  1042. "-march=mips64r2");
  1043. auto MArchDefault = makeMultilib("")
  1044. .flag("+m32")
  1045. .flag("-m64")
  1046. .flag("-mmicromips")
  1047. .flag("+march=mips32r2");
  1048. auto Mips16 = makeMultilib("/mips16").flag("+mips16");
  1049. auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
  1050. auto MAbi64 =
  1051. makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
  1052. auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
  1053. auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
  1054. auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
  1055. auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
  1056. MtiMipsMultilibsV1 =
  1057. MultilibSet()
  1058. .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
  1059. MArchDefault)
  1060. .Maybe(UCLibc)
  1061. .Maybe(Mips16)
  1062. .FilterOut("/mips64/mips16")
  1063. .FilterOut("/mips64r2/mips16")
  1064. .FilterOut("/micromips/mips16")
  1065. .Maybe(MAbi64)
  1066. .FilterOut("/micromips/64")
  1067. .FilterOut("/mips32/64")
  1068. .FilterOut("^/64")
  1069. .FilterOut("/mips16/64")
  1070. .Either(BigEndian, LittleEndian)
  1071. .Maybe(SoftFloat)
  1072. .Maybe(Nan2008)
  1073. .FilterOut(".*sof/nan2008")
  1074. .FilterOut(NonExistent)
  1075. .setIncludeDirsCallback([](const Multilib &M) {
  1076. std::vector<std::string> Dirs({"/include"});
  1077. if (StringRef(M.includeSuffix()).startswith("/uclibc"))
  1078. Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
  1079. else
  1080. Dirs.push_back("/../../../../sysroot/usr/include");
  1081. return Dirs;
  1082. });
  1083. }
  1084. // CodeScape IMG toolchain starting from v1.3.
  1085. MultilibSet MtiMipsMultilibsV2;
  1086. {
  1087. auto BeHard = makeMultilib("/mips-r2-hard")
  1088. .flag("+EB")
  1089. .flag("-msoft-float")
  1090. .flag("-mnan=2008")
  1091. .flag("-muclibc");
  1092. auto BeSoft = makeMultilib("/mips-r2-soft")
  1093. .flag("+EB")
  1094. .flag("+msoft-float")
  1095. .flag("-mnan=2008");
  1096. auto ElHard = makeMultilib("/mipsel-r2-hard")
  1097. .flag("+EL")
  1098. .flag("-msoft-float")
  1099. .flag("-mnan=2008")
  1100. .flag("-muclibc");
  1101. auto ElSoft = makeMultilib("/mipsel-r2-soft")
  1102. .flag("+EL")
  1103. .flag("+msoft-float")
  1104. .flag("-mnan=2008")
  1105. .flag("-mmicromips");
  1106. auto BeHardNan = makeMultilib("/mips-r2-hard-nan2008")
  1107. .flag("+EB")
  1108. .flag("-msoft-float")
  1109. .flag("+mnan=2008")
  1110. .flag("-muclibc");
  1111. auto ElHardNan = makeMultilib("/mipsel-r2-hard-nan2008")
  1112. .flag("+EL")
  1113. .flag("-msoft-float")
  1114. .flag("+mnan=2008")
  1115. .flag("-muclibc")
  1116. .flag("-mmicromips");
  1117. auto BeHardNanUclibc = makeMultilib("/mips-r2-hard-nan2008-uclibc")
  1118. .flag("+EB")
  1119. .flag("-msoft-float")
  1120. .flag("+mnan=2008")
  1121. .flag("+muclibc");
  1122. auto ElHardNanUclibc = makeMultilib("/mipsel-r2-hard-nan2008-uclibc")
  1123. .flag("+EL")
  1124. .flag("-msoft-float")
  1125. .flag("+mnan=2008")
  1126. .flag("+muclibc");
  1127. auto BeHardUclibc = makeMultilib("/mips-r2-hard-uclibc")
  1128. .flag("+EB")
  1129. .flag("-msoft-float")
  1130. .flag("-mnan=2008")
  1131. .flag("+muclibc");
  1132. auto ElHardUclibc = makeMultilib("/mipsel-r2-hard-uclibc")
  1133. .flag("+EL")
  1134. .flag("-msoft-float")
  1135. .flag("-mnan=2008")
  1136. .flag("+muclibc");
  1137. auto ElMicroHardNan = makeMultilib("/micromipsel-r2-hard-nan2008")
  1138. .flag("+EL")
  1139. .flag("-msoft-float")
  1140. .flag("+mnan=2008")
  1141. .flag("+mmicromips");
  1142. auto ElMicroSoft = makeMultilib("/micromipsel-r2-soft")
  1143. .flag("+EL")
  1144. .flag("+msoft-float")
  1145. .flag("-mnan=2008")
  1146. .flag("+mmicromips");
  1147. auto O32 =
  1148. makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
  1149. auto N32 =
  1150. makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
  1151. auto N64 =
  1152. makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
  1153. MtiMipsMultilibsV2 =
  1154. MultilibSet()
  1155. .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
  1156. BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
  1157. ElHardUclibc, ElMicroHardNan, ElMicroSoft})
  1158. .Either(O32, N32, N64)
  1159. .FilterOut(NonExistent)
  1160. .setIncludeDirsCallback([](const Multilib &M) {
  1161. return std::vector<std::string>({"/../../../../sysroot" +
  1162. M.includeSuffix() +
  1163. "/../usr/include"});
  1164. })
  1165. .setFilePathsCallback([](const Multilib &M) {
  1166. return std::vector<std::string>(
  1167. {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
  1168. });
  1169. }
  1170. for (auto Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
  1171. if (Candidate->select(Flags, Result.SelectedMultilib)) {
  1172. Result.Multilibs = *Candidate;
  1173. return true;
  1174. }
  1175. }
  1176. return false;
  1177. }
  1178. static bool findMipsImgMultilibs(const Multilib::flags_list &Flags,
  1179. FilterNonExistent &NonExistent,
  1180. DetectedMultilibs &Result) {
  1181. // CodeScape IMG toolchain v1.2 and early.
  1182. MultilibSet ImgMultilibsV1;
  1183. {
  1184. auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
  1185. auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
  1186. auto MAbi64 =
  1187. makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
  1188. ImgMultilibsV1 =
  1189. MultilibSet()
  1190. .Maybe(Mips64r6)
  1191. .Maybe(MAbi64)
  1192. .Maybe(LittleEndian)
  1193. .FilterOut(NonExistent)
  1194. .setIncludeDirsCallback([](const Multilib &M) {
  1195. return std::vector<std::string>(
  1196. {"/include", "/../../../../sysroot/usr/include"});
  1197. });
  1198. }
  1199. // CodeScape IMG toolchain starting from v1.3.
  1200. MultilibSet ImgMultilibsV2;
  1201. {
  1202. auto BeHard = makeMultilib("/mips-r6-hard")
  1203. .flag("+EB")
  1204. .flag("-msoft-float")
  1205. .flag("-mmicromips");
  1206. auto BeSoft = makeMultilib("/mips-r6-soft")
  1207. .flag("+EB")
  1208. .flag("+msoft-float")
  1209. .flag("-mmicromips");
  1210. auto ElHard = makeMultilib("/mipsel-r6-hard")
  1211. .flag("+EL")
  1212. .flag("-msoft-float")
  1213. .flag("-mmicromips");
  1214. auto ElSoft = makeMultilib("/mipsel-r6-soft")
  1215. .flag("+EL")
  1216. .flag("+msoft-float")
  1217. .flag("-mmicromips");
  1218. auto BeMicroHard = makeMultilib("/micromips-r6-hard")
  1219. .flag("+EB")
  1220. .flag("-msoft-float")
  1221. .flag("+mmicromips");
  1222. auto BeMicroSoft = makeMultilib("/micromips-r6-soft")
  1223. .flag("+EB")
  1224. .flag("+msoft-float")
  1225. .flag("+mmicromips");
  1226. auto ElMicroHard = makeMultilib("/micromipsel-r6-hard")
  1227. .flag("+EL")
  1228. .flag("-msoft-float")
  1229. .flag("+mmicromips");
  1230. auto ElMicroSoft = makeMultilib("/micromipsel-r6-soft")
  1231. .flag("+EL")
  1232. .flag("+msoft-float")
  1233. .flag("+mmicromips");
  1234. auto O32 =
  1235. makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
  1236. auto N32 =
  1237. makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
  1238. auto N64 =
  1239. makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
  1240. ImgMultilibsV2 =
  1241. MultilibSet()
  1242. .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
  1243. ElMicroHard, ElMicroSoft})
  1244. .Either(O32, N32, N64)
  1245. .FilterOut(NonExistent)
  1246. .setIncludeDirsCallback([](const Multilib &M) {
  1247. return std::vector<std::string>({"/../../../../sysroot" +
  1248. M.includeSuffix() +
  1249. "/../usr/include"});
  1250. })
  1251. .setFilePathsCallback([](const Multilib &M) {
  1252. return std::vector<std::string>(
  1253. {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
  1254. });
  1255. }
  1256. for (auto Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
  1257. if (Candidate->select(Flags, Result.SelectedMultilib)) {
  1258. Result.Multilibs = *Candidate;
  1259. return true;
  1260. }
  1261. }
  1262. return false;
  1263. }
  1264. bool clang::driver::findMIPSMultilibs(const Driver &D,
  1265. const llvm::Triple &TargetTriple,
  1266. StringRef Path, const ArgList &Args,
  1267. DetectedMultilibs &Result) {
  1268. FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
  1269. StringRef CPUName;
  1270. StringRef ABIName;
  1271. tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
  1272. llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
  1273. Multilib::flags_list Flags;
  1274. addMultilibFlag(TargetTriple.isMIPS32(), "m32", Flags);
  1275. addMultilibFlag(TargetTriple.isMIPS64(), "m64", Flags);
  1276. addMultilibFlag(isMips16(Args), "mips16", Flags);
  1277. addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
  1278. addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
  1279. CPUName == "mips32r5" || CPUName == "p5600",
  1280. "march=mips32r2", Flags);
  1281. addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
  1282. addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
  1283. addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
  1284. CPUName == "mips64r5" || CPUName == "octeon" ||
  1285. CPUName == "octeon+",
  1286. "march=mips64r2", Flags);
  1287. addMultilibFlag(CPUName == "mips64r6", "march=mips64r6", Flags);
  1288. addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
  1289. addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
  1290. addMultilibFlag(tools::mips::isNaN2008(D, Args, TargetTriple), "mnan=2008",
  1291. Flags);
  1292. addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
  1293. addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
  1294. addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
  1295. addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
  1296. addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
  1297. addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
  1298. if (TargetTriple.isAndroid())
  1299. return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
  1300. Result);
  1301. if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
  1302. TargetTriple.getOS() == llvm::Triple::Linux &&
  1303. TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
  1304. return findMipsMuslMultilibs(Flags, NonExistent, Result);
  1305. if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
  1306. TargetTriple.getOS() == llvm::Triple::Linux &&
  1307. TargetTriple.isGNUEnvironment())
  1308. return findMipsMtiMultilibs(Flags, NonExistent, Result);
  1309. if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  1310. TargetTriple.getOS() == llvm::Triple::Linux &&
  1311. TargetTriple.isGNUEnvironment())
  1312. return findMipsImgMultilibs(Flags, NonExistent, Result);
  1313. if (findMipsCsMultilibs(Flags, NonExistent, Result))
  1314. return true;
  1315. // Fallback to the regular toolchain-tree structure.
  1316. Multilib Default;
  1317. Result.Multilibs.push_back(Default);
  1318. Result.Multilibs.FilterOut(NonExistent);
  1319. if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
  1320. Result.BiarchSibling = Multilib();
  1321. return true;
  1322. }
  1323. return false;
  1324. }
  1325. static void findAndroidArmMultilibs(const Driver &D,
  1326. const llvm::Triple &TargetTriple,
  1327. StringRef Path, const ArgList &Args,
  1328. DetectedMultilibs &Result) {
  1329. // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
  1330. FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
  1331. Multilib ArmV7Multilib = makeMultilib("/armv7-a")
  1332. .flag("+march=armv7-a")
  1333. .flag("-mthumb");
  1334. Multilib ThumbMultilib = makeMultilib("/thumb")
  1335. .flag("-march=armv7-a")
  1336. .flag("+mthumb");
  1337. Multilib ArmV7ThumbMultilib = makeMultilib("/armv7-a/thumb")
  1338. .flag("+march=armv7-a")
  1339. .flag("+mthumb");
  1340. Multilib DefaultMultilib = makeMultilib("")
  1341. .flag("-march=armv7-a")
  1342. .flag("-mthumb");
  1343. MultilibSet AndroidArmMultilibs =
  1344. MultilibSet()
  1345. .Either(ThumbMultilib, ArmV7Multilib,
  1346. ArmV7ThumbMultilib, DefaultMultilib)
  1347. .FilterOut(NonExistent);
  1348. Multilib::flags_list Flags;
  1349. llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
  1350. bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
  1351. bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
  1352. bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
  1353. bool IsThumbMode = IsThumbArch ||
  1354. Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
  1355. (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
  1356. bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
  1357. (llvm::ARM::parseArchVersion(Arch) == 7 ||
  1358. (IsArmArch && Arch == "" && IsV7SubArch));
  1359. addMultilibFlag(IsArmV7Mode, "march=armv7-a", Flags);
  1360. addMultilibFlag(IsThumbMode, "mthumb", Flags);
  1361. if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilib))
  1362. Result.Multilibs = AndroidArmMultilibs;
  1363. }
  1364. static bool findMSP430Multilibs(const Driver &D,
  1365. const llvm::Triple &TargetTriple,
  1366. StringRef Path, const ArgList &Args,
  1367. DetectedMultilibs &Result) {
  1368. FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
  1369. Multilib WithoutExceptions = makeMultilib("/430").flag("-exceptions");
  1370. Multilib WithExceptions = makeMultilib("/430/exceptions").flag("+exceptions");
  1371. // FIXME: when clang starts to support msp430x ISA additional logic
  1372. // to select between multilib must be implemented
  1373. // Multilib MSP430xMultilib = makeMultilib("/large");
  1374. Result.Multilibs.push_back(WithoutExceptions);
  1375. Result.Multilibs.push_back(WithExceptions);
  1376. Result.Multilibs.FilterOut(NonExistent);
  1377. Multilib::flags_list Flags;
  1378. addMultilibFlag(Args.hasFlag(options::OPT_fexceptions,
  1379. options::OPT_fno_exceptions, false),
  1380. "exceptions", Flags);
  1381. if (Result.Multilibs.select(Flags, Result.SelectedMultilib))
  1382. return true;
  1383. return false;
  1384. }
  1385. static void findRISCVBareMetalMultilibs(const Driver &D,
  1386. const llvm::Triple &TargetTriple,
  1387. StringRef Path, const ArgList &Args,
  1388. DetectedMultilibs &Result) {
  1389. FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
  1390. struct RiscvMultilib {
  1391. StringRef march;
  1392. StringRef mabi;
  1393. };
  1394. // currently only support the set of multilibs like riscv-gnu-toolchain does.
  1395. // TODO: support MULTILIB_REUSE
  1396. constexpr RiscvMultilib RISCVMultilibSet[] = {
  1397. {"rv32i", "ilp32"}, {"rv32im", "ilp32"}, {"rv32iac", "ilp32"},
  1398. {"rv32imac", "ilp32"}, {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"},
  1399. {"rv64imafdc", "lp64d"}};
  1400. std::vector<Multilib> Ms;
  1401. for (auto Element : RISCVMultilibSet) {
  1402. // multilib path rule is ${march}/${mabi}
  1403. Ms.emplace_back(
  1404. makeMultilib((Twine(Element.march) + "/" + Twine(Element.mabi)).str())
  1405. .flag(Twine("+march=", Element.march).str())
  1406. .flag(Twine("+mabi=", Element.mabi).str()));
  1407. }
  1408. MultilibSet RISCVMultilibs =
  1409. MultilibSet()
  1410. .Either(ArrayRef<Multilib>(Ms))
  1411. .FilterOut(NonExistent)
  1412. .setFilePathsCallback([](const Multilib &M) {
  1413. return std::vector<std::string>(
  1414. {M.gccSuffix(),
  1415. "/../../../../riscv64-unknown-elf/lib" + M.gccSuffix(),
  1416. "/../../../../riscv32-unknown-elf/lib" + M.gccSuffix()});
  1417. });
  1418. Multilib::flags_list Flags;
  1419. llvm::StringSet<> Added_ABIs;
  1420. StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
  1421. StringRef MArch = tools::riscv::getRISCVArch(Args, TargetTriple);
  1422. for (auto Element : RISCVMultilibSet) {
  1423. addMultilibFlag(MArch == Element.march,
  1424. Twine("march=", Element.march).str().c_str(), Flags);
  1425. if (!Added_ABIs.count(Element.mabi)) {
  1426. Added_ABIs.insert(Element.mabi);
  1427. addMultilibFlag(ABIName == Element.mabi,
  1428. Twine("mabi=", Element.mabi).str().c_str(), Flags);
  1429. }
  1430. }
  1431. if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
  1432. Result.Multilibs = RISCVMultilibs;
  1433. }
  1434. static void findRISCVMultilibs(const Driver &D,
  1435. const llvm::Triple &TargetTriple, StringRef Path,
  1436. const ArgList &Args, DetectedMultilibs &Result) {
  1437. if (TargetTriple.getOS() == llvm::Triple::UnknownOS)
  1438. return findRISCVBareMetalMultilibs(D, TargetTriple, Path, Args, Result);
  1439. FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
  1440. Multilib Ilp32 = makeMultilib("lib32/ilp32").flag("+m32").flag("+mabi=ilp32");
  1441. Multilib Ilp32f =
  1442. makeMultilib("lib32/ilp32f").flag("+m32").flag("+mabi=ilp32f");
  1443. Multilib Ilp32d =
  1444. makeMultilib("lib32/ilp32d").flag("+m32").flag("+mabi=ilp32d");
  1445. Multilib Lp64 = makeMultilib("lib64/lp64").flag("+m64").flag("+mabi=lp64");
  1446. Multilib Lp64f = makeMultilib("lib64/lp64f").flag("+m64").flag("+mabi=lp64f");
  1447. Multilib Lp64d = makeMultilib("lib64/lp64d").flag("+m64").flag("+mabi=lp64d");
  1448. MultilibSet RISCVMultilibs =
  1449. MultilibSet()
  1450. .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
  1451. .FilterOut(NonExistent);
  1452. Multilib::flags_list Flags;
  1453. bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
  1454. StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
  1455. addMultilibFlag(!IsRV64, "m32", Flags);
  1456. addMultilibFlag(IsRV64, "m64", Flags);
  1457. addMultilibFlag(ABIName == "ilp32", "mabi=ilp32", Flags);
  1458. addMultilibFlag(ABIName == "ilp32f", "mabi=ilp32f", Flags);
  1459. addMultilibFlag(ABIName == "ilp32d", "mabi=ilp32d", Flags);
  1460. addMultilibFlag(ABIName == "lp64", "mabi=lp64", Flags);
  1461. addMultilibFlag(ABIName == "lp64f", "mabi=lp64f", Flags);
  1462. addMultilibFlag(ABIName == "lp64d", "mabi=lp64d", Flags);
  1463. if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
  1464. Result.Multilibs = RISCVMultilibs;
  1465. }
  1466. static bool findBiarchMultilibs(const Driver &D,
  1467. const llvm::Triple &TargetTriple,
  1468. StringRef Path, const ArgList &Args,
  1469. bool NeedsBiarchSuffix,
  1470. DetectedMultilibs &Result) {
  1471. Multilib Default;
  1472. // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
  1473. // in what would normally be GCCInstallPath and put the 64-bit
  1474. // libs in a subdirectory named 64. The simple logic we follow is that
  1475. // *if* there is a subdirectory of the right name with crtbegin.o in it,
  1476. // we use that. If not, and if not a biarch triple alias, we look for
  1477. // crtbegin.o without the subdirectory.
  1478. StringRef Suff64 = "/64";
  1479. // Solaris uses platform-specific suffixes instead of /64.
  1480. if (TargetTriple.getOS() == llvm::Triple::Solaris) {
  1481. switch (TargetTriple.getArch()) {
  1482. case llvm::Triple::x86:
  1483. case llvm::Triple::x86_64:
  1484. Suff64 = "/amd64";
  1485. break;
  1486. case llvm::Triple::sparc:
  1487. case llvm::Triple::sparcv9:
  1488. Suff64 = "/sparcv9";
  1489. break;
  1490. default:
  1491. break;
  1492. }
  1493. }
  1494. Multilib Alt64 = Multilib()
  1495. .gccSuffix(Suff64)
  1496. .includeSuffix(Suff64)
  1497. .flag("-m32")
  1498. .flag("+m64")
  1499. .flag("-mx32");
  1500. Multilib Alt32 = Multilib()
  1501. .gccSuffix("/32")
  1502. .includeSuffix("/32")
  1503. .flag("+m32")
  1504. .flag("-m64")
  1505. .flag("-mx32");
  1506. Multilib Altx32 = Multilib()
  1507. .gccSuffix("/x32")
  1508. .includeSuffix("/x32")
  1509. .flag("-m32")
  1510. .flag("-m64")
  1511. .flag("+mx32");
  1512. // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
  1513. FilterNonExistent NonExistent(
  1514. Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
  1515. // Determine default multilib from: 32, 64, x32
  1516. // Also handle cases such as 64 on 32, 32 on 64, etc.
  1517. enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
  1518. const bool IsX32 = TargetTriple.isX32();
  1519. if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
  1520. Want = WANT64;
  1521. else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
  1522. Want = WANT64;
  1523. else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
  1524. Want = WANT32;
  1525. else {
  1526. if (TargetTriple.isArch32Bit())
  1527. Want = NeedsBiarchSuffix ? WANT64 : WANT32;
  1528. else if (IsX32)
  1529. Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
  1530. else
  1531. Want = NeedsBiarchSuffix ? WANT32 : WANT64;
  1532. }
  1533. if (Want == WANT32)
  1534. Default.flag("+m32").flag("-m64").flag("-mx32");
  1535. else if (Want == WANT64)
  1536. Default.flag("-m32").flag("+m64").flag("-mx32");
  1537. else if (Want == WANTX32)
  1538. Default.flag("-m32").flag("-m64").flag("+mx32");
  1539. else
  1540. return false;
  1541. Result.Multilibs.push_back(Default);
  1542. Result.Multilibs.push_back(Alt64);
  1543. Result.Multilibs.push_back(Alt32);
  1544. Result.Multilibs.push_back(Altx32);
  1545. Result.Multilibs.FilterOut(NonExistent);
  1546. Multilib::flags_list Flags;
  1547. addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
  1548. addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
  1549. addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
  1550. if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
  1551. return false;
  1552. if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
  1553. Result.SelectedMultilib == Altx32)
  1554. Result.BiarchSibling = Default;
  1555. return true;
  1556. }
  1557. /// Generic_GCC - A tool chain using the 'gcc' command to perform
  1558. /// all subcommands; this relies on gcc translating the majority of
  1559. /// command line options.
  1560. /// Less-than for GCCVersion, implementing a Strict Weak Ordering.
  1561. bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
  1562. int RHSPatch,
  1563. StringRef RHSPatchSuffix) const {
  1564. if (Major != RHSMajor)
  1565. return Major < RHSMajor;
  1566. if (Minor != RHSMinor)
  1567. return Minor < RHSMinor;
  1568. if (Patch != RHSPatch) {
  1569. // Note that versions without a specified patch sort higher than those with
  1570. // a patch.
  1571. if (RHSPatch == -1)
  1572. return true;
  1573. if (Patch == -1)
  1574. return false;
  1575. // Otherwise just sort on the patch itself.
  1576. return Patch < RHSPatch;
  1577. }
  1578. if (PatchSuffix != RHSPatchSuffix) {
  1579. // Sort empty suffixes higher.
  1580. if (RHSPatchSuffix.empty())
  1581. return true;
  1582. if (PatchSuffix.empty())
  1583. return false;
  1584. // Provide a lexicographic sort to make this a total ordering.
  1585. return PatchSuffix < RHSPatchSuffix;
  1586. }
  1587. // The versions are equal.
  1588. return false;
  1589. }
  1590. /// Parse a GCCVersion object out of a string of text.
  1591. ///
  1592. /// This is the primary means of forming GCCVersion objects.
  1593. /*static*/
  1594. Generic_GCC::GCCVersion Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
  1595. const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
  1596. std::pair<StringRef, StringRef> First = VersionText.split('.');
  1597. std::pair<StringRef, StringRef> Second = First.second.split('.');
  1598. GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
  1599. if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
  1600. return BadVersion;
  1601. GoodVersion.MajorStr = First.first.str();
  1602. if (First.second.empty())
  1603. return GoodVersion;
  1604. StringRef MinorStr = Second.first;
  1605. if (Second.second.empty()) {
  1606. if (size_t EndNumber = MinorStr.find_first_not_of("0123456789")) {
  1607. GoodVersion.PatchSuffix = std::string(MinorStr.substr(EndNumber));
  1608. MinorStr = MinorStr.slice(0, EndNumber);
  1609. }
  1610. }
  1611. if (MinorStr.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
  1612. return BadVersion;
  1613. GoodVersion.MinorStr = MinorStr.str();
  1614. // First look for a number prefix and parse that if present. Otherwise just
  1615. // stash the entire patch string in the suffix, and leave the number
  1616. // unspecified. This covers versions strings such as:
  1617. // 5 (handled above)
  1618. // 4.4
  1619. // 4.4-patched
  1620. // 4.4.0
  1621. // 4.4.x
  1622. // 4.4.2-rc4
  1623. // 4.4.x-patched
  1624. // And retains any patch number it finds.
  1625. StringRef PatchText = Second.second;
  1626. if (!PatchText.empty()) {
  1627. if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
  1628. // Try to parse the number and any suffix.
  1629. if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
  1630. GoodVersion.Patch < 0)
  1631. return BadVersion;
  1632. GoodVersion.PatchSuffix = std::string(PatchText.substr(EndNumber));
  1633. }
  1634. }
  1635. return GoodVersion;
  1636. }
  1637. static llvm::StringRef getGCCToolchainDir(const ArgList &Args,
  1638. llvm::StringRef SysRoot) {
  1639. const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
  1640. if (A)
  1641. return A->getValue();
  1642. // If we have a SysRoot, ignore GCC_INSTALL_PREFIX.
  1643. // GCC_INSTALL_PREFIX specifies the gcc installation for the default
  1644. // sysroot and is likely not valid with a different sysroot.
  1645. if (!SysRoot.empty())
  1646. return "";
  1647. return GCC_INSTALL_PREFIX;
  1648. }
  1649. /// Initialize a GCCInstallationDetector from the driver.
  1650. ///
  1651. /// This performs all of the autodetection and sets up the various paths.
  1652. /// Once constructed, a GCCInstallationDetector is essentially immutable.
  1653. ///
  1654. /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
  1655. /// should instead pull the target out of the driver. This is currently
  1656. /// necessary because the driver doesn't store the final version of the target
  1657. /// triple.
  1658. void Generic_GCC::GCCInstallationDetector::init(
  1659. const llvm::Triple &TargetTriple, const ArgList &Args,
  1660. ArrayRef<std::string> ExtraTripleAliases) {
  1661. llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
  1662. ? TargetTriple.get64BitArchVariant()
  1663. : TargetTriple.get32BitArchVariant();
  1664. // The library directories which may contain GCC installations.
  1665. SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
  1666. // The compatible GCC triples for this particular architecture.
  1667. SmallVector<StringRef, 16> CandidateTripleAliases;
  1668. SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
  1669. CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
  1670. CandidateTripleAliases, CandidateBiarchLibDirs,
  1671. CandidateBiarchTripleAliases);
  1672. // Compute the set of prefixes for our search.
  1673. SmallVector<std::string, 8> Prefixes;
  1674. StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot);
  1675. if (GCCToolchainDir != "") {
  1676. if (GCCToolchainDir.back() == '/')
  1677. GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
  1678. Prefixes.push_back(std::string(GCCToolchainDir));
  1679. } else {
  1680. // If we have a SysRoot, try that first.
  1681. if (!D.SysRoot.empty()) {
  1682. Prefixes.push_back(D.SysRoot);
  1683. AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
  1684. }
  1685. // Then look for gcc installed alongside clang.
  1686. Prefixes.push_back(D.InstalledDir + "/..");
  1687. // Next, look for prefix(es) that correspond to distribution-supplied gcc
  1688. // installations.
  1689. if (D.SysRoot.empty()) {
  1690. // Typically /usr.
  1691. AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
  1692. }
  1693. // Try to respect gcc-config on Gentoo if --gcc-toolchain is not provided.
  1694. // This avoids accidentally enforcing the system GCC version when using a
  1695. // custom toolchain.
  1696. SmallVector<StringRef, 16> GentooTestTriples;
  1697. // Try to match an exact triple as target triple first.
  1698. // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
  1699. // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
  1700. // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
  1701. // triple x86_64-gentoo-linux-gnu is present.
  1702. GentooTestTriples.push_back(TargetTriple.str());
  1703. // Check rest of triples.
  1704. GentooTestTriples.append(ExtraTripleAliases.begin(),
  1705. ExtraTripleAliases.end());
  1706. GentooTestTriples.append(CandidateTripleAliases.begin(),
  1707. CandidateTripleAliases.end());
  1708. if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
  1709. CandidateBiarchTripleAliases))
  1710. return;
  1711. }
  1712. // Loop over the various components which exist and select the best GCC
  1713. // installation available. GCC installs are ranked by version number.
  1714. const GCCVersion VersionZero = GCCVersion::Parse("0.0.0");
  1715. Version = VersionZero;
  1716. for (const std::string &Prefix : Prefixes) {
  1717. auto &VFS = D.getVFS();
  1718. if (!VFS.exists(Prefix))
  1719. continue;
  1720. for (StringRef Suffix : CandidateLibDirs) {
  1721. const std::string LibDir = Prefix + Suffix.str();
  1722. if (!VFS.exists(LibDir))
  1723. continue;
  1724. // Maybe filter out <libdir>/gcc and <libdir>/gcc-cross.
  1725. bool GCCDirExists = VFS.exists(LibDir + "/gcc");
  1726. bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
  1727. // Try to match the exact target triple first.
  1728. ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, TargetTriple.str(),
  1729. false, GCCDirExists, GCCCrossDirExists);
  1730. // Try rest of possible triples.
  1731. for (StringRef Candidate : ExtraTripleAliases) // Try these first.
  1732. ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
  1733. GCCDirExists, GCCCrossDirExists);
  1734. for (StringRef Candidate : CandidateTripleAliases)
  1735. ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
  1736. GCCDirExists, GCCCrossDirExists);
  1737. }
  1738. for (StringRef Suffix : CandidateBiarchLibDirs) {
  1739. const std::string LibDir = Prefix + Suffix.str();
  1740. if (!VFS.exists(LibDir))
  1741. continue;
  1742. bool GCCDirExists = VFS.exists(LibDir + "/gcc");
  1743. bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
  1744. for (StringRef Candidate : CandidateBiarchTripleAliases)
  1745. ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, true,
  1746. GCCDirExists, GCCCrossDirExists);
  1747. }
  1748. // Skip other prefixes once a GCC installation is found.
  1749. if (Version > VersionZero)
  1750. break;
  1751. }
  1752. }
  1753. void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
  1754. for (const auto &InstallPath : CandidateGCCInstallPaths)
  1755. OS << "Found candidate GCC installation: " << InstallPath << "\n";
  1756. if (!GCCInstallPath.empty())
  1757. OS << "Selected GCC installation: " << GCCInstallPath << "\n";
  1758. for (const auto &Multilib : Multilibs)
  1759. OS << "Candidate multilib: " << Multilib << "\n";
  1760. if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
  1761. OS << "Selected multilib: " << SelectedMultilib << "\n";
  1762. }
  1763. bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
  1764. if (BiarchSibling.hasValue()) {
  1765. M = BiarchSibling.getValue();
  1766. return true;
  1767. }
  1768. return false;
  1769. }
  1770. void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
  1771. const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
  1772. StringRef SysRoot) {
  1773. if (TargetTriple.getOS() == llvm::Triple::Solaris) {
  1774. // Solaris is a special case.
  1775. // The GCC installation is under
  1776. // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
  1777. // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
  1778. // /usr/gcc/<version> as a prefix.
  1779. std::string PrefixDir = SysRoot.str() + "/usr/gcc";
  1780. std::error_code EC;
  1781. for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC),
  1782. LE;
  1783. !EC && LI != LE; LI = LI.increment(EC)) {
  1784. StringRef VersionText = llvm::sys::path::filename(LI->path());
  1785. GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
  1786. // Filter out obviously bad entries.
  1787. if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
  1788. continue;
  1789. std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
  1790. std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
  1791. if (!D.getVFS().exists(CandidateLibPath))
  1792. continue;
  1793. Prefixes.push_back(CandidatePrefix);
  1794. }
  1795. return;
  1796. }
  1797. // Non-Solaris is much simpler - most systems just go with "/usr".
  1798. if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux) {
  1799. // Yet, still look for RHEL/CentOS devtoolsets and gcc-toolsets.
  1800. Prefixes.push_back("/opt/rh/gcc-toolset-10/root/usr");
  1801. Prefixes.push_back("/opt/rh/devtoolset-10/root/usr");
  1802. Prefixes.push_back("/opt/rh/devtoolset-9/root/usr");
  1803. Prefixes.push_back("/opt/rh/devtoolset-8/root/usr");
  1804. Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
  1805. Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
  1806. Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
  1807. Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
  1808. Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
  1809. }
  1810. Prefixes.push_back(SysRoot.str() + "/usr");
  1811. }
  1812. /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
  1813. const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
  1814. SmallVectorImpl<StringRef> &LibDirs,
  1815. SmallVectorImpl<StringRef> &TripleAliases,
  1816. SmallVectorImpl<StringRef> &BiarchLibDirs,
  1817. SmallVectorImpl<StringRef> &BiarchTripleAliases) {
  1818. // Declare a bunch of static data sets that we'll select between below. These
  1819. // are specifically designed to always refer to string literals to avoid any
  1820. // lifetime or initialization issues.
  1821. //
  1822. // The *Triples variables hard code some triples so that, for example,
  1823. // --target=aarch64 (incomplete triple) can detect lib/aarch64-linux-gnu.
  1824. // They are not needed when the user has correct LLVM_DEFAULT_TARGET_TRIPLE
  1825. // and always uses the full --target (e.g. --target=aarch64-linux-gnu). The
  1826. // lists should shrink over time. Please don't add more elements to *Triples.
  1827. static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
  1828. static const char *const AArch64Triples[] = {
  1829. "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
  1830. "aarch64-suse-linux"};
  1831. static const char *const AArch64beLibDirs[] = {"/lib"};
  1832. static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
  1833. "aarch64_be-linux-gnu"};
  1834. static const char *const ARMLibDirs[] = {"/lib"};
  1835. static const char *const ARMTriples[] = {"arm-linux-gnueabi"};
  1836. static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
  1837. "armv7hl-redhat-linux-gnueabi",
  1838. "armv6hl-suse-linux-gnueabi",
  1839. "armv7hl-suse-linux-gnueabi"};
  1840. static const char *const ARMebLibDirs[] = {"/lib"};
  1841. static const char *const ARMebTriples[] = {"armeb-linux-gnueabi"};
  1842. static const char *const ARMebHFTriples[] = {
  1843. "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
  1844. static const char *const AVRLibDirs[] = {"/lib"};
  1845. static const char *const AVRTriples[] = {"avr"};
  1846. static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
  1847. static const char *const X86_64Triples[] = {
  1848. "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
  1849. "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
  1850. "x86_64-redhat-linux", "x86_64-suse-linux",
  1851. "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
  1852. "x86_64-slackware-linux", "x86_64-unknown-linux",
  1853. "x86_64-amazon-linux"};
  1854. static const char *const X32Triples[] = {"x86_64-linux-gnux32",
  1855. "x86_64-pc-linux-gnux32"};
  1856. static const char *const X32LibDirs[] = {"/libx32", "/lib"};
  1857. static const char *const X86LibDirs[] = {"/lib32", "/lib"};
  1858. static const char *const X86Triples[] = {
  1859. "i586-linux-gnu", "i686-linux-gnu", "i686-pc-linux-gnu",
  1860. "i386-redhat-linux6E", "i686-redhat-linux", "i386-redhat-linux",
  1861. "i586-suse-linux", "i686-montavista-linux", "i686-gnu",
  1862. };
  1863. static const char *const M68kLibDirs[] = {"/lib"};
  1864. static const char *const M68kTriples[] = {
  1865. "m68k-linux-gnu", "m68k-unknown-linux-gnu", "m68k-suse-linux"};
  1866. static const char *const MIPSLibDirs[] = {"/libo32", "/lib"};
  1867. static const char *const MIPSTriples[] = {
  1868. "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
  1869. "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
  1870. static const char *const MIPSELLibDirs[] = {"/libo32", "/lib"};
  1871. static const char *const MIPSELTriples[] = {
  1872. "mipsel-linux-gnu", "mips-img-linux-gnu", "mipsisa32r6el-linux-gnu"};
  1873. static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
  1874. static const char *const MIPS64Triples[] = {
  1875. "mips64-linux-gnu", "mips-mti-linux-gnu",
  1876. "mips-img-linux-gnu", "mips64-linux-gnuabi64",
  1877. "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"};
  1878. static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
  1879. static const char *const MIPS64ELTriples[] = {
  1880. "mips64el-linux-gnu", "mips-mti-linux-gnu",
  1881. "mips-img-linux-gnu", "mips64el-linux-gnuabi64",
  1882. "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64"};
  1883. static const char *const MIPSN32LibDirs[] = {"/lib32"};
  1884. static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32",
  1885. "mipsisa64r6-linux-gnuabin32"};
  1886. static const char *const MIPSN32ELLibDirs[] = {"/lib32"};
  1887. static const char *const MIPSN32ELTriples[] = {
  1888. "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"};
  1889. static const char *const MSP430LibDirs[] = {"/lib"};
  1890. static const char *const MSP430Triples[] = {"msp430-elf"};
  1891. static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
  1892. static const char *const PPCTriples[] = {
  1893. "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
  1894. // On 32-bit PowerPC systems running SUSE Linux, gcc is configured as a
  1895. // 64-bit compiler which defaults to "-m32", hence "powerpc64-suse-linux".
  1896. "powerpc64-suse-linux", "powerpc-montavista-linuxspe"};
  1897. static const char *const PPCLELibDirs[] = {"/lib32", "/lib"};
  1898. static const char *const PPCLETriples[] = {"powerpcle-linux-gnu",
  1899. "powerpcle-unknown-linux-gnu",
  1900. "powerpcle-linux-musl"};
  1901. static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
  1902. static const char *const PPC64Triples[] = {
  1903. "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
  1904. "powerpc64-suse-linux", "ppc64-redhat-linux"};
  1905. static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
  1906. static const char *const PPC64LETriples[] = {
  1907. "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
  1908. "powerpc64le-none-linux-gnu", "powerpc64le-suse-linux",
  1909. "ppc64le-redhat-linux"};
  1910. static const char *const RISCV32LibDirs[] = {"/lib32", "/lib"};
  1911. static const char *const RISCV32Triples[] = {"riscv32-unknown-linux-gnu",
  1912. "riscv32-linux-gnu",
  1913. "riscv32-unknown-elf"};
  1914. static const char *const RISCV64LibDirs[] = {"/lib64", "/lib"};
  1915. static const char *const RISCV64Triples[] = {"riscv64-unknown-linux-gnu",
  1916. "riscv64-linux-gnu",
  1917. "riscv64-unknown-elf"};
  1918. static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
  1919. static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
  1920. "sparcv8-linux-gnu"};
  1921. static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
  1922. static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
  1923. "sparcv9-linux-gnu"};
  1924. static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
  1925. static const char *const SystemZTriples[] = {
  1926. "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
  1927. "s390x-suse-linux", "s390x-redhat-linux"};
  1928. using std::begin;
  1929. using std::end;
  1930. if (TargetTriple.getOS() == llvm::Triple::Solaris) {
  1931. static const char *const SolarisLibDirs[] = {"/lib"};
  1932. static const char *const SolarisSparcV8Triples[] = {
  1933. "sparc-sun-solaris2.11", "sparc-sun-solaris2.12"};
  1934. static const char *const SolarisSparcV9Triples[] = {
  1935. "sparcv9-sun-solaris2.11", "sparcv9-sun-solaris2.12"};
  1936. static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11",
  1937. "i386-pc-solaris2.12"};
  1938. static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11",
  1939. "x86_64-pc-solaris2.12"};
  1940. LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
  1941. BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
  1942. switch (TargetTriple.getArch()) {
  1943. case llvm::Triple::x86:
  1944. TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
  1945. BiarchTripleAliases.append(begin(SolarisX86_64Triples),
  1946. end(SolarisX86_64Triples));
  1947. break;
  1948. case llvm::Triple::x86_64:
  1949. TripleAliases.append(begin(SolarisX86_64Triples),
  1950. end(SolarisX86_64Triples));
  1951. BiarchTripleAliases.append(begin(SolarisX86Triples),
  1952. end(SolarisX86Triples));
  1953. break;
  1954. case llvm::Triple::sparc:
  1955. TripleAliases.append(begin(SolarisSparcV8Triples),
  1956. end(SolarisSparcV8Triples));
  1957. BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
  1958. end(SolarisSparcV9Triples));
  1959. break;
  1960. case llvm::Triple::sparcv9:
  1961. TripleAliases.append(begin(SolarisSparcV9Triples),
  1962. end(SolarisSparcV9Triples));
  1963. BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
  1964. end(SolarisSparcV8Triples));
  1965. break;
  1966. default:
  1967. break;
  1968. }
  1969. return;
  1970. }
  1971. // Android targets should not use GNU/Linux tools or libraries.
  1972. if (TargetTriple.isAndroid()) {
  1973. static const char *const AArch64AndroidTriples[] = {
  1974. "aarch64-linux-android"};
  1975. static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
  1976. static const char *const MIPSELAndroidTriples[] = {"mipsel-linux-android"};
  1977. static const char *const MIPS64ELAndroidTriples[] = {
  1978. "mips64el-linux-android"};
  1979. static const char *const X86AndroidTriples[] = {"i686-linux-android"};
  1980. static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
  1981. switch (TargetTriple.getArch()) {
  1982. case llvm::Triple::aarch64:
  1983. LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
  1984. TripleAliases.append(begin(AArch64AndroidTriples),
  1985. end(AArch64AndroidTriples));
  1986. break;
  1987. case llvm::Triple::arm:
  1988. case llvm::Triple::thumb:
  1989. LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
  1990. TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
  1991. break;
  1992. case llvm::Triple::mipsel:
  1993. LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
  1994. TripleAliases.append(begin(MIPSELAndroidTriples),
  1995. end(MIPSELAndroidTriples));
  1996. BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
  1997. BiarchTripleAliases.append(begin(MIPS64ELAndroidTriples),
  1998. end(MIPS64ELAndroidTriples));
  1999. break;
  2000. case llvm::Triple::mips64el:
  2001. LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
  2002. TripleAliases.append(begin(MIPS64ELAndroidTriples),
  2003. end(MIPS64ELAndroidTriples));
  2004. BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
  2005. BiarchTripleAliases.append(begin(MIPSELAndroidTriples),
  2006. end(MIPSELAndroidTriples));
  2007. break;
  2008. case llvm::Triple::x86_64:
  2009. LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
  2010. TripleAliases.append(begin(X86_64AndroidTriples),
  2011. end(X86_64AndroidTriples));
  2012. BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
  2013. BiarchTripleAliases.append(begin(X86AndroidTriples),
  2014. end(X86AndroidTriples));
  2015. break;
  2016. case llvm::Triple::x86:
  2017. LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
  2018. TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
  2019. BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
  2020. BiarchTripleAliases.append(begin(X86_64AndroidTriples),
  2021. end(X86_64AndroidTriples));
  2022. break;
  2023. default:
  2024. break;
  2025. }
  2026. return;
  2027. }
  2028. switch (TargetTriple.getArch()) {
  2029. case llvm::Triple::aarch64:
  2030. LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
  2031. TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
  2032. BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
  2033. BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
  2034. break;
  2035. case llvm::Triple::aarch64_be:
  2036. LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
  2037. TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
  2038. BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
  2039. BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
  2040. break;
  2041. case llvm::Triple::arm:
  2042. case llvm::Triple::thumb:
  2043. LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
  2044. if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
  2045. TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
  2046. } else {
  2047. TripleAliases.append(begin(ARMTriples), end(ARMTriples));
  2048. }
  2049. break;
  2050. case llvm::Triple::armeb:
  2051. case llvm::Triple::thumbeb:
  2052. LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
  2053. if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
  2054. TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
  2055. } else {
  2056. TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
  2057. }
  2058. break;
  2059. case llvm::Triple::avr:
  2060. LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs));
  2061. TripleAliases.append(begin(AVRTriples), end(AVRTriples));
  2062. break;
  2063. case llvm::Triple::x86_64:
  2064. if (TargetTriple.isX32()) {
  2065. LibDirs.append(begin(X32LibDirs), end(X32LibDirs));
  2066. TripleAliases.append(begin(X32Triples), end(X32Triples));
  2067. BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
  2068. BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
  2069. } else {
  2070. LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
  2071. TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
  2072. BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
  2073. BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
  2074. }
  2075. BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
  2076. BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
  2077. break;
  2078. case llvm::Triple::x86:
  2079. LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
  2080. // MCU toolchain is 32 bit only and its triple alias is TargetTriple
  2081. // itself, which will be appended below.
  2082. if (!TargetTriple.isOSIAMCU()) {
  2083. TripleAliases.append(begin(X86Triples), end(X86Triples));
  2084. BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
  2085. BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
  2086. BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
  2087. BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
  2088. }
  2089. break;
  2090. case llvm::Triple::m68k:
  2091. LibDirs.append(begin(M68kLibDirs), end(M68kLibDirs));
  2092. TripleAliases.append(begin(M68kTriples), end(M68kTriples));
  2093. break;
  2094. case llvm::Triple::mips:
  2095. LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
  2096. TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
  2097. BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
  2098. BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
  2099. BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
  2100. BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
  2101. break;
  2102. case llvm::Triple::mipsel:
  2103. LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
  2104. TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
  2105. TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
  2106. BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
  2107. BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
  2108. BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
  2109. BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
  2110. break;
  2111. case llvm::Triple::mips64:
  2112. LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
  2113. TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
  2114. BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
  2115. BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
  2116. BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
  2117. BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
  2118. break;
  2119. case llvm::Triple::mips64el:
  2120. LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
  2121. TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
  2122. BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
  2123. BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
  2124. BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
  2125. BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
  2126. BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
  2127. break;
  2128. case llvm::Triple::msp430:
  2129. LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs));
  2130. TripleAliases.append(begin(MSP430Triples), end(MSP430Triples));
  2131. break;
  2132. case llvm::Triple::ppc:
  2133. LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
  2134. TripleAliases.append(begin(PPCTriples), end(PPCTriples));
  2135. BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
  2136. BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
  2137. break;
  2138. case llvm::Triple::ppcle:
  2139. LibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
  2140. TripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
  2141. BiarchLibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
  2142. BiarchTripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
  2143. break;
  2144. case llvm::Triple::ppc64:
  2145. LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
  2146. TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
  2147. BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
  2148. BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
  2149. break;
  2150. case llvm::Triple::ppc64le:
  2151. LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
  2152. TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
  2153. BiarchLibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
  2154. BiarchTripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
  2155. break;
  2156. case llvm::Triple::riscv32:
  2157. LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
  2158. TripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
  2159. BiarchLibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
  2160. BiarchTripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
  2161. break;
  2162. case llvm::Triple::riscv64:
  2163. LibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
  2164. TripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
  2165. BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
  2166. BiarchTripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
  2167. break;
  2168. case llvm::Triple::sparc:
  2169. case llvm::Triple::sparcel:
  2170. LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
  2171. TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
  2172. BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
  2173. BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
  2174. break;
  2175. case llvm::Triple::sparcv9:
  2176. LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
  2177. TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
  2178. BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
  2179. BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
  2180. break;
  2181. case llvm::Triple::systemz:
  2182. LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
  2183. TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
  2184. break;
  2185. default:
  2186. // By default, just rely on the standard lib directories and the original
  2187. // triple.
  2188. break;
  2189. }
  2190. // Always append the drivers target triple to the end, in case it doesn't
  2191. // match any of our aliases.
  2192. TripleAliases.push_back(TargetTriple.str());
  2193. // Also include the multiarch variant if it's different.
  2194. if (TargetTriple.str() != BiarchTriple.str())
  2195. BiarchTripleAliases.push_back(BiarchTriple.str());
  2196. }
  2197. bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
  2198. const llvm::Triple &TargetTriple, const ArgList &Args,
  2199. StringRef Path, bool NeedsBiarchSuffix) {
  2200. llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
  2201. DetectedMultilibs Detected;
  2202. // Android standalone toolchain could have multilibs for ARM and Thumb.
  2203. // Debian mips multilibs behave more like the rest of the biarch ones,
  2204. // so handle them there
  2205. if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
  2206. // It should also work without multilibs in a simplified toolchain.
  2207. findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
  2208. } else if (TargetTriple.isMIPS()) {
  2209. if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
  2210. return false;
  2211. } else if (TargetTriple.isRISCV()) {
  2212. findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
  2213. } else if (isMSP430(TargetArch)) {
  2214. findMSP430Multilibs(D, TargetTriple, Path, Args, Detected);
  2215. } else if (TargetArch == llvm::Triple::avr) {
  2216. // AVR has no multilibs.
  2217. } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
  2218. NeedsBiarchSuffix, Detected)) {
  2219. return false;
  2220. }
  2221. Multilibs = Detected.Multilibs;
  2222. SelectedMultilib = Detected.SelectedMultilib;
  2223. BiarchSibling = Detected.BiarchSibling;
  2224. return true;
  2225. }
  2226. void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
  2227. const llvm::Triple &TargetTriple, const ArgList &Args,
  2228. const std::string &LibDir, StringRef CandidateTriple,
  2229. bool NeedsBiarchSuffix, bool GCCDirExists, bool GCCCrossDirExists) {
  2230. // Locations relative to the system lib directory where GCC's triple-specific
  2231. // directories might reside.
  2232. struct GCCLibSuffix {
  2233. // Path from system lib directory to GCC triple-specific directory.
  2234. std::string LibSuffix;
  2235. // Path from GCC triple-specific directory back to system lib directory.
  2236. // This is one '..' component per component in LibSuffix.
  2237. StringRef ReversePath;
  2238. // Whether this library suffix is relevant for the triple.
  2239. bool Active;
  2240. } Suffixes[] = {
  2241. // This is the normal place.
  2242. {"gcc/" + CandidateTriple.str(), "../..", GCCDirExists},
  2243. // Debian puts cross-compilers in gcc-cross.
  2244. {"gcc-cross/" + CandidateTriple.str(), "../..", GCCCrossDirExists},
  2245. // The Freescale PPC SDK has the gcc libraries in
  2246. // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
  2247. // this on Freescale triples, though, since some systems put a *lot* of
  2248. // files in that location, not just GCC installation data.
  2249. {CandidateTriple.str(), "..",
  2250. TargetTriple.getVendor() == llvm::Triple::Freescale ||
  2251. TargetTriple.getVendor() == llvm::Triple::OpenEmbedded}};
  2252. for (auto &Suffix : Suffixes) {
  2253. if (!Suffix.Active)
  2254. continue;
  2255. StringRef LibSuffix = Suffix.LibSuffix;
  2256. std::error_code EC;
  2257. for (llvm::vfs::directory_iterator
  2258. LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
  2259. LE;
  2260. !EC && LI != LE; LI = LI.increment(EC)) {
  2261. StringRef VersionText = llvm::sys::path::filename(LI->path());
  2262. GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
  2263. if (CandidateVersion.Major != -1) // Filter obviously bad entries.
  2264. if (!CandidateGCCInstallPaths.insert(std::string(LI->path())).second)
  2265. continue; // Saw this path before; no need to look at it again.
  2266. if (CandidateVersion.isOlderThan(4, 1, 1))
  2267. continue;
  2268. if (CandidateVersion <= Version)
  2269. continue;
  2270. if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
  2271. NeedsBiarchSuffix))
  2272. continue;
  2273. Version = CandidateVersion;
  2274. GCCTriple.setTriple(CandidateTriple);
  2275. // FIXME: We hack together the directory name here instead of
  2276. // using LI to ensure stable path separators across Windows and
  2277. // Linux.
  2278. GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
  2279. GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
  2280. IsValid = true;
  2281. }
  2282. }
  2283. }
  2284. bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
  2285. const llvm::Triple &TargetTriple, const ArgList &Args,
  2286. const SmallVectorImpl<StringRef> &CandidateTriples,
  2287. const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
  2288. if (!D.getVFS().exists(D.SysRoot + GentooConfigDir))
  2289. return false;
  2290. for (StringRef CandidateTriple : CandidateTriples) {
  2291. if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
  2292. return true;
  2293. }
  2294. for (StringRef CandidateTriple : CandidateBiarchTriples) {
  2295. if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
  2296. return true;
  2297. }
  2298. return false;
  2299. }
  2300. bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
  2301. const llvm::Triple &TargetTriple, const ArgList &Args,
  2302. StringRef CandidateTriple, bool NeedsBiarchSuffix) {
  2303. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
  2304. D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir + "/config-" +
  2305. CandidateTriple.str());
  2306. if (File) {
  2307. SmallVector<StringRef, 2> Lines;
  2308. File.get()->getBuffer().split(Lines, "\n");
  2309. for (StringRef Line : Lines) {
  2310. Line = Line.trim();
  2311. // CURRENT=triple-version
  2312. if (!Line.consume_front("CURRENT="))
  2313. continue;
  2314. // Process the config file pointed to by CURRENT.
  2315. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
  2316. D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir + "/" +
  2317. Line.str());
  2318. std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
  2319. // List of paths to scan for libraries.
  2320. SmallVector<StringRef, 4> GentooScanPaths;
  2321. // Scan the Config file to find installed GCC libraries path.
  2322. // Typical content of the GCC config file:
  2323. // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
  2324. // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
  2325. // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
  2326. // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
  2327. // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
  2328. // We are looking for the paths listed in LDPATH=... .
  2329. if (ConfigFile) {
  2330. SmallVector<StringRef, 2> ConfigLines;
  2331. ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
  2332. for (StringRef ConfLine : ConfigLines) {
  2333. ConfLine = ConfLine.trim();
  2334. if (ConfLine.consume_front("LDPATH=")) {
  2335. // Drop '"' from front and back if present.
  2336. ConfLine.consume_back("\"");
  2337. ConfLine.consume_front("\"");
  2338. // Get all paths sperated by ':'
  2339. ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
  2340. }
  2341. }
  2342. }
  2343. // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
  2344. std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
  2345. + ActiveVersion.second.str();
  2346. GentooScanPaths.push_back(StringRef(basePath));
  2347. // Scan all paths for GCC libraries.
  2348. for (const auto &GentooScanPath : GentooScanPaths) {
  2349. std::string GentooPath = D.SysRoot + std::string(GentooScanPath);
  2350. if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
  2351. if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
  2352. NeedsBiarchSuffix))
  2353. continue;
  2354. Version = GCCVersion::Parse(ActiveVersion.second);
  2355. GCCInstallPath = GentooPath;
  2356. GCCParentLibPath = GentooPath + std::string("/../../..");
  2357. GCCTriple.setTriple(ActiveVersion.first);
  2358. IsValid = true;
  2359. return true;
  2360. }
  2361. }
  2362. }
  2363. }
  2364. return false;
  2365. }
  2366. Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
  2367. const ArgList &Args)
  2368. : ToolChain(D, Triple, Args), GCCInstallation(D),
  2369. CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) {
  2370. getProgramPaths().push_back(getDriver().getInstalledDir());
  2371. if (getDriver().getInstalledDir() != getDriver().Dir)
  2372. getProgramPaths().push_back(getDriver().Dir);
  2373. }
  2374. Generic_GCC::~Generic_GCC() {}
  2375. Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
  2376. switch (AC) {
  2377. case Action::PreprocessJobClass:
  2378. if (!Preprocess)
  2379. Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
  2380. return Preprocess.get();
  2381. case Action::CompileJobClass:
  2382. if (!Compile)
  2383. Compile.reset(new tools::gcc::Compiler(*this));
  2384. return Compile.get();
  2385. default:
  2386. return ToolChain::getTool(AC);
  2387. }
  2388. }
  2389. Tool *Generic_GCC::buildAssembler() const {
  2390. return new tools::gnutools::Assembler(*this);
  2391. }
  2392. Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
  2393. void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
  2394. // Print the information about how we detected the GCC installation.
  2395. GCCInstallation.print(OS);
  2396. CudaInstallation.print(OS);
  2397. RocmInstallation.print(OS);
  2398. }
  2399. bool Generic_GCC::IsUnwindTablesDefault(const ArgList &Args) const {
  2400. switch (getArch()) {
  2401. case llvm::Triple::aarch64:
  2402. case llvm::Triple::ppc:
  2403. case llvm::Triple::ppcle:
  2404. case llvm::Triple::ppc64:
  2405. case llvm::Triple::ppc64le:
  2406. case llvm::Triple::x86:
  2407. case llvm::Triple::x86_64:
  2408. return true;
  2409. default:
  2410. return false;
  2411. }
  2412. }
  2413. bool Generic_GCC::isPICDefault() const {
  2414. switch (getArch()) {
  2415. case llvm::Triple::x86_64:
  2416. return getTriple().isOSWindows();
  2417. case llvm::Triple::mips64:
  2418. case llvm::Triple::mips64el:
  2419. return true;
  2420. default:
  2421. return false;
  2422. }
  2423. }
  2424. bool Generic_GCC::isPIEDefault(const llvm::opt::ArgList &Args) const {
  2425. return false;
  2426. }
  2427. bool Generic_GCC::isPICDefaultForced() const {
  2428. return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
  2429. }
  2430. bool Generic_GCC::IsIntegratedAssemblerDefault() const {
  2431. switch (getTriple().getArch()) {
  2432. case llvm::Triple::x86:
  2433. case llvm::Triple::x86_64:
  2434. case llvm::Triple::aarch64:
  2435. case llvm::Triple::aarch64_be:
  2436. case llvm::Triple::arm:
  2437. case llvm::Triple::armeb:
  2438. case llvm::Triple::avr:
  2439. case llvm::Triple::bpfel:
  2440. case llvm::Triple::bpfeb:
  2441. case llvm::Triple::thumb:
  2442. case llvm::Triple::thumbeb:
  2443. case llvm::Triple::ppc:
  2444. case llvm::Triple::ppcle:
  2445. case llvm::Triple::ppc64:
  2446. case llvm::Triple::ppc64le:
  2447. case llvm::Triple::riscv32:
  2448. case llvm::Triple::riscv64:
  2449. case llvm::Triple::systemz:
  2450. case llvm::Triple::mips:
  2451. case llvm::Triple::mipsel:
  2452. case llvm::Triple::mips64:
  2453. case llvm::Triple::mips64el:
  2454. case llvm::Triple::msp430:
  2455. case llvm::Triple::m68k:
  2456. return true;
  2457. case llvm::Triple::sparc:
  2458. case llvm::Triple::sparcel:
  2459. case llvm::Triple::sparcv9:
  2460. if (getTriple().isOSFreeBSD() || getTriple().isOSOpenBSD() ||
  2461. getTriple().isOSSolaris())
  2462. return true;
  2463. return false;
  2464. default:
  2465. return false;
  2466. }
  2467. }
  2468. void Generic_GCC::PushPPaths(ToolChain::path_list &PPaths) {
  2469. // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
  2470. // least) put various tools in a triple-prefixed directory off of the parent
  2471. // of the GCC installation. We use the GCC triple here to ensure that we end
  2472. // up with tools that support the same amount of cross compiling as the
  2473. // detected GCC installation. For example, if we find a GCC installation
  2474. // targeting x86_64, but it is a bi-arch GCC installation, it can also be
  2475. // used to target i386.
  2476. if (GCCInstallation.isValid()) {
  2477. PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
  2478. GCCInstallation.getTriple().str() + "/bin")
  2479. .str());
  2480. }
  2481. }
  2482. void Generic_GCC::AddMultilibPaths(const Driver &D,
  2483. const std::string &SysRoot,
  2484. const std::string &OSLibDir,
  2485. const std::string &MultiarchTriple,
  2486. path_list &Paths) {
  2487. // Add the multilib suffixed paths where they are available.
  2488. if (GCCInstallation.isValid()) {
  2489. const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
  2490. const std::string &LibPath =
  2491. std::string(GCCInstallation.getParentLibPath());
  2492. // Sourcery CodeBench MIPS toolchain holds some libraries under
  2493. // a biarch-like suffix of the GCC installation.
  2494. if (const auto &PathsCallback = Multilibs.filePathsCallback())
  2495. for (const auto &Path : PathsCallback(SelectedMultilib))
  2496. addPathIfExists(D, GCCInstallation.getInstallPath() + Path, Paths);
  2497. // Add lib/gcc/$triple/$version, with an optional /multilib suffix.
  2498. addPathIfExists(
  2499. D, GCCInstallation.getInstallPath() + SelectedMultilib.gccSuffix(),
  2500. Paths);
  2501. // GCC cross compiling toolchains will install target libraries which ship
  2502. // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
  2503. // any part of the GCC installation in
  2504. // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
  2505. // debatable, but is the reality today. We need to search this tree even
  2506. // when we have a sysroot somewhere else. It is the responsibility of
  2507. // whomever is doing the cross build targeting a sysroot using a GCC
  2508. // installation that is *not* within the system root to ensure two things:
  2509. //
  2510. // 1) Any DSOs that are linked in from this tree or from the install path
  2511. // above must be present on the system root and found via an
  2512. // appropriate rpath.
  2513. // 2) There must not be libraries installed into
  2514. // <prefix>/<triple>/<libdir> unless they should be preferred over
  2515. // those within the system root.
  2516. //
  2517. // Note that this matches the GCC behavior. See the below comment for where
  2518. // Clang diverges from GCC's behavior.
  2519. addPathIfExists(D,
  2520. LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
  2521. SelectedMultilib.osSuffix(),
  2522. Paths);
  2523. // If the GCC installation we found is inside of the sysroot, we want to
  2524. // prefer libraries installed in the parent prefix of the GCC installation.
  2525. // It is important to *not* use these paths when the GCC installation is
  2526. // outside of the system root as that can pick up unintended libraries.
  2527. // This usually happens when there is an external cross compiler on the
  2528. // host system, and a more minimal sysroot available that is the target of
  2529. // the cross. Note that GCC does include some of these directories in some
  2530. // configurations but this seems somewhere between questionable and simply
  2531. // a bug.
  2532. if (StringRef(LibPath).startswith(SysRoot))
  2533. addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
  2534. }
  2535. }
  2536. void Generic_GCC::AddMultiarchPaths(const Driver &D,
  2537. const std::string &SysRoot,
  2538. const std::string &OSLibDir,
  2539. path_list &Paths) {
  2540. if (GCCInstallation.isValid()) {
  2541. const std::string &LibPath =
  2542. std::string(GCCInstallation.getParentLibPath());
  2543. const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
  2544. const Multilib &Multilib = GCCInstallation.getMultilib();
  2545. addPathIfExists(
  2546. D, LibPath + "/../" + GCCTriple.str() + "/lib" + Multilib.osSuffix(),
  2547. Paths);
  2548. }
  2549. }
  2550. void Generic_GCC::AddMultilibIncludeArgs(const ArgList &DriverArgs,
  2551. ArgStringList &CC1Args) const {
  2552. // Add include directories specific to the selected multilib set and multilib.
  2553. if (!GCCInstallation.isValid())
  2554. return;
  2555. // gcc TOOL_INCLUDE_DIR.
  2556. const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
  2557. std::string LibPath(GCCInstallation.getParentLibPath());
  2558. addSystemInclude(DriverArgs, CC1Args,
  2559. Twine(LibPath) + "/../" + GCCTriple.str() + "/include");
  2560. const auto &Callback = Multilibs.includeDirsCallback();
  2561. if (Callback) {
  2562. for (const auto &Path : Callback(GCCInstallation.getMultilib()))
  2563. addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
  2564. GCCInstallation.getInstallPath() + Path);
  2565. }
  2566. }
  2567. void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  2568. ArgStringList &CC1Args) const {
  2569. if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx,
  2570. options::OPT_nostdlibinc))
  2571. return;
  2572. switch (GetCXXStdlibType(DriverArgs)) {
  2573. case ToolChain::CST_Libcxx:
  2574. addLibCxxIncludePaths(DriverArgs, CC1Args);
  2575. break;
  2576. case ToolChain::CST_Libstdcxx:
  2577. addLibStdCxxIncludePaths(DriverArgs, CC1Args);
  2578. break;
  2579. }
  2580. }
  2581. void
  2582. Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
  2583. llvm::opt::ArgStringList &CC1Args) const {
  2584. const Driver &D = getDriver();
  2585. std::string SysRoot = computeSysRoot();
  2586. std::string Target = getTripleString();
  2587. auto AddIncludePath = [&](std::string Path) {
  2588. std::string Version = detectLibcxxVersion(Path);
  2589. if (Version.empty())
  2590. return false;
  2591. // First add the per-target include path if it exists.
  2592. std::string TargetDir = Path + "/" + Target + "/c++/" + Version;
  2593. if (D.getVFS().exists(TargetDir))
  2594. addSystemInclude(DriverArgs, CC1Args, TargetDir);
  2595. // Second add the generic one.
  2596. addSystemInclude(DriverArgs, CC1Args, Path + "/c++/" + Version);
  2597. return true;
  2598. };
  2599. // Android never uses the libc++ headers installed alongside the toolchain,
  2600. // which are generally incompatible with the NDK libraries anyway.
  2601. if (!getTriple().isAndroid())
  2602. if (AddIncludePath(getDriver().Dir + "/../include"))
  2603. return;
  2604. // If this is a development, non-installed, clang, libcxx will
  2605. // not be found at ../include/c++ but it likely to be found at
  2606. // one of the following two locations:
  2607. if (AddIncludePath(SysRoot + "/usr/local/include"))
  2608. return;
  2609. if (AddIncludePath(SysRoot + "/usr/include"))
  2610. return;
  2611. }
  2612. bool Generic_GCC::addLibStdCXXIncludePaths(Twine IncludeDir, StringRef Triple,
  2613. Twine IncludeSuffix,
  2614. const llvm::opt::ArgList &DriverArgs,
  2615. llvm::opt::ArgStringList &CC1Args,
  2616. bool DetectDebian) const {
  2617. if (!getVFS().exists(IncludeDir))
  2618. return false;
  2619. // Debian native gcc uses g++-multiarch-incdir.diff which uses
  2620. // include/x86_64-linux-gnu/c++/10$IncludeSuffix instead of
  2621. // include/c++/10/x86_64-linux-gnu$IncludeSuffix.
  2622. std::string Dir = IncludeDir.str();
  2623. StringRef Include =
  2624. llvm::sys::path::parent_path(llvm::sys::path::parent_path(Dir));
  2625. std::string Path =
  2626. (Include + "/" + Triple + Dir.substr(Include.size()) + IncludeSuffix)
  2627. .str();
  2628. if (DetectDebian && !getVFS().exists(Path))
  2629. return false;
  2630. // GPLUSPLUS_INCLUDE_DIR
  2631. addSystemInclude(DriverArgs, CC1Args, IncludeDir);
  2632. // GPLUSPLUS_TOOL_INCLUDE_DIR. If Triple is not empty, add a target-dependent
  2633. // include directory.
  2634. if (DetectDebian)
  2635. addSystemInclude(DriverArgs, CC1Args, Path);
  2636. else if (!Triple.empty())
  2637. addSystemInclude(DriverArgs, CC1Args,
  2638. IncludeDir + "/" + Triple + IncludeSuffix);
  2639. // GPLUSPLUS_BACKWARD_INCLUDE_DIR
  2640. addSystemInclude(DriverArgs, CC1Args, IncludeDir + "/backward");
  2641. return true;
  2642. }
  2643. bool Generic_GCC::addGCCLibStdCxxIncludePaths(
  2644. const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
  2645. StringRef DebianMultiarch) const {
  2646. assert(GCCInstallation.isValid());
  2647. // By default, look for the C++ headers in an include directory adjacent to
  2648. // the lib directory of the GCC installation. Note that this is expect to be
  2649. // equivalent to '/usr/include/c++/X.Y' in almost all cases.
  2650. StringRef LibDir = GCCInstallation.getParentLibPath();
  2651. StringRef InstallDir = GCCInstallation.getInstallPath();
  2652. StringRef TripleStr = GCCInstallation.getTriple().str();
  2653. const Multilib &Multilib = GCCInstallation.getMultilib();
  2654. const GCCVersion &Version = GCCInstallation.getVersion();
  2655. // Try /../$triple/include/c++/$version (gcc --print-multiarch is not empty).
  2656. if (addLibStdCXXIncludePaths(
  2657. LibDir.str() + "/../" + TripleStr + "/include/c++/" + Version.Text,
  2658. TripleStr, Multilib.includeSuffix(), DriverArgs, CC1Args))
  2659. return true;
  2660. // Detect Debian g++-multiarch-incdir.diff.
  2661. if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
  2662. DebianMultiarch, Multilib.includeSuffix(),
  2663. DriverArgs, CC1Args, /*Debian=*/true))
  2664. return true;
  2665. // Try /../include/c++/$version (gcc --print-multiarch is empty).
  2666. if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
  2667. TripleStr, Multilib.includeSuffix(), DriverArgs,
  2668. CC1Args))
  2669. return true;
  2670. // Otherwise, fall back on a bunch of options which don't use multiarch
  2671. // layouts for simplicity.
  2672. const std::string LibStdCXXIncludePathCandidates[] = {
  2673. // Gentoo is weird and places its headers inside the GCC install,
  2674. // so if the first attempt to find the headers fails, try these patterns.
  2675. InstallDir.str() + "/include/g++-v" + Version.Text,
  2676. InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
  2677. Version.MinorStr,
  2678. InstallDir.str() + "/include/g++-v" + Version.MajorStr,
  2679. };
  2680. for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
  2681. if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
  2682. Multilib.includeSuffix(), DriverArgs, CC1Args))
  2683. return true;
  2684. }
  2685. return false;
  2686. }
  2687. void
  2688. Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
  2689. llvm::opt::ArgStringList &CC1Args) const {
  2690. if (GCCInstallation.isValid()) {
  2691. addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
  2692. GCCInstallation.getTriple().str());
  2693. }
  2694. }
  2695. llvm::opt::DerivedArgList *
  2696. Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
  2697. Action::OffloadKind DeviceOffloadKind) const {
  2698. // If this tool chain is used for an OpenMP offloading device we have to make
  2699. // sure we always generate a shared library regardless of the commands the
  2700. // user passed to the host. This is required because the runtime library
  2701. // is required to load the device image dynamically at run time.
  2702. if (DeviceOffloadKind == Action::OFK_OpenMP) {
  2703. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  2704. const OptTable &Opts = getDriver().getOpts();
  2705. // Request the shared library. Given that these options are decided
  2706. // implicitly, they do not refer to any base argument.
  2707. DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
  2708. DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
  2709. // Filter all the arguments we don't care passing to the offloading
  2710. // toolchain as they can mess up with the creation of a shared library.
  2711. for (auto *A : Args) {
  2712. switch ((options::ID)A->getOption().getID()) {
  2713. default:
  2714. DAL->append(A);
  2715. break;
  2716. case options::OPT_shared:
  2717. case options::OPT_dynamic:
  2718. case options::OPT_static:
  2719. case options::OPT_fPIC:
  2720. case options::OPT_fno_PIC:
  2721. case options::OPT_fpic:
  2722. case options::OPT_fno_pic:
  2723. case options::OPT_fPIE:
  2724. case options::OPT_fno_PIE:
  2725. case options::OPT_fpie:
  2726. case options::OPT_fno_pie:
  2727. break;
  2728. }
  2729. }
  2730. return DAL;
  2731. }
  2732. return nullptr;
  2733. }
  2734. void Generic_ELF::anchor() {}
  2735. void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
  2736. ArgStringList &CC1Args,
  2737. Action::OffloadKind) const {
  2738. if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
  2739. options::OPT_fno_use_init_array, true))
  2740. CC1Args.push_back("-fno-use-init-array");
  2741. }