MCContext.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- MCContext.h - Machine Code Context -----------------------*- 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_MCCONTEXT_H
  14. #define LLVM_MC_MCCONTEXT_H
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/StringMap.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/BinaryFormat/Dwarf.h"
  22. #include "llvm/BinaryFormat/XCOFF.h"
  23. #include "llvm/MC/MCAsmMacro.h"
  24. #include "llvm/MC/MCDwarf.h"
  25. #include "llvm/MC/MCPseudoProbe.h"
  26. #include "llvm/MC/MCSection.h"
  27. #include "llvm/MC/SectionKind.h"
  28. #include "llvm/Support/Allocator.h"
  29. #include "llvm/Support/Compiler.h"
  30. #include "llvm/Support/Error.h"
  31. #include "llvm/Support/MD5.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <algorithm>
  34. #include <cassert>
  35. #include <cstddef>
  36. #include <cstdint>
  37. #include <functional>
  38. #include <map>
  39. #include <memory>
  40. #include <optional>
  41. #include <string>
  42. #include <utility>
  43. #include <vector>
  44. namespace llvm {
  45. class CodeViewContext;
  46. class MCAsmInfo;
  47. class MCInst;
  48. class MCLabel;
  49. class MCObjectFileInfo;
  50. class MCRegisterInfo;
  51. class MCSection;
  52. class MCSectionCOFF;
  53. class MCSectionDXContainer;
  54. class MCSectionELF;
  55. class MCSectionGOFF;
  56. class MCSectionMachO;
  57. class MCSectionSPIRV;
  58. class MCSectionWasm;
  59. class MCSectionXCOFF;
  60. class MCStreamer;
  61. class MCSubtargetInfo;
  62. class MCSymbol;
  63. class MCSymbolELF;
  64. class MCSymbolWasm;
  65. class MCSymbolXCOFF;
  66. class MCTargetOptions;
  67. class MDNode;
  68. template <typename T> class SmallVectorImpl;
  69. class SMDiagnostic;
  70. class SMLoc;
  71. class SourceMgr;
  72. enum class EmitDwarfUnwindType;
  73. /// Context object for machine code objects. This class owns all of the
  74. /// sections that it creates.
  75. ///
  76. class MCContext {
  77. public:
  78. using SymbolTable = StringMap<MCSymbol *, BumpPtrAllocator &>;
  79. using DiagHandlerTy =
  80. std::function<void(const SMDiagnostic &, bool, const SourceMgr &,
  81. std::vector<const MDNode *> &)>;
  82. enum Environment {
  83. IsMachO,
  84. IsELF,
  85. IsGOFF,
  86. IsCOFF,
  87. IsSPIRV,
  88. IsWasm,
  89. IsXCOFF,
  90. IsDXContainer
  91. };
  92. private:
  93. Environment Env;
  94. /// The name of the Segment where Swift5 Reflection Section data will be
  95. /// outputted
  96. StringRef Swift5ReflectionSegmentName;
  97. /// The triple for this object.
  98. Triple TT;
  99. /// The SourceMgr for this object, if any.
  100. const SourceMgr *SrcMgr;
  101. /// The SourceMgr for inline assembly, if any.
  102. std::unique_ptr<SourceMgr> InlineSrcMgr;
  103. std::vector<const MDNode *> LocInfos;
  104. DiagHandlerTy DiagHandler;
  105. /// The MCAsmInfo for this target.
  106. const MCAsmInfo *MAI;
  107. /// The MCRegisterInfo for this target.
  108. const MCRegisterInfo *MRI;
  109. /// The MCObjectFileInfo for this target.
  110. const MCObjectFileInfo *MOFI;
  111. /// The MCSubtargetInfo for this target.
  112. const MCSubtargetInfo *MSTI;
  113. std::unique_ptr<CodeViewContext> CVContext;
  114. /// Allocator object used for creating machine code objects.
  115. ///
  116. /// We use a bump pointer allocator to avoid the need to track all allocated
  117. /// objects.
  118. BumpPtrAllocator Allocator;
  119. SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
  120. SpecificBumpPtrAllocator<MCSectionDXContainer> DXCAllocator;
  121. SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
  122. SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
  123. SpecificBumpPtrAllocator<MCSectionGOFF> GOFFAllocator;
  124. SpecificBumpPtrAllocator<MCSectionSPIRV> SPIRVAllocator;
  125. SpecificBumpPtrAllocator<MCSectionWasm> WasmAllocator;
  126. SpecificBumpPtrAllocator<MCSectionXCOFF> XCOFFAllocator;
  127. SpecificBumpPtrAllocator<MCInst> MCInstAllocator;
  128. /// Bindings of names to symbols.
  129. SymbolTable Symbols;
  130. /// A mapping from a local label number and an instance count to a symbol.
  131. /// For example, in the assembly
  132. /// 1:
  133. /// 2:
  134. /// 1:
  135. /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
  136. DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
  137. /// Keeps tracks of names that were used both for used declared and
  138. /// artificial symbols. The value is "true" if the name has been used for a
  139. /// non-section symbol (there can be at most one of those, plus an unlimited
  140. /// number of section symbols with the same name).
  141. StringMap<bool, BumpPtrAllocator &> UsedNames;
  142. /// Keeps track of labels that are used in inline assembly.
  143. SymbolTable InlineAsmUsedLabelNames;
  144. /// The next ID to dole out to an unnamed assembler temporary symbol with
  145. /// a given prefix.
  146. StringMap<unsigned> NextID;
  147. /// Instances of directional local labels.
  148. DenseMap<unsigned, MCLabel *> Instances;
  149. /// NextInstance() creates the next instance of the directional local label
  150. /// for the LocalLabelVal and adds it to the map if needed.
  151. unsigned NextInstance(unsigned LocalLabelVal);
  152. /// GetInstance() gets the current instance of the directional local label
  153. /// for the LocalLabelVal and adds it to the map if needed.
  154. unsigned GetInstance(unsigned LocalLabelVal);
  155. /// LLVM_BB_ADDR_MAP version to emit.
  156. uint8_t BBAddrMapVersion = 1;
  157. /// The file name of the log file from the environment variable
  158. /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
  159. /// directive is used or it is an error.
  160. std::string SecureLogFile;
  161. /// The stream that gets written to for the .secure_log_unique directive.
  162. std::unique_ptr<raw_fd_ostream> SecureLog;
  163. /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
  164. /// catch errors if .secure_log_unique appears twice without
  165. /// .secure_log_reset appearing between them.
  166. bool SecureLogUsed = false;
  167. /// The compilation directory to use for DW_AT_comp_dir.
  168. SmallString<128> CompilationDir;
  169. /// Prefix replacement map for source file information.
  170. std::map<std::string, const std::string, std::greater<>> DebugPrefixMap;
  171. /// The main file name if passed in explicitly.
  172. std::string MainFileName;
  173. /// The dwarf file and directory tables from the dwarf .file directive.
  174. /// We now emit a line table for each compile unit. To reduce the prologue
  175. /// size of each line table, the files and directories used by each compile
  176. /// unit are separated.
  177. std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
  178. /// The current dwarf line information from the last dwarf .loc directive.
  179. MCDwarfLoc CurrentDwarfLoc;
  180. bool DwarfLocSeen = false;
  181. /// Generate dwarf debugging info for assembly source files.
  182. bool GenDwarfForAssembly = false;
  183. /// The current dwarf file number when generate dwarf debugging info for
  184. /// assembly source files.
  185. unsigned GenDwarfFileNumber = 0;
  186. /// Sections for generating the .debug_ranges and .debug_aranges sections.
  187. SetVector<MCSection *> SectionsForRanges;
  188. /// The information gathered from labels that will have dwarf label
  189. /// entries when generating dwarf assembly source files.
  190. std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
  191. /// The string to embed in the debug information for the compile unit, if
  192. /// non-empty.
  193. StringRef DwarfDebugFlags;
  194. /// The string to embed in as the dwarf AT_producer for the compile unit, if
  195. /// non-empty.
  196. StringRef DwarfDebugProducer;
  197. /// The maximum version of dwarf that we should emit.
  198. uint16_t DwarfVersion = 4;
  199. /// The format of dwarf that we emit.
  200. dwarf::DwarfFormat DwarfFormat = dwarf::DWARF32;
  201. /// Honor temporary labels, this is useful for debugging semantic
  202. /// differences between temporary and non-temporary labels (primarily on
  203. /// Darwin).
  204. bool AllowTemporaryLabels = true;
  205. bool UseNamesOnTempLabels = false;
  206. /// The Compile Unit ID that we are currently processing.
  207. unsigned DwarfCompileUnitID = 0;
  208. /// A collection of MCPseudoProbe in the current module
  209. MCPseudoProbeTable PseudoProbeTable;
  210. // Sections are differentiated by the quadruple (section_name, group_name,
  211. // unique_id, link_to_symbol_name). Sections sharing the same quadruple are
  212. // combined into one section.
  213. struct ELFSectionKey {
  214. std::string SectionName;
  215. StringRef GroupName;
  216. StringRef LinkedToName;
  217. unsigned UniqueID;
  218. ELFSectionKey(StringRef SectionName, StringRef GroupName,
  219. StringRef LinkedToName, unsigned UniqueID)
  220. : SectionName(SectionName), GroupName(GroupName),
  221. LinkedToName(LinkedToName), UniqueID(UniqueID) {}
  222. bool operator<(const ELFSectionKey &Other) const {
  223. if (SectionName != Other.SectionName)
  224. return SectionName < Other.SectionName;
  225. if (GroupName != Other.GroupName)
  226. return GroupName < Other.GroupName;
  227. if (int O = LinkedToName.compare(Other.LinkedToName))
  228. return O < 0;
  229. return UniqueID < Other.UniqueID;
  230. }
  231. };
  232. struct COFFSectionKey {
  233. std::string SectionName;
  234. StringRef GroupName;
  235. int SelectionKey;
  236. unsigned UniqueID;
  237. COFFSectionKey(StringRef SectionName, StringRef GroupName, int SelectionKey,
  238. unsigned UniqueID)
  239. : SectionName(SectionName), GroupName(GroupName),
  240. SelectionKey(SelectionKey), UniqueID(UniqueID) {}
  241. bool operator<(const COFFSectionKey &Other) const {
  242. if (SectionName != Other.SectionName)
  243. return SectionName < Other.SectionName;
  244. if (GroupName != Other.GroupName)
  245. return GroupName < Other.GroupName;
  246. if (SelectionKey != Other.SelectionKey)
  247. return SelectionKey < Other.SelectionKey;
  248. return UniqueID < Other.UniqueID;
  249. }
  250. };
  251. struct WasmSectionKey {
  252. std::string SectionName;
  253. StringRef GroupName;
  254. unsigned UniqueID;
  255. WasmSectionKey(StringRef SectionName, StringRef GroupName,
  256. unsigned UniqueID)
  257. : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {}
  258. bool operator<(const WasmSectionKey &Other) const {
  259. if (SectionName != Other.SectionName)
  260. return SectionName < Other.SectionName;
  261. if (GroupName != Other.GroupName)
  262. return GroupName < Other.GroupName;
  263. return UniqueID < Other.UniqueID;
  264. }
  265. };
  266. struct XCOFFSectionKey {
  267. // Section name.
  268. std::string SectionName;
  269. // Section property.
  270. // For csect section, it is storage mapping class.
  271. // For debug section, it is section type flags.
  272. union {
  273. XCOFF::StorageMappingClass MappingClass;
  274. XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags;
  275. };
  276. bool IsCsect;
  277. XCOFFSectionKey(StringRef SectionName,
  278. XCOFF::StorageMappingClass MappingClass)
  279. : SectionName(SectionName), MappingClass(MappingClass), IsCsect(true) {}
  280. XCOFFSectionKey(StringRef SectionName,
  281. XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags)
  282. : SectionName(SectionName), DwarfSubtypeFlags(DwarfSubtypeFlags),
  283. IsCsect(false) {}
  284. bool operator<(const XCOFFSectionKey &Other) const {
  285. if (IsCsect && Other.IsCsect)
  286. return std::tie(SectionName, MappingClass) <
  287. std::tie(Other.SectionName, Other.MappingClass);
  288. if (IsCsect != Other.IsCsect)
  289. return IsCsect;
  290. return std::tie(SectionName, DwarfSubtypeFlags) <
  291. std::tie(Other.SectionName, Other.DwarfSubtypeFlags);
  292. }
  293. };
  294. StringMap<MCSectionMachO *> MachOUniquingMap;
  295. std::map<ELFSectionKey, MCSectionELF *> ELFUniquingMap;
  296. std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
  297. std::map<std::string, MCSectionGOFF *> GOFFUniquingMap;
  298. std::map<WasmSectionKey, MCSectionWasm *> WasmUniquingMap;
  299. std::map<XCOFFSectionKey, MCSectionXCOFF *> XCOFFUniquingMap;
  300. StringMap<MCSectionDXContainer *> DXCUniquingMap;
  301. StringMap<bool> RelSecNames;
  302. SpecificBumpPtrAllocator<MCSubtargetInfo> MCSubtargetAllocator;
  303. /// Do automatic reset in destructor
  304. bool AutoReset;
  305. MCTargetOptions const *TargetOptions;
  306. bool HadError = false;
  307. void reportCommon(SMLoc Loc,
  308. std::function<void(SMDiagnostic &, const SourceMgr *)>);
  309. MCSymbol *createSymbolImpl(const StringMapEntry<bool> *Name,
  310. bool CanBeUnnamed);
  311. MCSymbol *createSymbol(StringRef Name, bool AlwaysAddSuffix,
  312. bool IsTemporary);
  313. MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
  314. unsigned Instance);
  315. MCSectionELF *createELFSectionImpl(StringRef Section, unsigned Type,
  316. unsigned Flags, SectionKind K,
  317. unsigned EntrySize,
  318. const MCSymbolELF *Group, bool IsComdat,
  319. unsigned UniqueID,
  320. const MCSymbolELF *LinkedToSym);
  321. MCSymbolXCOFF *createXCOFFSymbolImpl(const StringMapEntry<bool> *Name,
  322. bool IsTemporary);
  323. /// Map of currently defined macros.
  324. StringMap<MCAsmMacro> MacroMap;
  325. struct ELFEntrySizeKey {
  326. std::string SectionName;
  327. unsigned Flags;
  328. unsigned EntrySize;
  329. ELFEntrySizeKey(StringRef SectionName, unsigned Flags, unsigned EntrySize)
  330. : SectionName(SectionName), Flags(Flags), EntrySize(EntrySize) {}
  331. bool operator<(const ELFEntrySizeKey &Other) const {
  332. if (SectionName != Other.SectionName)
  333. return SectionName < Other.SectionName;
  334. if (Flags != Other.Flags)
  335. return Flags < Other.Flags;
  336. return EntrySize < Other.EntrySize;
  337. }
  338. };
  339. // Symbols must be assigned to a section with a compatible entry size and
  340. // flags. This map is used to assign unique IDs to sections to distinguish
  341. // between sections with identical names but incompatible entry sizes and/or
  342. // flags. This can occur when a symbol is explicitly assigned to a section,
  343. // e.g. via __attribute__((section("myname"))).
  344. std::map<ELFEntrySizeKey, unsigned> ELFEntrySizeMap;
  345. // This set is used to record the generic mergeable section names seen.
  346. // These are sections that are created as mergeable e.g. .debug_str. We need
  347. // to avoid assigning non-mergeable symbols to these sections. It is used
  348. // to prevent non-mergeable symbols being explicitly assigned to mergeable
  349. // sections (e.g. via _attribute_((section("myname")))).
  350. DenseSet<StringRef> ELFSeenGenericMergeableSections;
  351. public:
  352. explicit MCContext(const Triple &TheTriple, const MCAsmInfo *MAI,
  353. const MCRegisterInfo *MRI, const MCSubtargetInfo *MSTI,
  354. const SourceMgr *Mgr = nullptr,
  355. MCTargetOptions const *TargetOpts = nullptr,
  356. bool DoAutoReset = true,
  357. StringRef Swift5ReflSegmentName = {});
  358. MCContext(const MCContext &) = delete;
  359. MCContext &operator=(const MCContext &) = delete;
  360. ~MCContext();
  361. Environment getObjectFileType() const { return Env; }
  362. const StringRef &getSwift5ReflectionSegmentName() const {
  363. return Swift5ReflectionSegmentName;
  364. }
  365. const Triple &getTargetTriple() const { return TT; }
  366. const SourceMgr *getSourceManager() const { return SrcMgr; }
  367. void initInlineSourceManager();
  368. SourceMgr *getInlineSourceManager() { return InlineSrcMgr.get(); }
  369. std::vector<const MDNode *> &getLocInfos() { return LocInfos; }
  370. void setDiagnosticHandler(DiagHandlerTy DiagHandler) {
  371. this->DiagHandler = DiagHandler;
  372. }
  373. void setObjectFileInfo(const MCObjectFileInfo *Mofi) { MOFI = Mofi; }
  374. const MCAsmInfo *getAsmInfo() const { return MAI; }
  375. const MCRegisterInfo *getRegisterInfo() const { return MRI; }
  376. const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
  377. const MCSubtargetInfo *getSubtargetInfo() const { return MSTI; }
  378. CodeViewContext &getCVContext();
  379. void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
  380. void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
  381. /// \name Module Lifetime Management
  382. /// @{
  383. /// reset - return object to right after construction state to prepare
  384. /// to process a new module
  385. void reset();
  386. /// @}
  387. /// \name McInst Management
  388. /// Create and return a new MC instruction.
  389. MCInst *createMCInst();
  390. /// \name Symbol Management
  391. /// @{
  392. /// Create and return a new linker temporary symbol with a unique but
  393. /// unspecified name.
  394. MCSymbol *createLinkerPrivateTempSymbol();
  395. /// Create a temporary symbol with a unique name. The name will be omitted
  396. /// in the symbol table if UseNamesOnTempLabels is false (default except
  397. /// MCAsmStreamer). The overload without Name uses an unspecified name.
  398. MCSymbol *createTempSymbol();
  399. MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix = true);
  400. /// Create a temporary symbol with a unique name whose name cannot be
  401. /// omitted in the symbol table. This is rarely used.
  402. MCSymbol *createNamedTempSymbol();
  403. MCSymbol *createNamedTempSymbol(const Twine &Name);
  404. /// Create the definition of a directional local symbol for numbered label
  405. /// (used for "1:" definitions).
  406. MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
  407. /// Create and return a directional local symbol for numbered label (used
  408. /// for "1b" or 1f" references).
  409. MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
  410. /// Lookup the symbol inside with the specified \p Name. If it exists,
  411. /// return it. If not, create a forward reference and return it.
  412. ///
  413. /// \param Name - The symbol name, which must be unique across all symbols.
  414. MCSymbol *getOrCreateSymbol(const Twine &Name);
  415. /// Gets a symbol that will be defined to the final stack offset of a local
  416. /// variable after codegen.
  417. ///
  418. /// \param Idx - The index of a local variable passed to \@llvm.localescape.
  419. MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
  420. MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
  421. MCSymbol *getOrCreateLSDASymbol(StringRef FuncName);
  422. /// Get the symbol for \p Name, or null.
  423. MCSymbol *lookupSymbol(const Twine &Name) const;
  424. /// Set value for a symbol.
  425. void setSymbolValue(MCStreamer &Streamer, StringRef Sym, uint64_t Val);
  426. /// getSymbols - Get a reference for the symbol table for clients that
  427. /// want to, for example, iterate over all symbols. 'const' because we
  428. /// still want any modifications to the table itself to use the MCContext
  429. /// APIs.
  430. const SymbolTable &getSymbols() const { return Symbols; }
  431. /// isInlineAsmLabel - Return true if the name is a label referenced in
  432. /// inline assembly.
  433. MCSymbol *getInlineAsmLabel(StringRef Name) const {
  434. return InlineAsmUsedLabelNames.lookup(Name);
  435. }
  436. /// registerInlineAsmLabel - Records that the name is a label referenced in
  437. /// inline assembly.
  438. void registerInlineAsmLabel(MCSymbol *Sym);
  439. /// @}
  440. /// \name Section Management
  441. /// @{
  442. enum : unsigned {
  443. /// Pass this value as the UniqueID during section creation to get the
  444. /// generic section with the given name and characteristics. The usual
  445. /// sections such as .text use this ID.
  446. GenericSectionID = ~0U
  447. };
  448. /// Return the MCSection for the specified mach-o section. This requires
  449. /// the operands to be valid.
  450. MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
  451. unsigned TypeAndAttributes,
  452. unsigned Reserved2, SectionKind K,
  453. const char *BeginSymName = nullptr);
  454. MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
  455. unsigned TypeAndAttributes, SectionKind K,
  456. const char *BeginSymName = nullptr) {
  457. return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
  458. BeginSymName);
  459. }
  460. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  461. unsigned Flags) {
  462. return getELFSection(Section, Type, Flags, 0, "", false);
  463. }
  464. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  465. unsigned Flags, unsigned EntrySize) {
  466. return getELFSection(Section, Type, Flags, EntrySize, "", false,
  467. MCSection::NonUniqueID, nullptr);
  468. }
  469. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  470. unsigned Flags, unsigned EntrySize,
  471. const Twine &Group, bool IsComdat) {
  472. return getELFSection(Section, Type, Flags, EntrySize, Group, IsComdat,
  473. MCSection::NonUniqueID, nullptr);
  474. }
  475. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  476. unsigned Flags, unsigned EntrySize,
  477. const Twine &Group, bool IsComdat,
  478. unsigned UniqueID,
  479. const MCSymbolELF *LinkedToSym);
  480. MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
  481. unsigned Flags, unsigned EntrySize,
  482. const MCSymbolELF *Group, bool IsComdat,
  483. unsigned UniqueID,
  484. const MCSymbolELF *LinkedToSym);
  485. /// Get a section with the provided group identifier. This section is
  486. /// named by concatenating \p Prefix with '.' then \p Suffix. The \p Type
  487. /// describes the type of the section and \p Flags are used to further
  488. /// configure this named section.
  489. MCSectionELF *getELFNamedSection(const Twine &Prefix, const Twine &Suffix,
  490. unsigned Type, unsigned Flags,
  491. unsigned EntrySize = 0);
  492. MCSectionELF *createELFRelSection(const Twine &Name, unsigned Type,
  493. unsigned Flags, unsigned EntrySize,
  494. const MCSymbolELF *Group,
  495. const MCSectionELF *RelInfoSection);
  496. MCSectionELF *createELFGroupSection(const MCSymbolELF *Group, bool IsComdat);
  497. void recordELFMergeableSectionInfo(StringRef SectionName, unsigned Flags,
  498. unsigned UniqueID, unsigned EntrySize);
  499. bool isELFImplicitMergeableSectionNamePrefix(StringRef Name);
  500. bool isELFGenericMergeableSection(StringRef Name);
  501. /// Return the unique ID of the section with the given name, flags and entry
  502. /// size, if it exists.
  503. std::optional<unsigned> getELFUniqueIDForEntsize(StringRef SectionName,
  504. unsigned Flags,
  505. unsigned EntrySize);
  506. MCSectionGOFF *getGOFFSection(StringRef Section, SectionKind Kind,
  507. MCSection *Parent, const MCExpr *SubsectionId);
  508. MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
  509. SectionKind Kind, StringRef COMDATSymName,
  510. int Selection,
  511. unsigned UniqueID = GenericSectionID,
  512. const char *BeginSymName = nullptr);
  513. MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
  514. SectionKind Kind,
  515. const char *BeginSymName = nullptr);
  516. /// Gets or creates a section equivalent to Sec that is associated with the
  517. /// section containing KeySym. For example, to create a debug info section
  518. /// associated with an inline function, pass the normal debug info section
  519. /// as Sec and the function symbol as KeySym.
  520. MCSectionCOFF *
  521. getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym,
  522. unsigned UniqueID = GenericSectionID);
  523. MCSectionSPIRV *getSPIRVSection();
  524. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  525. unsigned Flags = 0) {
  526. return getWasmSection(Section, K, Flags, nullptr);
  527. }
  528. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  529. unsigned Flags, const char *BeginSymName) {
  530. return getWasmSection(Section, K, Flags, "", ~0, BeginSymName);
  531. }
  532. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  533. unsigned Flags, const Twine &Group,
  534. unsigned UniqueID) {
  535. return getWasmSection(Section, K, Flags, Group, UniqueID, nullptr);
  536. }
  537. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  538. unsigned Flags, const Twine &Group,
  539. unsigned UniqueID, const char *BeginSymName);
  540. MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
  541. unsigned Flags, const MCSymbolWasm *Group,
  542. unsigned UniqueID, const char *BeginSymName);
  543. /// Get the section for the provided Section name
  544. MCSectionDXContainer *getDXContainerSection(StringRef Section, SectionKind K);
  545. bool hasXCOFFSection(StringRef Section,
  546. XCOFF::CsectProperties CsectProp) const;
  547. MCSectionXCOFF *getXCOFFSection(
  548. StringRef Section, SectionKind K,
  549. std::optional<XCOFF::CsectProperties> CsectProp = std::nullopt,
  550. bool MultiSymbolsAllowed = false, const char *BeginSymName = nullptr,
  551. std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSubtypeFlags =
  552. std::nullopt);
  553. // Create and save a copy of STI and return a reference to the copy.
  554. MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI);
  555. uint8_t getBBAddrMapVersion() const { return BBAddrMapVersion; }
  556. /// @}
  557. /// \name Dwarf Management
  558. /// @{
  559. /// Get the compilation directory for DW_AT_comp_dir
  560. /// The compilation directory should be set with \c setCompilationDir before
  561. /// calling this function. If it is unset, an empty string will be returned.
  562. StringRef getCompilationDir() const { return CompilationDir; }
  563. /// Set the compilation directory for DW_AT_comp_dir
  564. void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
  565. /// Add an entry to the debug prefix map.
  566. void addDebugPrefixMapEntry(const std::string &From, const std::string &To);
  567. /// Remap one path in-place as per the debug prefix map.
  568. void remapDebugPath(SmallVectorImpl<char> &Path);
  569. // Remaps all debug directory paths in-place as per the debug prefix map.
  570. void RemapDebugPaths();
  571. /// Get the main file name for use in error messages and debug
  572. /// info. This can be set to ensure we've got the correct file name
  573. /// after preprocessing or for -save-temps.
  574. const std::string &getMainFileName() const { return MainFileName; }
  575. /// Set the main file name and override the default.
  576. void setMainFileName(StringRef S) { MainFileName = std::string(S); }
  577. /// Creates an entry in the dwarf file and directory tables.
  578. Expected<unsigned> getDwarfFile(StringRef Directory, StringRef FileName,
  579. unsigned FileNumber,
  580. std::optional<MD5::MD5Result> Checksum,
  581. std::optional<StringRef> Source,
  582. unsigned CUID);
  583. bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
  584. const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
  585. return MCDwarfLineTablesCUMap;
  586. }
  587. MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
  588. return MCDwarfLineTablesCUMap[CUID];
  589. }
  590. const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
  591. auto I = MCDwarfLineTablesCUMap.find(CUID);
  592. assert(I != MCDwarfLineTablesCUMap.end());
  593. return I->second;
  594. }
  595. const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
  596. return getMCDwarfLineTable(CUID).getMCDwarfFiles();
  597. }
  598. const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
  599. return getMCDwarfLineTable(CUID).getMCDwarfDirs();
  600. }
  601. unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
  602. void setDwarfCompileUnitID(unsigned CUIndex) { DwarfCompileUnitID = CUIndex; }
  603. /// Specifies the "root" file and directory of the compilation unit.
  604. /// These are "file 0" and "directory 0" in DWARF v5.
  605. void setMCLineTableRootFile(unsigned CUID, StringRef CompilationDir,
  606. StringRef Filename,
  607. std::optional<MD5::MD5Result> Checksum,
  608. std::optional<StringRef> Source) {
  609. getMCDwarfLineTable(CUID).setRootFile(CompilationDir, Filename, Checksum,
  610. Source);
  611. }
  612. /// Reports whether MD5 checksum usage is consistent (all-or-none).
  613. bool isDwarfMD5UsageConsistent(unsigned CUID) const {
  614. return getMCDwarfLineTable(CUID).isMD5UsageConsistent();
  615. }
  616. /// Saves the information from the currently parsed dwarf .loc directive
  617. /// and sets DwarfLocSeen. When the next instruction is assembled an entry
  618. /// in the line number table with this information and the address of the
  619. /// instruction will be created.
  620. void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
  621. unsigned Flags, unsigned Isa,
  622. unsigned Discriminator) {
  623. CurrentDwarfLoc.setFileNum(FileNum);
  624. CurrentDwarfLoc.setLine(Line);
  625. CurrentDwarfLoc.setColumn(Column);
  626. CurrentDwarfLoc.setFlags(Flags);
  627. CurrentDwarfLoc.setIsa(Isa);
  628. CurrentDwarfLoc.setDiscriminator(Discriminator);
  629. DwarfLocSeen = true;
  630. }
  631. void clearDwarfLocSeen() { DwarfLocSeen = false; }
  632. bool getDwarfLocSeen() { return DwarfLocSeen; }
  633. const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
  634. bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
  635. void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
  636. unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
  637. EmitDwarfUnwindType emitDwarfUnwindInfo() const;
  638. void setGenDwarfFileNumber(unsigned FileNumber) {
  639. GenDwarfFileNumber = FileNumber;
  640. }
  641. /// Specifies information about the "root file" for assembler clients
  642. /// (e.g., llvm-mc). Assumes compilation dir etc. have been set up.
  643. void setGenDwarfRootFile(StringRef FileName, StringRef Buffer);
  644. const SetVector<MCSection *> &getGenDwarfSectionSyms() {
  645. return SectionsForRanges;
  646. }
  647. bool addGenDwarfSection(MCSection *Sec) {
  648. return SectionsForRanges.insert(Sec);
  649. }
  650. void finalizeDwarfSections(MCStreamer &MCOS);
  651. const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
  652. return MCGenDwarfLabelEntries;
  653. }
  654. void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
  655. MCGenDwarfLabelEntries.push_back(E);
  656. }
  657. void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
  658. StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
  659. void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
  660. StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
  661. void setDwarfFormat(dwarf::DwarfFormat f) { DwarfFormat = f; }
  662. dwarf::DwarfFormat getDwarfFormat() const { return DwarfFormat; }
  663. void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
  664. uint16_t getDwarfVersion() const { return DwarfVersion; }
  665. /// @}
  666. StringRef getSecureLogFile() { return SecureLogFile; }
  667. raw_fd_ostream *getSecureLog() { return SecureLog.get(); }
  668. void setSecureLog(std::unique_ptr<raw_fd_ostream> Value) {
  669. SecureLog = std::move(Value);
  670. }
  671. bool getSecureLogUsed() { return SecureLogUsed; }
  672. void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
  673. void *allocate(unsigned Size, unsigned Align = 8) {
  674. return Allocator.Allocate(Size, Align);
  675. }
  676. void deallocate(void *Ptr) {}
  677. bool hadError() { return HadError; }
  678. void diagnose(const SMDiagnostic &SMD);
  679. void reportError(SMLoc L, const Twine &Msg);
  680. void reportWarning(SMLoc L, const Twine &Msg);
  681. const MCAsmMacro *lookupMacro(StringRef Name) {
  682. StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
  683. return (I == MacroMap.end()) ? nullptr : &I->getValue();
  684. }
  685. void defineMacro(StringRef Name, MCAsmMacro Macro) {
  686. MacroMap.insert(std::make_pair(Name, std::move(Macro)));
  687. }
  688. void undefineMacro(StringRef Name) { MacroMap.erase(Name); }
  689. MCPseudoProbeTable &getMCPseudoProbeTable() { return PseudoProbeTable; }
  690. };
  691. } // end namespace llvm
  692. // operator new and delete aren't allowed inside namespaces.
  693. // The throw specifications are mandated by the standard.
  694. /// Placement new for using the MCContext's allocator.
  695. ///
  696. /// This placement form of operator new uses the MCContext's allocator for
  697. /// obtaining memory. It is a non-throwing new, which means that it returns
  698. /// null on error. (If that is what the allocator does. The current does, so if
  699. /// this ever changes, this operator will have to be changed, too.)
  700. /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
  701. /// \code
  702. /// // Default alignment (8)
  703. /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
  704. /// // Specific alignment
  705. /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
  706. /// \endcode
  707. /// Please note that you cannot use delete on the pointer; it must be
  708. /// deallocated using an explicit destructor call followed by
  709. /// \c Context.Deallocate(Ptr).
  710. ///
  711. /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
  712. /// \param C The MCContext that provides the allocator.
  713. /// \param Alignment The alignment of the allocated memory (if the underlying
  714. /// allocator supports it).
  715. /// \return The allocated memory. Could be NULL.
  716. inline void *operator new(size_t Bytes, llvm::MCContext &C,
  717. size_t Alignment = 8) noexcept {
  718. return C.allocate(Bytes, Alignment);
  719. }
  720. /// Placement delete companion to the new above.
  721. ///
  722. /// This operator is just a companion to the new above. There is no way of
  723. /// invoking it directly; see the new operator for more details. This operator
  724. /// is called implicitly by the compiler if a placement new expression using
  725. /// the MCContext throws in the object constructor.
  726. inline void operator delete(void *Ptr, llvm::MCContext &C, size_t) noexcept {
  727. C.deallocate(Ptr);
  728. }
  729. /// This placement form of operator new[] uses the MCContext's allocator for
  730. /// obtaining memory. It is a non-throwing new[], which means that it returns
  731. /// null on error.
  732. /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
  733. /// \code
  734. /// // Default alignment (8)
  735. /// char *data = new (Context) char[10];
  736. /// // Specific alignment
  737. /// char *data = new (Context, 4) char[10];
  738. /// \endcode
  739. /// Please note that you cannot use delete on the pointer; it must be
  740. /// deallocated using an explicit destructor call followed by
  741. /// \c Context.Deallocate(Ptr).
  742. ///
  743. /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
  744. /// \param C The MCContext that provides the allocator.
  745. /// \param Alignment The alignment of the allocated memory (if the underlying
  746. /// allocator supports it).
  747. /// \return The allocated memory. Could be NULL.
  748. inline void *operator new[](size_t Bytes, llvm::MCContext &C,
  749. size_t Alignment = 8) noexcept {
  750. return C.allocate(Bytes, Alignment);
  751. }
  752. /// Placement delete[] companion to the new[] above.
  753. ///
  754. /// This operator is just a companion to the new[] above. There is no way of
  755. /// invoking it directly; see the new[] operator for more details. This operator
  756. /// is called implicitly by the compiler if a placement new[] expression using
  757. /// the MCContext throws in the object constructor.
  758. inline void operator delete[](void *Ptr, llvm::MCContext &C) noexcept {
  759. C.deallocate(Ptr);
  760. }
  761. #endif // LLVM_MC_MCCONTEXT_H
  762. #ifdef __GNUC__
  763. #pragma GCC diagnostic pop
  764. #endif