MCAssembler.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- MCAssembler.h - Object File Generation -------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_MC_MCASSEMBLER_H
  14. #define LLVM_MC_MCASSEMBLER_H
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/iterator.h"
  20. #include "llvm/ADT/iterator_range.h"
  21. #include "llvm/BinaryFormat/MachO.h"
  22. #include "llvm/MC/MCDirectives.h"
  23. #include "llvm/MC/MCDwarf.h"
  24. #include "llvm/MC/MCFixup.h"
  25. #include "llvm/MC/MCFragment.h"
  26. #include "llvm/MC/MCLinkerOptimizationHint.h"
  27. #include "llvm/MC/MCSymbol.h"
  28. #include "llvm/Support/VersionTuple.h"
  29. #include <cassert>
  30. #include <cstddef>
  31. #include <cstdint>
  32. #include <string>
  33. #include <utility>
  34. #include <vector>
  35. namespace llvm {
  36. class MCAsmBackend;
  37. class MCAsmLayout;
  38. class MCContext;
  39. class MCCodeEmitter;
  40. class MCFragment;
  41. class MCObjectWriter;
  42. class MCSection;
  43. class MCValue;
  44. // FIXME: This really doesn't belong here. See comments below.
  45. struct IndirectSymbolData {
  46. MCSymbol *Symbol;
  47. MCSection *Section;
  48. };
  49. // FIXME: Ditto this. Purely so the Streamer and the ObjectWriter can talk
  50. // to one another.
  51. struct DataRegionData {
  52. // This enum should be kept in sync w/ the mach-o definition in
  53. // llvm/Object/MachOFormat.h.
  54. enum KindTy { Data = 1, JumpTable8, JumpTable16, JumpTable32 } Kind;
  55. MCSymbol *Start;
  56. MCSymbol *End;
  57. };
  58. class MCAssembler {
  59. friend class MCAsmLayout;
  60. public:
  61. using SectionListType = std::vector<MCSection *>;
  62. using SymbolDataListType = std::vector<const MCSymbol *>;
  63. using const_iterator = pointee_iterator<SectionListType::const_iterator>;
  64. using iterator = pointee_iterator<SectionListType::iterator>;
  65. using const_symbol_iterator =
  66. pointee_iterator<SymbolDataListType::const_iterator>;
  67. using symbol_iterator = pointee_iterator<SymbolDataListType::iterator>;
  68. using symbol_range = iterator_range<symbol_iterator>;
  69. using const_symbol_range = iterator_range<const_symbol_iterator>;
  70. using const_indirect_symbol_iterator =
  71. std::vector<IndirectSymbolData>::const_iterator;
  72. using indirect_symbol_iterator = std::vector<IndirectSymbolData>::iterator;
  73. using const_data_region_iterator =
  74. std::vector<DataRegionData>::const_iterator;
  75. using data_region_iterator = std::vector<DataRegionData>::iterator;
  76. /// MachO specific deployment target version info.
  77. // A Major version of 0 indicates that no version information was supplied
  78. // and so the corresponding load command should not be emitted.
  79. using VersionInfoType = struct {
  80. bool EmitBuildVersion;
  81. union {
  82. MCVersionMinType Type; ///< Used when EmitBuildVersion==false.
  83. MachO::PlatformType Platform; ///< Used when EmitBuildVersion==true.
  84. } TypeOrPlatform;
  85. unsigned Major;
  86. unsigned Minor;
  87. unsigned Update;
  88. /// An optional version of the SDK that was used to build the source.
  89. VersionTuple SDKVersion;
  90. };
  91. private:
  92. MCContext &Context;
  93. std::unique_ptr<MCAsmBackend> Backend;
  94. std::unique_ptr<MCCodeEmitter> Emitter;
  95. std::unique_ptr<MCObjectWriter> Writer;
  96. SectionListType Sections;
  97. SymbolDataListType Symbols;
  98. std::vector<IndirectSymbolData> IndirectSymbols;
  99. std::vector<DataRegionData> DataRegions;
  100. /// The list of linker options to propagate into the object file.
  101. std::vector<std::vector<std::string>> LinkerOptions;
  102. /// List of declared file names
  103. std::vector<std::pair<std::string, size_t>> FileNames;
  104. MCDwarfLineTableParams LTParams;
  105. /// The set of function symbols for which a .thumb_func directive has
  106. /// been seen.
  107. //
  108. // FIXME: We really would like this in target specific code rather than
  109. // here. Maybe when the relocation stuff moves to target specific,
  110. // this can go with it? The streamer would need some target specific
  111. // refactoring too.
  112. mutable SmallPtrSet<const MCSymbol *, 32> ThumbFuncs;
  113. /// The bundle alignment size currently set in the assembler.
  114. ///
  115. /// By default it's 0, which means bundling is disabled.
  116. unsigned BundleAlignSize;
  117. bool RelaxAll : 1;
  118. bool SubsectionsViaSymbols : 1;
  119. bool IncrementalLinkerCompatible : 1;
  120. /// ELF specific e_header flags
  121. // It would be good if there were an MCELFAssembler class to hold this.
  122. // ELF header flags are used both by the integrated and standalone assemblers.
  123. // Access to the flags is necessary in cases where assembler directives affect
  124. // which flags to be set.
  125. unsigned ELFHeaderEFlags;
  126. /// Used to communicate Linker Optimization Hint information between
  127. /// the Streamer and the .o writer
  128. MCLOHContainer LOHContainer;
  129. VersionInfoType VersionInfo;
  130. VersionInfoType DarwinTargetVariantVersionInfo;
  131. /// Evaluate a fixup to a relocatable expression and the value which should be
  132. /// placed into the fixup.
  133. ///
  134. /// \param Layout The layout to use for evaluation.
  135. /// \param Fixup The fixup to evaluate.
  136. /// \param DF The fragment the fixup is inside.
  137. /// \param Target [out] On return, the relocatable expression the fixup
  138. /// evaluates to.
  139. /// \param Value [out] On return, the value of the fixup as currently laid
  140. /// out.
  141. /// \param WasForced [out] On return, the value in the fixup is set to the
  142. /// correct value if WasForced is true, even if evaluateFixup returns false.
  143. /// \return Whether the fixup value was fully resolved. This is true if the
  144. /// \p Value result is fixed, otherwise the value may change due to
  145. /// relocation.
  146. bool evaluateFixup(const MCAsmLayout &Layout, const MCFixup &Fixup,
  147. const MCFragment *DF, MCValue &Target,
  148. uint64_t &Value, bool &WasForced) const;
  149. /// Check whether a fixup can be satisfied, or whether it needs to be relaxed
  150. /// (increased in size, in order to hold its value correctly).
  151. bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCRelaxableFragment *DF,
  152. const MCAsmLayout &Layout) const;
  153. /// Check whether the given fragment needs relaxation.
  154. bool fragmentNeedsRelaxation(const MCRelaxableFragment *IF,
  155. const MCAsmLayout &Layout) const;
  156. /// Perform one layout iteration and return true if any offsets
  157. /// were adjusted.
  158. bool layoutOnce(MCAsmLayout &Layout);
  159. /// Perform one layout iteration of the given section and return true
  160. /// if any offsets were adjusted.
  161. bool layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec);
  162. /// Perform relaxation on a single fragment - returns true if the fragment
  163. /// changes as a result of relaxation.
  164. bool relaxFragment(MCAsmLayout &Layout, MCFragment &F);
  165. bool relaxInstruction(MCAsmLayout &Layout, MCRelaxableFragment &IF);
  166. bool relaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF);
  167. bool relaxBoundaryAlign(MCAsmLayout &Layout, MCBoundaryAlignFragment &BF);
  168. bool relaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF);
  169. bool relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
  170. MCDwarfCallFrameFragment &DF);
  171. bool relaxCVInlineLineTable(MCAsmLayout &Layout,
  172. MCCVInlineLineTableFragment &DF);
  173. bool relaxCVDefRange(MCAsmLayout &Layout, MCCVDefRangeFragment &DF);
  174. bool relaxPseudoProbeAddr(MCAsmLayout &Layout, MCPseudoProbeAddrFragment &DF);
  175. /// finishLayout - Finalize a layout, including fragment lowering.
  176. void finishLayout(MCAsmLayout &Layout);
  177. std::tuple<MCValue, uint64_t, bool>
  178. handleFixup(const MCAsmLayout &Layout, MCFragment &F, const MCFixup &Fixup);
  179. public:
  180. struct Symver {
  181. SMLoc Loc;
  182. const MCSymbol *Sym;
  183. StringRef Name;
  184. // True if .symver *, *@@@* or .symver *, *, remove.
  185. bool KeepOriginalSym;
  186. };
  187. std::vector<Symver> Symvers;
  188. /// Construct a new assembler instance.
  189. //
  190. // FIXME: How are we going to parameterize this? Two obvious options are stay
  191. // concrete and require clients to pass in a target like object. The other
  192. // option is to make this abstract, and have targets provide concrete
  193. // implementations as we do with AsmParser.
  194. MCAssembler(MCContext &Context, std::unique_ptr<MCAsmBackend> Backend,
  195. std::unique_ptr<MCCodeEmitter> Emitter,
  196. std::unique_ptr<MCObjectWriter> Writer);
  197. MCAssembler(const MCAssembler &) = delete;
  198. MCAssembler &operator=(const MCAssembler &) = delete;
  199. ~MCAssembler();
  200. /// Compute the effective fragment size assuming it is laid out at the given
  201. /// \p SectionAddress and \p FragmentOffset.
  202. uint64_t computeFragmentSize(const MCAsmLayout &Layout,
  203. const MCFragment &F) const;
  204. /// Find the symbol which defines the atom containing the given symbol, or
  205. /// null if there is no such symbol.
  206. const MCSymbol *getAtom(const MCSymbol &S) const;
  207. /// Check whether a particular symbol is visible to the linker and is required
  208. /// in the symbol table, or whether it can be discarded by the assembler. This
  209. /// also effects whether the assembler treats the label as potentially
  210. /// defining a separate atom.
  211. bool isSymbolLinkerVisible(const MCSymbol &SD) const;
  212. /// Emit the section contents to \p OS.
  213. void writeSectionData(raw_ostream &OS, const MCSection *Section,
  214. const MCAsmLayout &Layout) const;
  215. /// Check whether a given symbol has been flagged with .thumb_func.
  216. bool isThumbFunc(const MCSymbol *Func) const;
  217. /// Flag a function symbol as the target of a .thumb_func directive.
  218. void setIsThumbFunc(const MCSymbol *Func) { ThumbFuncs.insert(Func); }
  219. /// ELF e_header flags
  220. unsigned getELFHeaderEFlags() const { return ELFHeaderEFlags; }
  221. void setELFHeaderEFlags(unsigned Flags) { ELFHeaderEFlags = Flags; }
  222. /// MachO deployment target version information.
  223. const VersionInfoType &getVersionInfo() const { return VersionInfo; }
  224. void setVersionMin(MCVersionMinType Type, unsigned Major, unsigned Minor,
  225. unsigned Update,
  226. VersionTuple SDKVersion = VersionTuple()) {
  227. VersionInfo.EmitBuildVersion = false;
  228. VersionInfo.TypeOrPlatform.Type = Type;
  229. VersionInfo.Major = Major;
  230. VersionInfo.Minor = Minor;
  231. VersionInfo.Update = Update;
  232. VersionInfo.SDKVersion = SDKVersion;
  233. }
  234. void setBuildVersion(MachO::PlatformType Platform, unsigned Major,
  235. unsigned Minor, unsigned Update,
  236. VersionTuple SDKVersion = VersionTuple()) {
  237. VersionInfo.EmitBuildVersion = true;
  238. VersionInfo.TypeOrPlatform.Platform = Platform;
  239. VersionInfo.Major = Major;
  240. VersionInfo.Minor = Minor;
  241. VersionInfo.Update = Update;
  242. VersionInfo.SDKVersion = SDKVersion;
  243. }
  244. const VersionInfoType &getDarwinTargetVariantVersionInfo() const {
  245. return DarwinTargetVariantVersionInfo;
  246. }
  247. void setDarwinTargetVariantBuildVersion(MachO::PlatformType Platform,
  248. unsigned Major, unsigned Minor,
  249. unsigned Update,
  250. VersionTuple SDKVersion) {
  251. DarwinTargetVariantVersionInfo.EmitBuildVersion = true;
  252. DarwinTargetVariantVersionInfo.TypeOrPlatform.Platform = Platform;
  253. DarwinTargetVariantVersionInfo.Major = Major;
  254. DarwinTargetVariantVersionInfo.Minor = Minor;
  255. DarwinTargetVariantVersionInfo.Update = Update;
  256. DarwinTargetVariantVersionInfo.SDKVersion = SDKVersion;
  257. }
  258. /// Reuse an assembler instance
  259. ///
  260. void reset();
  261. MCContext &getContext() const { return Context; }
  262. MCAsmBackend *getBackendPtr() const { return Backend.get(); }
  263. MCCodeEmitter *getEmitterPtr() const { return Emitter.get(); }
  264. MCObjectWriter *getWriterPtr() const { return Writer.get(); }
  265. MCAsmBackend &getBackend() const { return *Backend; }
  266. MCCodeEmitter &getEmitter() const { return *Emitter; }
  267. MCObjectWriter &getWriter() const { return *Writer; }
  268. MCDwarfLineTableParams getDWARFLinetableParams() const { return LTParams; }
  269. void setDWARFLinetableParams(MCDwarfLineTableParams P) { LTParams = P; }
  270. /// Finish - Do final processing and write the object to the output stream.
  271. /// \p Writer is used for custom object writer (as the MCJIT does),
  272. /// if not specified it is automatically created from backend.
  273. void Finish();
  274. // Layout all section and prepare them for emission.
  275. void layout(MCAsmLayout &Layout);
  276. // FIXME: This does not belong here.
  277. bool getSubsectionsViaSymbols() const { return SubsectionsViaSymbols; }
  278. void setSubsectionsViaSymbols(bool Value) { SubsectionsViaSymbols = Value; }
  279. bool isIncrementalLinkerCompatible() const {
  280. return IncrementalLinkerCompatible;
  281. }
  282. void setIncrementalLinkerCompatible(bool Value) {
  283. IncrementalLinkerCompatible = Value;
  284. }
  285. bool getRelaxAll() const { return RelaxAll; }
  286. void setRelaxAll(bool Value) { RelaxAll = Value; }
  287. bool isBundlingEnabled() const { return BundleAlignSize != 0; }
  288. unsigned getBundleAlignSize() const { return BundleAlignSize; }
  289. void setBundleAlignSize(unsigned Size) {
  290. assert((Size == 0 || !(Size & (Size - 1))) &&
  291. "Expect a power-of-two bundle align size");
  292. BundleAlignSize = Size;
  293. }
  294. /// \name Section List Access
  295. /// @{
  296. iterator begin() { return Sections.begin(); }
  297. const_iterator begin() const { return Sections.begin(); }
  298. iterator end() { return Sections.end(); }
  299. const_iterator end() const { return Sections.end(); }
  300. size_t size() const { return Sections.size(); }
  301. /// @}
  302. /// \name Symbol List Access
  303. /// @{
  304. symbol_iterator symbol_begin() { return Symbols.begin(); }
  305. const_symbol_iterator symbol_begin() const { return Symbols.begin(); }
  306. symbol_iterator symbol_end() { return Symbols.end(); }
  307. const_symbol_iterator symbol_end() const { return Symbols.end(); }
  308. symbol_range symbols() { return make_range(symbol_begin(), symbol_end()); }
  309. const_symbol_range symbols() const {
  310. return make_range(symbol_begin(), symbol_end());
  311. }
  312. size_t symbol_size() const { return Symbols.size(); }
  313. /// @}
  314. /// \name Indirect Symbol List Access
  315. /// @{
  316. // FIXME: This is a total hack, this should not be here. Once things are
  317. // factored so that the streamer has direct access to the .o writer, it can
  318. // disappear.
  319. std::vector<IndirectSymbolData> &getIndirectSymbols() {
  320. return IndirectSymbols;
  321. }
  322. indirect_symbol_iterator indirect_symbol_begin() {
  323. return IndirectSymbols.begin();
  324. }
  325. const_indirect_symbol_iterator indirect_symbol_begin() const {
  326. return IndirectSymbols.begin();
  327. }
  328. indirect_symbol_iterator indirect_symbol_end() {
  329. return IndirectSymbols.end();
  330. }
  331. const_indirect_symbol_iterator indirect_symbol_end() const {
  332. return IndirectSymbols.end();
  333. }
  334. size_t indirect_symbol_size() const { return IndirectSymbols.size(); }
  335. /// @}
  336. /// \name Linker Option List Access
  337. /// @{
  338. std::vector<std::vector<std::string>> &getLinkerOptions() {
  339. return LinkerOptions;
  340. }
  341. /// @}
  342. /// \name Data Region List Access
  343. /// @{
  344. // FIXME: This is a total hack, this should not be here. Once things are
  345. // factored so that the streamer has direct access to the .o writer, it can
  346. // disappear.
  347. std::vector<DataRegionData> &getDataRegions() { return DataRegions; }
  348. data_region_iterator data_region_begin() { return DataRegions.begin(); }
  349. const_data_region_iterator data_region_begin() const {
  350. return DataRegions.begin();
  351. }
  352. data_region_iterator data_region_end() { return DataRegions.end(); }
  353. const_data_region_iterator data_region_end() const {
  354. return DataRegions.end();
  355. }
  356. size_t data_region_size() const { return DataRegions.size(); }
  357. /// @}
  358. /// \name Data Region List Access
  359. /// @{
  360. // FIXME: This is a total hack, this should not be here. Once things are
  361. // factored so that the streamer has direct access to the .o writer, it can
  362. // disappear.
  363. MCLOHContainer &getLOHContainer() { return LOHContainer; }
  364. const MCLOHContainer &getLOHContainer() const {
  365. return const_cast<MCAssembler *>(this)->getLOHContainer();
  366. }
  367. struct CGProfileEntry {
  368. const MCSymbolRefExpr *From;
  369. const MCSymbolRefExpr *To;
  370. uint64_t Count;
  371. };
  372. std::vector<CGProfileEntry> CGProfile;
  373. /// @}
  374. /// \name Backend Data Access
  375. /// @{
  376. bool registerSection(MCSection &Section);
  377. void registerSymbol(const MCSymbol &Symbol, bool *Created = nullptr);
  378. MutableArrayRef<std::pair<std::string, size_t>> getFileNames() {
  379. return FileNames;
  380. }
  381. void addFileName(StringRef FileName) {
  382. FileNames.emplace_back(std::string(FileName), Symbols.size());
  383. }
  384. /// Write the necessary bundle padding to \p OS.
  385. /// Expects a fragment \p F containing instructions and its size \p FSize.
  386. void writeFragmentPadding(raw_ostream &OS, const MCEncodedFragment &F,
  387. uint64_t FSize) const;
  388. /// @}
  389. void dump() const;
  390. };
  391. /// Compute the amount of padding required before the fragment \p F to
  392. /// obey bundling restrictions, where \p FOffset is the fragment's offset in
  393. /// its section and \p FSize is the fragment's size.
  394. uint64_t computeBundlePadding(const MCAssembler &Assembler,
  395. const MCEncodedFragment *F, uint64_t FOffset,
  396. uint64_t FSize);
  397. } // end namespace llvm
  398. #endif // LLVM_MC_MCASSEMBLER_H
  399. #ifdef __GNUC__
  400. #pragma GCC diagnostic pop
  401. #endif