MCContext.h 33 KB

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