xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
1 //===- llvm/CodeGen/DwarfCompileUnit.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_DWARFCOMPILEUNIT_H
14 #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
15 
16 #include "DwarfDebug.h"
17 #include "DwarfUnit.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/BinaryFormat/Dwarf.h"
24 #include "llvm/CodeGen/DbgEntityHistoryCalculator.h"
25 #include "llvm/CodeGen/LexicalScopes.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/Support/Casting.h"
28 #include <cassert>
29 #include <cstdint>
30 #include <memory>
31 
32 namespace llvm {
33 
34 class AsmPrinter;
35 class DIE;
36 class DIELoc;
37 class DIEValueList;
38 class DwarfFile;
39 class GlobalVariable;
40 class MCExpr;
41 class MCSymbol;
42 class MDNode;
43 
44 enum class UnitKind { Skeleton, Full };
45 
46 class DwarfCompileUnit final : public DwarfUnit {
47   /// A numeric ID unique among all CUs in the module
48   unsigned UniqueID;
49   bool HasRangeLists = false;
50 
51   /// The start of the unit line section, this is also
52   /// reused in appyStmtList.
53   MCSymbol *LineTableStartSym;
54 
55   /// Skeleton unit associated with this unit.
56   DwarfCompileUnit *Skeleton = nullptr;
57 
58   /// The start of the unit within its section.
59   MCSymbol *LabelBegin = nullptr;
60 
61   /// The start of the unit macro info within macro section.
62   MCSymbol *MacroLabelBegin;
63 
64   /// GlobalNames - A map of globally visible named entities for this unit.
65   StringMap<const DIE *> GlobalNames;
66 
67   /// GlobalTypes - A map of globally visible types for this unit.
68   StringMap<const DIE *> GlobalTypes;
69 
70   // List of ranges for a given compile unit.
71   SmallVector<RangeSpan, 2> CURanges;
72 
73   // The base address of this unit, if any. Used for relative references in
74   // ranges/locs.
75   const MCSymbol *BaseAddress = nullptr;
76 
77   using MDNodeSetVector =
78       SetVector<const MDNode *, SmallVector<const MDNode *, 4>,
79                 SmallPtrSet<const MDNode *, 4>>;
80 
81   // List of entities (either static locals, types or imports) that
82   // belong to subprograms within this CU.
83   MDNodeSetVector DeferredLocalDecls;
84 
85   // List of concrete lexical block scopes belong to subprograms within this CU.
86   DenseMap<const DILocalScope *, DIE *> LexicalBlockDIEs;
87 
88   // List of abstract local scopes (either DISubprogram or DILexicalBlock).
89   DenseMap<const DILocalScope *, DIE *> AbstractLocalScopeDIEs;
90 
91   DenseMap<const DINode *, std::unique_ptr<DbgEntity>> AbstractEntities;
92 
93   /// DWO ID for correlating skeleton and split units.
94   uint64_t DWOId = 0;
95 
96   const DIFile *LastFile = nullptr;
97   unsigned LastFileID;
98 
99   /// Construct a DIE for the given DbgVariable without initializing the
100   /// DbgVariable's DIE reference.
101   DIE *constructVariableDIEImpl(const DbgVariable &DV, bool Abstract);
102 
103   bool isDwoUnit() const override;
104 
105   DenseMap<const DILocalScope *, DIE *> &getAbstractScopeDIEs() {
106     if (isDwoUnit() && !DD->shareAcrossDWOCUs())
107       return AbstractLocalScopeDIEs;
108     return DU->getAbstractScopeDIEs();
109   }
110 
111   DenseMap<const DINode *, std::unique_ptr<DbgEntity>> &getAbstractEntities() {
112     if (isDwoUnit() && !DD->shareAcrossDWOCUs())
113       return AbstractEntities;
114     return DU->getAbstractEntities();
115   }
116 
117   void finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) override;
118 
119   /// Add info for Wasm-global-based relocation.
120   void addWasmRelocBaseGlobal(DIELoc *Loc, StringRef GlobalName,
121                               uint64_t GlobalIndex);
122 
123 public:
124   DwarfCompileUnit(unsigned UID, const DICompileUnit *Node, AsmPrinter *A,
125                    DwarfDebug *DW, DwarfFile *DWU,
126                    UnitKind Kind = UnitKind::Full);
127 
128   bool hasRangeLists() const { return HasRangeLists; }
129   unsigned getUniqueID() const { return UniqueID; }
130 
131   DwarfCompileUnit *getSkeleton() const {
132     return Skeleton;
133   }
134 
135   bool includeMinimalInlineScopes() const;
136 
137   void initStmtList();
138 
139   /// Apply the DW_AT_stmt_list from this compile unit to the specified DIE.
140   void applyStmtList(DIE &D);
141 
142   /// Get line table start symbol for this unit.
143   MCSymbol *getLineTableStartSym() const { return LineTableStartSym; }
144 
145   /// A pair of GlobalVariable and DIExpression.
146   struct GlobalExpr {
147     const GlobalVariable *Var;
148     const DIExpression *Expr;
149   };
150 
151   struct BaseTypeRef {
152     BaseTypeRef(unsigned BitSize, dwarf::TypeKind Encoding) :
153       BitSize(BitSize), Encoding(Encoding) {}
154     unsigned BitSize;
155     dwarf::TypeKind Encoding;
156     DIE *Die = nullptr;
157   };
158 
159   std::vector<BaseTypeRef> ExprRefedBaseTypes;
160 
161   /// Get or create global variable DIE.
162   DIE *
163   getOrCreateGlobalVariableDIE(const DIGlobalVariable *GV,
164                                ArrayRef<GlobalExpr> GlobalExprs);
165 
166   DIE *getOrCreateCommonBlock(const DICommonBlock *CB,
167                               ArrayRef<GlobalExpr> GlobalExprs);
168 
169   void addLocationAttribute(DIE *ToDIE, const DIGlobalVariable *GV,
170                             ArrayRef<GlobalExpr> GlobalExprs);
171 
172   /// addLabelAddress - Add a dwarf label attribute data and value using
173   /// either DW_FORM_addr or DW_FORM_GNU_addr_index.
174   void addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
175                        const MCSymbol *Label);
176 
177   /// addLocalLabelAddress - Add a dwarf label attribute data and value using
178   /// DW_FORM_addr only.
179   void addLocalLabelAddress(DIE &Die, dwarf::Attribute Attribute,
180                             const MCSymbol *Label);
181 
182   DwarfCompileUnit &getCU() override { return *this; }
183 
184   unsigned getOrCreateSourceID(const DIFile *File) override;
185 
186   /// addRange - Add an address range to the list of ranges for this unit.
187   void addRange(RangeSpan Range);
188 
189   void attachLowHighPC(DIE &D, const MCSymbol *Begin, const MCSymbol *End);
190 
191   /// Find DIE for the given subprogram and attach appropriate
192   /// DW_AT_low_pc and DW_AT_high_pc attributes. If there are global
193   /// variables in this scope then create and insert DIEs for these
194   /// variables.
195   DIE &updateSubprogramScopeDIE(const DISubprogram *SP);
196   DIE &updateSubprogramScopeDIEImpl(const DISubprogram *SP, DIE *SPDie);
197 
198   void constructScopeDIE(LexicalScope *Scope, DIE &ParentScopeDIE);
199 
200   /// A helper function to construct a RangeSpanList for a given
201   /// lexical scope.
202   void addScopeRangeList(DIE &ScopeDIE, SmallVector<RangeSpan, 2> Range);
203 
204   void attachRangesOrLowHighPC(DIE &D, SmallVector<RangeSpan, 2> Ranges);
205 
206   void attachRangesOrLowHighPC(DIE &D,
207                                const SmallVectorImpl<InsnRange> &Ranges);
208 
209   /// This scope represents an inlined body of a function. Construct a
210   /// DIE to represent this concrete inlined copy of the function.
211   DIE *constructInlinedScopeDIE(LexicalScope *Scope, DIE &ParentScopeDIE);
212 
213   /// Construct new DW_TAG_lexical_block for this scope and
214   /// attach DW_AT_low_pc/DW_AT_high_pc labels.
215   DIE *constructLexicalScopeDIE(LexicalScope *Scope);
216 
217   /// Get a DIE for the given DILexicalBlock.
218   /// Note that this function assumes that the DIE has been already created
219   /// and it's an error, if it hasn't.
220   DIE *getLexicalBlockDIE(const DILexicalBlock *LB);
221 
222   /// constructVariableDIE - Construct a DIE for the given DbgVariable.
223   DIE *constructVariableDIE(DbgVariable &DV, bool Abstract = false);
224 
225   DIE *constructVariableDIE(DbgVariable &DV, const LexicalScope &Scope,
226                             DIE *&ObjectPointer);
227 
228   /// Construct a DIE for the given DbgLabel.
229   DIE *constructLabelDIE(DbgLabel &DL, const LexicalScope &Scope);
230 
231   void createBaseTypeDIEs();
232 
233   /// Construct a DIE for a given scope.
234   /// This instance of 'getOrCreateContextDIE()' can handle DILocalScope.
235   DIE *getOrCreateContextDIE(const DIScope *Ty) override;
236 
237   /// Construct a DIE for this subprogram scope.
238   DIE &constructSubprogramScopeDIE(const DISubprogram *Sub,
239                                    LexicalScope *Scope);
240 
241   DIE *createAndAddScopeChildren(LexicalScope *Scope, DIE &ScopeDIE);
242 
243   void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
244 
245   /// Whether to use the GNU analog for a DWARF5 tag, attribute, or location
246   /// atom. Only applicable when emitting otherwise DWARF4-compliant debug info.
247   bool useGNUAnalogForDwarf5Feature() const;
248 
249   /// This takes a DWARF 5 tag and returns it or a GNU analog.
250   dwarf::Tag getDwarf5OrGNUTag(dwarf::Tag Tag) const;
251 
252   /// This takes a DWARF 5 attribute and returns it or a GNU analog.
253   dwarf::Attribute getDwarf5OrGNUAttr(dwarf::Attribute Attr) const;
254 
255   /// This takes a DWARF 5 location atom and either returns it or a GNU analog.
256   dwarf::LocationAtom getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const;
257 
258   /// Construct a call site entry DIE describing a call within \p Scope to a
259   /// callee described by \p CalleeSP.
260   /// \p IsTail specifies whether the call is a tail call.
261   /// \p PCAddr points to the PC value after the call instruction.
262   /// \p CallAddr points to the PC value at the call instruction (or is null).
263   /// \p CallReg is a register location for an indirect call. For direct calls
264   /// the \p CallReg is set to 0.
265   DIE &constructCallSiteEntryDIE(DIE &ScopeDIE, const DISubprogram *CalleeSP,
266                                  bool IsTail, const MCSymbol *PCAddr,
267                                  const MCSymbol *CallAddr, unsigned CallReg);
268   /// Construct call site parameter DIEs for the \p CallSiteDIE. The \p Params
269   /// were collected by the \ref collectCallSiteParameters.
270   /// Note: The order of parameters does not matter, since debuggers recognize
271   ///       call site parameters by the DW_AT_location attribute.
272   void constructCallSiteParmEntryDIEs(DIE &CallSiteDIE,
273                                       SmallVector<DbgCallSiteParam, 4> &Params);
274 
275   /// Get or create a DIE for an imported entity.
276   DIE *getOrCreateImportedEntityDIE(const DIImportedEntity *IE);
277   DIE *constructImportedEntityDIE(const DIImportedEntity *IE);
278 
279   void finishSubprogramDefinition(const DISubprogram *SP);
280   void finishEntityDefinition(const DbgEntity *Entity);
281 
282   /// Find abstract variable associated with Var.
283   using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
284   DbgEntity *getExistingAbstractEntity(const DINode *Node);
285   void createAbstractEntity(const DINode *Node, LexicalScope *Scope);
286 
287   /// Set the skeleton unit associated with this unit.
288   void setSkeleton(DwarfCompileUnit &Skel) { Skeleton = &Skel; }
289 
290   unsigned getHeaderSize() const override {
291     // DWARF v5 added the DWO ID to the header for split/skeleton units.
292     unsigned DWOIdSize =
293         DD->getDwarfVersion() >= 5 && DD->useSplitDwarf() ? sizeof(uint64_t)
294                                                           : 0;
295     return DwarfUnit::getHeaderSize() + DWOIdSize;
296   }
297   unsigned getLength() {
298     return Asm->getUnitLengthFieldByteSize() + // Length field
299            getHeaderSize() + getUnitDie().getSize();
300   }
301 
302   void emitHeader(bool UseOffsets) override;
303 
304   /// Add the DW_AT_addr_base attribute to the unit DIE.
305   void addAddrTableBase();
306 
307   MCSymbol *getLabelBegin() const {
308     assert(LabelBegin && "LabelBegin is not initialized");
309     return LabelBegin;
310   }
311 
312   MCSymbol *getMacroLabelBegin() const {
313     return MacroLabelBegin;
314   }
315 
316   /// Add a new global name to the compile unit.
317   void addGlobalName(StringRef Name, const DIE &Die,
318                      const DIScope *Context) override;
319 
320   /// Add a new global name present in a type unit to this compile unit.
321   void addGlobalNameForTypeUnit(StringRef Name, const DIScope *Context);
322 
323   /// Add a new global type to the compile unit.
324   void addGlobalType(const DIType *Ty, const DIE &Die,
325                      const DIScope *Context) override;
326 
327   /// Add a new global type present in a type unit to this compile unit.
328   void addGlobalTypeUnitType(const DIType *Ty, const DIScope *Context);
329 
330   const StringMap<const DIE *> &getGlobalNames() const { return GlobalNames; }
331   const StringMap<const DIE *> &getGlobalTypes() const { return GlobalTypes; }
332 
333   /// Add DW_AT_location attribute for a DbgVariable based on provided
334   /// MachineLocation.
335   void addVariableAddress(const DbgVariable &DV, DIE &Die,
336                           MachineLocation Location);
337   /// Add an address attribute to a die based on the location provided.
338   void addAddress(DIE &Die, dwarf::Attribute Attribute,
339                   const MachineLocation &Location);
340 
341   /// Start with the address based on the location provided, and generate the
342   /// DWARF information necessary to find the actual variable (navigating the
343   /// extra location information encoded in the type) based on the starting
344   /// location.  Add the DWARF information to the die.
345   void addComplexAddress(const DbgVariable &DV, DIE &Die,
346                          dwarf::Attribute Attribute,
347                          const MachineLocation &Location);
348 
349   /// Add a Dwarf loclistptr attribute data and value.
350   void addLocationList(DIE &Die, dwarf::Attribute Attribute, unsigned Index);
351   void applyVariableAttributes(const DbgVariable &Var, DIE &VariableDie);
352 
353   /// Add a Dwarf expression attribute data and value.
354   void addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr);
355 
356   void applySubprogramAttributesToDefinition(const DISubprogram *SP,
357                                              DIE &SPDie);
358 
359   void applyLabelAttributes(const DbgLabel &Label, DIE &LabelDie);
360 
361   /// getRanges - Get the list of ranges for this unit.
362   const SmallVectorImpl<RangeSpan> &getRanges() const { return CURanges; }
363   SmallVector<RangeSpan, 2> takeRanges() { return std::move(CURanges); }
364 
365   void setBaseAddress(const MCSymbol *Base) { BaseAddress = Base; }
366   const MCSymbol *getBaseAddress() const { return BaseAddress; }
367 
368   uint64_t getDWOId() const { return DWOId; }
369   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
370 
371   bool hasDwarfPubSections() const;
372 
373   void addBaseTypeRef(DIEValueList &Die, int64_t Idx);
374 
375   MDNodeSetVector &getDeferredLocalDecls() { return DeferredLocalDecls; }
376 };
377 
378 } // end namespace llvm
379 
380 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
381