xref: /llvm-project/llvm/include/llvm/IR/DebugProgramInstruction.h (revision 8e702735090388a3231a863e343f880d0f96fecb)
1 //===-- llvm/DebugProgramInstruction.h - Stream of debug info ---*- 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 // Data structures for storing variable assignment information in LLVM. In the
10 // dbg.value design, a dbg.value intrinsic specifies the position in a block
11 // a source variable take on an LLVM Value:
12 //
13 //    %foo = add i32 1, %0
14 //    dbg.value(metadata i32 %foo, ...)
15 //    %bar = void call @ext(%foo);
16 //
17 // and all information is stored in the Value / Metadata hierachy defined
18 // elsewhere in LLVM. In the "DbgRecord" design, each instruction /may/ have a
19 // connection with a DbgMarker, which identifies a position immediately before
20 // the instruction, and each DbgMarker /may/ then have connections to DbgRecords
21 // which record the variable assignment information. To illustrate:
22 //
23 //    %foo = add i32 1, %0
24 //       ; foo->DebugMarker == nullptr
25 //       ;; There are no variable assignments / debug records "in front" of
26 //       ;; the instruction for %foo, therefore it has no DebugMarker.
27 //    %bar = void call @ext(%foo)
28 //       ; bar->DebugMarker = {
29 //       ;   StoredDbgRecords = {
30 //       ;     DbgVariableRecord(metadata i32 %foo, ...)
31 //       ;   }
32 //       ; }
33 //       ;; There is a debug-info record in front of the %bar instruction,
34 //       ;; thus it points at a DbgMarker object. That DbgMarker contains a
35 //       ;; DbgVariableRecord in its ilist, storing the equivalent information
36 //       ;; to the dbg.value above: the Value, DILocalVariable, etc.
37 //
38 // This structure separates the two concerns of the position of the debug-info
39 // in the function, and the Value that it refers to. It also creates a new
40 // "place" in-between the Value / Metadata hierachy where we can customise
41 // storage and allocation techniques to better suite debug-info workloads.
42 // NB: as of the initial prototype, none of that has actually been attempted
43 // yet.
44 //
45 //===----------------------------------------------------------------------===//
46 
47 #ifndef LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
48 #define LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
49 
50 #include "llvm/ADT/ilist.h"
51 #include "llvm/ADT/ilist_node.h"
52 #include "llvm/ADT/iterator.h"
53 #include "llvm/IR/DbgVariableFragmentInfo.h"
54 #include "llvm/IR/DebugLoc.h"
55 #include "llvm/IR/Instruction.h"
56 #include "llvm/IR/SymbolTableListTraits.h"
57 #include "llvm/Support/Casting.h"
58 
59 namespace llvm {
60 
61 class Instruction;
62 class BasicBlock;
63 class MDNode;
64 class Module;
65 class DbgVariableIntrinsic;
66 class DbgInfoIntrinsic;
67 class DbgLabelInst;
68 class DIAssignID;
69 class DbgMarker;
70 class DbgVariableRecord;
71 class raw_ostream;
72 
73 /// A typed tracking MDNode reference that does not require a definition for its
74 /// parameter type. Necessary to avoid including DebugInfoMetadata.h, which has
75 /// a significant impact on compile times if included in this file.
76 template <typename T> class DbgRecordParamRef {
77   TrackingMDNodeRef Ref;
78 
79 public:
80 public:
81   DbgRecordParamRef() = default;
82 
83   /// Construct from the templated type.
84   DbgRecordParamRef(const T *Param);
85 
86   /// Construct from an \a MDNode.
87   ///
88   /// Note: if \c Param does not have the template type, a verifier check will
89   /// fail, and accessors will crash.  However, construction from other nodes
90   /// is supported in order to handle forward references when reading textual
91   /// IR.
92   explicit DbgRecordParamRef(const MDNode *Param);
93 
94   /// Get the underlying type.
95   ///
96   /// \pre !*this or \c isa<T>(getAsMDNode()).
97   /// @{
98   T *get() const;
99   operator T *() const { return get(); }
100   T *operator->() const { return get(); }
101   T &operator*() const { return *get(); }
102   /// @}
103 
104   /// Check for null.
105   ///
106   /// Check for null in a way that is safe with broken debug info.
107   explicit operator bool() const { return Ref; }
108 
109   /// Return \c this as a \a MDNode.
110   MDNode *getAsMDNode() const { return Ref; }
111 
112   bool operator==(const DbgRecordParamRef &Other) const {
113     return Ref == Other.Ref;
114   }
115   bool operator!=(const DbgRecordParamRef &Other) const {
116     return Ref != Other.Ref;
117   }
118 };
119 
120 /// Base class for non-instruction debug metadata records that have positions
121 /// within IR. Features various methods copied across from the Instruction
122 /// class to aid ease-of-use. DbgRecords should always be linked into a
123 /// DbgMarker's StoredDbgRecords list. The marker connects a DbgRecord back to
124 /// its position in the BasicBlock.
125 ///
126 /// We need a discriminator for dyn/isa casts. In order to avoid paying for a
127 /// vtable for "virtual" functions too, subclasses must add a new discriminator
128 /// value (RecordKind) and cases to a few functions in the base class:
129 ///   deleteRecord
130 ///   clone
131 ///   isIdenticalToWhenDefined
132 ///   both print methods
133 ///   createDebugIntrinsic
134 class DbgRecord : public ilist_node<DbgRecord> {
135 public:
136   /// Marker that this DbgRecord is linked into.
137   DbgMarker *Marker = nullptr;
138   /// Subclass discriminator.
139   enum Kind : uint8_t { ValueKind, LabelKind };
140 
141 protected:
142   DebugLoc DbgLoc;
143   Kind RecordKind; ///< Subclass discriminator.
144 
145 public:
146   DbgRecord(Kind RecordKind, DebugLoc DL)
147       : DbgLoc(DL), RecordKind(RecordKind) {}
148 
149   /// Methods that dispatch to subclass implementations. These need to be
150   /// manually updated when a new subclass is added.
151   ///@{
152   void deleteRecord();
153   DbgRecord *clone() const;
154   void print(raw_ostream &O, bool IsForDebug = false) const;
155   void print(raw_ostream &O, ModuleSlotTracker &MST, bool IsForDebug) const;
156   bool isIdenticalToWhenDefined(const DbgRecord &R) const;
157   /// Convert this DbgRecord back into an appropriate llvm.dbg.* intrinsic.
158   /// \p InsertBefore Optional position to insert this intrinsic.
159   /// \returns A new llvm.dbg.* intrinsic representiung this DbgRecord.
160   DbgInfoIntrinsic *createDebugIntrinsic(Module *M,
161                                          Instruction *InsertBefore) const;
162   ///@}
163 
164   /// Same as isIdenticalToWhenDefined but checks DebugLoc too.
165   bool isEquivalentTo(const DbgRecord &R) const;
166 
167   Kind getRecordKind() const { return RecordKind; }
168 
169   void setMarker(DbgMarker *M) { Marker = M; }
170 
171   DbgMarker *getMarker() { return Marker; }
172   const DbgMarker *getMarker() const { return Marker; }
173 
174   BasicBlock *getBlock();
175   const BasicBlock *getBlock() const;
176 
177   Function *getFunction();
178   const Function *getFunction() const;
179 
180   Module *getModule();
181   const Module *getModule() const;
182 
183   LLVMContext &getContext();
184   const LLVMContext &getContext() const;
185 
186   const Instruction *getInstruction() const;
187   const BasicBlock *getParent() const;
188   BasicBlock *getParent();
189 
190   void removeFromParent();
191   void eraseFromParent();
192 
193   DbgRecord *getNextNode() { return &*std::next(getIterator()); }
194   DbgRecord *getPrevNode() { return &*std::prev(getIterator()); }
195 
196   // Some generic lambdas supporting intrinsic-based debug-info mean we need
197   // to support both iterator and instruction position based insertion.
198   void insertBefore(DbgRecord *InsertBefore);
199   void insertAfter(DbgRecord *InsertAfter);
200   void moveBefore(DbgRecord *MoveBefore);
201   void moveAfter(DbgRecord *MoveAfter);
202 
203   void insertBefore(self_iterator InsertBefore);
204   void insertAfter(self_iterator InsertAfter);
205   void moveBefore(self_iterator MoveBefore);
206   void moveAfter(self_iterator MoveAfter);
207 
208   DebugLoc getDebugLoc() const { return DbgLoc; }
209   void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
210 
211   void dump() const;
212 
213   using self_iterator = simple_ilist<DbgRecord>::iterator;
214   using const_self_iterator = simple_ilist<DbgRecord>::const_iterator;
215 
216 protected:
217   /// Similarly to Value, we avoid paying the cost of a vtable
218   /// by protecting the dtor and having deleteRecord dispatch
219   /// cleanup.
220   /// Use deleteRecord to delete a generic record.
221   ~DbgRecord() = default;
222 };
223 
224 inline raw_ostream &operator<<(raw_ostream &OS, const DbgRecord &R) {
225   R.print(OS);
226   return OS;
227 }
228 
229 /// Records a position in IR for a source label (DILabel). Corresponds to the
230 /// llvm.dbg.label intrinsic.
231 class DbgLabelRecord : public DbgRecord {
232   DbgRecordParamRef<DILabel> Label;
233 
234   /// This constructor intentionally left private, so that it is only called via
235   /// "createUnresolvedDbgLabelRecord", which clearly expresses that it is for
236   /// parsing only.
237   DbgLabelRecord(MDNode *Label, MDNode *DL);
238 
239 public:
240   DbgLabelRecord(DILabel *Label, DebugLoc DL);
241 
242   /// For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved
243   /// MDNodes. Trying to access the resulting DbgLabelRecord's fields before
244   /// they are resolved, or if they resolve to the wrong type, will result in a
245   /// crash.
246   static DbgLabelRecord *createUnresolvedDbgLabelRecord(MDNode *Label,
247                                                         MDNode *DL);
248 
249   DbgLabelRecord *clone() const;
250   void print(raw_ostream &O, bool IsForDebug = false) const;
251   void print(raw_ostream &ROS, ModuleSlotTracker &MST, bool IsForDebug) const;
252   DbgLabelInst *createDebugIntrinsic(Module *M,
253                                      Instruction *InsertBefore) const;
254 
255   void setLabel(DILabel *NewLabel) { Label = NewLabel; }
256   DILabel *getLabel() const { return Label.get(); }
257   MDNode *getRawLabel() const { return Label.getAsMDNode(); };
258 
259   /// Support type inquiry through isa, cast, and dyn_cast.
260   static bool classof(const DbgRecord *E) {
261     return E->getRecordKind() == LabelKind;
262   }
263 };
264 
265 /// Record of a variable value-assignment, aka a non instruction representation
266 /// of the dbg.value intrinsic.
267 ///
268 /// This class inherits from DebugValueUser to allow LLVM's metadata facilities
269 /// to update our references to metadata beneath our feet.
270 class DbgVariableRecord : public DbgRecord, protected DebugValueUser {
271   friend class DebugValueUser;
272 
273 public:
274   enum class LocationType : uint8_t {
275     Declare,
276     Value,
277     Assign,
278 
279     End, ///< Marks the end of the concrete types.
280     Any, ///< To indicate all LocationTypes in searches.
281   };
282   /// Classification of the debug-info record that this DbgVariableRecord
283   /// represents. Essentially, "does this correspond to a dbg.value,
284   /// dbg.declare, or dbg.assign?".
285   /// FIXME: We could use spare padding bits from DbgRecord for this.
286   LocationType Type;
287 
288   // NB: there is no explicit "Value" field in this class, it's effectively the
289   // DebugValueUser superclass instead. The referred to Value can either be a
290   // ValueAsMetadata or a DIArgList.
291 
292   DbgRecordParamRef<DILocalVariable> Variable;
293   DbgRecordParamRef<DIExpression> Expression;
294   DbgRecordParamRef<DIExpression> AddressExpression;
295 
296 public:
297   /// Create a new DbgVariableRecord representing the intrinsic \p DVI, for
298   /// example the assignment represented by a dbg.value.
299   DbgVariableRecord(const DbgVariableIntrinsic *DVI);
300   DbgVariableRecord(const DbgVariableRecord &DVR);
301   /// Directly construct a new DbgVariableRecord representing a dbg.value
302   /// intrinsic assigning \p Location to the DV / Expr / DI variable.
303   DbgVariableRecord(Metadata *Location, DILocalVariable *DV, DIExpression *Expr,
304                     const DILocation *DI,
305                     LocationType Type = LocationType::Value);
306   DbgVariableRecord(Metadata *Value, DILocalVariable *Variable,
307                     DIExpression *Expression, DIAssignID *AssignID,
308                     Metadata *Address, DIExpression *AddressExpression,
309                     const DILocation *DI);
310 
311 private:
312   /// Private constructor for creating new instances during parsing only. Only
313   /// called through `createUnresolvedDbgVariableRecord` below, which makes
314   /// clear that this is used for parsing only, and will later return a subclass
315   /// depending on which Type is passed.
316   DbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable,
317                     MDNode *Expression, MDNode *AssignID, Metadata *Address,
318                     MDNode *AddressExpression, MDNode *DI);
319 
320 public:
321   /// Used to create DbgVariableRecords during parsing, where some metadata
322   /// references may still be unresolved. Although for some fields a generic
323   /// `Metadata*` argument is accepted for forward type-references, the verifier
324   /// and accessors will reject incorrect types later on. The function is used
325   /// for all types of DbgVariableRecords for simplicity while parsing, but
326   /// asserts if any necessary fields are empty or unused fields are not empty,
327   /// i.e. if the #dbg_assign fields are used for a non-dbg-assign type.
328   static DbgVariableRecord *
329   createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val,
330                                     MDNode *Variable, MDNode *Expression,
331                                     MDNode *AssignID, Metadata *Address,
332                                     MDNode *AddressExpression, MDNode *DI);
333 
334   static DbgVariableRecord *
335   createDVRAssign(Value *Val, DILocalVariable *Variable,
336                   DIExpression *Expression, DIAssignID *AssignID,
337                   Value *Address, DIExpression *AddressExpression,
338                   const DILocation *DI);
339   static DbgVariableRecord *
340   createLinkedDVRAssign(Instruction *LinkedInstr, Value *Val,
341                         DILocalVariable *Variable, DIExpression *Expression,
342                         Value *Address, DIExpression *AddressExpression,
343                         const DILocation *DI);
344 
345   static DbgVariableRecord *createDbgVariableRecord(Value *Location,
346                                                     DILocalVariable *DV,
347                                                     DIExpression *Expr,
348                                                     const DILocation *DI);
349   static DbgVariableRecord *
350   createDbgVariableRecord(Value *Location, DILocalVariable *DV,
351                           DIExpression *Expr, const DILocation *DI,
352                           DbgVariableRecord &InsertBefore);
353   static DbgVariableRecord *createDVRDeclare(Value *Address,
354                                              DILocalVariable *DV,
355                                              DIExpression *Expr,
356                                              const DILocation *DI);
357   static DbgVariableRecord *
358   createDVRDeclare(Value *Address, DILocalVariable *DV, DIExpression *Expr,
359                    const DILocation *DI, DbgVariableRecord &InsertBefore);
360 
361   /// Iterator for ValueAsMetadata that internally uses direct pointer iteration
362   /// over either a ValueAsMetadata* or a ValueAsMetadata**, dereferencing to the
363   /// ValueAsMetadata .
364   class location_op_iterator
365       : public iterator_facade_base<location_op_iterator,
366                                     std::bidirectional_iterator_tag, Value *> {
367     PointerUnion<ValueAsMetadata *, ValueAsMetadata **> I;
368 
369   public:
370     location_op_iterator(ValueAsMetadata *SingleIter) : I(SingleIter) {}
371     location_op_iterator(ValueAsMetadata **MultiIter) : I(MultiIter) {}
372 
373     location_op_iterator(const location_op_iterator &R) : I(R.I) {}
374     location_op_iterator &operator=(const location_op_iterator &R) {
375       I = R.I;
376       return *this;
377     }
378     bool operator==(const location_op_iterator &RHS) const {
379       return I == RHS.I;
380     }
381     const Value *operator*() const {
382       ValueAsMetadata *VAM = isa<ValueAsMetadata *>(I)
383                                  ? cast<ValueAsMetadata *>(I)
384                                  : *cast<ValueAsMetadata **>(I);
385       return VAM->getValue();
386     };
387     Value *operator*() {
388       ValueAsMetadata *VAM = isa<ValueAsMetadata *>(I)
389                                  ? cast<ValueAsMetadata *>(I)
390                                  : *cast<ValueAsMetadata **>(I);
391       return VAM->getValue();
392     }
393     location_op_iterator &operator++() {
394       if (auto *VAM = dyn_cast<ValueAsMetadata *>(I))
395         I = VAM + 1;
396       else
397         I = cast<ValueAsMetadata **>(I) + 1;
398       return *this;
399     }
400     location_op_iterator &operator--() {
401       if (auto *VAM = dyn_cast<ValueAsMetadata *>(I))
402         I = VAM - 1;
403       else
404         I = cast<ValueAsMetadata **>(I) - 1;
405       return *this;
406     }
407   };
408 
409   bool isDbgDeclare() const { return Type == LocationType::Declare; }
410   bool isDbgValue() const { return Type == LocationType::Value; }
411 
412   /// Get the locations corresponding to the variable referenced by the debug
413   /// info intrinsic.  Depending on the intrinsic, this could be the
414   /// variable's value or its address.
415   iterator_range<location_op_iterator> location_ops() const;
416 
417   Value *getVariableLocationOp(unsigned OpIdx) const;
418 
419   void replaceVariableLocationOp(Value *OldValue, Value *NewValue,
420                                  bool AllowEmpty = false);
421   void replaceVariableLocationOp(unsigned OpIdx, Value *NewValue);
422   /// Adding a new location operand will always result in this intrinsic using
423   /// an ArgList, and must always be accompanied by a new expression that uses
424   /// the new operand.
425   void addVariableLocationOps(ArrayRef<Value *> NewValues,
426                               DIExpression *NewExpr);
427 
428   unsigned getNumVariableLocationOps() const;
429 
430   bool hasArgList() const { return isa<DIArgList>(getRawLocation()); }
431   /// Returns true if this DbgVariableRecord has no empty MDNodes in its
432   /// location list.
433   bool hasValidLocation() const { return getVariableLocationOp(0) != nullptr; }
434 
435   /// Does this describe the address of a local variable. True for dbg.addr
436   /// and dbg.declare, but not dbg.value, which describes its value.
437   bool isAddressOfVariable() const { return Type == LocationType::Declare; }
438 
439   /// Determine if this describes the value of a local variable. It is false for
440   /// dbg.declare, but true for dbg.value, which describes its value.
441   bool isValueOfVariable() const { return Type == LocationType::Value; }
442 
443   LocationType getType() const { return Type; }
444 
445   void setKillLocation();
446   bool isKillLocation() const;
447 
448   void setVariable(DILocalVariable *NewVar) { Variable = NewVar; }
449   DILocalVariable *getVariable() const { return Variable.get(); };
450   MDNode *getRawVariable() const { return Variable.getAsMDNode(); }
451 
452   void setExpression(DIExpression *NewExpr) { Expression = NewExpr; }
453   DIExpression *getExpression() const { return Expression.get(); }
454   MDNode *getRawExpression() const { return Expression.getAsMDNode(); }
455 
456   /// Returns the metadata operand for the first location description. i.e.,
457   /// dbg intrinsic dbg.value,declare operand and dbg.assign 1st location
458   /// operand (the "value componenet"). Note the operand (singular) may be
459   /// a DIArgList which is a list of values.
460   Metadata *getRawLocation() const { return DebugValues[0]; }
461 
462   Value *getValue(unsigned OpIdx = 0) const {
463     return getVariableLocationOp(OpIdx);
464   }
465 
466   /// Use of this should generally be avoided; instead,
467   /// replaceVariableLocationOp and addVariableLocationOps should be used where
468   /// possible to avoid creating invalid state.
469   void setRawLocation(Metadata *NewLocation) {
470     assert((isa<ValueAsMetadata>(NewLocation) || isa<DIArgList>(NewLocation) ||
471             isa<MDNode>(NewLocation)) &&
472            "Location for a DbgVariableRecord must be either ValueAsMetadata or "
473            "DIArgList");
474     resetDebugValue(0, NewLocation);
475   }
476 
477   std::optional<DbgVariableFragmentInfo> getFragment() const;
478   /// Get the FragmentInfo for the variable if it exists, otherwise return a
479   /// FragmentInfo that covers the entire variable if the variable size is
480   /// known, otherwise return a zero-sized fragment.
481   DbgVariableFragmentInfo getFragmentOrEntireVariable() const {
482     if (auto Frag = getFragment())
483       return *Frag;
484     if (auto Sz = getFragmentSizeInBits())
485       return {*Sz, 0};
486     return {0, 0};
487   }
488   /// Get the size (in bits) of the variable, or fragment of the variable that
489   /// is described.
490   std::optional<uint64_t> getFragmentSizeInBits() const;
491 
492   bool isEquivalentTo(const DbgVariableRecord &Other) const {
493     return DbgLoc == Other.DbgLoc && isIdenticalToWhenDefined(Other);
494   }
495   // Matches the definition of the Instruction version, equivalent to above but
496   // without checking DbgLoc.
497   bool isIdenticalToWhenDefined(const DbgVariableRecord &Other) const {
498     return std::tie(Type, DebugValues, Variable, Expression,
499                     AddressExpression) ==
500            std::tie(Other.Type, Other.DebugValues, Other.Variable,
501                     Other.Expression, Other.AddressExpression);
502   }
503 
504   /// @name DbgAssign Methods
505   /// @{
506   bool isDbgAssign() const { return getType() == LocationType::Assign; }
507 
508   Value *getAddress() const;
509   Metadata *getRawAddress() const {
510     return isDbgAssign() ? DebugValues[1] : DebugValues[0];
511   }
512   Metadata *getRawAssignID() const { return DebugValues[2]; }
513   DIAssignID *getAssignID() const;
514   DIExpression *getAddressExpression() const { return AddressExpression.get(); }
515   MDNode *getRawAddressExpression() const {
516     return AddressExpression.getAsMDNode();
517   }
518   void setAddressExpression(DIExpression *NewExpr) {
519     AddressExpression = NewExpr;
520   }
521   void setAssignId(DIAssignID *New);
522   void setAddress(Value *V) { resetDebugValue(1, ValueAsMetadata::get(V)); }
523   /// Kill the address component.
524   void setKillAddress();
525   /// Check whether this kills the address component. This doesn't take into
526   /// account the position of the intrinsic, therefore a returned value of false
527   /// does not guarentee the address is a valid location for the variable at the
528   /// intrinsic's position in IR.
529   bool isKillAddress() const;
530 
531   /// @}
532 
533   DbgVariableRecord *clone() const;
534   /// Convert this DbgVariableRecord back into a dbg.value intrinsic.
535   /// \p InsertBefore Optional position to insert this intrinsic.
536   /// \returns A new dbg.value intrinsic representiung this DbgVariableRecord.
537   DbgVariableIntrinsic *createDebugIntrinsic(Module *M,
538                                              Instruction *InsertBefore) const;
539 
540   /// Handle changes to the location of the Value(s) that we refer to happening
541   /// "under our feet".
542   void handleChangedLocation(Metadata *NewLocation);
543 
544   void print(raw_ostream &O, bool IsForDebug = false) const;
545   void print(raw_ostream &ROS, ModuleSlotTracker &MST, bool IsForDebug) const;
546 
547   /// Support type inquiry through isa, cast, and dyn_cast.
548   static bool classof(const DbgRecord *E) {
549     return E->getRecordKind() == ValueKind;
550   }
551 };
552 
553 /// Filter the DbgRecord range to DbgVariableRecord types only and downcast.
554 static inline auto
555 filterDbgVars(iterator_range<simple_ilist<DbgRecord>::iterator> R) {
556   return map_range(
557       make_filter_range(R,
558                         [](DbgRecord &E) { return isa<DbgVariableRecord>(E); }),
559       [](DbgRecord &E) { return std::ref(cast<DbgVariableRecord>(E)); });
560 }
561 
562 /// Per-instruction record of debug-info. If an Instruction is the position of
563 /// some debugging information, it points at a DbgMarker storing that info. Each
564 /// marker points back at the instruction that owns it. Various utilities are
565 /// provided for manipulating the DbgRecords contained within this marker.
566 ///
567 /// This class has a rough surface area, because it's needed to preserve the
568 /// one arefact that we can't yet eliminate from the intrinsic / dbg.value
569 /// debug-info design: the order of records is significant, and duplicates can
570 /// exist. Thus, if one has a run of debug-info records such as:
571 ///    dbg.value(...
572 ///    %foo = barinst
573 ///    dbg.value(...
574 /// and remove barinst, then the dbg.values must be preserved in the correct
575 /// order. Hence, the use of iterators to select positions to insert things
576 /// into, or the occasional InsertAtHead parameter indicating that new records
577 /// should go at the start of the list.
578 ///
579 /// There are only five or six places in LLVM that truly rely on this ordering,
580 /// which we can improve in the future. Additionally, many improvements in the
581 /// way that debug-info is stored can be achieved in this class, at a future
582 /// date.
583 class DbgMarker {
584 public:
585   DbgMarker() {}
586   /// Link back to the Instruction that owns this marker. Can be null during
587   /// operations that move a marker from one instruction to another.
588   Instruction *MarkedInstr = nullptr;
589 
590   /// List of DbgRecords, the non-instruction equivalent of llvm.dbg.*
591   /// intrinsics. There is a one-to-one relationship between each debug
592   /// intrinsic in a block and each DbgRecord once the representation has been
593   /// converted, and the ordering is meaningful in the same way.
594   simple_ilist<DbgRecord> StoredDbgRecords;
595   bool empty() const { return StoredDbgRecords.empty(); }
596 
597   const BasicBlock *getParent() const;
598   BasicBlock *getParent();
599 
600   /// Handle the removal of a marker: the position of debug-info has gone away,
601   /// but the stored debug records should not. Drop them onto the next
602   /// instruction, or otherwise work out what to do with them.
603   void removeMarker();
604   void dump() const;
605 
606   void removeFromParent();
607   void eraseFromParent();
608 
609   /// Implement operator<< on DbgMarker.
610   void print(raw_ostream &O, bool IsForDebug = false) const;
611   void print(raw_ostream &ROS, ModuleSlotTracker &MST, bool IsForDebug) const;
612 
613   /// Produce a range over all the DbgRecords in this Marker.
614   iterator_range<simple_ilist<DbgRecord>::iterator> getDbgRecordRange();
615   iterator_range<simple_ilist<DbgRecord>::const_iterator>
616   getDbgRecordRange() const;
617   /// Transfer any DbgRecords from \p Src into this DbgMarker. If \p
618   /// InsertAtHead is true, place them before existing DbgRecords, otherwise
619   /// afterwards.
620   void absorbDebugValues(DbgMarker &Src, bool InsertAtHead);
621   /// Transfer the DbgRecords in \p Range from \p Src into this DbgMarker. If
622   /// \p InsertAtHead is true, place them before existing DbgRecords, otherwise
623   // afterwards.
624   void absorbDebugValues(iterator_range<DbgRecord::self_iterator> Range,
625                          DbgMarker &Src, bool InsertAtHead);
626   /// Insert a DbgRecord into this DbgMarker, at the end of the list. If
627   /// \p InsertAtHead is true, at the start.
628   void insertDbgRecord(DbgRecord *New, bool InsertAtHead);
629   /// Insert a DbgRecord prior to a DbgRecord contained within this marker.
630   void insertDbgRecord(DbgRecord *New, DbgRecord *InsertBefore);
631   /// Insert a DbgRecord after a DbgRecord contained within this marker.
632   void insertDbgRecordAfter(DbgRecord *New, DbgRecord *InsertAfter);
633   /// Clone all DbgMarkers from \p From into this marker. There are numerous
634   /// options to customise the source/destination, due to gnarliness, see class
635   /// comment.
636   /// \p FromHere If non-null, copy from FromHere to the end of From's
637   /// DbgRecords
638   /// \p InsertAtHead Place the cloned DbgRecords at the start of
639   /// StoredDbgRecords
640   /// \returns Range over all the newly cloned DbgRecords
641   iterator_range<simple_ilist<DbgRecord>::iterator>
642   cloneDebugInfoFrom(DbgMarker *From,
643                      std::optional<simple_ilist<DbgRecord>::iterator> FromHere,
644                      bool InsertAtHead = false);
645   /// Erase all DbgRecords in this DbgMarker.
646   void dropDbgRecords();
647   /// Erase a single DbgRecord from this marker. In an ideal future, we would
648   /// never erase an assignment in this way, but it's the equivalent to
649   /// erasing a debug intrinsic from a block.
650   void dropOneDbgRecord(DbgRecord *DR);
651 
652   /// We generally act like all llvm Instructions have a range of DbgRecords
653   /// attached to them, but in reality sometimes we don't allocate the DbgMarker
654   /// to save time and memory, but still have to return ranges of DbgRecords.
655   /// When we need to describe such an unallocated DbgRecord range, use this
656   /// static markers range instead. This will bite us if someone tries to insert
657   /// a DbgRecord in that range, but they should be using the Official (TM) API
658   /// for that.
659   static DbgMarker EmptyDbgMarker;
660   static iterator_range<simple_ilist<DbgRecord>::iterator>
661   getEmptyDbgRecordRange() {
662     return make_range(EmptyDbgMarker.StoredDbgRecords.end(),
663                       EmptyDbgMarker.StoredDbgRecords.end());
664   }
665 };
666 
667 inline raw_ostream &operator<<(raw_ostream &OS, const DbgMarker &Marker) {
668   Marker.print(OS);
669   return OS;
670 }
671 
672 /// Inline helper to return a range of DbgRecords attached to a marker. It needs
673 /// to be inlined as it's frequently called, but also come after the declaration
674 /// of DbgMarker. Thus: it's pre-declared by users like Instruction, then an
675 /// inlineable body defined here.
676 inline iterator_range<simple_ilist<DbgRecord>::iterator>
677 getDbgRecordRange(DbgMarker *DebugMarker) {
678   if (!DebugMarker)
679     return DbgMarker::getEmptyDbgRecordRange();
680   return DebugMarker->getDbgRecordRange();
681 }
682 
683 DEFINE_ISA_CONVERSION_FUNCTIONS(DbgRecord, LLVMDbgRecordRef)
684 
685 /// Used to temporarily set the debug info format of a function, module, or
686 /// basic block for the duration of this object's lifetime, after which the
687 /// prior state will be restored.
688 template <typename T> class ScopedDbgInfoFormatSetter {
689   T &Obj;
690   bool OldState;
691 
692 public:
693   ScopedDbgInfoFormatSetter(T &Obj, bool NewState)
694       : Obj(Obj), OldState(Obj.IsNewDbgInfoFormat) {
695     Obj.setIsNewDbgInfoFormat(NewState);
696   }
697   ~ScopedDbgInfoFormatSetter() { Obj.setIsNewDbgInfoFormat(OldState); }
698 };
699 
700 template <typename T>
701 ScopedDbgInfoFormatSetter(T &Obj,
702                           bool NewState) -> ScopedDbgInfoFormatSetter<T>;
703 
704 } // namespace llvm
705 
706 #endif // LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
707