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