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