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