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