1 //===- DebugInfo.h - Debug Information Helpers ------------------*- 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 defines a bunch of datatypes that are useful for creating and
10 // walking debug info in LLVM IR form. They essentially provide wrappers around
11 // the information in the global variables that's needed when constructing the
12 // DWARF information.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_IR_DEBUGINFO_H
17 #define LLVM_IR_DEBUGINFO_H
18
19 #include "llvm/ADT/DenseMapInfo.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/TinyPtrVector.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/PassManager.h"
30 #include <optional>
31
32 namespace llvm {
33
34 class DbgDeclareInst;
35 class DbgValueInst;
36 class DbgVariableIntrinsic;
37 class DPValue;
38 class Instruction;
39 class Module;
40
41 /// Finds dbg.declare intrinsics declaring local variables as living in the
42 /// memory that 'V' points to.
43 void findDbgDeclares(SmallVectorImpl<DbgDeclareInst *> &DbgUsers, Value *V,
44 SmallVectorImpl<DPValue *> *DPValues = nullptr);
45
46 /// Finds the llvm.dbg.value intrinsics describing a value.
47 void findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues,
48 Value *V, SmallVectorImpl<DPValue *> *DPValues = nullptr);
49
50 /// Finds the debug info intrinsics describing a value.
51 void findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgInsts,
52 Value *V, SmallVectorImpl<DPValue *> *DPValues = nullptr);
53
54 /// Find subprogram that is enclosing this scope.
55 DISubprogram *getDISubprogram(const MDNode *Scope);
56
57 /// Produce a DebugLoc to use for each dbg.declare that is promoted to a
58 /// dbg.value.
59 DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII);
60
61 /// Strip debug info in the module if it exists.
62 ///
63 /// To do this, we remove all calls to the debugger intrinsics and any named
64 /// metadata for debugging. We also remove debug locations for instructions.
65 /// Return true if module is modified.
66 bool StripDebugInfo(Module &M);
67 bool stripDebugInfo(Function &F);
68
69 /// Downgrade the debug info in a module to contain only line table information.
70 ///
71 /// In order to convert debug info to what -gline-tables-only would have
72 /// created, this does the following:
73 /// 1) Delete all debug intrinsics.
74 /// 2) Delete all non-CU named metadata debug info nodes.
75 /// 3) Create new DebugLocs for each instruction.
76 /// 4) Create a new CU debug info, and similarly for every metadata node
77 /// that's reachable from the CU debug info.
78 /// All debug type metadata nodes are unreachable and garbage collected.
79 bool stripNonLineTableDebugInfo(Module &M);
80
81 /// Update the debug locations contained within the MD_loop metadata attached
82 /// to the instruction \p I, if one exists. \p Updater is applied to Metadata
83 /// operand in the MD_loop metadata: the returned value is included in the
84 /// updated loop metadata node if it is non-null.
85 void updateLoopMetadataDebugLocations(
86 Instruction &I, function_ref<Metadata *(Metadata *)> Updater);
87
88 /// Return Debug Info Metadata Version by checking module flags.
89 unsigned getDebugMetadataVersionFromModule(const Module &M);
90
91 /// Utility to find all debug info in a module.
92 ///
93 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
94 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
95 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
96 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
97 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
98 /// used by the CUs.
99 class DebugInfoFinder {
100 public:
101 /// Process entire module and collect debug info anchors.
102 void processModule(const Module &M);
103 /// Process a single instruction and collect debug info anchors.
104 void processInstruction(const Module &M, const Instruction &I);
105
106 /// Process a DILocalVariable.
107 void processVariable(const Module &M, const DILocalVariable *DVI);
108 /// Process debug info location.
109 void processLocation(const Module &M, const DILocation *Loc);
110 // Process a DPValue, much like a DbgVariableIntrinsic.
111 void processDPValue(const Module &M, const DPValue &DPV);
112
113 /// Process subprogram.
114 void processSubprogram(DISubprogram *SP);
115
116 /// Clear all lists.
117 void reset();
118
119 private:
120 void processCompileUnit(DICompileUnit *CU);
121 void processScope(DIScope *Scope);
122 void processType(DIType *DT);
123 bool addCompileUnit(DICompileUnit *CU);
124 bool addGlobalVariable(DIGlobalVariableExpression *DIG);
125 bool addScope(DIScope *Scope);
126 bool addSubprogram(DISubprogram *SP);
127 bool addType(DIType *DT);
128
129 public:
130 using compile_unit_iterator =
131 SmallVectorImpl<DICompileUnit *>::const_iterator;
132 using subprogram_iterator = SmallVectorImpl<DISubprogram *>::const_iterator;
133 using global_variable_expression_iterator =
134 SmallVectorImpl<DIGlobalVariableExpression *>::const_iterator;
135 using type_iterator = SmallVectorImpl<DIType *>::const_iterator;
136 using scope_iterator = SmallVectorImpl<DIScope *>::const_iterator;
137
compile_units()138 iterator_range<compile_unit_iterator> compile_units() const {
139 return make_range(CUs.begin(), CUs.end());
140 }
141
subprograms()142 iterator_range<subprogram_iterator> subprograms() const {
143 return make_range(SPs.begin(), SPs.end());
144 }
145
global_variables()146 iterator_range<global_variable_expression_iterator> global_variables() const {
147 return make_range(GVs.begin(), GVs.end());
148 }
149
types()150 iterator_range<type_iterator> types() const {
151 return make_range(TYs.begin(), TYs.end());
152 }
153
scopes()154 iterator_range<scope_iterator> scopes() const {
155 return make_range(Scopes.begin(), Scopes.end());
156 }
157
compile_unit_count()158 unsigned compile_unit_count() const { return CUs.size(); }
global_variable_count()159 unsigned global_variable_count() const { return GVs.size(); }
subprogram_count()160 unsigned subprogram_count() const { return SPs.size(); }
type_count()161 unsigned type_count() const { return TYs.size(); }
scope_count()162 unsigned scope_count() const { return Scopes.size(); }
163
164 private:
165 SmallVector<DICompileUnit *, 8> CUs;
166 SmallVector<DISubprogram *, 8> SPs;
167 SmallVector<DIGlobalVariableExpression *, 8> GVs;
168 SmallVector<DIType *, 8> TYs;
169 SmallVector<DIScope *, 8> Scopes;
170 SmallPtrSet<const MDNode *, 32> NodesSeen;
171 };
172
173 /// Assignment Tracking (at).
174 namespace at {
175 //
176 // Utilities for enumerating storing instructions from an assignment ID.
177 //
178 /// A range of instructions.
179 using AssignmentInstRange =
180 iterator_range<SmallVectorImpl<Instruction *>::iterator>;
181 /// Return a range of instructions (typically just one) that have \p ID
182 /// as an attachment.
183 /// Iterators invalidated by adding or removing DIAssignID metadata to/from any
184 /// instruction (including by deleting or cloning instructions).
185 AssignmentInstRange getAssignmentInsts(DIAssignID *ID);
186 /// Return a range of instructions (typically just one) that perform the
187 /// assignment that \p DAI encodes.
188 /// Iterators invalidated by adding or removing DIAssignID metadata to/from any
189 /// instruction (including by deleting or cloning instructions).
getAssignmentInsts(const DbgAssignIntrinsic * DAI)190 inline AssignmentInstRange getAssignmentInsts(const DbgAssignIntrinsic *DAI) {
191 return getAssignmentInsts(DAI->getAssignID());
192 }
193
194 //
195 // Utilities for enumerating llvm.dbg.assign intrinsic from an assignment ID.
196 //
197 /// High level: this is an iterator for llvm.dbg.assign intrinsics.
198 /// Implementation details: this is a wrapper around Value's User iterator that
199 /// dereferences to a DbgAssignIntrinsic ptr rather than a User ptr.
200 class DbgAssignIt
201 : public iterator_adaptor_base<DbgAssignIt, Value::user_iterator,
202 typename std::iterator_traits<
203 Value::user_iterator>::iterator_category,
204 DbgAssignIntrinsic *, std::ptrdiff_t,
205 DbgAssignIntrinsic **,
206 DbgAssignIntrinsic *&> {
207 public:
DbgAssignIt(Value::user_iterator It)208 DbgAssignIt(Value::user_iterator It) : iterator_adaptor_base(It) {}
209 DbgAssignIntrinsic *operator*() const { return cast<DbgAssignIntrinsic>(*I); }
210 };
211 /// A range of llvm.dbg.assign intrinsics.
212 using AssignmentMarkerRange = iterator_range<DbgAssignIt>;
213 /// Return a range of dbg.assign intrinsics which use \ID as an operand.
214 /// Iterators invalidated by deleting an intrinsic contained in this range.
215 AssignmentMarkerRange getAssignmentMarkers(DIAssignID *ID);
216 /// Return a range of dbg.assign intrinsics for which \p Inst performs the
217 /// assignment they encode.
218 /// Iterators invalidated by deleting an intrinsic contained in this range.
getAssignmentMarkers(const Instruction * Inst)219 inline AssignmentMarkerRange getAssignmentMarkers(const Instruction *Inst) {
220 if (auto *ID = Inst->getMetadata(LLVMContext::MD_DIAssignID))
221 return getAssignmentMarkers(cast<DIAssignID>(ID));
222 else
223 return make_range(Value::user_iterator(), Value::user_iterator());
224 }
225
226 /// Delete the llvm.dbg.assign intrinsics linked to \p Inst.
227 void deleteAssignmentMarkers(const Instruction *Inst);
228
229 /// Replace all uses (and attachments) of \p Old with \p New.
230 void RAUW(DIAssignID *Old, DIAssignID *New);
231
232 /// Remove all Assignment Tracking related intrinsics and metadata from \p F.
233 void deleteAll(Function *F);
234
235 /// Calculate the fragment of the variable in \p DAI covered
236 /// from (Dest + SliceOffsetInBits) to
237 /// to (Dest + SliceOffsetInBits + SliceSizeInBits)
238 ///
239 /// Return false if it can't be calculated for any reason.
240 /// Result is set to nullopt if the intersect equals the variable fragment (or
241 /// variable size) in DAI.
242 ///
243 /// Result contains a zero-sized fragment if there's no intersect.
244 bool calculateFragmentIntersect(
245 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,
246 uint64_t SliceSizeInBits, const DbgAssignIntrinsic *DAI,
247 std::optional<DIExpression::FragmentInfo> &Result);
248
249 /// Helper struct for trackAssignments, below. We don't use the similar
250 /// DebugVariable class because trackAssignments doesn't (yet?) understand
251 /// partial variables (fragment info) as input and want to make that clear and
252 /// explicit using types. In addition, eventually we will want to understand
253 /// expressions that modify the base address too, which a DebugVariable doesn't
254 /// capture.
255 struct VarRecord {
256 DILocalVariable *Var;
257 DILocation *DL;
258
VarRecordVarRecord259 VarRecord(DbgVariableIntrinsic *DVI)
260 : Var(DVI->getVariable()), DL(getDebugValueLoc(DVI)) {}
VarRecordVarRecord261 VarRecord(DILocalVariable *Var, DILocation *DL) : Var(Var), DL(DL) {}
262 friend bool operator<(const VarRecord &LHS, const VarRecord &RHS) {
263 return std::tie(LHS.Var, LHS.DL) < std::tie(RHS.Var, RHS.DL);
264 }
265 friend bool operator==(const VarRecord &LHS, const VarRecord &RHS) {
266 return std::tie(LHS.Var, LHS.DL) == std::tie(RHS.Var, RHS.DL);
267 }
268 };
269
270 } // namespace at
271
272 template <> struct DenseMapInfo<at::VarRecord> {
273 static inline at::VarRecord getEmptyKey() {
274 return at::VarRecord(DenseMapInfo<DILocalVariable *>::getEmptyKey(),
275 DenseMapInfo<DILocation *>::getEmptyKey());
276 }
277
278 static inline at::VarRecord getTombstoneKey() {
279 return at::VarRecord(DenseMapInfo<DILocalVariable *>::getTombstoneKey(),
280 DenseMapInfo<DILocation *>::getTombstoneKey());
281 }
282
283 static unsigned getHashValue(const at::VarRecord &Var) {
284 return hash_combine(Var.Var, Var.DL);
285 }
286
287 static bool isEqual(const at::VarRecord &A, const at::VarRecord &B) {
288 return A == B;
289 }
290 };
291
292 namespace at {
293 /// Map of backing storage to a set of variables that are stored to it.
294 /// TODO: Backing storage shouldn't be limited to allocas only. Some local
295 /// variables have their storage allocated by the calling function (addresses
296 /// passed in with sret & byval parameters).
297 using StorageToVarsMap =
298 DenseMap<const AllocaInst *, SmallSetVector<VarRecord, 2>>;
299
300 /// Track assignments to \p Vars between \p Start and \p End.
301
302 void trackAssignments(Function::iterator Start, Function::iterator End,
303 const StorageToVarsMap &Vars, const DataLayout &DL,
304 bool DebugPrints = false);
305
306 /// Describes properties of a store that has a static size and offset into a
307 /// some base storage. Used by the getAssignmentInfo functions.
308 struct AssignmentInfo {
309 AllocaInst const *Base; ///< Base storage.
310 uint64_t OffsetInBits; ///< Offset into Base.
311 uint64_t SizeInBits; ///< Number of bits stored.
312 bool StoreToWholeAlloca; ///< SizeInBits equals the size of the base storage.
313
314 AssignmentInfo(const DataLayout &DL, AllocaInst const *Base,
315 uint64_t OffsetInBits, uint64_t SizeInBits)
316 : Base(Base), OffsetInBits(OffsetInBits), SizeInBits(SizeInBits),
317 StoreToWholeAlloca(
318 OffsetInBits == 0 &&
319 SizeInBits == DL.getTypeSizeInBits(Base->getAllocatedType())) {}
320 };
321
322 std::optional<AssignmentInfo> getAssignmentInfo(const DataLayout &DL,
323 const MemIntrinsic *I);
324 std::optional<AssignmentInfo> getAssignmentInfo(const DataLayout &DL,
325 const StoreInst *SI);
326 std::optional<AssignmentInfo> getAssignmentInfo(const DataLayout &DL,
327 const AllocaInst *AI);
328
329 } // end namespace at
330
331 /// Convert @llvm.dbg.declare intrinsics into sets of @llvm.dbg.assign
332 /// intrinsics by treating stores to the dbg.declare'd address as assignments
333 /// to the variable. Not all kinds of variables are supported yet; those will
334 /// be left with their dbg.declare intrinsics.
335 /// The pass sets the debug-info-assignment-tracking module flag to true to
336 /// indicate assignment tracking has been enabled.
337 class AssignmentTrackingPass : public PassInfoMixin<AssignmentTrackingPass> {
338 /// Note: this method does not set the debug-info-assignment-tracking module
339 /// flag.
340 bool runOnFunction(Function &F);
341
342 public:
343 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
344 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
345 };
346
347 /// Return true if assignment tracking is enabled for module \p M.
348 bool isAssignmentTrackingEnabled(const Module &M);
349
350 } // end namespace llvm
351
352 #endif // LLVM_IR_DEBUGINFO_H
353