DwarfExpression.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //===- llvm/CodeGen/DwarfExpression.h - Dwarf Compile Unit ------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for writing dwarf compile unit.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFEXPRESSION_H
  13. #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFEXPRESSION_H
  14. #include "ByteStreamer.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/IR/DebugInfoMetadata.h"
  18. #include <cassert>
  19. #include <cstdint>
  20. #include <iterator>
  21. #include <optional>
  22. namespace llvm {
  23. class AsmPrinter;
  24. class APInt;
  25. class DwarfCompileUnit;
  26. class DIELoc;
  27. class TargetRegisterInfo;
  28. class MachineLocation;
  29. /// Holds a DIExpression and keeps track of how many operands have been consumed
  30. /// so far.
  31. class DIExpressionCursor {
  32. DIExpression::expr_op_iterator Start, End;
  33. public:
  34. DIExpressionCursor(const DIExpression *Expr) {
  35. if (!Expr) {
  36. assert(Start == End);
  37. return;
  38. }
  39. Start = Expr->expr_op_begin();
  40. End = Expr->expr_op_end();
  41. }
  42. DIExpressionCursor(ArrayRef<uint64_t> Expr)
  43. : Start(Expr.begin()), End(Expr.end()) {}
  44. DIExpressionCursor(const DIExpressionCursor &) = default;
  45. /// Consume one operation.
  46. std::optional<DIExpression::ExprOperand> take() {
  47. if (Start == End)
  48. return std::nullopt;
  49. return *(Start++);
  50. }
  51. /// Consume N operations.
  52. void consume(unsigned N) { std::advance(Start, N); }
  53. /// Return the current operation.
  54. std::optional<DIExpression::ExprOperand> peek() const {
  55. if (Start == End)
  56. return std::nullopt;
  57. return *(Start);
  58. }
  59. /// Return the next operation.
  60. std::optional<DIExpression::ExprOperand> peekNext() const {
  61. if (Start == End)
  62. return std::nullopt;
  63. auto Next = Start.getNext();
  64. if (Next == End)
  65. return std::nullopt;
  66. return *Next;
  67. }
  68. /// Determine whether there are any operations left in this expression.
  69. operator bool() const { return Start != End; }
  70. DIExpression::expr_op_iterator begin() const { return Start; }
  71. DIExpression::expr_op_iterator end() const { return End; }
  72. /// Retrieve the fragment information, if any.
  73. std::optional<DIExpression::FragmentInfo> getFragmentInfo() const {
  74. return DIExpression::getFragmentInfo(Start, End);
  75. }
  76. };
  77. /// Base class containing the logic for constructing DWARF expressions
  78. /// independently of whether they are emitted into a DIE or into a .debug_loc
  79. /// entry.
  80. ///
  81. /// Some DWARF operations, e.g. DW_OP_entry_value, need to calculate the size
  82. /// of a succeeding DWARF block before the latter is emitted to the output.
  83. /// To handle such cases, data can conditionally be emitted to a temporary
  84. /// buffer, which can later on be committed to the main output. The size of the
  85. /// temporary buffer is queryable, allowing for the size of the data to be
  86. /// emitted before the data is committed.
  87. class DwarfExpression {
  88. protected:
  89. /// Holds information about all subregisters comprising a register location.
  90. struct Register {
  91. int DwarfRegNo;
  92. unsigned SubRegSize;
  93. const char *Comment;
  94. /// Create a full register, no extra DW_OP_piece operators necessary.
  95. static Register createRegister(int RegNo, const char *Comment) {
  96. return {RegNo, 0, Comment};
  97. }
  98. /// Create a subregister that needs a DW_OP_piece operator with SizeInBits.
  99. static Register createSubRegister(int RegNo, unsigned SizeInBits,
  100. const char *Comment) {
  101. return {RegNo, SizeInBits, Comment};
  102. }
  103. bool isSubRegister() const { return SubRegSize; }
  104. };
  105. /// Whether we are currently emitting an entry value operation.
  106. bool IsEmittingEntryValue = false;
  107. DwarfCompileUnit &CU;
  108. /// The register location, if any.
  109. SmallVector<Register, 2> DwarfRegs;
  110. /// Current Fragment Offset in Bits.
  111. uint64_t OffsetInBits = 0;
  112. /// Sometimes we need to add a DW_OP_bit_piece to describe a subregister.
  113. unsigned SubRegisterSizeInBits : 16;
  114. unsigned SubRegisterOffsetInBits : 16;
  115. /// The kind of location description being produced.
  116. enum { Unknown = 0, Register, Memory, Implicit };
  117. /// Additional location flags which may be combined with any location kind.
  118. /// Currently, entry values are not supported for the Memory location kind.
  119. enum { EntryValue = 1 << 0, Indirect = 1 << 1, CallSiteParamValue = 1 << 2 };
  120. unsigned LocationKind : 3;
  121. unsigned SavedLocationKind : 3;
  122. unsigned LocationFlags : 3;
  123. unsigned DwarfVersion : 4;
  124. public:
  125. /// Set the location (\p Loc) and \ref DIExpression (\p DIExpr) to describe.
  126. void setLocation(const MachineLocation &Loc, const DIExpression *DIExpr);
  127. bool isUnknownLocation() const { return LocationKind == Unknown; }
  128. bool isMemoryLocation() const { return LocationKind == Memory; }
  129. bool isRegisterLocation() const { return LocationKind == Register; }
  130. bool isImplicitLocation() const { return LocationKind == Implicit; }
  131. bool isEntryValue() const { return LocationFlags & EntryValue; }
  132. bool isIndirect() const { return LocationFlags & Indirect; }
  133. bool isParameterValue() { return LocationFlags & CallSiteParamValue; }
  134. std::optional<uint8_t> TagOffset;
  135. protected:
  136. /// Push a DW_OP_piece / DW_OP_bit_piece for emitting later, if one is needed
  137. /// to represent a subregister.
  138. void setSubRegisterPiece(unsigned SizeInBits, unsigned OffsetInBits) {
  139. assert(SizeInBits < 65536 && OffsetInBits < 65536);
  140. SubRegisterSizeInBits = SizeInBits;
  141. SubRegisterOffsetInBits = OffsetInBits;
  142. }
  143. /// Add masking operations to stencil out a subregister.
  144. void maskSubRegister();
  145. /// Output a dwarf operand and an optional assembler comment.
  146. virtual void emitOp(uint8_t Op, const char *Comment = nullptr) = 0;
  147. /// Emit a raw signed value.
  148. virtual void emitSigned(int64_t Value) = 0;
  149. /// Emit a raw unsigned value.
  150. virtual void emitUnsigned(uint64_t Value) = 0;
  151. virtual void emitData1(uint8_t Value) = 0;
  152. virtual void emitBaseTypeRef(uint64_t Idx) = 0;
  153. /// Start emitting data to the temporary buffer. The data stored in the
  154. /// temporary buffer can be committed to the main output using
  155. /// commitTemporaryBuffer().
  156. virtual void enableTemporaryBuffer() = 0;
  157. /// Disable emission to the temporary buffer. This does not commit data
  158. /// in the temporary buffer to the main output.
  159. virtual void disableTemporaryBuffer() = 0;
  160. /// Return the emitted size, in number of bytes, for the data stored in the
  161. /// temporary buffer.
  162. virtual unsigned getTemporaryBufferSize() = 0;
  163. /// Commit the data stored in the temporary buffer to the main output.
  164. virtual void commitTemporaryBuffer() = 0;
  165. /// Emit a normalized unsigned constant.
  166. void emitConstu(uint64_t Value);
  167. /// Return whether the given machine register is the frame register in the
  168. /// current function.
  169. virtual bool isFrameRegister(const TargetRegisterInfo &TRI,
  170. llvm::Register MachineReg) = 0;
  171. /// Emit a DW_OP_reg operation. Note that this is only legal inside a DWARF
  172. /// register location description.
  173. void addReg(int DwarfReg, const char *Comment = nullptr);
  174. /// Emit a DW_OP_breg operation.
  175. void addBReg(int DwarfReg, int Offset);
  176. /// Emit DW_OP_fbreg <Offset>.
  177. void addFBReg(int Offset);
  178. /// Emit a partial DWARF register operation.
  179. ///
  180. /// \param MachineReg The register number.
  181. /// \param MaxSize If the register must be composed from
  182. /// sub-registers this is an upper bound
  183. /// for how many bits the emitted DW_OP_piece
  184. /// may cover.
  185. ///
  186. /// If size and offset is zero an operation for the entire register is
  187. /// emitted: Some targets do not provide a DWARF register number for every
  188. /// register. If this is the case, this function will attempt to emit a DWARF
  189. /// register by emitting a fragment of a super-register or by piecing together
  190. /// multiple subregisters that alias the register.
  191. ///
  192. /// \return false if no DWARF register exists for MachineReg.
  193. bool addMachineReg(const TargetRegisterInfo &TRI, llvm::Register MachineReg,
  194. unsigned MaxSize = ~1U);
  195. /// Emit a DW_OP_piece or DW_OP_bit_piece operation for a variable fragment.
  196. /// \param OffsetInBits This is an optional offset into the location that
  197. /// is at the top of the DWARF stack.
  198. void addOpPiece(unsigned SizeInBits, unsigned OffsetInBits = 0);
  199. /// Emit a shift-right dwarf operation.
  200. void addShr(unsigned ShiftBy);
  201. /// Emit a bitwise and dwarf operation.
  202. void addAnd(unsigned Mask);
  203. /// Emit a DW_OP_stack_value, if supported.
  204. ///
  205. /// The proper way to describe a constant value is DW_OP_constu <const>,
  206. /// DW_OP_stack_value. Unfortunately, DW_OP_stack_value was not available
  207. /// until DWARF 4, so we will continue to generate DW_OP_constu <const> for
  208. /// DWARF 2 and DWARF 3. Technically, this is incorrect since DW_OP_const
  209. /// <const> actually describes a value at a constant address, not a constant
  210. /// value. However, in the past there was no better way to describe a
  211. /// constant value, so the producers and consumers started to rely on
  212. /// heuristics to disambiguate the value vs. location status of the
  213. /// expression. See PR21176 for more details.
  214. void addStackValue();
  215. /// Finalize an entry value by emitting its size operand, and committing the
  216. /// DWARF block which has been emitted to the temporary buffer.
  217. void finalizeEntryValue();
  218. /// Cancel the emission of an entry value.
  219. void cancelEntryValue();
  220. ~DwarfExpression() = default;
  221. public:
  222. DwarfExpression(unsigned DwarfVersion, DwarfCompileUnit &CU)
  223. : CU(CU), SubRegisterSizeInBits(0), SubRegisterOffsetInBits(0),
  224. LocationKind(Unknown), SavedLocationKind(Unknown),
  225. LocationFlags(Unknown), DwarfVersion(DwarfVersion) {}
  226. /// This needs to be called last to commit any pending changes.
  227. void finalize();
  228. /// Emit a signed constant.
  229. void addSignedConstant(int64_t Value);
  230. /// Emit an unsigned constant.
  231. void addUnsignedConstant(uint64_t Value);
  232. /// Emit an unsigned constant.
  233. void addUnsignedConstant(const APInt &Value);
  234. /// Emit an floating point constant.
  235. void addConstantFP(const APFloat &Value, const AsmPrinter &AP);
  236. /// Lock this down to become a memory location description.
  237. void setMemoryLocationKind() {
  238. assert(isUnknownLocation());
  239. LocationKind = Memory;
  240. }
  241. /// Lock this down to become an entry value location.
  242. void setEntryValueFlags(const MachineLocation &Loc);
  243. /// Lock this down to become a call site parameter location.
  244. void setCallSiteParamValueFlag() { LocationFlags |= CallSiteParamValue; }
  245. /// Emit a machine register location. As an optimization this may also consume
  246. /// the prefix of a DwarfExpression if a more efficient representation for
  247. /// combining the register location and the first operation exists.
  248. ///
  249. /// \param FragmentOffsetInBits If this is one fragment out of a
  250. /// fragmented
  251. /// location, this is the offset of the
  252. /// fragment inside the entire variable.
  253. /// \return false if no DWARF register exists
  254. /// for MachineReg.
  255. bool addMachineRegExpression(const TargetRegisterInfo &TRI,
  256. DIExpressionCursor &Expr,
  257. llvm::Register MachineReg,
  258. unsigned FragmentOffsetInBits = 0);
  259. /// Begin emission of an entry value dwarf operation. The entry value's
  260. /// first operand is the size of the DWARF block (its second operand),
  261. /// which needs to be calculated at time of emission, so we don't emit
  262. /// any operands here.
  263. void beginEntryValueExpression(DIExpressionCursor &ExprCursor);
  264. /// Return the index of a base type with the given properties and
  265. /// create one if necessary.
  266. unsigned getOrCreateBaseType(unsigned BitSize, dwarf::TypeKind Encoding);
  267. /// Emit all remaining operations in the DIExpressionCursor. The
  268. /// cursor must not contain any DW_OP_LLVM_arg operations.
  269. void addExpression(DIExpressionCursor &&Expr);
  270. /// Emit all remaining operations in the DIExpressionCursor.
  271. /// DW_OP_LLVM_arg operations are resolved by calling (\p InsertArg).
  272. //
  273. /// \return false if any call to (\p InsertArg) returns false.
  274. bool addExpression(
  275. DIExpressionCursor &&Expr,
  276. llvm::function_ref<bool(unsigned, DIExpressionCursor &)> InsertArg);
  277. /// If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to
  278. /// the fragment described by \c Expr.
  279. void addFragmentOffset(const DIExpression *Expr);
  280. void emitLegacySExt(unsigned FromBits);
  281. void emitLegacyZExt(unsigned FromBits);
  282. /// Emit location information expressed via WebAssembly location + offset
  283. /// The Index is an identifier for locals, globals or operand stack.
  284. void addWasmLocation(unsigned Index, uint64_t Offset);
  285. };
  286. /// DwarfExpression implementation for .debug_loc entries.
  287. class DebugLocDwarfExpression final : public DwarfExpression {
  288. struct TempBuffer {
  289. SmallString<32> Bytes;
  290. std::vector<std::string> Comments;
  291. BufferByteStreamer BS;
  292. TempBuffer(bool GenerateComments) : BS(Bytes, Comments, GenerateComments) {}
  293. };
  294. std::unique_ptr<TempBuffer> TmpBuf;
  295. BufferByteStreamer &OutBS;
  296. bool IsBuffering = false;
  297. /// Return the byte streamer that currently is being emitted to.
  298. ByteStreamer &getActiveStreamer() { return IsBuffering ? TmpBuf->BS : OutBS; }
  299. void emitOp(uint8_t Op, const char *Comment = nullptr) override;
  300. void emitSigned(int64_t Value) override;
  301. void emitUnsigned(uint64_t Value) override;
  302. void emitData1(uint8_t Value) override;
  303. void emitBaseTypeRef(uint64_t Idx) override;
  304. void enableTemporaryBuffer() override;
  305. void disableTemporaryBuffer() override;
  306. unsigned getTemporaryBufferSize() override;
  307. void commitTemporaryBuffer() override;
  308. bool isFrameRegister(const TargetRegisterInfo &TRI,
  309. llvm::Register MachineReg) override;
  310. public:
  311. DebugLocDwarfExpression(unsigned DwarfVersion, BufferByteStreamer &BS,
  312. DwarfCompileUnit &CU)
  313. : DwarfExpression(DwarfVersion, CU), OutBS(BS) {}
  314. };
  315. /// DwarfExpression implementation for singular DW_AT_location.
  316. class DIEDwarfExpression final : public DwarfExpression {
  317. const AsmPrinter &AP;
  318. DIELoc &OutDIE;
  319. DIELoc TmpDIE;
  320. bool IsBuffering = false;
  321. /// Return the DIE that currently is being emitted to.
  322. DIELoc &getActiveDIE() { return IsBuffering ? TmpDIE : OutDIE; }
  323. void emitOp(uint8_t Op, const char *Comment = nullptr) override;
  324. void emitSigned(int64_t Value) override;
  325. void emitUnsigned(uint64_t Value) override;
  326. void emitData1(uint8_t Value) override;
  327. void emitBaseTypeRef(uint64_t Idx) override;
  328. void enableTemporaryBuffer() override;
  329. void disableTemporaryBuffer() override;
  330. unsigned getTemporaryBufferSize() override;
  331. void commitTemporaryBuffer() override;
  332. bool isFrameRegister(const TargetRegisterInfo &TRI,
  333. llvm::Register MachineReg) override;
  334. public:
  335. DIEDwarfExpression(const AsmPrinter &AP, DwarfCompileUnit &CU, DIELoc &DIE);
  336. DIELoc *finalize() {
  337. DwarfExpression::finalize();
  338. return &OutDIE;
  339. }
  340. };
  341. } // end namespace llvm
  342. #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFEXPRESSION_H