1 //===-- llvm/CodeGen/DwarfUnit.h - Dwarf Compile Unit ---*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf compile unit.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFUNIT_H
15 #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFUNIT_H
16 
17 #include "DwarfDebug.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/DIE.h"
23 #include "llvm/IR/DIBuilder.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/MC/MCDwarf.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCSection.h"
28 
29 namespace llvm {
30 
31 class MachineLocation;
32 class MachineOperand;
33 class ConstantInt;
34 class ConstantFP;
35 class DbgVariable;
36 class DwarfCompileUnit;
37 
38 //===----------------------------------------------------------------------===//
39 /// This dwarf writer support class manages information associated with a
40 /// source file.
41 class DwarfUnit : public DIEUnit {
42 protected:
43   /// MDNode for the compile unit.
44   const DICompileUnit *CUNode;
45 
46   // All DIEValues are allocated through this allocator.
47   BumpPtrAllocator DIEValueAllocator;
48 
49   /// Target of Dwarf emission.
50   AsmPrinter *Asm;
51 
52   // Holders for some common dwarf information.
53   DwarfDebug *DD;
54   DwarfFile *DU;
55 
56   /// An anonymous type for index type.  Owned by DIEUnit.
57   DIE *IndexTyDie;
58 
59   /// Tracks the mapping of unit level debug information variables to debug
60   /// information entries.
61   DenseMap<const MDNode *, DIE *> MDNodeToDieMap;
62 
63   /// A list of all the DIEBlocks in use.
64   std::vector<DIEBlock *> DIEBlocks;
65 
66   /// A list of all the DIELocs in use.
67   std::vector<DIELoc *> DIELocs;
68 
69   /// This map is used to keep track of subprogram DIEs that need
70   /// DW_AT_containing_type attribute. This attribute points to a DIE that
71   /// corresponds to the MDNode mapped with the subprogram DIE.
72   DenseMap<DIE *, const DINode *> ContainingTypeMap;
73 
74   DwarfUnit(dwarf::Tag, const DICompileUnit *Node, AsmPrinter *A, DwarfDebug *DW,
75             DwarfFile *DWU);
76 
77   bool applySubprogramDefinitionAttributes(const DISubprogram *SP, DIE &SPDie);
78 
79   bool shareAcrossDWOCUs() const;
80   bool isShareableAcrossCUs(const DINode *D) const;
81 
82 public:
83   // Accessors.
84   AsmPrinter* getAsmPrinter() const { return Asm; }
85   uint16_t getLanguage() const { return CUNode->getSourceLanguage(); }
86   const DICompileUnit *getCUNode() const { return CUNode; }
87 
88   uint16_t getDwarfVersion() const { return DD->getDwarfVersion(); }
89 
90   /// Return true if this compile unit has something to write out.
91   bool hasContent() const { return getUnitDie().hasChildren(); }
92 
93   /// Get string containing language specific context for a global name.
94   ///
95   /// Walks the metadata parent chain in a language specific manner (using the
96   /// compile unit language) and returns it as a string. This is done at the
97   /// metadata level because DIEs may not currently have been added to the
98   /// parent context and walking the DIEs looking for names is more expensive
99   /// than walking the metadata.
100   std::string getParentContextString(const DIScope *Context) const;
101 
102   /// Add a new global name to the compile unit.
103   virtual void addGlobalName(StringRef Name, const DIE &Die,
104                              const DIScope *Context) = 0;
105 
106   /// Add a new global type to the compile unit.
107   virtual void addGlobalType(const DIType *Ty, const DIE &Die,
108                              const DIScope *Context) = 0;
109 
110   /// Returns the DIE map slot for the specified debug variable.
111   ///
112   /// We delegate the request to DwarfDebug when the MDNode can be part of the
113   /// type system, since DIEs for the type system can be shared across CUs and
114   /// the mappings are kept in DwarfDebug.
115   DIE *getDIE(const DINode *D) const;
116 
117   /// Returns a fresh newly allocated DIELoc.
118   DIELoc *getDIELoc() { return new (DIEValueAllocator) DIELoc; }
119 
120   /// Insert DIE into the map.
121   ///
122   /// We delegate the request to DwarfDebug when the MDNode can be part of the
123   /// type system, since DIEs for the type system can be shared across CUs and
124   /// the mappings are kept in DwarfDebug.
125   void insertDIE(const DINode *Desc, DIE *D);
126 
127   /// Add a flag that is true to the DIE.
128   void addFlag(DIE &Die, dwarf::Attribute Attribute);
129 
130   /// Add an unsigned integer attribute data and value.
131   void addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
132                Optional<dwarf::Form> Form, uint64_t Integer);
133 
134   void addUInt(DIEValueList &Block, dwarf::Form Form, uint64_t Integer);
135 
136   /// Add an signed integer attribute data and value.
137   void addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
138                Optional<dwarf::Form> Form, int64_t Integer);
139 
140   void addSInt(DIELoc &Die, Optional<dwarf::Form> Form, int64_t Integer);
141 
142   /// Add a string attribute data and value.
143   ///
144   /// We always emit a reference to the string pool instead of immediate
145   /// strings so that DIEs have more predictable sizes. In the case of split
146   /// dwarf we emit an index into another table which gets us the static offset
147   /// into the string table.
148   void addString(DIE &Die, dwarf::Attribute Attribute, StringRef Str);
149 
150   /// Add a Dwarf label attribute data and value.
151   DIEValueList::value_iterator addLabel(DIEValueList &Die,
152                                         dwarf::Attribute Attribute,
153                                         dwarf::Form Form,
154                                         const MCSymbol *Label);
155 
156   void addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label);
157 
158   /// Add an offset into a section attribute data and value.
159   void addSectionOffset(DIE &Die, dwarf::Attribute Attribute, uint64_t Integer);
160 
161   /// Add a dwarf op address data and value using the form given and an
162   /// op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
163   void addOpAddress(DIELoc &Die, const MCSymbol *Sym);
164 
165   /// Add a label delta attribute data and value.
166   void addLabelDelta(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Hi,
167                      const MCSymbol *Lo);
168 
169   /// Add a DIE attribute data and value.
170   void addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry);
171 
172   /// Add a DIE attribute data and value.
173   void addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIEEntry Entry);
174 
175   /// Add a type's DW_AT_signature and set the  declaration flag.
176   void addDIETypeSignature(DIE &Die, uint64_t Signature);
177 
178   /// Add block data.
179   void addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc);
180 
181   /// Add block data.
182   void addBlock(DIE &Die, dwarf::Attribute Attribute, DIEBlock *Block);
183 
184   /// Add location information to specified debug information entry.
185   void addSourceLine(DIE &Die, unsigned Line, const DIFile *File);
186   void addSourceLine(DIE &Die, const DILocalVariable *V);
187   void addSourceLine(DIE &Die, const DIGlobalVariable *G);
188   void addSourceLine(DIE &Die, const DISubprogram *SP);
189   void addSourceLine(DIE &Die, const DILabel *L);
190   void addSourceLine(DIE &Die, const DIType *Ty);
191   void addSourceLine(DIE &Die, const DIObjCProperty *Ty);
192 
193   /// Add constant value entry in variable DIE.
194   void addConstantValue(DIE &Die, const MachineOperand &MO, const DIType *Ty);
195   void addConstantValue(DIE &Die, const ConstantInt *CI, const DIType *Ty);
196   void addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty);
197   void addConstantValue(DIE &Die, const APInt &Val, bool Unsigned);
198   void addConstantValue(DIE &Die, bool Unsigned, uint64_t Val);
199 
200   /// Add constant value entry in variable DIE.
201   void addConstantFPValue(DIE &Die, const MachineOperand &MO);
202   void addConstantFPValue(DIE &Die, const ConstantFP *CFP);
203 
204   /// Add a linkage name, if it isn't empty.
205   void addLinkageName(DIE &Die, StringRef LinkageName);
206 
207   /// Add template parameters in buffer.
208   void addTemplateParams(DIE &Buffer, DINodeArray TParams);
209 
210   /// Add thrown types.
211   void addThrownTypes(DIE &Die, DINodeArray ThrownTypes);
212 
213   // FIXME: Should be reformulated in terms of addComplexAddress.
214   /// Start with the address based on the location provided, and generate the
215   /// DWARF information necessary to find the actual Block variable (navigating
216   /// the Block struct) based on the starting location.  Add the DWARF
217   /// information to the die.  Obsolete, please use addComplexAddress instead.
218   void addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
219                             dwarf::Attribute Attribute,
220                             const MachineLocation &Location);
221 
222   /// Add a new type attribute to the specified entity.
223   ///
224   /// This takes and attribute parameter because DW_AT_friend attributes are
225   /// also type references.
226   void addType(DIE &Entity, const DIType *Ty,
227                dwarf::Attribute Attribute = dwarf::DW_AT_type);
228 
229   DIE *getOrCreateNameSpace(const DINamespace *NS);
230   DIE *getOrCreateModule(const DIModule *M);
231   DIE *getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal = false);
232 
233   void applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
234                                  bool SkipSPAttributes = false);
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            sizeof(int32_t) + // 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   /// Add the DW_AT_loclists_base attribute to the unit DIE.
276   void addLoclistsBase();
277 
278   /// Add the DW_AT_addr_base attribute to the unit DIE.
279   void addAddrTableBase();
280 
281   virtual DwarfCompileUnit &getCU() = 0;
282 
283   void constructTypeDIE(DIE &Buffer, const DICompositeType *CTy);
284 
285   /// addSectionDelta - Add a label delta attribute data and value.
286   DIE::value_iterator addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
287                                       const MCSymbol *Hi, const MCSymbol *Lo);
288 
289   /// Add a Dwarf section label attribute data and value.
290   DIE::value_iterator addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
291                                       const MCSymbol *Label,
292                                       const MCSymbol *Sec);
293 
294   /// If the \p File has an MD5 checksum, return it as an MD5Result
295   /// allocated in the MCContext.
296   MD5::MD5Result *getMD5AsBytes(const DIFile *File) const;
297 
298 protected:
299   ~DwarfUnit();
300 
301   /// Create new static data member DIE.
302   DIE *getOrCreateStaticMemberDIE(const DIDerivedType *DT);
303 
304   /// Look up the source ID for the given file. If none currently exists,
305   /// create a new ID and insert it in the line table.
306   virtual unsigned getOrCreateSourceID(const DIFile *File) = 0;
307 
308   /// Look in the DwarfDebug map for the MDNode that corresponds to the
309   /// reference.
310   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
311     return Ref.resolve();
312   }
313 
314   /// If this is a named finished type then include it in the list of types for
315   /// the accelerator tables.
316   void updateAcceleratorTables(const DIScope *Context, const DIType *Ty,
317                                const DIE &TyDIE);
318 
319   /// Emit the common part of the header for this unit.
320   void emitCommonHeader(bool UseOffsets, dwarf::UnitType UT);
321 
322 private:
323   void constructTypeDIE(DIE &Buffer, const DIBasicType *BTy);
324   void constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy);
325   void constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy);
326   void constructSubrangeDIE(DIE &Buffer, const DISubrange *SR, DIE *IndexTy);
327   void constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy);
328   void constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy);
329   DIE &constructMemberDIE(DIE &Buffer, const DIDerivedType *DT);
330   void constructTemplateTypeParameterDIE(DIE &Buffer,
331                                          const DITemplateTypeParameter *TP);
332   void constructTemplateValueParameterDIE(DIE &Buffer,
333                                           const DITemplateValueParameter *TVP);
334 
335   /// Return the default lower bound for an array.
336   ///
337   /// If the DWARF version doesn't handle the language, return -1.
338   int64_t getDefaultLowerBound() const;
339 
340   /// Get an anonymous type for index type.
341   DIE *getIndexTyDie();
342 
343   /// Set D as anonymous type for index which can be reused later.
344   void setIndexTyDie(DIE *D) { IndexTyDie = D; }
345 
346   virtual bool isDwoUnit() const = 0;
347   const MCSymbol *getCrossSectionRelativeBaseAddress() const override;
348 };
349 
350 class DwarfTypeUnit final : public DwarfUnit {
351   uint64_t TypeSignature;
352   const DIE *Ty;
353   DwarfCompileUnit &CU;
354   MCDwarfDwoLineTable *SplitLineTable;
355   bool UsedLineTable = false;
356 
357   unsigned getOrCreateSourceID(const DIFile *File) override;
358   bool isDwoUnit() const override;
359 
360 public:
361   DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A, DwarfDebug *DW,
362                 DwarfFile *DWU, MCDwarfDwoLineTable *SplitLineTable = nullptr);
363 
364   void setTypeSignature(uint64_t Signature) { TypeSignature = Signature; }
365   void setType(const DIE *Ty) { this->Ty = Ty; }
366 
367   /// Get context owner's DIE.
368   DIE *createTypeDIE(const DICompositeType *Ty);
369 
370   /// Emit the header for this unit, not including the initial length field.
371   void emitHeader(bool UseOffsets) override;
372   unsigned getHeaderSize() const override {
373     return DwarfUnit::getHeaderSize() + sizeof(uint64_t) + // Type Signature
374            sizeof(uint32_t);                               // Type DIE Offset
375   }
376   void addGlobalName(StringRef Name, const DIE &Die,
377                      const DIScope *Context) override;
378   void addGlobalType(const DIType *Ty, const DIE &Die,
379                      const DIScope *Context) override;
380   DwarfCompileUnit &getCU() override { return CU; }
381 };
382 } // end llvm namespace
383 #endif
384