DwarfExpression.h 15 KB

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