TargetLoweringObjectFileImpl.cpp 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658
  1. //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements classes used to handle lowerings specific to common
  10. // object file formats.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
  14. #include "llvm/ADT/SmallString.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/BinaryFormat/COFF.h"
  20. #include "llvm/BinaryFormat/Dwarf.h"
  21. #include "llvm/BinaryFormat/ELF.h"
  22. #include "llvm/BinaryFormat/MachO.h"
  23. #include "llvm/BinaryFormat/Wasm.h"
  24. #include "llvm/CodeGen/BasicBlockSectionUtils.h"
  25. #include "llvm/CodeGen/MachineBasicBlock.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineModuleInfo.h"
  28. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  29. #include "llvm/IR/Comdat.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/DerivedTypes.h"
  33. #include "llvm/IR/DiagnosticInfo.h"
  34. #include "llvm/IR/DiagnosticPrinter.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/GlobalAlias.h"
  37. #include "llvm/IR/GlobalObject.h"
  38. #include "llvm/IR/GlobalValue.h"
  39. #include "llvm/IR/GlobalVariable.h"
  40. #include "llvm/IR/Mangler.h"
  41. #include "llvm/IR/Metadata.h"
  42. #include "llvm/IR/Module.h"
  43. #include "llvm/IR/PseudoProbe.h"
  44. #include "llvm/IR/Type.h"
  45. #include "llvm/MC/MCAsmInfo.h"
  46. #include "llvm/MC/MCContext.h"
  47. #include "llvm/MC/MCExpr.h"
  48. #include "llvm/MC/MCSectionCOFF.h"
  49. #include "llvm/MC/MCSectionELF.h"
  50. #include "llvm/MC/MCSectionGOFF.h"
  51. #include "llvm/MC/MCSectionMachO.h"
  52. #include "llvm/MC/MCSectionWasm.h"
  53. #include "llvm/MC/MCSectionXCOFF.h"
  54. #include "llvm/MC/MCStreamer.h"
  55. #include "llvm/MC/MCSymbol.h"
  56. #include "llvm/MC/MCSymbolELF.h"
  57. #include "llvm/MC/MCValue.h"
  58. #include "llvm/MC/SectionKind.h"
  59. #include "llvm/ProfileData/InstrProf.h"
  60. #include "llvm/Support/Base64.h"
  61. #include "llvm/Support/Casting.h"
  62. #include "llvm/Support/CodeGen.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include "llvm/Support/Format.h"
  65. #include "llvm/Support/raw_ostream.h"
  66. #include "llvm/Target/TargetMachine.h"
  67. #include <cassert>
  68. #include <string>
  69. using namespace llvm;
  70. using namespace dwarf;
  71. static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
  72. StringRef &Section) {
  73. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  74. M.getModuleFlagsMetadata(ModuleFlags);
  75. for (const auto &MFE: ModuleFlags) {
  76. // Ignore flags with 'Require' behaviour.
  77. if (MFE.Behavior == Module::Require)
  78. continue;
  79. StringRef Key = MFE.Key->getString();
  80. if (Key == "Objective-C Image Info Version") {
  81. Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
  82. } else if (Key == "Objective-C Garbage Collection" ||
  83. Key == "Objective-C GC Only" ||
  84. Key == "Objective-C Is Simulated" ||
  85. Key == "Objective-C Class Properties" ||
  86. Key == "Objective-C Image Swift Version") {
  87. Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
  88. } else if (Key == "Objective-C Image Info Section") {
  89. Section = cast<MDString>(MFE.Val)->getString();
  90. }
  91. // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
  92. // "Objective-C Garbage Collection".
  93. else if (Key == "Swift ABI Version") {
  94. Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
  95. } else if (Key == "Swift Major Version") {
  96. Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
  97. } else if (Key == "Swift Minor Version") {
  98. Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
  99. }
  100. }
  101. }
  102. //===----------------------------------------------------------------------===//
  103. // ELF
  104. //===----------------------------------------------------------------------===//
  105. TargetLoweringObjectFileELF::TargetLoweringObjectFileELF() {
  106. SupportDSOLocalEquivalentLowering = true;
  107. }
  108. void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
  109. const TargetMachine &TgtM) {
  110. TargetLoweringObjectFile::Initialize(Ctx, TgtM);
  111. CodeModel::Model CM = TgtM.getCodeModel();
  112. InitializeELF(TgtM.Options.UseInitArray);
  113. switch (TgtM.getTargetTriple().getArch()) {
  114. case Triple::arm:
  115. case Triple::armeb:
  116. case Triple::thumb:
  117. case Triple::thumbeb:
  118. if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
  119. break;
  120. // Fallthrough if not using EHABI
  121. [[fallthrough]];
  122. case Triple::ppc:
  123. case Triple::ppcle:
  124. case Triple::x86:
  125. PersonalityEncoding = isPositionIndependent()
  126. ? dwarf::DW_EH_PE_indirect |
  127. dwarf::DW_EH_PE_pcrel |
  128. dwarf::DW_EH_PE_sdata4
  129. : dwarf::DW_EH_PE_absptr;
  130. LSDAEncoding = isPositionIndependent()
  131. ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
  132. : dwarf::DW_EH_PE_absptr;
  133. TTypeEncoding = isPositionIndependent()
  134. ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  135. dwarf::DW_EH_PE_sdata4
  136. : dwarf::DW_EH_PE_absptr;
  137. break;
  138. case Triple::x86_64:
  139. if (isPositionIndependent()) {
  140. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  141. ((CM == CodeModel::Small || CM == CodeModel::Medium)
  142. ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
  143. LSDAEncoding = dwarf::DW_EH_PE_pcrel |
  144. (CM == CodeModel::Small
  145. ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
  146. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  147. ((CM == CodeModel::Small || CM == CodeModel::Medium)
  148. ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
  149. } else {
  150. PersonalityEncoding =
  151. (CM == CodeModel::Small || CM == CodeModel::Medium)
  152. ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
  153. LSDAEncoding = (CM == CodeModel::Small)
  154. ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
  155. TTypeEncoding = (CM == CodeModel::Small)
  156. ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
  157. }
  158. break;
  159. case Triple::hexagon:
  160. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  161. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  162. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  163. if (isPositionIndependent()) {
  164. PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
  165. LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
  166. TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
  167. }
  168. break;
  169. case Triple::aarch64:
  170. case Triple::aarch64_be:
  171. case Triple::aarch64_32:
  172. // The small model guarantees static code/data size < 4GB, but not where it
  173. // will be in memory. Most of these could end up >2GB away so even a signed
  174. // pc-relative 32-bit address is insufficient, theoretically.
  175. if (isPositionIndependent()) {
  176. // ILP32 uses sdata4 instead of sdata8
  177. if (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32) {
  178. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  179. dwarf::DW_EH_PE_sdata4;
  180. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  181. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  182. dwarf::DW_EH_PE_sdata4;
  183. } else {
  184. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  185. dwarf::DW_EH_PE_sdata8;
  186. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
  187. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  188. dwarf::DW_EH_PE_sdata8;
  189. }
  190. } else {
  191. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  192. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  193. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  194. }
  195. break;
  196. case Triple::lanai:
  197. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  198. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  199. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  200. break;
  201. case Triple::mips:
  202. case Triple::mipsel:
  203. case Triple::mips64:
  204. case Triple::mips64el:
  205. // MIPS uses indirect pointer to refer personality functions and types, so
  206. // that the eh_frame section can be read-only. DW.ref.personality will be
  207. // generated for relocation.
  208. PersonalityEncoding = dwarf::DW_EH_PE_indirect;
  209. // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
  210. // identify N64 from just a triple.
  211. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  212. dwarf::DW_EH_PE_sdata4;
  213. // We don't support PC-relative LSDA references in GAS so we use the default
  214. // DW_EH_PE_absptr for those.
  215. // FreeBSD must be explicit about the data size and using pcrel since it's
  216. // assembler/linker won't do the automatic conversion that the Linux tools
  217. // do.
  218. if (TgtM.getTargetTriple().isOSFreeBSD()) {
  219. PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  220. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  221. }
  222. break;
  223. case Triple::ppc64:
  224. case Triple::ppc64le:
  225. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  226. dwarf::DW_EH_PE_udata8;
  227. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
  228. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  229. dwarf::DW_EH_PE_udata8;
  230. break;
  231. case Triple::sparcel:
  232. case Triple::sparc:
  233. if (isPositionIndependent()) {
  234. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  235. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  236. dwarf::DW_EH_PE_sdata4;
  237. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  238. dwarf::DW_EH_PE_sdata4;
  239. } else {
  240. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  241. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  242. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  243. }
  244. CallSiteEncoding = dwarf::DW_EH_PE_udata4;
  245. break;
  246. case Triple::riscv32:
  247. case Triple::riscv64:
  248. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  249. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  250. dwarf::DW_EH_PE_sdata4;
  251. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  252. dwarf::DW_EH_PE_sdata4;
  253. CallSiteEncoding = dwarf::DW_EH_PE_udata4;
  254. break;
  255. case Triple::sparcv9:
  256. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  257. if (isPositionIndependent()) {
  258. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  259. dwarf::DW_EH_PE_sdata4;
  260. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  261. dwarf::DW_EH_PE_sdata4;
  262. } else {
  263. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  264. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  265. }
  266. break;
  267. case Triple::systemz:
  268. // All currently-defined code models guarantee that 4-byte PC-relative
  269. // values will be in range.
  270. if (isPositionIndependent()) {
  271. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  272. dwarf::DW_EH_PE_sdata4;
  273. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  274. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  275. dwarf::DW_EH_PE_sdata4;
  276. } else {
  277. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  278. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  279. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  280. }
  281. break;
  282. case Triple::loongarch32:
  283. case Triple::loongarch64:
  284. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  285. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  286. dwarf::DW_EH_PE_sdata4;
  287. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  288. dwarf::DW_EH_PE_sdata4;
  289. break;
  290. default:
  291. break;
  292. }
  293. }
  294. void TargetLoweringObjectFileELF::getModuleMetadata(Module &M) {
  295. SmallVector<GlobalValue *, 4> Vec;
  296. collectUsedGlobalVariables(M, Vec, false);
  297. for (GlobalValue *GV : Vec)
  298. if (auto *GO = dyn_cast<GlobalObject>(GV))
  299. Used.insert(GO);
  300. }
  301. void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
  302. Module &M) const {
  303. auto &C = getContext();
  304. if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
  305. auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
  306. ELF::SHF_EXCLUDE);
  307. Streamer.switchSection(S);
  308. for (const auto *Operand : LinkerOptions->operands()) {
  309. if (cast<MDNode>(Operand)->getNumOperands() != 2)
  310. report_fatal_error("invalid llvm.linker.options");
  311. for (const auto &Option : cast<MDNode>(Operand)->operands()) {
  312. Streamer.emitBytes(cast<MDString>(Option)->getString());
  313. Streamer.emitInt8(0);
  314. }
  315. }
  316. }
  317. if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
  318. auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
  319. ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
  320. Streamer.switchSection(S);
  321. for (const auto *Operand : DependentLibraries->operands()) {
  322. Streamer.emitBytes(
  323. cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
  324. Streamer.emitInt8(0);
  325. }
  326. }
  327. if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
  328. // Emit a descriptor for every function including functions that have an
  329. // available external linkage. We may not want this for imported functions
  330. // that has code in another thinLTO module but we don't have a good way to
  331. // tell them apart from inline functions defined in header files. Therefore
  332. // we put each descriptor in a separate comdat section and rely on the
  333. // linker to deduplicate.
  334. for (const auto *Operand : FuncInfo->operands()) {
  335. const auto *MD = cast<MDNode>(Operand);
  336. auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
  337. auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
  338. auto *Name = cast<MDString>(MD->getOperand(2));
  339. auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
  340. TM->getFunctionSections() ? Name->getString() : StringRef());
  341. Streamer.switchSection(S);
  342. Streamer.emitInt64(GUID->getZExtValue());
  343. Streamer.emitInt64(Hash->getZExtValue());
  344. Streamer.emitULEB128IntValue(Name->getString().size());
  345. Streamer.emitBytes(Name->getString());
  346. }
  347. }
  348. if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) {
  349. // Emit the metadata for llvm statistics into .llvm_stats section, which is
  350. // formatted as a list of key/value pair, the value is base64 encoded.
  351. auto *S = C.getObjectFileInfo()->getLLVMStatsSection();
  352. Streamer.switchSection(S);
  353. for (const auto *Operand : LLVMStats->operands()) {
  354. const auto *MD = cast<MDNode>(Operand);
  355. assert(MD->getNumOperands() % 2 == 0 &&
  356. ("Operand num should be even for a list of key/value pair"));
  357. for (size_t I = 0; I < MD->getNumOperands(); I += 2) {
  358. // Encode the key string size.
  359. auto *Key = cast<MDString>(MD->getOperand(I));
  360. Streamer.emitULEB128IntValue(Key->getString().size());
  361. Streamer.emitBytes(Key->getString());
  362. // Encode the value into a Base64 string.
  363. std::string Value = encodeBase64(
  364. Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1))
  365. ->getZExtValue())
  366. .str());
  367. Streamer.emitULEB128IntValue(Value.size());
  368. Streamer.emitBytes(Value);
  369. }
  370. }
  371. }
  372. unsigned Version = 0;
  373. unsigned Flags = 0;
  374. StringRef Section;
  375. GetObjCImageInfo(M, Version, Flags, Section);
  376. if (!Section.empty()) {
  377. auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
  378. Streamer.switchSection(S);
  379. Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
  380. Streamer.emitInt32(Version);
  381. Streamer.emitInt32(Flags);
  382. Streamer.addBlankLine();
  383. }
  384. emitCGProfileMetadata(Streamer, M);
  385. }
  386. MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
  387. const GlobalValue *GV, const TargetMachine &TM,
  388. MachineModuleInfo *MMI) const {
  389. unsigned Encoding = getPersonalityEncoding();
  390. if ((Encoding & 0x80) == DW_EH_PE_indirect)
  391. return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
  392. TM.getSymbol(GV)->getName());
  393. if ((Encoding & 0x70) == DW_EH_PE_absptr)
  394. return TM.getSymbol(GV);
  395. report_fatal_error("We do not support this DWARF encoding yet!");
  396. }
  397. void TargetLoweringObjectFileELF::emitPersonalityValue(
  398. MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
  399. SmallString<64> NameData("DW.ref.");
  400. NameData += Sym->getName();
  401. MCSymbolELF *Label =
  402. cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
  403. Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
  404. Streamer.emitSymbolAttribute(Label, MCSA_Weak);
  405. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
  406. MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
  407. ELF::SHT_PROGBITS, Flags, 0);
  408. unsigned Size = DL.getPointerSize();
  409. Streamer.switchSection(Sec);
  410. Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0));
  411. Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
  412. const MCExpr *E = MCConstantExpr::create(Size, getContext());
  413. Streamer.emitELFSize(Label, E);
  414. Streamer.emitLabel(Label);
  415. Streamer.emitSymbolValue(Sym, Size);
  416. }
  417. const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
  418. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  419. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  420. if (Encoding & DW_EH_PE_indirect) {
  421. MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
  422. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
  423. // Add information about the stub reference to ELFMMI so that the stub
  424. // gets emitted by the asmprinter.
  425. MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
  426. if (!StubSym.getPointer()) {
  427. MCSymbol *Sym = TM.getSymbol(GV);
  428. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  429. }
  430. return TargetLoweringObjectFile::
  431. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  432. Encoding & ~DW_EH_PE_indirect, Streamer);
  433. }
  434. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  435. MMI, Streamer);
  436. }
  437. static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
  438. // N.B.: The defaults used in here are not the same ones used in MC.
  439. // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
  440. // both gas and MC will produce a section with no flags. Given
  441. // section(".eh_frame") gcc will produce:
  442. //
  443. // .section .eh_frame,"a",@progbits
  444. if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
  445. /*AddSegmentInfo=*/false) ||
  446. Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
  447. /*AddSegmentInfo=*/false) ||
  448. Name == ".llvmbc" || Name == ".llvmcmd")
  449. return SectionKind::getMetadata();
  450. if (Name.empty() || Name[0] != '.') return K;
  451. // Default implementation based on some magic section names.
  452. if (Name == ".bss" ||
  453. Name.startswith(".bss.") ||
  454. Name.startswith(".gnu.linkonce.b.") ||
  455. Name.startswith(".llvm.linkonce.b.") ||
  456. Name == ".sbss" ||
  457. Name.startswith(".sbss.") ||
  458. Name.startswith(".gnu.linkonce.sb.") ||
  459. Name.startswith(".llvm.linkonce.sb."))
  460. return SectionKind::getBSS();
  461. if (Name == ".tdata" ||
  462. Name.startswith(".tdata.") ||
  463. Name.startswith(".gnu.linkonce.td.") ||
  464. Name.startswith(".llvm.linkonce.td."))
  465. return SectionKind::getThreadData();
  466. if (Name == ".tbss" ||
  467. Name.startswith(".tbss.") ||
  468. Name.startswith(".gnu.linkonce.tb.") ||
  469. Name.startswith(".llvm.linkonce.tb."))
  470. return SectionKind::getThreadBSS();
  471. return K;
  472. }
  473. static bool hasPrefix(StringRef SectionName, StringRef Prefix) {
  474. return SectionName.consume_front(Prefix) &&
  475. (SectionName.empty() || SectionName[0] == '.');
  476. }
  477. static unsigned getELFSectionType(StringRef Name, SectionKind K) {
  478. // Use SHT_NOTE for section whose name starts with ".note" to allow
  479. // emitting ELF notes from C variable declaration.
  480. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
  481. if (Name.startswith(".note"))
  482. return ELF::SHT_NOTE;
  483. if (hasPrefix(Name, ".init_array"))
  484. return ELF::SHT_INIT_ARRAY;
  485. if (hasPrefix(Name, ".fini_array"))
  486. return ELF::SHT_FINI_ARRAY;
  487. if (hasPrefix(Name, ".preinit_array"))
  488. return ELF::SHT_PREINIT_ARRAY;
  489. if (hasPrefix(Name, ".llvm.offloading"))
  490. return ELF::SHT_LLVM_OFFLOADING;
  491. if (K.isBSS() || K.isThreadBSS())
  492. return ELF::SHT_NOBITS;
  493. return ELF::SHT_PROGBITS;
  494. }
  495. static unsigned getELFSectionFlags(SectionKind K) {
  496. unsigned Flags = 0;
  497. if (!K.isMetadata() && !K.isExclude())
  498. Flags |= ELF::SHF_ALLOC;
  499. if (K.isExclude())
  500. Flags |= ELF::SHF_EXCLUDE;
  501. if (K.isText())
  502. Flags |= ELF::SHF_EXECINSTR;
  503. if (K.isExecuteOnly())
  504. Flags |= ELF::SHF_ARM_PURECODE;
  505. if (K.isWriteable())
  506. Flags |= ELF::SHF_WRITE;
  507. if (K.isThreadLocal())
  508. Flags |= ELF::SHF_TLS;
  509. if (K.isMergeableCString() || K.isMergeableConst())
  510. Flags |= ELF::SHF_MERGE;
  511. if (K.isMergeableCString())
  512. Flags |= ELF::SHF_STRINGS;
  513. return Flags;
  514. }
  515. static const Comdat *getELFComdat(const GlobalValue *GV) {
  516. const Comdat *C = GV->getComdat();
  517. if (!C)
  518. return nullptr;
  519. if (C->getSelectionKind() != Comdat::Any &&
  520. C->getSelectionKind() != Comdat::NoDeduplicate)
  521. report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
  522. "SelectionKind::NoDeduplicate, '" +
  523. C->getName() + "' cannot be lowered.");
  524. return C;
  525. }
  526. static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
  527. const TargetMachine &TM) {
  528. MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
  529. if (!MD)
  530. return nullptr;
  531. const MDOperand &Op = MD->getOperand(0);
  532. if (!Op.get())
  533. return nullptr;
  534. auto *VM = dyn_cast<ValueAsMetadata>(Op);
  535. if (!VM)
  536. report_fatal_error("MD_associated operand is not ValueAsMetadata");
  537. auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
  538. return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
  539. }
  540. static unsigned getEntrySizeForKind(SectionKind Kind) {
  541. if (Kind.isMergeable1ByteCString())
  542. return 1;
  543. else if (Kind.isMergeable2ByteCString())
  544. return 2;
  545. else if (Kind.isMergeable4ByteCString())
  546. return 4;
  547. else if (Kind.isMergeableConst4())
  548. return 4;
  549. else if (Kind.isMergeableConst8())
  550. return 8;
  551. else if (Kind.isMergeableConst16())
  552. return 16;
  553. else if (Kind.isMergeableConst32())
  554. return 32;
  555. else {
  556. // We shouldn't have mergeable C strings or mergeable constants that we
  557. // didn't handle above.
  558. assert(!Kind.isMergeableCString() && "unknown string width");
  559. assert(!Kind.isMergeableConst() && "unknown data width");
  560. return 0;
  561. }
  562. }
  563. /// Return the section prefix name used by options FunctionsSections and
  564. /// DataSections.
  565. static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
  566. if (Kind.isText())
  567. return ".text";
  568. if (Kind.isReadOnly())
  569. return ".rodata";
  570. if (Kind.isBSS())
  571. return ".bss";
  572. if (Kind.isThreadData())
  573. return ".tdata";
  574. if (Kind.isThreadBSS())
  575. return ".tbss";
  576. if (Kind.isData())
  577. return ".data";
  578. if (Kind.isReadOnlyWithRel())
  579. return ".data.rel.ro";
  580. llvm_unreachable("Unknown section kind");
  581. }
  582. static SmallString<128>
  583. getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
  584. Mangler &Mang, const TargetMachine &TM,
  585. unsigned EntrySize, bool UniqueSectionName) {
  586. SmallString<128> Name;
  587. if (Kind.isMergeableCString()) {
  588. // We also need alignment here.
  589. // FIXME: this is getting the alignment of the character, not the
  590. // alignment of the global!
  591. Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
  592. cast<GlobalVariable>(GO));
  593. std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
  594. Name = SizeSpec + utostr(Alignment.value());
  595. } else if (Kind.isMergeableConst()) {
  596. Name = ".rodata.cst";
  597. Name += utostr(EntrySize);
  598. } else {
  599. Name = getSectionPrefixForGlobal(Kind);
  600. }
  601. bool HasPrefix = false;
  602. if (const auto *F = dyn_cast<Function>(GO)) {
  603. if (std::optional<StringRef> Prefix = F->getSectionPrefix()) {
  604. raw_svector_ostream(Name) << '.' << *Prefix;
  605. HasPrefix = true;
  606. }
  607. }
  608. if (UniqueSectionName) {
  609. Name.push_back('.');
  610. TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
  611. } else if (HasPrefix)
  612. // For distinguishing between .text.${text-section-prefix}. (with trailing
  613. // dot) and .text.${function-name}
  614. Name.push_back('.');
  615. return Name;
  616. }
  617. namespace {
  618. class LoweringDiagnosticInfo : public DiagnosticInfo {
  619. const Twine &Msg;
  620. public:
  621. LoweringDiagnosticInfo(const Twine &DiagMsg,
  622. DiagnosticSeverity Severity = DS_Error)
  623. : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
  624. void print(DiagnosticPrinter &DP) const override { DP << Msg; }
  625. };
  626. }
  627. /// Calculate an appropriate unique ID for a section, and update Flags,
  628. /// EntrySize and NextUniqueID where appropriate.
  629. static unsigned
  630. calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName,
  631. SectionKind Kind, const TargetMachine &TM,
  632. MCContext &Ctx, Mangler &Mang, unsigned &Flags,
  633. unsigned &EntrySize, unsigned &NextUniqueID,
  634. const bool Retain, const bool ForceUnique) {
  635. // Increment uniqueID if we are forced to emit a unique section.
  636. // This works perfectly fine with section attribute or pragma section as the
  637. // sections with the same name are grouped together by the assembler.
  638. if (ForceUnique)
  639. return NextUniqueID++;
  640. // A section can have at most one associated section. Put each global with
  641. // MD_associated in a unique section.
  642. const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
  643. if (Associated) {
  644. Flags |= ELF::SHF_LINK_ORDER;
  645. return NextUniqueID++;
  646. }
  647. if (Retain) {
  648. if (TM.getTargetTriple().isOSSolaris())
  649. Flags |= ELF::SHF_SUNW_NODISCARD;
  650. else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
  651. Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36))
  652. Flags |= ELF::SHF_GNU_RETAIN;
  653. return NextUniqueID++;
  654. }
  655. // If two symbols with differing sizes end up in the same mergeable section
  656. // that section can be assigned an incorrect entry size. To avoid this we
  657. // usually put symbols of the same size into distinct mergeable sections with
  658. // the same name. Doing so relies on the ",unique ," assembly feature. This
  659. // feature is not avalible until bintuils version 2.35
  660. // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
  661. const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
  662. Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
  663. if (!SupportsUnique) {
  664. Flags &= ~ELF::SHF_MERGE;
  665. EntrySize = 0;
  666. return MCContext::GenericSectionID;
  667. }
  668. const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
  669. const bool SeenSectionNameBefore =
  670. Ctx.isELFGenericMergeableSection(SectionName);
  671. // If this is the first ocurrence of this section name, treat it as the
  672. // generic section
  673. if (!SymbolMergeable && !SeenSectionNameBefore)
  674. return MCContext::GenericSectionID;
  675. // Symbols must be placed into sections with compatible entry sizes. Generate
  676. // unique sections for symbols that have not been assigned to compatible
  677. // sections.
  678. const auto PreviousID =
  679. Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
  680. if (PreviousID)
  681. return *PreviousID;
  682. // If the user has specified the same section name as would be created
  683. // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
  684. // to unique the section as the entry size for this symbol will be
  685. // compatible with implicitly created sections.
  686. SmallString<128> ImplicitSectionNameStem =
  687. getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false);
  688. if (SymbolMergeable &&
  689. Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
  690. SectionName.startswith(ImplicitSectionNameStem))
  691. return MCContext::GenericSectionID;
  692. // We have seen this section name before, but with different flags or entity
  693. // size. Create a new unique ID.
  694. return NextUniqueID++;
  695. }
  696. static MCSection *selectExplicitSectionGlobal(
  697. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
  698. MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
  699. bool Retain, bool ForceUnique) {
  700. StringRef SectionName = GO->getSection();
  701. // Check if '#pragma clang section' name is applicable.
  702. // Note that pragma directive overrides -ffunction-section, -fdata-section
  703. // and so section name is exactly as user specified and not uniqued.
  704. const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
  705. if (GV && GV->hasImplicitSection()) {
  706. auto Attrs = GV->getAttributes();
  707. if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
  708. SectionName = Attrs.getAttribute("bss-section").getValueAsString();
  709. } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
  710. SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
  711. } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
  712. SectionName = Attrs.getAttribute("relro-section").getValueAsString();
  713. } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
  714. SectionName = Attrs.getAttribute("data-section").getValueAsString();
  715. }
  716. }
  717. const Function *F = dyn_cast<Function>(GO);
  718. if (F && F->hasFnAttribute("implicit-section-name")) {
  719. SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
  720. }
  721. // Infer section flags from the section name if we can.
  722. Kind = getELFKindForNamedSection(SectionName, Kind);
  723. StringRef Group = "";
  724. bool IsComdat = false;
  725. unsigned Flags = getELFSectionFlags(Kind);
  726. if (const Comdat *C = getELFComdat(GO)) {
  727. Group = C->getName();
  728. IsComdat = C->getSelectionKind() == Comdat::Any;
  729. Flags |= ELF::SHF_GROUP;
  730. }
  731. unsigned EntrySize = getEntrySizeForKind(Kind);
  732. const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
  733. GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
  734. Retain, ForceUnique);
  735. const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
  736. MCSectionELF *Section = Ctx.getELFSection(
  737. SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
  738. Group, IsComdat, UniqueID, LinkedToSym);
  739. // Make sure that we did not get some other section with incompatible sh_link.
  740. // This should not be possible due to UniqueID code above.
  741. assert(Section->getLinkedToSymbol() == LinkedToSym &&
  742. "Associated symbol mismatch between sections");
  743. if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
  744. Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
  745. // If we are using GNU as before 2.35, then this symbol might have
  746. // been placed in an incompatible mergeable section. Emit an error if this
  747. // is the case to avoid creating broken output.
  748. if ((Section->getFlags() & ELF::SHF_MERGE) &&
  749. (Section->getEntrySize() != getEntrySizeForKind(Kind)))
  750. GO->getContext().diagnose(LoweringDiagnosticInfo(
  751. "Symbol '" + GO->getName() + "' from module '" +
  752. (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
  753. "' required a section with entry-size=" +
  754. Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
  755. SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
  756. ": Explicit assignment by pragma or attribute of an incompatible "
  757. "symbol to this section?"));
  758. }
  759. return Section;
  760. }
  761. MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
  762. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  763. return selectExplicitSectionGlobal(GO, Kind, TM, getContext(), getMangler(),
  764. NextUniqueID, Used.count(GO),
  765. /* ForceUnique = */false);
  766. }
  767. static MCSectionELF *selectELFSectionForGlobal(
  768. MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
  769. const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
  770. unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
  771. StringRef Group = "";
  772. bool IsComdat = false;
  773. if (const Comdat *C = getELFComdat(GO)) {
  774. Flags |= ELF::SHF_GROUP;
  775. Group = C->getName();
  776. IsComdat = C->getSelectionKind() == Comdat::Any;
  777. }
  778. // Get the section entry size based on the kind.
  779. unsigned EntrySize = getEntrySizeForKind(Kind);
  780. bool UniqueSectionName = false;
  781. unsigned UniqueID = MCContext::GenericSectionID;
  782. if (EmitUniqueSection) {
  783. if (TM.getUniqueSectionNames()) {
  784. UniqueSectionName = true;
  785. } else {
  786. UniqueID = *NextUniqueID;
  787. (*NextUniqueID)++;
  788. }
  789. }
  790. SmallString<128> Name = getELFSectionNameForGlobal(
  791. GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
  792. // Use 0 as the unique ID for execute-only text.
  793. if (Kind.isExecuteOnly())
  794. UniqueID = 0;
  795. return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
  796. EntrySize, Group, IsComdat, UniqueID,
  797. AssociatedSymbol);
  798. }
  799. static MCSection *selectELFSectionForGlobal(
  800. MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
  801. const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
  802. unsigned Flags, unsigned *NextUniqueID) {
  803. const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
  804. if (LinkedToSym) {
  805. EmitUniqueSection = true;
  806. Flags |= ELF::SHF_LINK_ORDER;
  807. }
  808. if (Retain) {
  809. if (TM.getTargetTriple().isOSSolaris()) {
  810. EmitUniqueSection = true;
  811. Flags |= ELF::SHF_SUNW_NODISCARD;
  812. } else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
  813. Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) {
  814. EmitUniqueSection = true;
  815. Flags |= ELF::SHF_GNU_RETAIN;
  816. }
  817. }
  818. MCSectionELF *Section = selectELFSectionForGlobal(
  819. Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
  820. NextUniqueID, LinkedToSym);
  821. assert(Section->getLinkedToSymbol() == LinkedToSym);
  822. return Section;
  823. }
  824. MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
  825. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  826. unsigned Flags = getELFSectionFlags(Kind);
  827. // If we have -ffunction-section or -fdata-section then we should emit the
  828. // global value to a uniqued section specifically for it.
  829. bool EmitUniqueSection = false;
  830. if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
  831. if (Kind.isText())
  832. EmitUniqueSection = TM.getFunctionSections();
  833. else
  834. EmitUniqueSection = TM.getDataSections();
  835. }
  836. EmitUniqueSection |= GO->hasComdat();
  837. return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
  838. Used.count(GO), EmitUniqueSection, Flags,
  839. &NextUniqueID);
  840. }
  841. MCSection *TargetLoweringObjectFileELF::getUniqueSectionForFunction(
  842. const Function &F, const TargetMachine &TM) const {
  843. SectionKind Kind = SectionKind::getText();
  844. unsigned Flags = getELFSectionFlags(Kind);
  845. // If the function's section names is pre-determined via pragma or a
  846. // section attribute, call selectExplicitSectionGlobal.
  847. if (F.hasSection() || F.hasFnAttribute("implicit-section-name"))
  848. return selectExplicitSectionGlobal(
  849. &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
  850. Used.count(&F), /* ForceUnique = */true);
  851. else
  852. return selectELFSectionForGlobal(
  853. getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
  854. /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
  855. }
  856. MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
  857. const Function &F, const TargetMachine &TM) const {
  858. // If the function can be removed, produce a unique section so that
  859. // the table doesn't prevent the removal.
  860. const Comdat *C = F.getComdat();
  861. bool EmitUniqueSection = TM.getFunctionSections() || C;
  862. if (!EmitUniqueSection)
  863. return ReadOnlySection;
  864. return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
  865. getMangler(), TM, EmitUniqueSection,
  866. ELF::SHF_ALLOC, &NextUniqueID,
  867. /* AssociatedSymbol */ nullptr);
  868. }
  869. MCSection *TargetLoweringObjectFileELF::getSectionForLSDA(
  870. const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
  871. // If neither COMDAT nor function sections, use the monolithic LSDA section.
  872. // Re-use this path if LSDASection is null as in the Arm EHABI.
  873. if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
  874. return LSDASection;
  875. const auto *LSDA = cast<MCSectionELF>(LSDASection);
  876. unsigned Flags = LSDA->getFlags();
  877. const MCSymbolELF *LinkedToSym = nullptr;
  878. StringRef Group;
  879. bool IsComdat = false;
  880. if (const Comdat *C = getELFComdat(&F)) {
  881. Flags |= ELF::SHF_GROUP;
  882. Group = C->getName();
  883. IsComdat = C->getSelectionKind() == Comdat::Any;
  884. }
  885. // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
  886. // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
  887. if (TM.getFunctionSections() &&
  888. (getContext().getAsmInfo()->useIntegratedAssembler() &&
  889. getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
  890. Flags |= ELF::SHF_LINK_ORDER;
  891. LinkedToSym = cast<MCSymbolELF>(&FnSym);
  892. }
  893. // Append the function name as the suffix like GCC, assuming
  894. // -funique-section-names applies to .gcc_except_table sections.
  895. return getContext().getELFSection(
  896. (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
  897. : LSDA->getName()),
  898. LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
  899. LinkedToSym);
  900. }
  901. bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
  902. bool UsesLabelDifference, const Function &F) const {
  903. // We can always create relative relocations, so use another section
  904. // that can be marked non-executable.
  905. return false;
  906. }
  907. /// Given a mergeable constant with the specified size and relocation
  908. /// information, return a section that it should be placed in.
  909. MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
  910. const DataLayout &DL, SectionKind Kind, const Constant *C,
  911. Align &Alignment) const {
  912. if (Kind.isMergeableConst4() && MergeableConst4Section)
  913. return MergeableConst4Section;
  914. if (Kind.isMergeableConst8() && MergeableConst8Section)
  915. return MergeableConst8Section;
  916. if (Kind.isMergeableConst16() && MergeableConst16Section)
  917. return MergeableConst16Section;
  918. if (Kind.isMergeableConst32() && MergeableConst32Section)
  919. return MergeableConst32Section;
  920. if (Kind.isReadOnly())
  921. return ReadOnlySection;
  922. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  923. return DataRelROSection;
  924. }
  925. /// Returns a unique section for the given machine basic block.
  926. MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock(
  927. const Function &F, const MachineBasicBlock &MBB,
  928. const TargetMachine &TM) const {
  929. assert(MBB.isBeginSection() && "Basic block does not start a section!");
  930. unsigned UniqueID = MCContext::GenericSectionID;
  931. // For cold sections use the .text.split. prefix along with the parent
  932. // function name. All cold blocks for the same function go to the same
  933. // section. Similarly all exception blocks are grouped by symbol name
  934. // under the .text.eh prefix. For regular sections, we either use a unique
  935. // name, or a unique ID for the section.
  936. SmallString<128> Name;
  937. if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
  938. Name += BBSectionsColdTextPrefix;
  939. Name += MBB.getParent()->getName();
  940. } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
  941. Name += ".text.eh.";
  942. Name += MBB.getParent()->getName();
  943. } else {
  944. Name += MBB.getParent()->getSection()->getName();
  945. if (TM.getUniqueBasicBlockSectionNames()) {
  946. if (!Name.endswith("."))
  947. Name += ".";
  948. Name += MBB.getSymbol()->getName();
  949. } else {
  950. UniqueID = NextUniqueID++;
  951. }
  952. }
  953. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
  954. std::string GroupName;
  955. if (F.hasComdat()) {
  956. Flags |= ELF::SHF_GROUP;
  957. GroupName = F.getComdat()->getName().str();
  958. }
  959. return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
  960. 0 /* Entry Size */, GroupName,
  961. F.hasComdat(), UniqueID, nullptr);
  962. }
  963. static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
  964. bool IsCtor, unsigned Priority,
  965. const MCSymbol *KeySym) {
  966. std::string Name;
  967. unsigned Type;
  968. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
  969. StringRef Comdat = KeySym ? KeySym->getName() : "";
  970. if (KeySym)
  971. Flags |= ELF::SHF_GROUP;
  972. if (UseInitArray) {
  973. if (IsCtor) {
  974. Type = ELF::SHT_INIT_ARRAY;
  975. Name = ".init_array";
  976. } else {
  977. Type = ELF::SHT_FINI_ARRAY;
  978. Name = ".fini_array";
  979. }
  980. if (Priority != 65535) {
  981. Name += '.';
  982. Name += utostr(Priority);
  983. }
  984. } else {
  985. // The default scheme is .ctor / .dtor, so we have to invert the priority
  986. // numbering.
  987. if (IsCtor)
  988. Name = ".ctors";
  989. else
  990. Name = ".dtors";
  991. if (Priority != 65535)
  992. raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
  993. Type = ELF::SHT_PROGBITS;
  994. }
  995. return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
  996. }
  997. MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
  998. unsigned Priority, const MCSymbol *KeySym) const {
  999. return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
  1000. KeySym);
  1001. }
  1002. MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
  1003. unsigned Priority, const MCSymbol *KeySym) const {
  1004. return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
  1005. KeySym);
  1006. }
  1007. const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
  1008. const GlobalValue *LHS, const GlobalValue *RHS,
  1009. const TargetMachine &TM) const {
  1010. // We may only use a PLT-relative relocation to refer to unnamed_addr
  1011. // functions.
  1012. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
  1013. return nullptr;
  1014. // Basic correctness checks.
  1015. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  1016. RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
  1017. RHS->isThreadLocal())
  1018. return nullptr;
  1019. return MCBinaryExpr::createSub(
  1020. MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
  1021. getContext()),
  1022. MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
  1023. }
  1024. const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent(
  1025. const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
  1026. assert(supportDSOLocalEquivalentLowering());
  1027. const auto *GV = Equiv->getGlobalValue();
  1028. // A PLT entry is not needed for dso_local globals.
  1029. if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
  1030. return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
  1031. return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind,
  1032. getContext());
  1033. }
  1034. MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
  1035. // Use ".GCC.command.line" since this feature is to support clang's
  1036. // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
  1037. // same name.
  1038. return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
  1039. ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
  1040. }
  1041. void
  1042. TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
  1043. UseInitArray = UseInitArray_;
  1044. MCContext &Ctx = getContext();
  1045. if (!UseInitArray) {
  1046. StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
  1047. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  1048. StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
  1049. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  1050. return;
  1051. }
  1052. StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
  1053. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  1054. StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
  1055. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  1056. }
  1057. //===----------------------------------------------------------------------===//
  1058. // MachO
  1059. //===----------------------------------------------------------------------===//
  1060. TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() {
  1061. SupportIndirectSymViaGOTPCRel = true;
  1062. }
  1063. void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
  1064. const TargetMachine &TM) {
  1065. TargetLoweringObjectFile::Initialize(Ctx, TM);
  1066. if (TM.getRelocationModel() == Reloc::Static) {
  1067. StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
  1068. SectionKind::getData());
  1069. StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
  1070. SectionKind::getData());
  1071. } else {
  1072. StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
  1073. MachO::S_MOD_INIT_FUNC_POINTERS,
  1074. SectionKind::getData());
  1075. StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
  1076. MachO::S_MOD_TERM_FUNC_POINTERS,
  1077. SectionKind::getData());
  1078. }
  1079. PersonalityEncoding =
  1080. dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  1081. LSDAEncoding = dwarf::DW_EH_PE_pcrel;
  1082. TTypeEncoding =
  1083. dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  1084. }
  1085. MCSection *TargetLoweringObjectFileMachO::getStaticDtorSection(
  1086. unsigned Priority, const MCSymbol *KeySym) const {
  1087. // TODO(yln): Remove -lower-global-dtors-via-cxa-atexit fallback flag
  1088. // (LowerGlobalDtorsViaCxaAtExit) and always issue a fatal error here.
  1089. if (TM->Options.LowerGlobalDtorsViaCxaAtExit)
  1090. report_fatal_error("@llvm.global_dtors should have been lowered already");
  1091. return StaticDtorSection;
  1092. }
  1093. void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
  1094. Module &M) const {
  1095. // Emit the linker options if present.
  1096. if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
  1097. for (const auto *Option : LinkerOptions->operands()) {
  1098. SmallVector<std::string, 4> StrOptions;
  1099. for (const auto &Piece : cast<MDNode>(Option)->operands())
  1100. StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
  1101. Streamer.emitLinkerOptions(StrOptions);
  1102. }
  1103. }
  1104. unsigned VersionVal = 0;
  1105. unsigned ImageInfoFlags = 0;
  1106. StringRef SectionVal;
  1107. GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
  1108. emitCGProfileMetadata(Streamer, M);
  1109. // The section is mandatory. If we don't have it, then we don't have GC info.
  1110. if (SectionVal.empty())
  1111. return;
  1112. StringRef Segment, Section;
  1113. unsigned TAA = 0, StubSize = 0;
  1114. bool TAAParsed;
  1115. if (Error E = MCSectionMachO::ParseSectionSpecifier(
  1116. SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
  1117. // If invalid, report the error with report_fatal_error.
  1118. report_fatal_error("Invalid section specifier '" + Section +
  1119. "': " + toString(std::move(E)) + ".");
  1120. }
  1121. // Get the section.
  1122. MCSectionMachO *S = getContext().getMachOSection(
  1123. Segment, Section, TAA, StubSize, SectionKind::getData());
  1124. Streamer.switchSection(S);
  1125. Streamer.emitLabel(getContext().
  1126. getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
  1127. Streamer.emitInt32(VersionVal);
  1128. Streamer.emitInt32(ImageInfoFlags);
  1129. Streamer.addBlankLine();
  1130. }
  1131. static void checkMachOComdat(const GlobalValue *GV) {
  1132. const Comdat *C = GV->getComdat();
  1133. if (!C)
  1134. return;
  1135. report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
  1136. "' cannot be lowered.");
  1137. }
  1138. MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
  1139. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1140. StringRef SectionName = GO->getSection();
  1141. const Function *F = dyn_cast<Function>(GO);
  1142. if (F && F->hasFnAttribute("implicit-section-name")) {
  1143. SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
  1144. }
  1145. // Parse the section specifier and create it if valid.
  1146. StringRef Segment, Section;
  1147. unsigned TAA = 0, StubSize = 0;
  1148. bool TAAParsed;
  1149. checkMachOComdat(GO);
  1150. if (Error E = MCSectionMachO::ParseSectionSpecifier(
  1151. SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
  1152. // If invalid, report the error with report_fatal_error.
  1153. report_fatal_error("Global variable '" + GO->getName() +
  1154. "' has an invalid section specifier '" +
  1155. GO->getSection() + "': " + toString(std::move(E)) + ".");
  1156. }
  1157. // Get the section.
  1158. MCSectionMachO *S =
  1159. getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
  1160. // If TAA wasn't set by ParseSectionSpecifier() above,
  1161. // use the value returned by getMachOSection() as a default.
  1162. if (!TAAParsed)
  1163. TAA = S->getTypeAndAttributes();
  1164. // Okay, now that we got the section, verify that the TAA & StubSize agree.
  1165. // If the user declared multiple globals with different section flags, we need
  1166. // to reject it here.
  1167. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
  1168. // If invalid, report the error with report_fatal_error.
  1169. report_fatal_error("Global variable '" + GO->getName() +
  1170. "' section type or attributes does not match previous"
  1171. " section specifier");
  1172. }
  1173. return S;
  1174. }
  1175. MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
  1176. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1177. checkMachOComdat(GO);
  1178. // Handle thread local data.
  1179. if (Kind.isThreadBSS()) return TLSBSSSection;
  1180. if (Kind.isThreadData()) return TLSDataSection;
  1181. if (Kind.isText())
  1182. return GO->isWeakForLinker() ? TextCoalSection : TextSection;
  1183. // If this is weak/linkonce, put this in a coalescable section, either in text
  1184. // or data depending on if it is writable.
  1185. if (GO->isWeakForLinker()) {
  1186. if (Kind.isReadOnly())
  1187. return ConstTextCoalSection;
  1188. if (Kind.isReadOnlyWithRel())
  1189. return ConstDataCoalSection;
  1190. return DataCoalSection;
  1191. }
  1192. // FIXME: Alignment check should be handled by section classifier.
  1193. if (Kind.isMergeable1ByteCString() &&
  1194. GO->getParent()->getDataLayout().getPreferredAlign(
  1195. cast<GlobalVariable>(GO)) < Align(32))
  1196. return CStringSection;
  1197. // Do not put 16-bit arrays in the UString section if they have an
  1198. // externally visible label, this runs into issues with certain linker
  1199. // versions.
  1200. if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
  1201. GO->getParent()->getDataLayout().getPreferredAlign(
  1202. cast<GlobalVariable>(GO)) < Align(32))
  1203. return UStringSection;
  1204. // With MachO only variables whose corresponding symbol starts with 'l' or
  1205. // 'L' can be merged, so we only try merging GVs with private linkage.
  1206. if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
  1207. if (Kind.isMergeableConst4())
  1208. return FourByteConstantSection;
  1209. if (Kind.isMergeableConst8())
  1210. return EightByteConstantSection;
  1211. if (Kind.isMergeableConst16())
  1212. return SixteenByteConstantSection;
  1213. }
  1214. // Otherwise, if it is readonly, but not something we can specially optimize,
  1215. // just drop it in .const.
  1216. if (Kind.isReadOnly())
  1217. return ReadOnlySection;
  1218. // If this is marked const, put it into a const section. But if the dynamic
  1219. // linker needs to write to it, put it in the data segment.
  1220. if (Kind.isReadOnlyWithRel())
  1221. return ConstDataSection;
  1222. // Put zero initialized globals with strong external linkage in the
  1223. // DATA, __common section with the .zerofill directive.
  1224. if (Kind.isBSSExtern())
  1225. return DataCommonSection;
  1226. // Put zero initialized globals with local linkage in __DATA,__bss directive
  1227. // with the .zerofill directive (aka .lcomm).
  1228. if (Kind.isBSSLocal())
  1229. return DataBSSSection;
  1230. // Otherwise, just drop the variable in the normal data section.
  1231. return DataSection;
  1232. }
  1233. MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
  1234. const DataLayout &DL, SectionKind Kind, const Constant *C,
  1235. Align &Alignment) const {
  1236. // If this constant requires a relocation, we have to put it in the data
  1237. // segment, not in the text segment.
  1238. if (Kind.isData() || Kind.isReadOnlyWithRel())
  1239. return ConstDataSection;
  1240. if (Kind.isMergeableConst4())
  1241. return FourByteConstantSection;
  1242. if (Kind.isMergeableConst8())
  1243. return EightByteConstantSection;
  1244. if (Kind.isMergeableConst16())
  1245. return SixteenByteConstantSection;
  1246. return ReadOnlySection; // .const
  1247. }
  1248. const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
  1249. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  1250. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  1251. // The mach-o version of this method defaults to returning a stub reference.
  1252. if (Encoding & DW_EH_PE_indirect) {
  1253. MachineModuleInfoMachO &MachOMMI =
  1254. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  1255. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  1256. // Add information about the stub reference to MachOMMI so that the stub
  1257. // gets emitted by the asmprinter.
  1258. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  1259. if (!StubSym.getPointer()) {
  1260. MCSymbol *Sym = TM.getSymbol(GV);
  1261. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  1262. }
  1263. return TargetLoweringObjectFile::
  1264. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  1265. Encoding & ~DW_EH_PE_indirect, Streamer);
  1266. }
  1267. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  1268. MMI, Streamer);
  1269. }
  1270. MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
  1271. const GlobalValue *GV, const TargetMachine &TM,
  1272. MachineModuleInfo *MMI) const {
  1273. // The mach-o version of this method defaults to returning a stub reference.
  1274. MachineModuleInfoMachO &MachOMMI =
  1275. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  1276. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  1277. // Add information about the stub reference to MachOMMI so that the stub
  1278. // gets emitted by the asmprinter.
  1279. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  1280. if (!StubSym.getPointer()) {
  1281. MCSymbol *Sym = TM.getSymbol(GV);
  1282. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  1283. }
  1284. return SSym;
  1285. }
  1286. const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
  1287. const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
  1288. int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  1289. // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
  1290. // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
  1291. // through a non_lazy_ptr stub instead. One advantage is that it allows the
  1292. // computation of deltas to final external symbols. Example:
  1293. //
  1294. // _extgotequiv:
  1295. // .long _extfoo
  1296. //
  1297. // _delta:
  1298. // .long _extgotequiv-_delta
  1299. //
  1300. // is transformed to:
  1301. //
  1302. // _delta:
  1303. // .long L_extfoo$non_lazy_ptr-(_delta+0)
  1304. //
  1305. // .section __IMPORT,__pointers,non_lazy_symbol_pointers
  1306. // L_extfoo$non_lazy_ptr:
  1307. // .indirect_symbol _extfoo
  1308. // .long 0
  1309. //
  1310. // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
  1311. // may point to both local (same translation unit) and global (other
  1312. // translation units) symbols. Example:
  1313. //
  1314. // .section __DATA,__pointers,non_lazy_symbol_pointers
  1315. // L1:
  1316. // .indirect_symbol _myGlobal
  1317. // .long 0
  1318. // L2:
  1319. // .indirect_symbol _myLocal
  1320. // .long _myLocal
  1321. //
  1322. // If the symbol is local, instead of the symbol's index, the assembler
  1323. // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
  1324. // Then the linker will notice the constant in the table and will look at the
  1325. // content of the symbol.
  1326. MachineModuleInfoMachO &MachOMMI =
  1327. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  1328. MCContext &Ctx = getContext();
  1329. // The offset must consider the original displacement from the base symbol
  1330. // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
  1331. Offset = -MV.getConstant();
  1332. const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
  1333. // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
  1334. // non_lazy_ptr stubs.
  1335. SmallString<128> Name;
  1336. StringRef Suffix = "$non_lazy_ptr";
  1337. Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
  1338. Name += Sym->getName();
  1339. Name += Suffix;
  1340. MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
  1341. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
  1342. if (!StubSym.getPointer())
  1343. StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
  1344. !GV->hasLocalLinkage());
  1345. const MCExpr *BSymExpr =
  1346. MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
  1347. const MCExpr *LHS =
  1348. MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
  1349. if (!Offset)
  1350. return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
  1351. const MCExpr *RHS =
  1352. MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
  1353. return MCBinaryExpr::createSub(LHS, RHS, Ctx);
  1354. }
  1355. static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
  1356. const MCSection &Section) {
  1357. if (!AsmInfo.isSectionAtomizableBySymbols(Section))
  1358. return true;
  1359. // FIXME: we should be able to use private labels for sections that can't be
  1360. // dead-stripped (there's no issue with blocking atomization there), but `ld
  1361. // -r` sometimes drops the no_dead_strip attribute from sections so for safety
  1362. // we don't allow it.
  1363. return false;
  1364. }
  1365. void TargetLoweringObjectFileMachO::getNameWithPrefix(
  1366. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  1367. const TargetMachine &TM) const {
  1368. bool CannotUsePrivateLabel = true;
  1369. if (auto *GO = GV->getAliaseeObject()) {
  1370. SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
  1371. const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
  1372. CannotUsePrivateLabel =
  1373. !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
  1374. }
  1375. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  1376. }
  1377. //===----------------------------------------------------------------------===//
  1378. // COFF
  1379. //===----------------------------------------------------------------------===//
  1380. static unsigned
  1381. getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
  1382. unsigned Flags = 0;
  1383. bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
  1384. if (K.isMetadata())
  1385. Flags |=
  1386. COFF::IMAGE_SCN_MEM_DISCARDABLE;
  1387. else if (K.isExclude())
  1388. Flags |=
  1389. COFF::IMAGE_SCN_LNK_REMOVE | COFF::IMAGE_SCN_MEM_DISCARDABLE;
  1390. else if (K.isText())
  1391. Flags |=
  1392. COFF::IMAGE_SCN_MEM_EXECUTE |
  1393. COFF::IMAGE_SCN_MEM_READ |
  1394. COFF::IMAGE_SCN_CNT_CODE |
  1395. (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
  1396. else if (K.isBSS())
  1397. Flags |=
  1398. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  1399. COFF::IMAGE_SCN_MEM_READ |
  1400. COFF::IMAGE_SCN_MEM_WRITE;
  1401. else if (K.isThreadLocal())
  1402. Flags |=
  1403. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1404. COFF::IMAGE_SCN_MEM_READ |
  1405. COFF::IMAGE_SCN_MEM_WRITE;
  1406. else if (K.isReadOnly() || K.isReadOnlyWithRel())
  1407. Flags |=
  1408. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1409. COFF::IMAGE_SCN_MEM_READ;
  1410. else if (K.isWriteable())
  1411. Flags |=
  1412. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1413. COFF::IMAGE_SCN_MEM_READ |
  1414. COFF::IMAGE_SCN_MEM_WRITE;
  1415. return Flags;
  1416. }
  1417. static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
  1418. const Comdat *C = GV->getComdat();
  1419. assert(C && "expected GV to have a Comdat!");
  1420. StringRef ComdatGVName = C->getName();
  1421. const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
  1422. if (!ComdatGV)
  1423. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  1424. "' does not exist.");
  1425. if (ComdatGV->getComdat() != C)
  1426. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  1427. "' is not a key for its COMDAT.");
  1428. return ComdatGV;
  1429. }
  1430. static int getSelectionForCOFF(const GlobalValue *GV) {
  1431. if (const Comdat *C = GV->getComdat()) {
  1432. const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
  1433. if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
  1434. ComdatKey = GA->getAliaseeObject();
  1435. if (ComdatKey == GV) {
  1436. switch (C->getSelectionKind()) {
  1437. case Comdat::Any:
  1438. return COFF::IMAGE_COMDAT_SELECT_ANY;
  1439. case Comdat::ExactMatch:
  1440. return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
  1441. case Comdat::Largest:
  1442. return COFF::IMAGE_COMDAT_SELECT_LARGEST;
  1443. case Comdat::NoDeduplicate:
  1444. return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  1445. case Comdat::SameSize:
  1446. return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
  1447. }
  1448. } else {
  1449. return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
  1450. }
  1451. }
  1452. return 0;
  1453. }
  1454. MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
  1455. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1456. int Selection = 0;
  1457. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  1458. StringRef Name = GO->getSection();
  1459. StringRef COMDATSymName = "";
  1460. if (GO->hasComdat()) {
  1461. Selection = getSelectionForCOFF(GO);
  1462. const GlobalValue *ComdatGV;
  1463. if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
  1464. ComdatGV = getComdatGVForCOFF(GO);
  1465. else
  1466. ComdatGV = GO;
  1467. if (!ComdatGV->hasPrivateLinkage()) {
  1468. MCSymbol *Sym = TM.getSymbol(ComdatGV);
  1469. COMDATSymName = Sym->getName();
  1470. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  1471. } else {
  1472. Selection = 0;
  1473. }
  1474. }
  1475. return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
  1476. Selection);
  1477. }
  1478. static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
  1479. if (Kind.isText())
  1480. return ".text";
  1481. if (Kind.isBSS())
  1482. return ".bss";
  1483. if (Kind.isThreadLocal())
  1484. return ".tls$";
  1485. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  1486. return ".rdata";
  1487. return ".data";
  1488. }
  1489. MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
  1490. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1491. // If we have -ffunction-sections then we should emit the global value to a
  1492. // uniqued section specifically for it.
  1493. bool EmitUniquedSection;
  1494. if (Kind.isText())
  1495. EmitUniquedSection = TM.getFunctionSections();
  1496. else
  1497. EmitUniquedSection = TM.getDataSections();
  1498. if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
  1499. SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
  1500. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  1501. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  1502. int Selection = getSelectionForCOFF(GO);
  1503. if (!Selection)
  1504. Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  1505. const GlobalValue *ComdatGV;
  1506. if (GO->hasComdat())
  1507. ComdatGV = getComdatGVForCOFF(GO);
  1508. else
  1509. ComdatGV = GO;
  1510. unsigned UniqueID = MCContext::GenericSectionID;
  1511. if (EmitUniquedSection)
  1512. UniqueID = NextUniqueID++;
  1513. if (!ComdatGV->hasPrivateLinkage()) {
  1514. MCSymbol *Sym = TM.getSymbol(ComdatGV);
  1515. StringRef COMDATSymName = Sym->getName();
  1516. if (const auto *F = dyn_cast<Function>(GO))
  1517. if (std::optional<StringRef> Prefix = F->getSectionPrefix())
  1518. raw_svector_ostream(Name) << '$' << *Prefix;
  1519. // Append "$symbol" to the section name *before* IR-level mangling is
  1520. // applied when targetting mingw. This is what GCC does, and the ld.bfd
  1521. // COFF linker will not properly handle comdats otherwise.
  1522. if (getContext().getTargetTriple().isWindowsGNUEnvironment())
  1523. raw_svector_ostream(Name) << '$' << ComdatGV->getName();
  1524. return getContext().getCOFFSection(Name, Characteristics, Kind,
  1525. COMDATSymName, Selection, UniqueID);
  1526. } else {
  1527. SmallString<256> TmpData;
  1528. getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
  1529. return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
  1530. Selection, UniqueID);
  1531. }
  1532. }
  1533. if (Kind.isText())
  1534. return TextSection;
  1535. if (Kind.isThreadLocal())
  1536. return TLSDataSection;
  1537. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  1538. return ReadOnlySection;
  1539. // Note: we claim that common symbols are put in BSSSection, but they are
  1540. // really emitted with the magic .comm directive, which creates a symbol table
  1541. // entry but not a section.
  1542. if (Kind.isBSS() || Kind.isCommon())
  1543. return BSSSection;
  1544. return DataSection;
  1545. }
  1546. void TargetLoweringObjectFileCOFF::getNameWithPrefix(
  1547. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  1548. const TargetMachine &TM) const {
  1549. bool CannotUsePrivateLabel = false;
  1550. if (GV->hasPrivateLinkage() &&
  1551. ((isa<Function>(GV) && TM.getFunctionSections()) ||
  1552. (isa<GlobalVariable>(GV) && TM.getDataSections())))
  1553. CannotUsePrivateLabel = true;
  1554. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  1555. }
  1556. MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
  1557. const Function &F, const TargetMachine &TM) const {
  1558. // If the function can be removed, produce a unique section so that
  1559. // the table doesn't prevent the removal.
  1560. const Comdat *C = F.getComdat();
  1561. bool EmitUniqueSection = TM.getFunctionSections() || C;
  1562. if (!EmitUniqueSection)
  1563. return ReadOnlySection;
  1564. // FIXME: we should produce a symbol for F instead.
  1565. if (F.hasPrivateLinkage())
  1566. return ReadOnlySection;
  1567. MCSymbol *Sym = TM.getSymbol(&F);
  1568. StringRef COMDATSymName = Sym->getName();
  1569. SectionKind Kind = SectionKind::getReadOnly();
  1570. StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
  1571. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  1572. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  1573. unsigned UniqueID = NextUniqueID++;
  1574. return getContext().getCOFFSection(
  1575. SecName, Characteristics, Kind, COMDATSymName,
  1576. COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
  1577. }
  1578. void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
  1579. Module &M) const {
  1580. emitLinkerDirectives(Streamer, M);
  1581. unsigned Version = 0;
  1582. unsigned Flags = 0;
  1583. StringRef Section;
  1584. GetObjCImageInfo(M, Version, Flags, Section);
  1585. if (!Section.empty()) {
  1586. auto &C = getContext();
  1587. auto *S = C.getCOFFSection(Section,
  1588. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1589. COFF::IMAGE_SCN_MEM_READ,
  1590. SectionKind::getReadOnly());
  1591. Streamer.switchSection(S);
  1592. Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
  1593. Streamer.emitInt32(Version);
  1594. Streamer.emitInt32(Flags);
  1595. Streamer.addBlankLine();
  1596. }
  1597. emitCGProfileMetadata(Streamer, M);
  1598. }
  1599. void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
  1600. MCStreamer &Streamer, Module &M) const {
  1601. if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
  1602. // Emit the linker options to the linker .drectve section. According to the
  1603. // spec, this section is a space-separated string containing flags for
  1604. // linker.
  1605. MCSection *Sec = getDrectveSection();
  1606. Streamer.switchSection(Sec);
  1607. for (const auto *Option : LinkerOptions->operands()) {
  1608. for (const auto &Piece : cast<MDNode>(Option)->operands()) {
  1609. // Lead with a space for consistency with our dllexport implementation.
  1610. std::string Directive(" ");
  1611. Directive.append(std::string(cast<MDString>(Piece)->getString()));
  1612. Streamer.emitBytes(Directive);
  1613. }
  1614. }
  1615. }
  1616. // Emit /EXPORT: flags for each exported global as necessary.
  1617. std::string Flags;
  1618. for (const GlobalValue &GV : M.global_values()) {
  1619. raw_string_ostream OS(Flags);
  1620. emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
  1621. getMangler());
  1622. OS.flush();
  1623. if (!Flags.empty()) {
  1624. Streamer.switchSection(getDrectveSection());
  1625. Streamer.emitBytes(Flags);
  1626. }
  1627. Flags.clear();
  1628. }
  1629. // Emit /INCLUDE: flags for each used global as necessary.
  1630. if (const auto *LU = M.getNamedGlobal("llvm.used")) {
  1631. assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
  1632. assert(isa<ArrayType>(LU->getValueType()) &&
  1633. "expected llvm.used to be an array type");
  1634. if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
  1635. for (const Value *Op : A->operands()) {
  1636. const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
  1637. // Global symbols with internal or private linkage are not visible to
  1638. // the linker, and thus would cause an error when the linker tried to
  1639. // preserve the symbol due to the `/include:` directive.
  1640. if (GV->hasLocalLinkage())
  1641. continue;
  1642. raw_string_ostream OS(Flags);
  1643. emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
  1644. getMangler());
  1645. OS.flush();
  1646. if (!Flags.empty()) {
  1647. Streamer.switchSection(getDrectveSection());
  1648. Streamer.emitBytes(Flags);
  1649. }
  1650. Flags.clear();
  1651. }
  1652. }
  1653. }
  1654. }
  1655. void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
  1656. const TargetMachine &TM) {
  1657. TargetLoweringObjectFile::Initialize(Ctx, TM);
  1658. this->TM = &TM;
  1659. const Triple &T = TM.getTargetTriple();
  1660. if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
  1661. StaticCtorSection =
  1662. Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1663. COFF::IMAGE_SCN_MEM_READ,
  1664. SectionKind::getReadOnly());
  1665. StaticDtorSection =
  1666. Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1667. COFF::IMAGE_SCN_MEM_READ,
  1668. SectionKind::getReadOnly());
  1669. } else {
  1670. StaticCtorSection = Ctx.getCOFFSection(
  1671. ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1672. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  1673. SectionKind::getData());
  1674. StaticDtorSection = Ctx.getCOFFSection(
  1675. ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1676. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  1677. SectionKind::getData());
  1678. }
  1679. }
  1680. static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
  1681. const Triple &T, bool IsCtor,
  1682. unsigned Priority,
  1683. const MCSymbol *KeySym,
  1684. MCSectionCOFF *Default) {
  1685. if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
  1686. // If the priority is the default, use .CRT$XCU, possibly associative.
  1687. if (Priority == 65535)
  1688. return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
  1689. // Otherwise, we need to compute a new section name. Low priorities should
  1690. // run earlier. The linker will sort sections ASCII-betically, and we need a
  1691. // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
  1692. // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
  1693. // low priorities need to sort before 'L', since the CRT uses that
  1694. // internally, so we use ".CRT$XCA00001" for them. We have a contract with
  1695. // the frontend that "init_seg(compiler)" corresponds to priority 200 and
  1696. // "init_seg(lib)" corresponds to priority 400, and those respectively use
  1697. // 'C' and 'L' without the priority suffix. Priorities between 200 and 400
  1698. // use 'C' with the priority as a suffix.
  1699. SmallString<24> Name;
  1700. char LastLetter = 'T';
  1701. bool AddPrioritySuffix = Priority != 200 && Priority != 400;
  1702. if (Priority < 200)
  1703. LastLetter = 'A';
  1704. else if (Priority < 400)
  1705. LastLetter = 'C';
  1706. else if (Priority == 400)
  1707. LastLetter = 'L';
  1708. raw_svector_ostream OS(Name);
  1709. OS << ".CRT$X" << (IsCtor ? "C" : "T") << LastLetter;
  1710. if (AddPrioritySuffix)
  1711. OS << format("%05u", Priority);
  1712. MCSectionCOFF *Sec = Ctx.getCOFFSection(
  1713. Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
  1714. SectionKind::getReadOnly());
  1715. return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
  1716. }
  1717. std::string Name = IsCtor ? ".ctors" : ".dtors";
  1718. if (Priority != 65535)
  1719. raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
  1720. return Ctx.getAssociativeCOFFSection(
  1721. Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1722. COFF::IMAGE_SCN_MEM_READ |
  1723. COFF::IMAGE_SCN_MEM_WRITE,
  1724. SectionKind::getData()),
  1725. KeySym, 0);
  1726. }
  1727. MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
  1728. unsigned Priority, const MCSymbol *KeySym) const {
  1729. return getCOFFStaticStructorSection(
  1730. getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
  1731. cast<MCSectionCOFF>(StaticCtorSection));
  1732. }
  1733. MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
  1734. unsigned Priority, const MCSymbol *KeySym) const {
  1735. return getCOFFStaticStructorSection(
  1736. getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
  1737. cast<MCSectionCOFF>(StaticDtorSection));
  1738. }
  1739. const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
  1740. const GlobalValue *LHS, const GlobalValue *RHS,
  1741. const TargetMachine &TM) const {
  1742. const Triple &T = TM.getTargetTriple();
  1743. if (T.isOSCygMing())
  1744. return nullptr;
  1745. // Our symbols should exist in address space zero, cowardly no-op if
  1746. // otherwise.
  1747. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  1748. RHS->getType()->getPointerAddressSpace() != 0)
  1749. return nullptr;
  1750. // Both ptrtoint instructions must wrap global objects:
  1751. // - Only global variables are eligible for image relative relocations.
  1752. // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
  1753. // We expect __ImageBase to be a global variable without a section, externally
  1754. // defined.
  1755. //
  1756. // It should look something like this: @__ImageBase = external constant i8
  1757. if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
  1758. LHS->isThreadLocal() || RHS->isThreadLocal() ||
  1759. RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
  1760. cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
  1761. return nullptr;
  1762. return MCSymbolRefExpr::create(TM.getSymbol(LHS),
  1763. MCSymbolRefExpr::VK_COFF_IMGREL32,
  1764. getContext());
  1765. }
  1766. static std::string APIntToHexString(const APInt &AI) {
  1767. unsigned Width = (AI.getBitWidth() / 8) * 2;
  1768. std::string HexString = toString(AI, 16, /*Signed=*/false);
  1769. llvm::transform(HexString, HexString.begin(), tolower);
  1770. unsigned Size = HexString.size();
  1771. assert(Width >= Size && "hex string is too large!");
  1772. HexString.insert(HexString.begin(), Width - Size, '0');
  1773. return HexString;
  1774. }
  1775. static std::string scalarConstantToHexString(const Constant *C) {
  1776. Type *Ty = C->getType();
  1777. if (isa<UndefValue>(C)) {
  1778. return APIntToHexString(APInt::getZero(Ty->getPrimitiveSizeInBits()));
  1779. } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
  1780. return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
  1781. } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
  1782. return APIntToHexString(CI->getValue());
  1783. } else {
  1784. unsigned NumElements;
  1785. if (auto *VTy = dyn_cast<VectorType>(Ty))
  1786. NumElements = cast<FixedVectorType>(VTy)->getNumElements();
  1787. else
  1788. NumElements = Ty->getArrayNumElements();
  1789. std::string HexString;
  1790. for (int I = NumElements - 1, E = -1; I != E; --I)
  1791. HexString += scalarConstantToHexString(C->getAggregateElement(I));
  1792. return HexString;
  1793. }
  1794. }
  1795. MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
  1796. const DataLayout &DL, SectionKind Kind, const Constant *C,
  1797. Align &Alignment) const {
  1798. if (Kind.isMergeableConst() && C &&
  1799. getContext().getAsmInfo()->hasCOFFComdatConstants()) {
  1800. // This creates comdat sections with the given symbol name, but unless
  1801. // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
  1802. // will be created with a null storage class, which makes GNU binutils
  1803. // error out.
  1804. const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1805. COFF::IMAGE_SCN_MEM_READ |
  1806. COFF::IMAGE_SCN_LNK_COMDAT;
  1807. std::string COMDATSymName;
  1808. if (Kind.isMergeableConst4()) {
  1809. if (Alignment <= 4) {
  1810. COMDATSymName = "__real@" + scalarConstantToHexString(C);
  1811. Alignment = Align(4);
  1812. }
  1813. } else if (Kind.isMergeableConst8()) {
  1814. if (Alignment <= 8) {
  1815. COMDATSymName = "__real@" + scalarConstantToHexString(C);
  1816. Alignment = Align(8);
  1817. }
  1818. } else if (Kind.isMergeableConst16()) {
  1819. // FIXME: These may not be appropriate for non-x86 architectures.
  1820. if (Alignment <= 16) {
  1821. COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
  1822. Alignment = Align(16);
  1823. }
  1824. } else if (Kind.isMergeableConst32()) {
  1825. if (Alignment <= 32) {
  1826. COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
  1827. Alignment = Align(32);
  1828. }
  1829. }
  1830. if (!COMDATSymName.empty())
  1831. return getContext().getCOFFSection(".rdata", Characteristics, Kind,
  1832. COMDATSymName,
  1833. COFF::IMAGE_COMDAT_SELECT_ANY);
  1834. }
  1835. return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
  1836. Alignment);
  1837. }
  1838. //===----------------------------------------------------------------------===//
  1839. // Wasm
  1840. //===----------------------------------------------------------------------===//
  1841. static const Comdat *getWasmComdat(const GlobalValue *GV) {
  1842. const Comdat *C = GV->getComdat();
  1843. if (!C)
  1844. return nullptr;
  1845. if (C->getSelectionKind() != Comdat::Any)
  1846. report_fatal_error("WebAssembly COMDATs only support "
  1847. "SelectionKind::Any, '" + C->getName() + "' cannot be "
  1848. "lowered.");
  1849. return C;
  1850. }
  1851. static unsigned getWasmSectionFlags(SectionKind K) {
  1852. unsigned Flags = 0;
  1853. if (K.isThreadLocal())
  1854. Flags |= wasm::WASM_SEG_FLAG_TLS;
  1855. if (K.isMergeableCString())
  1856. Flags |= wasm::WASM_SEG_FLAG_STRINGS;
  1857. // TODO(sbc): Add suport for K.isMergeableConst()
  1858. return Flags;
  1859. }
  1860. MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
  1861. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1862. // We don't support explict section names for functions in the wasm object
  1863. // format. Each function has to be in its own unique section.
  1864. if (isa<Function>(GO)) {
  1865. return SelectSectionForGlobal(GO, Kind, TM);
  1866. }
  1867. StringRef Name = GO->getSection();
  1868. // Certain data sections we treat as named custom sections rather than
  1869. // segments within the data section.
  1870. // This could be avoided if all data segements (the wasm sense) were
  1871. // represented as their own sections (in the llvm sense).
  1872. // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
  1873. if (Name == ".llvmcmd" || Name == ".llvmbc")
  1874. Kind = SectionKind::getMetadata();
  1875. StringRef Group = "";
  1876. if (const Comdat *C = getWasmComdat(GO)) {
  1877. Group = C->getName();
  1878. }
  1879. unsigned Flags = getWasmSectionFlags(Kind);
  1880. MCSectionWasm *Section = getContext().getWasmSection(
  1881. Name, Kind, Flags, Group, MCContext::GenericSectionID);
  1882. return Section;
  1883. }
  1884. static MCSectionWasm *selectWasmSectionForGlobal(
  1885. MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
  1886. const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
  1887. StringRef Group = "";
  1888. if (const Comdat *C = getWasmComdat(GO)) {
  1889. Group = C->getName();
  1890. }
  1891. bool UniqueSectionNames = TM.getUniqueSectionNames();
  1892. SmallString<128> Name = getSectionPrefixForGlobal(Kind);
  1893. if (const auto *F = dyn_cast<Function>(GO)) {
  1894. const auto &OptionalPrefix = F->getSectionPrefix();
  1895. if (OptionalPrefix)
  1896. raw_svector_ostream(Name) << '.' << *OptionalPrefix;
  1897. }
  1898. if (EmitUniqueSection && UniqueSectionNames) {
  1899. Name.push_back('.');
  1900. TM.getNameWithPrefix(Name, GO, Mang, true);
  1901. }
  1902. unsigned UniqueID = MCContext::GenericSectionID;
  1903. if (EmitUniqueSection && !UniqueSectionNames) {
  1904. UniqueID = *NextUniqueID;
  1905. (*NextUniqueID)++;
  1906. }
  1907. unsigned Flags = getWasmSectionFlags(Kind);
  1908. return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
  1909. }
  1910. MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
  1911. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1912. if (Kind.isCommon())
  1913. report_fatal_error("mergable sections not supported yet on wasm");
  1914. // If we have -ffunction-section or -fdata-section then we should emit the
  1915. // global value to a uniqued section specifically for it.
  1916. bool EmitUniqueSection = false;
  1917. if (Kind.isText())
  1918. EmitUniqueSection = TM.getFunctionSections();
  1919. else
  1920. EmitUniqueSection = TM.getDataSections();
  1921. EmitUniqueSection |= GO->hasComdat();
  1922. return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
  1923. EmitUniqueSection, &NextUniqueID);
  1924. }
  1925. bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
  1926. bool UsesLabelDifference, const Function &F) const {
  1927. // We can always create relative relocations, so use another section
  1928. // that can be marked non-executable.
  1929. return false;
  1930. }
  1931. const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
  1932. const GlobalValue *LHS, const GlobalValue *RHS,
  1933. const TargetMachine &TM) const {
  1934. // We may only use a PLT-relative relocation to refer to unnamed_addr
  1935. // functions.
  1936. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
  1937. return nullptr;
  1938. // Basic correctness checks.
  1939. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  1940. RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
  1941. RHS->isThreadLocal())
  1942. return nullptr;
  1943. return MCBinaryExpr::createSub(
  1944. MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
  1945. getContext()),
  1946. MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
  1947. }
  1948. void TargetLoweringObjectFileWasm::InitializeWasm() {
  1949. StaticCtorSection =
  1950. getContext().getWasmSection(".init_array", SectionKind::getData());
  1951. // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
  1952. // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
  1953. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  1954. }
  1955. MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
  1956. unsigned Priority, const MCSymbol *KeySym) const {
  1957. return Priority == UINT16_MAX ?
  1958. StaticCtorSection :
  1959. getContext().getWasmSection(".init_array." + utostr(Priority),
  1960. SectionKind::getData());
  1961. }
  1962. MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
  1963. unsigned Priority, const MCSymbol *KeySym) const {
  1964. report_fatal_error("@llvm.global_dtors should have been lowered already");
  1965. }
  1966. //===----------------------------------------------------------------------===//
  1967. // XCOFF
  1968. //===----------------------------------------------------------------------===//
  1969. bool TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(
  1970. const MachineFunction *MF) {
  1971. if (!MF->getLandingPads().empty())
  1972. return true;
  1973. const Function &F = MF->getFunction();
  1974. if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
  1975. return false;
  1976. const GlobalValue *Per =
  1977. dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
  1978. assert(Per && "Personality routine is not a GlobalValue type.");
  1979. if (isNoOpWithoutInvoke(classifyEHPersonality(Per)))
  1980. return false;
  1981. return true;
  1982. }
  1983. bool TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(
  1984. const MachineFunction *MF) {
  1985. const Function &F = MF->getFunction();
  1986. if (!F.hasStackProtectorFnAttr())
  1987. return false;
  1988. // FIXME: check presence of canary word
  1989. // There are cases that the stack protectors are not really inserted even if
  1990. // the attributes are on.
  1991. return true;
  1992. }
  1993. MCSymbol *
  1994. TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(const MachineFunction *MF) {
  1995. return MF->getMMI().getContext().getOrCreateSymbol(
  1996. "__ehinfo." + Twine(MF->getFunctionNumber()));
  1997. }
  1998. MCSymbol *
  1999. TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV,
  2000. const TargetMachine &TM) const {
  2001. // We always use a qualname symbol for a GV that represents
  2002. // a declaration, a function descriptor, or a common symbol.
  2003. // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
  2004. // also return a qualname so that a label symbol could be avoided.
  2005. // It is inherently ambiguous when the GO represents the address of a
  2006. // function, as the GO could either represent a function descriptor or a
  2007. // function entry point. We choose to always return a function descriptor
  2008. // here.
  2009. if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
  2010. if (GO->isDeclarationForLinker())
  2011. return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
  2012. ->getQualNameSymbol();
  2013. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
  2014. if (GVar->hasAttribute("toc-data"))
  2015. return cast<MCSectionXCOFF>(
  2016. SectionForGlobal(GVar, SectionKind::getData(), TM))
  2017. ->getQualNameSymbol();
  2018. SectionKind GOKind = getKindForGlobal(GO, TM);
  2019. if (GOKind.isText())
  2020. return cast<MCSectionXCOFF>(
  2021. getSectionForFunctionDescriptor(cast<Function>(GO), TM))
  2022. ->getQualNameSymbol();
  2023. if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
  2024. GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
  2025. return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
  2026. ->getQualNameSymbol();
  2027. }
  2028. // For all other cases, fall back to getSymbol to return the unqualified name.
  2029. return nullptr;
  2030. }
  2031. MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
  2032. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  2033. if (!GO->hasSection())
  2034. report_fatal_error("#pragma clang section is not yet supported");
  2035. StringRef SectionName = GO->getSection();
  2036. // Handle the XCOFF::TD case first, then deal with the rest.
  2037. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
  2038. if (GVar->hasAttribute("toc-data"))
  2039. return getContext().getXCOFFSection(
  2040. SectionName, Kind,
  2041. XCOFF::CsectProperties(/*MappingClass*/ XCOFF::XMC_TD, XCOFF::XTY_SD),
  2042. /* MultiSymbolsAllowed*/ true);
  2043. XCOFF::StorageMappingClass MappingClass;
  2044. if (Kind.isText())
  2045. MappingClass = XCOFF::XMC_PR;
  2046. else if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS())
  2047. MappingClass = XCOFF::XMC_RW;
  2048. else if (Kind.isReadOnly())
  2049. MappingClass = XCOFF::XMC_RO;
  2050. else
  2051. report_fatal_error("XCOFF other section types not yet implemented.");
  2052. return getContext().getXCOFFSection(
  2053. SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
  2054. /* MultiSymbolsAllowed*/ true);
  2055. }
  2056. MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
  2057. const GlobalObject *GO, const TargetMachine &TM) const {
  2058. assert(GO->isDeclarationForLinker() &&
  2059. "Tried to get ER section for a defined global.");
  2060. SmallString<128> Name;
  2061. getNameWithPrefix(Name, GO, TM);
  2062. XCOFF::StorageMappingClass SMC =
  2063. isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
  2064. if (GO->isThreadLocal())
  2065. SMC = XCOFF::XMC_UL;
  2066. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
  2067. if (GVar->hasAttribute("toc-data"))
  2068. SMC = XCOFF::XMC_TD;
  2069. // Externals go into a csect of type ER.
  2070. return getContext().getXCOFFSection(
  2071. Name, SectionKind::getMetadata(),
  2072. XCOFF::CsectProperties(SMC, XCOFF::XTY_ER));
  2073. }
  2074. MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
  2075. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  2076. // Handle the XCOFF::TD case first, then deal with the rest.
  2077. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
  2078. if (GVar->hasAttribute("toc-data")) {
  2079. SmallString<128> Name;
  2080. getNameWithPrefix(Name, GO, TM);
  2081. return getContext().getXCOFFSection(
  2082. Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, XCOFF::XTY_SD),
  2083. /* MultiSymbolsAllowed*/ true);
  2084. }
  2085. // Common symbols go into a csect with matching name which will get mapped
  2086. // into the .bss section.
  2087. // Zero-initialized local TLS symbols go into a csect with matching name which
  2088. // will get mapped into the .tbss section.
  2089. if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
  2090. SmallString<128> Name;
  2091. getNameWithPrefix(Name, GO, TM);
  2092. XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
  2093. : Kind.isCommon() ? XCOFF::XMC_RW
  2094. : XCOFF::XMC_UL;
  2095. return getContext().getXCOFFSection(
  2096. Name, Kind, XCOFF::CsectProperties(SMC, XCOFF::XTY_CM));
  2097. }
  2098. if (Kind.isMergeableCString()) {
  2099. Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
  2100. cast<GlobalVariable>(GO));
  2101. unsigned EntrySize = getEntrySizeForKind(Kind);
  2102. std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
  2103. SmallString<128> Name;
  2104. Name = SizeSpec + utostr(Alignment.value());
  2105. if (TM.getDataSections())
  2106. getNameWithPrefix(Name, GO, TM);
  2107. return getContext().getXCOFFSection(
  2108. Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD),
  2109. /* MultiSymbolsAllowed*/ !TM.getDataSections());
  2110. }
  2111. if (Kind.isText()) {
  2112. if (TM.getFunctionSections()) {
  2113. return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
  2114. ->getRepresentedCsect();
  2115. }
  2116. return TextSection;
  2117. }
  2118. // TODO: We may put Kind.isReadOnlyWithRel() under option control, because
  2119. // user may want to have read-only data with relocations placed into a
  2120. // read-only section by the compiler.
  2121. // For BSS kind, zero initialized data must be emitted to the .data section
  2122. // because external linkage control sections that get mapped to the .bss
  2123. // section will be linked as tentative defintions, which is only appropriate
  2124. // for SectionKind::Common.
  2125. if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
  2126. if (TM.getDataSections()) {
  2127. SmallString<128> Name;
  2128. getNameWithPrefix(Name, GO, TM);
  2129. return getContext().getXCOFFSection(
  2130. Name, SectionKind::getData(),
  2131. XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD));
  2132. }
  2133. return DataSection;
  2134. }
  2135. if (Kind.isReadOnly()) {
  2136. if (TM.getDataSections()) {
  2137. SmallString<128> Name;
  2138. getNameWithPrefix(Name, GO, TM);
  2139. return getContext().getXCOFFSection(
  2140. Name, SectionKind::getReadOnly(),
  2141. XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
  2142. }
  2143. return ReadOnlySection;
  2144. }
  2145. // External/weak TLS data and initialized local TLS data are not eligible
  2146. // to be put into common csect. If data sections are enabled, thread
  2147. // data are emitted into separate sections. Otherwise, thread data
  2148. // are emitted into the .tdata section.
  2149. if (Kind.isThreadLocal()) {
  2150. if (TM.getDataSections()) {
  2151. SmallString<128> Name;
  2152. getNameWithPrefix(Name, GO, TM);
  2153. return getContext().getXCOFFSection(
  2154. Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TL, XCOFF::XTY_SD));
  2155. }
  2156. return TLSDataSection;
  2157. }
  2158. report_fatal_error("XCOFF other section types not yet implemented.");
  2159. }
  2160. MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
  2161. const Function &F, const TargetMachine &TM) const {
  2162. assert (!F.getComdat() && "Comdat not supported on XCOFF.");
  2163. if (!TM.getFunctionSections())
  2164. return ReadOnlySection;
  2165. // If the function can be removed, produce a unique section so that
  2166. // the table doesn't prevent the removal.
  2167. SmallString<128> NameStr(".rodata.jmp..");
  2168. getNameWithPrefix(NameStr, &F, TM);
  2169. return getContext().getXCOFFSection(
  2170. NameStr, SectionKind::getReadOnly(),
  2171. XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
  2172. }
  2173. bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
  2174. bool UsesLabelDifference, const Function &F) const {
  2175. return false;
  2176. }
  2177. /// Given a mergeable constant with the specified size and relocation
  2178. /// information, return a section that it should be placed in.
  2179. MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
  2180. const DataLayout &DL, SectionKind Kind, const Constant *C,
  2181. Align &Alignment) const {
  2182. // TODO: Enable emiting constant pool to unique sections when we support it.
  2183. if (Alignment > Align(16))
  2184. report_fatal_error("Alignments greater than 16 not yet supported.");
  2185. if (Alignment == Align(8)) {
  2186. assert(ReadOnly8Section && "Section should always be initialized.");
  2187. return ReadOnly8Section;
  2188. }
  2189. if (Alignment == Align(16)) {
  2190. assert(ReadOnly16Section && "Section should always be initialized.");
  2191. return ReadOnly16Section;
  2192. }
  2193. return ReadOnlySection;
  2194. }
  2195. void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
  2196. const TargetMachine &TgtM) {
  2197. TargetLoweringObjectFile::Initialize(Ctx, TgtM);
  2198. TTypeEncoding =
  2199. dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel |
  2200. (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
  2201. : dwarf::DW_EH_PE_sdata8);
  2202. PersonalityEncoding = 0;
  2203. LSDAEncoding = 0;
  2204. CallSiteEncoding = dwarf::DW_EH_PE_udata4;
  2205. // AIX debug for thread local location is not ready. And for integrated as
  2206. // mode, the relocatable address for the thread local variable will cause
  2207. // linker error. So disable the location attribute generation for thread local
  2208. // variables for now.
  2209. // FIXME: when TLS debug on AIX is ready, remove this setting.
  2210. SupportDebugThreadLocalLocation = false;
  2211. }
  2212. MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
  2213. unsigned Priority, const MCSymbol *KeySym) const {
  2214. report_fatal_error("no static constructor section on AIX");
  2215. }
  2216. MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
  2217. unsigned Priority, const MCSymbol *KeySym) const {
  2218. report_fatal_error("no static destructor section on AIX");
  2219. }
  2220. const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
  2221. const GlobalValue *LHS, const GlobalValue *RHS,
  2222. const TargetMachine &TM) const {
  2223. /* Not implemented yet, but don't crash, return nullptr. */
  2224. return nullptr;
  2225. }
  2226. XCOFF::StorageClass
  2227. TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) {
  2228. assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
  2229. switch (GV->getLinkage()) {
  2230. case GlobalValue::InternalLinkage:
  2231. case GlobalValue::PrivateLinkage:
  2232. return XCOFF::C_HIDEXT;
  2233. case GlobalValue::ExternalLinkage:
  2234. case GlobalValue::CommonLinkage:
  2235. case GlobalValue::AvailableExternallyLinkage:
  2236. return XCOFF::C_EXT;
  2237. case GlobalValue::ExternalWeakLinkage:
  2238. case GlobalValue::LinkOnceAnyLinkage:
  2239. case GlobalValue::LinkOnceODRLinkage:
  2240. case GlobalValue::WeakAnyLinkage:
  2241. case GlobalValue::WeakODRLinkage:
  2242. return XCOFF::C_WEAKEXT;
  2243. case GlobalValue::AppendingLinkage:
  2244. report_fatal_error(
  2245. "There is no mapping that implements AppendingLinkage for XCOFF.");
  2246. }
  2247. llvm_unreachable("Unknown linkage type!");
  2248. }
  2249. MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
  2250. const GlobalValue *Func, const TargetMachine &TM) const {
  2251. assert((isa<Function>(Func) ||
  2252. (isa<GlobalAlias>(Func) &&
  2253. isa_and_nonnull<Function>(
  2254. cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
  2255. "Func must be a function or an alias which has a function as base "
  2256. "object.");
  2257. SmallString<128> NameStr;
  2258. NameStr.push_back('.');
  2259. getNameWithPrefix(NameStr, Func, TM);
  2260. // When -function-sections is enabled and explicit section is not specified,
  2261. // it's not necessary to emit function entry point label any more. We will use
  2262. // function entry point csect instead. And for function delcarations, the
  2263. // undefined symbols gets treated as csect with XTY_ER property.
  2264. if (((TM.getFunctionSections() && !Func->hasSection()) ||
  2265. Func->isDeclaration()) &&
  2266. isa<Function>(Func)) {
  2267. return getContext()
  2268. .getXCOFFSection(
  2269. NameStr, SectionKind::getText(),
  2270. XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclaration()
  2271. ? XCOFF::XTY_ER
  2272. : XCOFF::XTY_SD))
  2273. ->getQualNameSymbol();
  2274. }
  2275. return getContext().getOrCreateSymbol(NameStr);
  2276. }
  2277. MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
  2278. const Function *F, const TargetMachine &TM) const {
  2279. SmallString<128> NameStr;
  2280. getNameWithPrefix(NameStr, F, TM);
  2281. return getContext().getXCOFFSection(
  2282. NameStr, SectionKind::getData(),
  2283. XCOFF::CsectProperties(XCOFF::XMC_DS, XCOFF::XTY_SD));
  2284. }
  2285. MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
  2286. const MCSymbol *Sym, const TargetMachine &TM) const {
  2287. // Use TE storage-mapping class when large code model is enabled so that
  2288. // the chance of needing -bbigtoc is decreased.
  2289. return getContext().getXCOFFSection(
  2290. cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
  2291. XCOFF::CsectProperties(
  2292. TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC,
  2293. XCOFF::XTY_SD));
  2294. }
  2295. MCSection *TargetLoweringObjectFileXCOFF::getSectionForLSDA(
  2296. const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
  2297. auto *LSDA = cast<MCSectionXCOFF>(LSDASection);
  2298. if (TM.getFunctionSections()) {
  2299. // If option -ffunction-sections is on, append the function name to the
  2300. // name of the LSDA csect so that each function has its own LSDA csect.
  2301. // This helps the linker to garbage-collect EH info of unused functions.
  2302. SmallString<128> NameStr = LSDA->getName();
  2303. raw_svector_ostream(NameStr) << '.' << F.getName();
  2304. LSDA = getContext().getXCOFFSection(NameStr, LSDA->getKind(),
  2305. LSDA->getCsectProp());
  2306. }
  2307. return LSDA;
  2308. }
  2309. //===----------------------------------------------------------------------===//
  2310. // GOFF
  2311. //===----------------------------------------------------------------------===//
  2312. TargetLoweringObjectFileGOFF::TargetLoweringObjectFileGOFF() = default;
  2313. MCSection *TargetLoweringObjectFileGOFF::getExplicitSectionGlobal(
  2314. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  2315. return SelectSectionForGlobal(GO, Kind, TM);
  2316. }
  2317. MCSection *TargetLoweringObjectFileGOFF::SelectSectionForGlobal(
  2318. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  2319. auto *Symbol = TM.getSymbol(GO);
  2320. if (Kind.isBSS())
  2321. return getContext().getGOFFSection(Symbol->getName(), SectionKind::getBSS(),
  2322. nullptr, nullptr);
  2323. return getContext().getObjectFileInfo()->getTextSection();
  2324. }