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