1//===-- llvm/CodeGen/DwarfUnit.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_DWARFUNIT_H
14#define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFUNIT_H
15
16#include "DwarfDebug.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/CodeGen/AsmPrinter.h"
19#include "llvm/CodeGen/DIE.h"
20#include "llvm/IR/DebugInfoMetadata.h"
21#include "llvm/Target/TargetMachine.h"
22#include <optional>
23#include <string>
24
25namespace llvm {
26
27class ConstantFP;
28class ConstantInt;
29class DwarfCompileUnit;
30class MCDwarfDwoLineTable;
31class MCSymbol;
32
33//===----------------------------------------------------------------------===//
34/// This dwarf writer support class manages information associated with a
35/// source file.
36class DwarfUnit : public DIEUnit {
37protected:
38 /// A numeric ID unique among all CUs in the module
39 unsigned UniqueID;
40 /// MDNode for the compile unit.
41 const DICompileUnit *CUNode;
42
43 // All DIEValues are allocated through this allocator.
44 BumpPtrAllocator DIEValueAllocator;
45
46 /// Target of Dwarf emission.
47 AsmPrinter *Asm;
48
49 /// The start of the unit within its section.
50 MCSymbol *LabelBegin = nullptr;
51
52 /// Emitted at the end of the CU and used to compute the CU Length field.
53 MCSymbol *EndLabel = nullptr;
54
55 // Holders for some common dwarf information.
56 DwarfDebug *DD;
57 DwarfFile *DU;
58
59 /// An anonymous type for index type. Owned by DIEUnit.
60 DIE *IndexTyDie = nullptr;
61
62 /// Tracks the mapping of unit level debug information variables to debug
63 /// information entries.
64 DenseMap<const MDNode *, DIE *> MDNodeToDieMap;
65
66 /// A list of all the DIEBlocks in use.
67 std::vector<DIEBlock *> DIEBlocks;
68
69 /// A list of all the DIELocs in use.
70 std::vector<DIELoc *> DIELocs;
71
72 /// This map is used to keep track of subprogram DIEs that need
73 /// DW_AT_containing_type attribute. This attribute points to a DIE that
74 /// corresponds to the MDNode mapped with the subprogram DIE.
75 DenseMap<DIE *, const DINode *> ContainingTypeMap;
76 DenseMap<DIE *, const DINode *> PropertyForwardMap;
77
78 DwarfUnit(dwarf::Tag, const DICompileUnit *Node, AsmPrinter *A,
79 DwarfDebug *DW, DwarfFile *DWU, unsigned UniqueID = 0);
80
81 bool applySubprogramDefinitionAttributes(const DISubprogram *SP, DIE &SPDie, bool Minimal);
82
83 bool isShareableAcrossCUs(const DINode *D) const;
84
85 template <typename T>
86 void addAttribute(DIEValueList &Die, dwarf::Attribute Attribute,
87 dwarf::Form Form, T &&Value) {
88 // For strict DWARF mode, only generate attributes available to current
89 // DWARF version.
90 // Attribute 0 is used when emitting form-encoded values in blocks, which
91 // don't have attributes (only forms) so we cannot detect their DWARF
92 // version compatibility here and assume they are compatible.
93 if (Attribute != 0 && Asm->TM.Options.DebugStrictDwarf &&
94 DD->getDwarfVersion() < dwarf::AttributeVersion(A: Attribute))
95 return;
96
97 Die.addValue(Alloc&: DIEValueAllocator,
98 V: DIEValue(Attribute, Form, std::forward<T>(Value)));
99 }
100
101public:
102 /// Gets Unique ID for this unit.
103 unsigned getUniqueID() const { return UniqueID; }
104 // Accessors.
105 AsmPrinter* getAsmPrinter() const { return Asm; }
106 /// Get the the symbol for start of the section for this unit.
107 MCSymbol *getLabelBegin() const {
108 assert(LabelBegin && "LabelBegin is not initialized");
109 return LabelBegin;
110 }
111 MCSymbol *getEndLabel() const { return EndLabel; }
112 llvm::dwarf::SourceLanguage getSourceLanguage() const;
113 const DICompileUnit *getCUNode() const { return CUNode; }
114 DwarfDebug &getDwarfDebug() const { return *DD; }
115
116 /// Return true if this compile unit has something to write out.
117 bool hasContent() const { return getUnitDie().hasChildren(); }
118
119 /// Get string containing language specific context for a global name.
120 ///
121 /// Walks the metadata parent chain in a language specific manner (using the
122 /// compile unit language) and returns it as a string. This is done at the
123 /// metadata level because DIEs may not currently have been added to the
124 /// parent context and walking the DIEs looking for names is more expensive
125 /// than walking the metadata.
126 std::string getParentContextString(const DIScope *Context) const;
127
128 /// Add a new global name to the compile unit.
129 virtual void addGlobalName(StringRef Name, const DIE &Die,
130 const DIScope *Context) = 0;
131
132 /// Add a new global type to the compile unit.
133 virtual void addGlobalTypeImpl(const DIType *Ty, const DIE &Die,
134 const DIScope *Context) = 0;
135
136 void addGlobalType(const DIType *Ty, const DIE &Die, const DIScope *Context);
137
138 /// Returns the DIE map slot for the specified debug variable.
139 ///
140 /// We delegate the request to DwarfDebug when the MDNode can be part of the
141 /// type system, since DIEs for the type system can be shared across CUs and
142 /// the mappings are kept in DwarfDebug.
143 DIE *getDIE(const DINode *D) const;
144
145 /// Returns a fresh newly allocated DIELoc.
146 DIELoc *getDIELoc() { return new (DIEValueAllocator) DIELoc; }
147
148 /// Insert DIE into the map.
149 ///
150 /// We delegate the request to DwarfDebug when the MDNode can be part of the
151 /// type system, since DIEs for the type system can be shared across CUs and
152 /// the mappings are kept in DwarfDebug.
153 void insertDIE(const DINode *Desc, DIE *D);
154
155 void insertDIE(DIE *D);
156
157 /// Add a flag that is true to the DIE.
158 void addFlag(DIE &Die, dwarf::Attribute Attribute);
159
160 /// Add an unsigned integer attribute data and value.
161 void addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
162 std::optional<dwarf::Form> Form, uint64_t Integer);
163
164 void addUInt(DIEValueList &Block, dwarf::Form Form, uint64_t Integer);
165
166 /// Add an signed integer attribute data and value.
167 void addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
168 std::optional<dwarf::Form> Form, int64_t Integer);
169
170 void addSInt(DIEValueList &Die, std::optional<dwarf::Form> Form,
171 int64_t Integer);
172
173 /// Add an integer attribute data and value; value may be any width.
174 void addInt(DIE &Die, dwarf::Attribute Attribute, const APInt &Integer,
175 bool Unsigned);
176
177 /// Add a string attribute data and value.
178 ///
179 /// We always emit a reference to the string pool instead of immediate
180 /// strings so that DIEs have more predictable sizes. In the case of split
181 /// dwarf we emit an index into another table which gets us the static offset
182 /// into the string table.
183 void addString(DIE &Die, dwarf::Attribute Attribute, StringRef Str);
184
185 /// Add a Dwarf label attribute data and value.
186 void addLabel(DIEValueList &Die, dwarf::Attribute Attribute, dwarf::Form Form,
187 const MCSymbol *Label);
188
189 void addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label);
190
191 /// Add an offset into a section attribute data and value.
192 void addSectionOffset(DIE &Die, dwarf::Attribute Attribute, uint64_t Integer);
193
194 /// Add a dwarf op address data and value using the form given and an
195 /// op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
196 void addOpAddress(DIELoc &Die, const MCSymbol *Sym);
197 void addPoolOpAddress(DIEValueList &Die, const MCSymbol *Label);
198
199 /// Add a label delta attribute data and value.
200 void addLabelDelta(DIEValueList &Die, dwarf::Attribute Attribute,
201 const MCSymbol *Hi, const MCSymbol *Lo);
202
203 /// Add a DIE attribute data and value.
204 void addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry);
205
206 /// Add a DIE attribute data and value.
207 void addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIEEntry Entry);
208
209 /// Add a type's DW_AT_signature and set the declaration flag.
210 void addDIETypeSignature(DIE &Die, uint64_t Signature);
211
212 /// Add block data.
213 void addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc);
214
215 /// Add block data.
216 void addBlock(DIE &Die, dwarf::Attribute Attribute, DIEBlock *Block);
217 void addBlock(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
218 DIEBlock *Block);
219
220 /// Add an expression as block data.
221 void addBlock(DIE &Die, dwarf::Attribute Attribute, const DIExpression *Expr);
222
223 /// Add location information to specified debug information entry.
224 void addSourceLine(DIE &Die, unsigned Line, unsigned Column,
225 const DIFile *File);
226 void addSourceLine(DIE &Die, const DILocalVariable *V);
227 void addSourceLine(DIE &Die, const DIGlobalVariable *G);
228 void addSourceLine(DIE &Die, const DISubprogram *SP);
229 void addSourceLine(DIE &Die, const DILabel *L);
230 void addSourceLine(DIE &Die, const DIType *Ty);
231 void addSourceLine(DIE &Die, const DIObjCProperty *Ty);
232 void addSourceLine(DIE &Die, const DIProperty *P);
233
234 /// Add constant value entry in variable DIE.
235 void addConstantValue(DIE &Die, const ConstantInt *CI, const DIType *Ty);
236 void addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty);
237 void addConstantValue(DIE &Die, const APInt &Val, bool Unsigned);
238 void addConstantValue(DIE &Die, uint64_t Val, const DIType *Ty);
239 void addConstantValue(DIE &Die, bool Unsigned, uint64_t Val);
240
241 /// Add constant value entry in variable DIE.
242 void addConstantFPValue(DIE &Die, const ConstantFP *CFP);
243
244 /// Add a linkage name, if it isn't empty.
245 void addLinkageName(DIE &Die, StringRef LinkageName);
246
247 /// Add template parameters in buffer.
248 void addTemplateParams(DIE &Buffer, DINodeArray TParams);
249
250 /// Add thrown types.
251 void addThrownTypes(DIE &Die, DINodeArray ThrownTypes);
252
253 /// Add the accessibility attribute.
254 void addAccess(DIE &Die, DINode::DIFlags Flags);
255
256 /// Add a new type attribute to the specified entity.
257 ///
258 /// This takes and attribute parameter because DW_AT_friend attributes are
259 /// also type references.
260 void addType(DIE &Entity, const DIType *Ty,
261 dwarf::Attribute Attribute = dwarf::DW_AT_type);
262
263 DIE *getOrCreateNameSpace(const DINamespace *NS);
264 DIE *getOrCreateModule(const DIModule *M);
265 virtual DIE *getOrCreateSubprogramDIE(const DISubprogram *SP,
266 const Function *FnHint,
267 bool Minimal = false);
268
269 void applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
270 bool SkipSPAttributes = false);
271
272 /// Creates type DIE with specific context.
273 DIE *createTypeDIE(const DIScope *Context, DIE &ContextDIE, const DIType *Ty);
274
275 /// Find existing DIE or create new DIE for the given type.
276 virtual DIE *getOrCreateTypeDIE(const MDNode *TyNode);
277
278 /// Get context owner's DIE.
279 virtual DIE *getOrCreateContextDIE(const DIScope *Context);
280
281 /// Construct DIEs for types that contain vtables.
282 void constructContainingTypeDIEs();
283
284 void constructPropertyForwardDIEs();
285
286 /// Construct function argument DIEs.
287 ///
288 /// \returns The index of the object parameter in \c Args if one exists.
289 /// Returns std::nullopt otherwise.
290 std::optional<unsigned> constructSubprogramArguments(DIE &Buffer,
291 DITypeArray Args);
292
293 /// Create a DIE with the given Tag, add the DIE to its parent, and
294 /// call insertDIE if MD is not null.
295 DIE &createAndAddDIE(dwarf::Tag Tag, DIE &Parent, const DINode *N = nullptr);
296
297 bool useSegmentedStringOffsetsTable() const {
298 return DD->useSegmentedStringOffsetsTable();
299 }
300
301 /// Compute the size of a header for this unit, not including the initial
302 /// length field.
303 virtual unsigned getHeaderSize() const {
304 return sizeof(int16_t) + // DWARF version number
305 Asm->getDwarfOffsetByteSize() + // Offset Into Abbrev. Section
306 sizeof(int8_t) + // Pointer Size (in bytes)
307 (DD->getDwarfVersion() >= 5 ? sizeof(int8_t)
308 : 0); // DWARF v5 unit type
309 }
310
311 /// Emit the header for this unit, not including the initial length field.
312 virtual void emitHeader(bool UseOffsets) = 0;
313
314 /// Add the DW_AT_str_offsets_base attribute to the unit DIE.
315 void addStringOffsetsStart();
316
317 /// Add the DW_AT_rnglists_base attribute to the unit DIE.
318 void addRnglistsBase();
319
320 virtual DwarfCompileUnit &getCU() = 0;
321
322 void constructTypeDIE(DIE &Buffer, const DICompositeType *CTy);
323
324 /// Add a Dwarf section label attribute data and value. If the current unit
325 /// is a DWO, this function will instead emit a section delta.
326 void addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
327 const MCSymbol *Label, const MCSymbol *Sec);
328
329 /// Add DW_TAG_LLVM_annotation.
330 void addAnnotation(DIE &Buffer, DINodeArray Annotations);
331
332 /// Get context owner's DIE.
333 DIE *createTypeDIE(const DICompositeType *Ty);
334
335 /// If this is a named finished type then include it in the list of types for
336 /// the accelerator tables.
337 void updateAcceleratorTables(const DIScope *Context, const DIType *Ty,
338 const DIE &TyDIE);
339
340protected:
341 ~DwarfUnit() override;
342
343 /// Create new static data member DIE.
344 DIE *getOrCreateStaticMemberDIE(const DIDerivedType *DT);
345
346 /// Look up the source ID for the given file. If none currently exists,
347 /// create a new ID and insert it in the line table.
348 virtual unsigned getOrCreateSourceID(const DIFile *File) = 0;
349
350 /// Emit the common part of the header for this unit.
351 void emitCommonHeader(bool UseOffsets, dwarf::UnitType UT);
352
353 bool shouldPlaceInUnitDIE(const DISubprogram *SP, bool Minimal) {
354 // Add subprogram definitions to the CU die directly.
355 return Minimal || SP->getDeclaration();
356 }
357
358 DIE *getOrCreateSubprogramContextDIE(const DISubprogram *SP,
359 bool IgnoreScope) {
360 if (IgnoreScope)
361 return &getUnitDie();
362 return getOrCreateContextDIE(Context: SP->getScope());
363 }
364
365private:
366 DISourceLanguageName getLanguage() const {
367 return CUNode->getSourceLanguage();
368 }
369
370 /// Emit the bytes of an APInt value into an existing DIEBlock,
371 /// respecting target endianness.
372 void addIntToBlock(DIEBlock &Block, const APInt &Val);
373
374 /// A helper to add a wide integer constant to a DIE using a block
375 /// form.
376 void addIntAsBlock(DIE &Die, dwarf::Attribute Attribute, const APInt &Val);
377
378 // Add discriminant constants to a DW_TAG_variant DIE.
379 void addDiscriminant(DIE &Variant, Constant *Discriminant, bool IsUnsigned);
380
381 void constructTypeDIE(DIE &Buffer, const DIBasicType *BTy);
382 void constructTypeDIE(DIE &Buffer, const DIFixedPointType *BTy);
383 void constructTypeDIE(DIE &Buffer, const DIStringType *BTy);
384 void constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy);
385 void constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy);
386 void constructSubrangeDIE(DIE &Buffer, const DISubrangeType *SR,
387 bool ForArray = false);
388 void constructSubrangeDIE(DIE &Buffer, const DISubrange *SR);
389 void constructGenericSubrangeDIE(DIE &Buffer, const DIGenericSubrange *SR);
390 void constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy);
391 void constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy);
392 DIE &constructMemberDIE(DIE &Buffer, const DIDerivedType *DT);
393 void constructPropertyDIE(DIE &Buffer, const DIProperty *P);
394 void constructTemplateTypeParameterDIE(DIE &Buffer,
395 const DITemplateTypeParameter *TP);
396 void constructTemplateValueParameterDIE(DIE &Buffer,
397 const DITemplateValueParameter *TVP);
398
399 /// Return the default lower bound for an array.
400 ///
401 /// If the DWARF version doesn't handle the language, return -1.
402 int64_t getDefaultLowerBound() const;
403
404 /// Get an anonymous type for index type.
405 DIE *getIndexTyDie();
406
407 /// Set D as anonymous type for index which can be reused later.
408 void setIndexTyDie(DIE *D) { IndexTyDie = D; }
409
410 virtual void finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) = 0;
411
412 virtual bool isDwoUnit() const = 0;
413 const MCSymbol *getCrossSectionRelativeBaseAddress() const override;
414
415 /// Returns 'true' if the current DwarfVersion is compatible
416 /// with the specified \p Version.
417 bool isCompatibleWithVersion(uint16_t Version) const;
418
419 /// addSectionDelta - Add a label delta attribute data and value.
420 void addSectionDelta(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Hi,
421 const MCSymbol *Lo);
422};
423
424class DwarfTypeUnit final : public DwarfUnit {
425 uint64_t TypeSignature;
426 const DIE *Ty;
427 DwarfCompileUnit &CU;
428 MCDwarfDwoLineTable *SplitLineTable;
429 bool UsedLineTable = false;
430
431 unsigned getOrCreateSourceID(const DIFile *File) override;
432 void finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) override;
433 bool isDwoUnit() const override;
434
435public:
436 DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A, DwarfDebug *DW,
437 DwarfFile *DWU, unsigned UniqueID,
438 MCDwarfDwoLineTable *SplitLineTable = nullptr);
439
440 void setTypeSignature(uint64_t Signature) { TypeSignature = Signature; }
441 /// Returns Type Signature.
442 uint64_t getTypeSignature() const { return TypeSignature; }
443 void setType(const DIE *Ty) { this->Ty = Ty; }
444
445 /// Emit the header for this unit, not including the initial length field.
446 void emitHeader(bool UseOffsets) override;
447 unsigned getHeaderSize() const override {
448 return DwarfUnit::getHeaderSize() + sizeof(uint64_t) + // Type Signature
449 Asm->getDwarfOffsetByteSize(); // Type DIE Offset
450 }
451 void addGlobalName(StringRef Name, const DIE &Die,
452 const DIScope *Context) override;
453 void addGlobalTypeImpl(const DIType *Ty, const DIE &Die,
454 const DIScope *Context) override;
455 DwarfCompileUnit &getCU() override { return CU; }
456};
457} // end llvm namespace
458#endif
459