1//===- InstrRefBasedImpl.h - Tracking Debug Value MIs ---------------------===//
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#ifndef LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
10#define LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
11
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/IndexedMap.h"
14#include "llvm/ADT/SmallPtrSet.h"
15#include "llvm/ADT/SmallVector.h"
16#include "llvm/ADT/UniqueVector.h"
17#include "llvm/CodeGen/LexicalScopes.h"
18#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/CodeGen/MachineInstr.h"
20#include "llvm/CodeGen/TargetRegisterInfo.h"
21#include "llvm/IR/DebugInfoMetadata.h"
22#include "llvm/Support/Compiler.h"
23#include <optional>
24
25#include "LiveDebugValues.h"
26
27class TransferTracker;
28
29// Forward dec of unit test class, so that we can peer into the LDV object.
30class InstrRefLDVTest;
31
32namespace LiveDebugValues {
33
34class MLocTracker;
35class DbgOpIDMap;
36
37using namespace llvm;
38
39using DebugVariableID = unsigned;
40using VarAndLoc = std::pair<DebugVariable, const DILocation *>;
41
42/// Mapping from DebugVariable to/from a unique identifying number. Each
43/// DebugVariable consists of three pointers, and after a small amount of
44/// work to identify overlapping fragments of variables we mostly only use
45/// DebugVariables as identities of variables. It's much more compile-time
46/// efficient to use an ID number instead, which this class provides.
47class DebugVariableMap {
48 DenseMap<DebugVariable, unsigned> VarToIdx;
49 SmallVector<VarAndLoc> IdxToVar;
50
51public:
52 DebugVariableID getDVID(const DebugVariable &Var) const {
53 auto It = VarToIdx.find(Val: Var);
54 assert(It != VarToIdx.end());
55 return It->second;
56 }
57
58 DebugVariableID insertDVID(DebugVariable &Var, const DILocation *Loc) {
59 unsigned Size = VarToIdx.size();
60 auto ItPair = VarToIdx.insert(KV: {Var, Size});
61 if (ItPair.second) {
62 IdxToVar.push_back(Elt: {Var, Loc});
63 return Size;
64 }
65
66 return ItPair.first->second;
67 }
68
69 const VarAndLoc &lookupDVID(DebugVariableID ID) const { return IdxToVar[ID]; }
70
71 void clear() {
72 VarToIdx.clear();
73 IdxToVar.clear();
74 }
75};
76
77/// Handle-class for a particular "location". This value-type uniquely
78/// symbolises a register or stack location, allowing manipulation of locations
79/// without concern for where that location is. Practically, this allows us to
80/// treat the state of the machine at a particular point as an array of values,
81/// rather than a map of values.
82class LocIdx {
83 unsigned Location;
84
85 // Default constructor is private, initializing to an illegal location number.
86 // Use only for "not an entry" elements in IndexedMaps.
87 LocIdx() : Location(UINT_MAX) {}
88
89public:
90#define NUM_LOC_BITS 24
91 LocIdx(unsigned L) : Location(L) {
92 assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
93 }
94
95 static LocIdx MakeIllegalLoc() { return LocIdx(); }
96
97 bool isIllegal() const { return Location == UINT_MAX; }
98
99 uint64_t asU64() const { return Location; }
100
101 bool operator==(unsigned L) const { return Location == L; }
102
103 bool operator==(const LocIdx &L) const { return Location == L.Location; }
104
105 bool operator!=(unsigned L) const { return !(*this == L); }
106
107 bool operator!=(const LocIdx &L) const { return !(*this == L); }
108
109 bool operator<(const LocIdx &Other) const {
110 return Location < Other.Location;
111 }
112};
113
114// The location at which a spilled value resides. It consists of a register and
115// an offset.
116struct SpillLoc {
117 unsigned SpillBase;
118 StackOffset SpillOffset;
119 bool operator==(const SpillLoc &Other) const {
120 return std::make_pair(x: SpillBase, y: SpillOffset) ==
121 std::make_pair(x: Other.SpillBase, y: Other.SpillOffset);
122 }
123 bool operator<(const SpillLoc &Other) const {
124 return std::make_tuple(args: SpillBase, args: SpillOffset.getFixed(),
125 args: SpillOffset.getScalable()) <
126 std::make_tuple(args: Other.SpillBase, args: Other.SpillOffset.getFixed(),
127 args: Other.SpillOffset.getScalable());
128 }
129};
130
131/// Unique identifier for a value defined by an instruction, as a value type.
132/// Casts back and forth to a uint64_t. Probably replacable with something less
133/// bit-constrained. Each value identifies the instruction and machine location
134/// where the value is defined, although there may be no corresponding machine
135/// operand for it (ex: regmasks clobbering values). The instructions are
136/// one-based, and definitions that are PHIs have instruction number zero.
137///
138/// The obvious limits of a 1M block function or 1M instruction blocks are
139/// problematic; but by that point we should probably have bailed out of
140/// trying to analyse the function.
141class ValueIDNum {
142 union {
143 struct {
144 uint64_t BlockNo : 20; /// The block where the def happens.
145 uint64_t InstNo : 20; /// The Instruction where the def happens.
146 /// One based, is distance from start of block.
147 uint64_t LocNo
148 : NUM_LOC_BITS; /// The machine location where the def happens.
149 } s;
150 uint64_t Value;
151 } u;
152
153 static_assert(sizeof(u) == 8, "Badly packed ValueIDNum?");
154
155public:
156 // Default-initialize to EmptyValue. This is necessary to make IndexedMaps
157 // of values to work.
158 ValueIDNum() { u.Value = EmptyValue.asU64(); }
159
160 ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) {
161 u.s = {.BlockNo: Block, .InstNo: Inst, .LocNo: Loc};
162 }
163
164 ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) {
165 u.s = {.BlockNo: Block, .InstNo: Inst, .LocNo: Loc.asU64()};
166 }
167
168 uint64_t getBlock() const { return u.s.BlockNo; }
169 uint64_t getInst() const { return u.s.InstNo; }
170 uint64_t getLoc() const { return u.s.LocNo; }
171 bool isPHI() const { return u.s.InstNo == 0; }
172
173 uint64_t asU64() const { return u.Value; }
174
175 static ValueIDNum fromU64(uint64_t v) {
176 ValueIDNum Val;
177 Val.u.Value = v;
178 return Val;
179 }
180
181 bool operator<(const ValueIDNum &Other) const {
182 return asU64() < Other.asU64();
183 }
184
185 bool operator==(const ValueIDNum &Other) const {
186 return u.Value == Other.u.Value;
187 }
188
189 bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
190
191 std::string asString(const std::string &mlocname) const {
192 return Twine("Value{bb: ")
193 .concat(Suffix: Twine(u.s.BlockNo)
194 .concat(Suffix: Twine(", inst: ")
195 .concat(Suffix: (u.s.InstNo ? Twine(u.s.InstNo)
196 : Twine("live-in"))
197 .concat(Suffix: Twine(", loc: ").concat(
198 Suffix: Twine(mlocname)))
199 .concat(Suffix: Twine("}")))))
200 .str();
201 }
202
203 LLVM_ABI_FOR_TEST static ValueIDNum EmptyValue;
204};
205
206} // End namespace LiveDebugValues
207
208namespace llvm {
209using namespace LiveDebugValues;
210
211template <> struct DenseMapInfo<LocIdx> {
212 static unsigned getHashValue(const LocIdx &Loc) { return Loc.asU64(); }
213
214 static bool isEqual(const LocIdx &A, const LocIdx &B) { return A == B; }
215};
216
217template <> struct DenseMapInfo<ValueIDNum> {
218 static unsigned getHashValue(const ValueIDNum &Val) {
219 return hash_value(value: Val.asU64());
220 }
221
222 static bool isEqual(const ValueIDNum &A, const ValueIDNum &B) {
223 return A == B;
224 }
225};
226
227} // end namespace llvm
228
229namespace LiveDebugValues {
230using namespace llvm;
231
232/// Type for a table of values in a block.
233using ValueTable = SmallVector<ValueIDNum, 0>;
234
235/// A collection of ValueTables, one per BB in a function, with convenient
236/// accessor methods.
237struct FuncValueTable {
238 FuncValueTable(int NumBBs, int NumLocs) {
239 Storage.reserve(N: NumBBs);
240 for (int i = 0; i != NumBBs; ++i)
241 Storage.push_back(
242 Elt: std::make_unique<ValueTable>(args&: NumLocs, args&: ValueIDNum::EmptyValue));
243 }
244
245 /// Returns the ValueTable associated with MBB.
246 ValueTable &operator[](const MachineBasicBlock &MBB) const {
247 return (*this)[MBB.getNumber()];
248 }
249
250 /// Returns the ValueTable associated with the MachineBasicBlock whose number
251 /// is MBBNum.
252 ValueTable &operator[](int MBBNum) const {
253 auto &TablePtr = Storage[MBBNum];
254 assert(TablePtr && "Trying to access a deleted table");
255 return *TablePtr;
256 }
257
258 /// Returns the ValueTable associated with the entry MachineBasicBlock.
259 ValueTable &tableForEntryMBB() const { return (*this)[0]; }
260
261 /// Returns true if the ValueTable associated with MBB has not been freed.
262 bool hasTableFor(MachineBasicBlock &MBB) const {
263 return Storage[MBB.getNumber()] != nullptr;
264 }
265
266 /// Frees the memory of the ValueTable associated with MBB.
267 void ejectTableForBlock(const MachineBasicBlock &MBB) {
268 Storage[MBB.getNumber()].reset();
269 }
270
271private:
272 /// ValueTables are stored as unique_ptrs to allow for deallocation during
273 /// LDV; this was measured to have a significant impact on compiler memory
274 /// usage.
275 SmallVector<std::unique_ptr<ValueTable>, 0> Storage;
276};
277
278/// Thin wrapper around an integer -- designed to give more type safety to
279/// spill location numbers.
280class SpillLocationNo {
281public:
282 explicit SpillLocationNo(unsigned SpillNo) : SpillNo(SpillNo) {}
283 unsigned SpillNo;
284 unsigned id() const { return SpillNo; }
285
286 bool operator<(const SpillLocationNo &Other) const {
287 return SpillNo < Other.SpillNo;
288 }
289
290 bool operator==(const SpillLocationNo &Other) const {
291 return SpillNo == Other.SpillNo;
292 }
293 bool operator!=(const SpillLocationNo &Other) const {
294 return !(*this == Other);
295 }
296};
297
298/// Meta qualifiers for a value. Pair of whatever expression is used to qualify
299/// the value, and Boolean of whether or not it's indirect.
300class DbgValueProperties {
301public:
302 DbgValueProperties(const DIExpression *DIExpr, bool Indirect, bool IsVariadic)
303 : DIExpr(DIExpr), Indirect(Indirect), IsVariadic(IsVariadic) {}
304
305 /// Extract properties from an existing DBG_VALUE instruction.
306 DbgValueProperties(const MachineInstr &MI) {
307 assert(MI.isDebugValue());
308 assert(MI.getDebugExpression()->getNumLocationOperands() == 0 ||
309 MI.isDebugValueList() || MI.isUndefDebugValue());
310 IsVariadic = MI.isDebugValueList();
311 DIExpr = MI.getDebugExpression();
312 Indirect = MI.isDebugOffsetImm();
313 }
314
315 bool isJoinable(const DbgValueProperties &Other) const {
316 return DIExpression::isEqualExpression(FirstExpr: DIExpr, FirstIndirect: Indirect, SecondExpr: Other.DIExpr,
317 SecondIndirect: Other.Indirect);
318 }
319
320 bool operator==(const DbgValueProperties &Other) const {
321 return std::tie(args: DIExpr, args: Indirect, args: IsVariadic) ==
322 std::tie(args: Other.DIExpr, args: Other.Indirect, args: Other.IsVariadic);
323 }
324
325 bool operator!=(const DbgValueProperties &Other) const {
326 return !(*this == Other);
327 }
328
329 unsigned getLocationOpCount() const {
330 return IsVariadic ? DIExpr->getNumLocationOperands() : 1;
331 }
332
333 const DIExpression *DIExpr;
334 bool Indirect;
335 bool IsVariadic;
336};
337
338/// TODO: Might pack better if we changed this to a Struct of Arrays, since
339/// MachineOperand is width 32, making this struct width 33. We could also
340/// potentially avoid storing the whole MachineOperand (sizeof=32), instead
341/// choosing to store just the contents portion (sizeof=8) and a Kind enum,
342/// since we already know it is some type of immediate value.
343/// Stores a single debug operand, which can either be a MachineOperand for
344/// directly storing immediate values, or a ValueIDNum representing some value
345/// computed at some point in the program. IsConst is used as a discriminator.
346struct DbgOp {
347 union {
348 ValueIDNum ID;
349 MachineOperand MO;
350 };
351 bool IsConst;
352
353 DbgOp() : ID(ValueIDNum::EmptyValue), IsConst(false) {}
354 DbgOp(ValueIDNum ID) : ID(ID), IsConst(false) {}
355 DbgOp(MachineOperand MO) : MO(MO), IsConst(true) {}
356
357 bool isUndef() const { return !IsConst && ID == ValueIDNum::EmptyValue; }
358
359#ifndef NDEBUG
360 void dump(const MLocTracker *MTrack) const;
361#endif
362};
363
364/// A DbgOp whose ID (if any) has resolved to an actual location, LocIdx. Used
365/// when working with concrete debug values, i.e. when joining MLocs and VLocs
366/// in the TransferTracker or emitting DBG_VALUE/DBG_VALUE_LIST instructions in
367/// the MLocTracker.
368struct ResolvedDbgOp {
369 union {
370 LocIdx Loc;
371 MachineOperand MO;
372 };
373 bool IsConst;
374
375 ResolvedDbgOp(LocIdx Loc) : Loc(Loc), IsConst(false) {}
376 ResolvedDbgOp(MachineOperand MO) : MO(MO), IsConst(true) {}
377
378 bool operator==(const ResolvedDbgOp &Other) const {
379 if (IsConst != Other.IsConst)
380 return false;
381 if (IsConst)
382 return MO.isIdenticalTo(Other: Other.MO);
383 return Loc == Other.Loc;
384 }
385
386#ifndef NDEBUG
387 void dump(const MLocTracker *MTrack) const;
388#endif
389};
390
391/// An ID used in the DbgOpIDMap (below) to lookup a stored DbgOp. This is used
392/// in place of actual DbgOps inside of a DbgValue to reduce its size, as
393/// DbgValue is very frequently used and passed around, and the actual DbgOp is
394/// over 8x larger than this class, due to storing a MachineOperand. This ID
395/// should be equal for all equal DbgOps, and also encodes whether the mapped
396/// DbgOp is a constant, meaning that for simple equality or const-ness checks
397/// it is not necessary to lookup this ID.
398struct DbgOpID {
399 struct IsConstIndexPair {
400 uint32_t IsConst : 1;
401 uint32_t Index : 31;
402 };
403
404 union {
405 struct IsConstIndexPair ID;
406 uint32_t RawID;
407 };
408
409 DbgOpID() : RawID(UndefID.RawID) {
410 static_assert(sizeof(DbgOpID) == 4, "DbgOpID should fit within 4 bytes.");
411 }
412 DbgOpID(uint32_t RawID) : RawID(RawID) {}
413 DbgOpID(bool IsConst, uint32_t Index) : ID({.IsConst: IsConst, .Index: Index}) {}
414
415 LLVM_ABI_FOR_TEST static DbgOpID UndefID;
416
417 bool operator==(const DbgOpID &Other) const { return RawID == Other.RawID; }
418 bool operator!=(const DbgOpID &Other) const { return !(*this == Other); }
419
420 uint32_t asU32() const { return RawID; }
421
422 bool isUndef() const { return *this == UndefID; }
423 bool isConst() const { return ID.IsConst && !isUndef(); }
424 uint32_t getIndex() const { return ID.Index; }
425
426#ifndef NDEBUG
427 void dump(const MLocTracker *MTrack, const DbgOpIDMap *OpStore) const;
428#endif
429};
430
431/// Class storing the complete set of values that are observed by DbgValues
432/// within the current function. Allows 2-way lookup, with `find` returning the
433/// Op for a given ID and `insert` returning the ID for a given Op (creating one
434/// if none exists).
435class DbgOpIDMap {
436
437 SmallVector<ValueIDNum, 0> ValueOps;
438 SmallVector<MachineOperand, 0> ConstOps;
439
440 DenseMap<ValueIDNum, DbgOpID> ValueOpToID;
441 DenseMap<MachineOperand, DbgOpID> ConstOpToID;
442
443public:
444 /// If \p Op does not already exist in this map, it is inserted and the
445 /// corresponding DbgOpID is returned. If Op already exists in this map, then
446 /// no change is made and the existing ID for Op is returned.
447 /// Calling this with the undef DbgOp will always return DbgOpID::UndefID.
448 DbgOpID insert(DbgOp Op) {
449 if (Op.isUndef())
450 return DbgOpID::UndefID;
451 if (Op.IsConst)
452 return insertConstOp(MO&: Op.MO);
453 return insertValueOp(VID: Op.ID);
454 }
455 /// Returns the DbgOp associated with \p ID. Should only be used for IDs
456 /// returned from calling `insert` from this map or DbgOpID::UndefID.
457 DbgOp find(DbgOpID ID) const {
458 if (ID == DbgOpID::UndefID)
459 return DbgOp();
460 if (ID.isConst())
461 return DbgOp(ConstOps[ID.getIndex()]);
462 return DbgOp(ValueOps[ID.getIndex()]);
463 }
464
465 void clear() {
466 ValueOps.clear();
467 ConstOps.clear();
468 ValueOpToID.clear();
469 ConstOpToID.clear();
470 }
471
472private:
473 DbgOpID insertConstOp(MachineOperand &MO) {
474 auto [It, Inserted] = ConstOpToID.try_emplace(Key: MO, Args: true, Args: ConstOps.size());
475 if (Inserted)
476 ConstOps.push_back(Elt: MO);
477 return It->second;
478 }
479 DbgOpID insertValueOp(ValueIDNum VID) {
480 auto [It, Inserted] = ValueOpToID.try_emplace(Key: VID, Args: false, Args: ValueOps.size());
481 if (Inserted)
482 ValueOps.push_back(Elt: VID);
483 return It->second;
484 }
485};
486
487// We set the maximum number of operands that we will handle to keep DbgValue
488// within a reasonable size (64 bytes), as we store and pass a lot of them
489// around.
490#define MAX_DBG_OPS 8
491
492/// Class recording the (high level) _value_ of a variable. Identifies the value
493/// of the variable as a list of ValueIDNums and constant MachineOperands, or as
494/// an empty list for undef debug values or VPHI values which we have not found
495/// valid locations for.
496/// This class also stores meta-information about how the value is qualified.
497/// Used to reason about variable values when performing the second
498/// (DebugVariable specific) dataflow analysis.
499class DbgValue {
500private:
501 /// If Kind is Def or VPHI, the set of IDs corresponding to the DbgOps that
502 /// are used. VPHIs set every ID to EmptyID when we have not found a valid
503 /// machine-value for every operand, and sets them to the corresponding
504 /// machine-values when we have found all of them.
505 DbgOpID DbgOps[MAX_DBG_OPS];
506 unsigned OpCount;
507
508public:
509 /// For a NoVal or VPHI DbgValue, which block it was generated in.
510 int BlockNo;
511
512 /// Qualifiers for the ValueIDNum above.
513 DbgValueProperties Properties;
514
515 typedef enum {
516 Undef, // Represents a DBG_VALUE $noreg in the transfer function only.
517 Def, // This value is defined by some combination of constants,
518 // instructions, or PHI values.
519 VPHI, // Incoming values to BlockNo differ, those values must be joined by
520 // a PHI in this block.
521 NoVal, // Empty DbgValue indicating an unknown value. Used as initializer,
522 // before dominating blocks values are propagated in.
523 } KindT;
524 /// Discriminator for whether this is a constant or an in-program value.
525 KindT Kind;
526
527 DbgValue(ArrayRef<DbgOpID> DbgOps, const DbgValueProperties &Prop)
528 : OpCount(DbgOps.size()), BlockNo(0), Properties(Prop), Kind(Def) {
529 static_assert(sizeof(DbgValue) <= 64,
530 "DbgValue should fit within 64 bytes.");
531 assert(DbgOps.size() == Prop.getLocationOpCount());
532 if (DbgOps.size() > MAX_DBG_OPS ||
533 any_of(Range&: DbgOps, P: [](DbgOpID ID) { return ID.isUndef(); })) {
534 Kind = Undef;
535 OpCount = 0;
536#define DEBUG_TYPE "LiveDebugValues"
537 if (DbgOps.size() > MAX_DBG_OPS) {
538 LLVM_DEBUG(dbgs() << "Found DbgValue with more than maximum allowed "
539 "operands.\n");
540 }
541#undef DEBUG_TYPE
542 } else {
543 for (unsigned Idx = 0; Idx < DbgOps.size(); ++Idx)
544 this->DbgOps[Idx] = DbgOps[Idx];
545 }
546 }
547
548 DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
549 : OpCount(0), BlockNo(BlockNo), Properties(Prop), Kind(Kind) {
550 assert(Kind == NoVal || Kind == VPHI);
551 }
552
553 DbgValue(const DbgValueProperties &Prop, KindT Kind)
554 : OpCount(0), BlockNo(0), Properties(Prop), Kind(Kind) {
555 assert(Kind == Undef &&
556 "Empty DbgValue constructor must pass in Undef kind");
557 }
558
559#ifndef NDEBUG
560 void dump(const MLocTracker *MTrack = nullptr,
561 const DbgOpIDMap *OpStore = nullptr) const;
562#endif
563
564 bool operator==(const DbgValue &Other) const {
565 if (std::tie(args: Kind, args: Properties) != std::tie(args: Other.Kind, args: Other.Properties))
566 return false;
567 else if (Kind == Def && !equal(LRange: getDbgOpIDs(), RRange: Other.getDbgOpIDs()))
568 return false;
569 else if (Kind == NoVal && BlockNo != Other.BlockNo)
570 return false;
571 else if (Kind == VPHI && BlockNo != Other.BlockNo)
572 return false;
573 else if (Kind == VPHI && !equal(LRange: getDbgOpIDs(), RRange: Other.getDbgOpIDs()))
574 return false;
575
576 return true;
577 }
578
579 bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
580
581 // Returns an array of all the machine values used to calculate this variable
582 // value, or an empty list for an Undef or unjoined VPHI.
583 ArrayRef<DbgOpID> getDbgOpIDs() const { return {DbgOps, OpCount}; }
584
585 // Returns either DbgOps[Index] if this DbgValue has Debug Operands, or
586 // the ID for ValueIDNum::EmptyValue otherwise (i.e. if this is an Undef,
587 // NoVal, or an unjoined VPHI).
588 DbgOpID getDbgOpID(unsigned Index) const {
589 if (!OpCount)
590 return DbgOpID::UndefID;
591 assert(Index < OpCount);
592 return DbgOps[Index];
593 }
594 // Replaces this DbgValue's existing DbgOpIDs (if any) with the contents of
595 // \p NewIDs. The number of DbgOpIDs passed must be equal to the number of
596 // arguments expected by this DbgValue's properties (the return value of
597 // `getLocationOpCount()`).
598 void setDbgOpIDs(ArrayRef<DbgOpID> NewIDs) {
599 // We can go from no ops to some ops, but not from some ops to no ops.
600 assert(NewIDs.size() == getLocationOpCount() &&
601 "Incorrect number of Debug Operands for this DbgValue.");
602 OpCount = NewIDs.size();
603 for (unsigned Idx = 0; Idx < NewIDs.size(); ++Idx)
604 DbgOps[Idx] = NewIDs[Idx];
605 }
606
607 // The number of debug operands expected by this DbgValue's expression.
608 // getDbgOpIDs() should return an array of this length, unless this is an
609 // Undef or an unjoined VPHI.
610 unsigned getLocationOpCount() const {
611 return Properties.getLocationOpCount();
612 }
613
614 // Returns true if this or Other are unjoined PHIs, which do not have defined
615 // Loc Ops, or if the `n`th Loc Op for this has a different constness to the
616 // `n`th Loc Op for Other.
617 bool hasJoinableLocOps(const DbgValue &Other) const {
618 if (isUnjoinedPHI() || Other.isUnjoinedPHI())
619 return true;
620 for (unsigned Idx = 0; Idx < getLocationOpCount(); ++Idx) {
621 if (getDbgOpID(Index: Idx).isConst() != Other.getDbgOpID(Index: Idx).isConst())
622 return false;
623 }
624 return true;
625 }
626
627 bool isUnjoinedPHI() const { return Kind == VPHI && OpCount == 0; }
628
629 bool hasIdenticalValidLocOps(const DbgValue &Other) const {
630 if (!OpCount)
631 return false;
632 return equal(LRange: getDbgOpIDs(), RRange: Other.getDbgOpIDs());
633 }
634};
635
636class LocIdxToIndexFunctor {
637public:
638 using argument_type = LocIdx;
639 unsigned operator()(const LocIdx &L) const { return L.asU64(); }
640};
641
642/// Tracker for what values are in machine locations. Listens to the Things
643/// being Done by various instructions, and maintains a table of what machine
644/// locations have what values (as defined by a ValueIDNum).
645///
646/// There are potentially a much larger number of machine locations on the
647/// target machine than the actual working-set size of the function. On x86 for
648/// example, we're extremely unlikely to want to track values through control
649/// or debug registers. To avoid doing so, MLocTracker has several layers of
650/// indirection going on, described below, to avoid unnecessarily tracking
651/// any location.
652///
653/// Here's a sort of diagram of the indexes, read from the bottom up:
654///
655/// Size on stack Offset on stack
656/// \ /
657/// Stack Idx (Where in slot is this?)
658/// /
659/// /
660/// Slot Num (%stack.0) /
661/// FrameIdx => SpillNum /
662/// \ /
663/// SpillID (int) Register number (int)
664/// \ /
665/// LocationID => LocIdx
666/// |
667/// LocIdx => ValueIDNum
668///
669/// The aim here is that the LocIdx => ValueIDNum vector is just an array of
670/// values in numbered locations, so that later analyses can ignore whether the
671/// location is a register or otherwise. To map a register / spill location to
672/// a LocIdx, you have to use the (sparse) LocationID => LocIdx map. And to
673/// build a LocationID for a stack slot, you need to combine identifiers for
674/// which stack slot it is and where within that slot is being described.
675///
676/// Register mask operands cause trouble by technically defining every register;
677/// various hacks are used to avoid tracking registers that are never read and
678/// only written by regmasks.
679class MLocTracker {
680public:
681 MachineFunction &MF;
682 const TargetInstrInfo &TII;
683 const TargetRegisterInfo &TRI;
684 const TargetLowering &TLI;
685
686 /// IndexedMap type, mapping from LocIdx to ValueIDNum.
687 using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
688
689 /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
690 /// packed, entries only exist for locations that are being tracked.
691 LocToValueType LocIdxToIDNum;
692
693 /// "Map" of machine location IDs (i.e., raw register or spill number) to the
694 /// LocIdx key / number for that location. There are always at least as many
695 /// as the number of registers on the target -- if the value in the register
696 /// is not being tracked, then the LocIdx value will be zero. New entries are
697 /// appended if a new spill slot begins being tracked.
698 /// This, and the corresponding reverse map persist for the analysis of the
699 /// whole function, and is necessarying for decoding various vectors of
700 /// values.
701 std::vector<LocIdx> LocIDToLocIdx;
702
703 /// Inverse map of LocIDToLocIdx.
704 IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
705
706 /// When clobbering register masks, we chose to not believe the machine model
707 /// and don't clobber SP. Do the same for SP aliases, and for efficiency,
708 /// keep a set of them here.
709 SmallSet<Register, 8> SPAliases;
710
711 /// Unique-ification of spill. Used to number them -- their LocID number is
712 /// the index in SpillLocs minus one plus NumRegs.
713 UniqueVector<SpillLoc> SpillLocs;
714
715 // If we discover a new machine location, assign it an mphi with this
716 // block number.
717 unsigned CurBB = -1;
718
719 /// Cached local copy of the number of registers the target has.
720 unsigned NumRegs;
721
722 /// Number of slot indexes the target has -- distinct segments of a stack
723 /// slot that can take on the value of a subregister, when a super-register
724 /// is written to the stack.
725 unsigned NumSlotIdxes;
726
727 /// Collection of register mask operands that have been observed. Second part
728 /// of pair indicates the instruction that they happened in. Used to
729 /// reconstruct where defs happened if we start tracking a location later
730 /// on.
731 SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
732
733 /// Pair for describing a position within a stack slot -- first the size in
734 /// bits, then the offset.
735 typedef std::pair<unsigned short, unsigned short> StackSlotPos;
736
737 /// Map from a size/offset pair describing a position in a stack slot, to a
738 /// numeric identifier for that position. Allows easier identification of
739 /// individual positions.
740 DenseMap<StackSlotPos, unsigned> StackSlotIdxes;
741
742 /// Inverse of StackSlotIdxes.
743 DenseMap<unsigned, StackSlotPos> StackIdxesToPos;
744
745 /// Iterator for locations and the values they contain. Dereferencing
746 /// produces a struct/pair containing the LocIdx key for this location,
747 /// and a reference to the value currently stored. Simplifies the process
748 /// of seeking a particular location.
749 class MLocIterator {
750 LocToValueType &ValueMap;
751 LocIdx Idx;
752
753 public:
754 class value_type {
755 public:
756 value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {}
757 const LocIdx Idx; /// Read-only index of this location.
758 ValueIDNum &Value; /// Reference to the stored value at this location.
759 };
760
761 MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
762 : ValueMap(ValueMap), Idx(Idx) {}
763
764 bool operator==(const MLocIterator &Other) const {
765 assert(&ValueMap == &Other.ValueMap);
766 return Idx == Other.Idx;
767 }
768
769 bool operator!=(const MLocIterator &Other) const {
770 return !(*this == Other);
771 }
772
773 void operator++() { Idx = LocIdx(Idx.asU64() + 1); }
774
775 value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); }
776 };
777
778 LLVM_ABI_FOR_TEST MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
779 const TargetRegisterInfo &TRI,
780 const TargetLowering &TLI);
781
782 /// Produce location ID number for a Register. Provides some small amount of
783 /// type safety.
784 /// \param Reg The register we're looking up.
785 unsigned getLocID(Register Reg) { return Reg.id(); }
786
787 /// Produce location ID number for a spill position.
788 /// \param Spill The number of the spill we're fetching the location for.
789 /// \param SpillSubReg Subregister within the spill we're addressing.
790 unsigned getLocID(SpillLocationNo Spill, unsigned SpillSubReg) {
791 unsigned short Size = TRI.getSubRegIdxSize(Idx: SpillSubReg);
792 unsigned short Offs = TRI.getSubRegIdxOffset(Idx: SpillSubReg);
793 return getLocID(Spill, Idx: {Size, Offs});
794 }
795
796 /// Produce location ID number for a spill position.
797 /// \param Spill The number of the spill we're fetching the location for.
798 /// \apram SpillIdx size/offset within the spill slot to be addressed.
799 unsigned getLocID(SpillLocationNo Spill, StackSlotPos Idx) {
800 unsigned SlotNo = Spill.id() - 1;
801 SlotNo *= NumSlotIdxes;
802 assert(StackSlotIdxes.contains(Idx));
803 SlotNo += StackSlotIdxes[Idx];
804 SlotNo += NumRegs;
805 return SlotNo;
806 }
807
808 /// Given a spill number, and a slot within the spill, calculate the ID number
809 /// for that location.
810 unsigned getSpillIDWithIdx(SpillLocationNo Spill, unsigned Idx) {
811 unsigned SlotNo = Spill.id() - 1;
812 SlotNo *= NumSlotIdxes;
813 SlotNo += Idx;
814 SlotNo += NumRegs;
815 return SlotNo;
816 }
817
818 /// Return the spill number that a location ID corresponds to.
819 SpillLocationNo locIDToSpill(unsigned ID) const {
820 assert(ID >= NumRegs);
821 ID -= NumRegs;
822 // Truncate away the index part, leaving only the spill number.
823 ID /= NumSlotIdxes;
824 return SpillLocationNo(ID + 1); // The UniqueVector is one-based.
825 }
826
827 /// Returns the spill-slot size/offs that a location ID corresponds to.
828 StackSlotPos locIDToSpillIdx(unsigned ID) const {
829 assert(ID >= NumRegs);
830 ID -= NumRegs;
831 unsigned Idx = ID % NumSlotIdxes;
832 return StackIdxesToPos.find(Val: Idx)->second;
833 }
834
835 unsigned getNumLocs() const { return LocIdxToIDNum.size(); }
836
837 /// Reset all locations to contain a PHI value at the designated block. Used
838 /// sometimes for actual PHI values, othertimes to indicate the block entry
839 /// value (before any more information is known).
840 void setMPhis(unsigned NewCurBB) {
841 CurBB = NewCurBB;
842 for (auto Location : locations())
843 Location.Value = {CurBB, 0, Location.Idx};
844 }
845
846 /// Load values for each location from array of ValueIDNums. Take current
847 /// bbnum just in case we read a value from a hitherto untouched register.
848 void loadFromArray(ValueTable &Locs, unsigned NewCurBB) {
849 CurBB = NewCurBB;
850 // Iterate over all tracked locations, and load each locations live-in
851 // value into our local index.
852 for (auto Location : locations())
853 Location.Value = Locs[Location.Idx.asU64()];
854 }
855
856 /// Wipe any un-necessary location records after traversing a block.
857 void reset() {
858 // We could reset all the location values too; however either loadFromArray
859 // or setMPhis should be called before this object is re-used. Just
860 // clear Masks, they're definitely not needed.
861 Masks.clear();
862 }
863
864 /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
865 /// the information in this pass uninterpretable.
866 void clear() {
867 reset();
868 LocIDToLocIdx.clear();
869 LocIdxToLocID.clear();
870 LocIdxToIDNum.clear();
871 // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from
872 // 0
873 SpillLocs = decltype(SpillLocs)();
874 StackSlotIdxes.clear();
875 StackIdxesToPos.clear();
876
877 LocIDToLocIdx.resize(new_size: NumRegs, x: LocIdx::MakeIllegalLoc());
878 }
879
880 /// Set a locaiton to a certain value.
881 void setMLoc(LocIdx L, ValueIDNum Num) {
882 assert(L.asU64() < LocIdxToIDNum.size());
883 LocIdxToIDNum[L] = Num;
884 }
885
886 /// Read the value of a particular location
887 ValueIDNum readMLoc(LocIdx L) {
888 assert(L.asU64() < LocIdxToIDNum.size());
889 return LocIdxToIDNum[L];
890 }
891
892 /// Create a LocIdx for an untracked register ID. Initialize it to either an
893 /// mphi value representing a live-in, or a recent register mask clobber.
894 LLVM_ABI_FOR_TEST LocIdx trackRegister(unsigned ID);
895
896 LocIdx lookupOrTrackRegister(unsigned ID) {
897 LocIdx &Index = LocIDToLocIdx[ID];
898 if (Index.isIllegal())
899 Index = trackRegister(ID);
900 return Index;
901 }
902
903 /// Is register R currently tracked by MLocTracker?
904 bool isRegisterTracked(Register R) {
905 LocIdx &Index = LocIDToLocIdx[R];
906 return !Index.isIllegal();
907 }
908
909 /// Record a definition of the specified register at the given block / inst.
910 /// This doesn't take a ValueIDNum, because the definition and its location
911 /// are synonymous.
912 void defReg(Register R, unsigned BB, unsigned Inst) {
913 unsigned ID = getLocID(Reg: R);
914 LocIdx Idx = lookupOrTrackRegister(ID);
915 ValueIDNum ValueID = {BB, Inst, Idx};
916 LocIdxToIDNum[Idx] = ValueID;
917 }
918
919 /// Set a register to a value number. To be used if the value number is
920 /// known in advance.
921 void setReg(Register R, ValueIDNum ValueID) {
922 unsigned ID = getLocID(Reg: R);
923 LocIdx Idx = lookupOrTrackRegister(ID);
924 LocIdxToIDNum[Idx] = ValueID;
925 }
926
927 ValueIDNum readReg(Register R) {
928 unsigned ID = getLocID(Reg: R);
929 LocIdx Idx = lookupOrTrackRegister(ID);
930 return LocIdxToIDNum[Idx];
931 }
932
933 /// Reset a register value to zero / empty. Needed to replicate the
934 /// VarLoc implementation where a copy to/from a register effectively
935 /// clears the contents of the source register. (Values can only have one
936 /// machine location in VarLocBasedImpl).
937 void wipeRegister(Register R) {
938 unsigned ID = getLocID(Reg: R);
939 LocIdx Idx = LocIDToLocIdx[ID];
940 LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
941 }
942
943 /// Determine the LocIdx of an existing register.
944 LocIdx getRegMLoc(Register R) {
945 unsigned ID = getLocID(Reg: R);
946 assert(ID < LocIDToLocIdx.size());
947 assert(LocIDToLocIdx[ID] != UINT_MAX); // Sentinel for IndexedMap.
948 return LocIDToLocIdx[ID];
949 }
950
951 /// Record a RegMask operand being executed. Defs any register we currently
952 /// track, stores a pointer to the mask in case we have to account for it
953 /// later.
954 void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID);
955
956 /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
957 /// Returns std::nullopt when in scenarios where a spill slot could be
958 /// tracked, but we would likely run into resource limitations.
959 LLVM_ABI_FOR_TEST std::optional<SpillLocationNo>
960 getOrTrackSpillLoc(SpillLoc L);
961
962 // Get LocIdx of a spill ID.
963 LocIdx getSpillMLoc(unsigned SpillID) {
964 assert(LocIDToLocIdx[SpillID] != UINT_MAX); // Sentinel for IndexedMap.
965 return LocIDToLocIdx[SpillID];
966 }
967
968 /// Return true if Idx is a spill machine location.
969 bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; }
970
971 /// How large is this location (aka, how wide is a value defined there?).
972 unsigned getLocSizeInBits(LocIdx L) const {
973 unsigned ID = LocIdxToLocID[L];
974 if (!isSpill(Idx: L)) {
975 return TRI.getRegSizeInBits(Reg: Register(ID), MRI: MF.getRegInfo());
976 } else {
977 // The slot location on the stack is uninteresting, we care about the
978 // position of the value within the slot (which comes with a size).
979 StackSlotPos Pos = locIDToSpillIdx(ID);
980 return Pos.first;
981 }
982 }
983
984 MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); }
985
986 MLocIterator end() {
987 return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
988 }
989
990 /// Return a range over all locations currently tracked.
991 iterator_range<MLocIterator> locations() {
992 return llvm::make_range(x: begin(), y: end());
993 }
994
995 std::string LocIdxToName(LocIdx Idx) const;
996
997 std::string IDAsString(const ValueIDNum &Num) const;
998
999#ifndef NDEBUG
1000 LLVM_DUMP_METHOD void dump();
1001
1002 LLVM_DUMP_METHOD void dump_mloc_map();
1003#endif
1004
1005 /// Create a DBG_VALUE based on debug operands \p DbgOps. Qualify it with the
1006 /// information in \pProperties, for variable Var. Don't insert it anywhere,
1007 /// just return the builder for it.
1008 MachineInstrBuilder emitLoc(const SmallVectorImpl<ResolvedDbgOp> &DbgOps,
1009 const DebugVariable &Var, const DILocation *DILoc,
1010 const DbgValueProperties &Properties);
1011};
1012
1013/// Types for recording sets of variable fragments that overlap. For a given
1014/// local variable, we record all other fragments of that variable that could
1015/// overlap it, to reduce search time.
1016using FragmentOfVar =
1017 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
1018using OverlapMap =
1019 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
1020
1021/// Collection of DBG_VALUEs observed when traversing a block. Records each
1022/// variable and the value the DBG_VALUE refers to. Requires the machine value
1023/// location dataflow algorithm to have run already, so that values can be
1024/// identified.
1025class VLocTracker {
1026public:
1027 /// Ref to function-wide map of DebugVariable <=> ID-numbers.
1028 DebugVariableMap &DVMap;
1029 /// Map DebugVariable to the latest Value it's defined to have.
1030 /// Needs to be a MapVector because we determine order-in-the-input-MIR from
1031 /// the order in this container. (FIXME: likely no longer true as the ordering
1032 /// is now provided by DebugVariableMap).
1033 /// We only retain the last DbgValue in each block for each variable, to
1034 /// determine the blocks live-out variable value. The Vars container forms the
1035 /// transfer function for this block, as part of the dataflow analysis. The
1036 /// movement of values between locations inside of a block is handled at a
1037 /// much later stage, in the TransferTracker class.
1038 SmallMapVector<DebugVariableID, DbgValue, 8> Vars;
1039 SmallDenseMap<DebugVariableID, const DILocation *, 8> Scopes;
1040 MachineBasicBlock *MBB = nullptr;
1041 const OverlapMap &OverlappingFragments;
1042 DbgValueProperties EmptyProperties;
1043
1044public:
1045 VLocTracker(DebugVariableMap &DVMap, const OverlapMap &O,
1046 const DIExpression *EmptyExpr)
1047 : DVMap(DVMap), OverlappingFragments(O),
1048 EmptyProperties(EmptyExpr, false, false) {}
1049
1050 void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
1051 const SmallVectorImpl<DbgOpID> &DebugOps) {
1052 assert(MI.isDebugValueLike());
1053 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1054 MI.getDebugLoc()->getInlinedAt());
1055 // Either insert or fetch an ID number for this variable.
1056 DebugVariableID VarID = DVMap.insertDVID(Var, Loc: MI.getDebugLoc().get());
1057 DbgValue Rec = (DebugOps.size() > 0)
1058 ? DbgValue(DebugOps, Properties)
1059 : DbgValue(Properties, DbgValue::Undef);
1060
1061 // Attempt insertion; overwrite if it's already mapped.
1062 Vars.insert_or_assign(Key: VarID, Val&: Rec);
1063 Scopes[VarID] = MI.getDebugLoc().get();
1064
1065 considerOverlaps(Var, Loc: MI.getDebugLoc().get());
1066 }
1067
1068 void considerOverlaps(const DebugVariable &Var, const DILocation *Loc) {
1069 auto Overlaps = OverlappingFragments.find(
1070 Val: {Var.getVariable(), Var.getFragmentOrDefault()});
1071 if (Overlaps == OverlappingFragments.end())
1072 return;
1073
1074 // Otherwise: terminate any overlapped variable locations.
1075 for (auto FragmentInfo : Overlaps->second) {
1076 // The "empty" fragment is stored as DebugVariable::DefaultFragment, so
1077 // that it overlaps with everything, however its cannonical representation
1078 // in a DebugVariable is as "None".
1079 std::optional<DIExpression::FragmentInfo> OptFragmentInfo = FragmentInfo;
1080 if (DebugVariable::isDefaultFragment(F: FragmentInfo))
1081 OptFragmentInfo = std::nullopt;
1082
1083 DebugVariable Overlapped(Var.getVariable(), OptFragmentInfo,
1084 Var.getInlinedAt());
1085 // Produce an ID number for this overlapping fragment of a variable.
1086 DebugVariableID OverlappedID = DVMap.insertDVID(Var&: Overlapped, Loc);
1087 DbgValue Rec = DbgValue(EmptyProperties, DbgValue::Undef);
1088
1089 // Attempt insertion; overwrite if it's already mapped.
1090 Vars.insert_or_assign(Key: OverlappedID, Val&: Rec);
1091 Scopes[OverlappedID] = Loc;
1092 }
1093 }
1094
1095 void clear() {
1096 Vars.clear();
1097 Scopes.clear();
1098 }
1099};
1100
1101// XXX XXX docs
1102class InstrRefBasedLDV : public LDVImpl {
1103public:
1104 friend class ::InstrRefLDVTest;
1105
1106 using FragmentInfo = DIExpression::FragmentInfo;
1107 using OptFragmentInfo = std::optional<DIExpression::FragmentInfo>;
1108
1109 // Helper while building OverlapMap, a map of all fragments seen for a given
1110 // DILocalVariable.
1111 using VarToFragments =
1112 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
1113
1114 /// Machine location/value transfer function, a mapping of which locations
1115 /// are assigned which new values.
1116 using MLocTransferMap = SmallDenseMap<LocIdx, ValueIDNum>;
1117
1118 /// Live in/out structure for the variable values: a per-block map of
1119 /// variables to their values.
1120 using LiveIdxT = SmallDenseMap<const MachineBasicBlock *, DbgValue *, 16>;
1121
1122 using VarAndLoc = std::pair<DebugVariableID, DbgValue>;
1123
1124 /// Type for a live-in value: the predecessor block, and its value.
1125 using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
1126
1127 /// Vector (per block) of a collection (inner smallvector) of live-ins.
1128 /// Used as the result type for the variable value dataflow problem.
1129 using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
1130
1131 /// Mapping from lexical scopes to a DILocation in that scope.
1132 using ScopeToDILocT = DenseMap<const LexicalScope *, const DILocation *>;
1133
1134 /// Mapping from lexical scopes to variables in that scope.
1135 using ScopeToVarsT =
1136 DenseMap<const LexicalScope *, SmallSet<DebugVariableID, 4>>;
1137
1138 /// Mapping from lexical scopes to blocks where variables in that scope are
1139 /// assigned. Such blocks aren't necessarily "in" the lexical scope, it's
1140 /// just a block where an assignment happens.
1141 using ScopeToAssignBlocksT = DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>;
1142
1143private:
1144 MachineDominatorTree *DomTree;
1145 const TargetRegisterInfo *TRI;
1146 const MachineRegisterInfo *MRI;
1147 const TargetInstrInfo *TII;
1148 const TargetFrameLowering *TFI;
1149 const MachineFrameInfo *MFI;
1150 BitVector CalleeSavedRegs;
1151 LexicalScopes LS;
1152
1153 // An empty DIExpression. Used default / placeholder DbgValueProperties
1154 // objects, as we can't have null expressions.
1155 const DIExpression *EmptyExpr;
1156
1157 /// Object to track machine locations as we step through a block. Could
1158 /// probably be a field rather than a pointer, as it's always used.
1159 MLocTracker *MTracker = nullptr;
1160
1161 /// Number of the current block LiveDebugValues is stepping through.
1162 unsigned CurBB = -1;
1163
1164 /// Number of the current instruction LiveDebugValues is evaluating.
1165 unsigned CurInst;
1166
1167 /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
1168 /// steps through a block. Reads the values at each location from the
1169 /// MLocTracker object.
1170 VLocTracker *VTracker = nullptr;
1171
1172 /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
1173 /// between locations during stepping, creates new DBG_VALUEs when values move
1174 /// location.
1175 TransferTracker *TTracker = nullptr;
1176
1177 /// Blocks which are artificial, i.e. blocks which exclusively contain
1178 /// instructions without DebugLocs, or with line 0 locations.
1179 SmallPtrSet<MachineBasicBlock *, 16> ArtificialBlocks;
1180
1181 // Mapping of blocks to and from their RPOT order.
1182 SmallVector<MachineBasicBlock *> OrderToBB;
1183 DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder;
1184 DenseMap<unsigned, unsigned> BBNumToRPO;
1185
1186 /// Pair of MachineInstr, and its 1-based offset into the containing block.
1187 using InstAndNum = std::pair<const MachineInstr *, unsigned>;
1188 /// Map from debug instruction number to the MachineInstr labelled with that
1189 /// number, and its location within the function. Used to transform
1190 /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
1191 std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
1192
1193 /// Record of where we observed a DBG_PHI instruction.
1194 class DebugPHIRecord {
1195 public:
1196 /// Instruction number of this DBG_PHI.
1197 uint64_t InstrNum;
1198 /// Block where DBG_PHI occurred.
1199 MachineBasicBlock *MBB;
1200 /// The value number read by the DBG_PHI -- or std::nullopt if it didn't
1201 /// refer to a value.
1202 std::optional<ValueIDNum> ValueRead;
1203 /// Register/Stack location the DBG_PHI reads -- or std::nullopt if it
1204 /// referred to something unexpected.
1205 std::optional<LocIdx> ReadLoc;
1206
1207 operator unsigned() const { return InstrNum; }
1208 };
1209
1210 /// Map from instruction numbers defined by DBG_PHIs to a record of what that
1211 /// DBG_PHI read and where. Populated and edited during the machine value
1212 /// location problem -- we use LLVMs SSA Updater to fix changes by
1213 /// optimizations that destroy PHI instructions.
1214 SmallVector<DebugPHIRecord, 32> DebugPHINumToValue;
1215
1216 // Map of overlapping variable fragments.
1217 OverlapMap OverlapFragments;
1218 VarToFragments SeenFragments;
1219
1220 /// Mapping of DBG_INSTR_REF instructions to their values, for those
1221 /// DBG_INSTR_REFs that call resolveDbgPHIs. These variable references solve
1222 /// a mini SSA problem caused by DBG_PHIs being cloned, this collection caches
1223 /// the result.
1224 DenseMap<std::pair<MachineInstr *, unsigned>, std::optional<ValueIDNum>>
1225 SeenDbgPHIs;
1226
1227 DbgOpIDMap DbgOpStore;
1228
1229 /// Mapping between DebugVariables and unique ID numbers. This is a more
1230 /// efficient way to represent the identity of a variable, versus a plain
1231 /// DebugVariable.
1232 DebugVariableMap DVMap;
1233
1234 /// True if we need to examine call instructions for stack clobbers. We
1235 /// normally assume that they don't clobber SP, but stack probes on Windows
1236 /// do.
1237 bool AdjustsStackInCalls = false;
1238
1239 /// If AdjustsStackInCalls is true, this holds the name of the target's stack
1240 /// probe function, which is the function we expect will alter the stack
1241 /// pointer.
1242 StringRef StackProbeSymbolName;
1243
1244 /// Tests whether this instruction is a spill to a stack slot.
1245 std::optional<SpillLocationNo> isSpillInstruction(const MachineInstr &MI,
1246 MachineFunction *MF);
1247
1248 /// Decide if @MI is a spill instruction and return true if it is. We use 2
1249 /// criteria to make this decision:
1250 /// - Is this instruction a store to a spill slot?
1251 /// - Is there a register operand that is both used and killed?
1252 /// TODO: Store optimization can fold spills into other stores (including
1253 /// other spills). We do not handle this yet (more than one memory operand).
1254 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
1255 unsigned &Reg);
1256
1257 /// If a given instruction is identified as a spill, return the spill slot
1258 /// and set \p Reg to the spilled register.
1259 std::optional<SpillLocationNo> isRestoreInstruction(const MachineInstr &MI,
1260 MachineFunction *MF,
1261 unsigned &Reg);
1262
1263 /// Given a spill instruction, extract the spill slot information, ensure it's
1264 /// tracked, and return the spill number.
1265 std::optional<SpillLocationNo>
1266 extractSpillBaseRegAndOffset(const MachineInstr &MI);
1267
1268 /// For an instruction reference given by \p InstNo and \p OpNo in instruction
1269 /// \p MI returns the Value pointed to by that instruction reference if any
1270 /// exists, otherwise returns std::nullopt.
1271 std::optional<ValueIDNum> getValueForInstrRef(unsigned InstNo, unsigned OpNo,
1272 MachineInstr &MI,
1273 const FuncValueTable *MLiveOuts,
1274 const FuncValueTable *MLiveIns);
1275
1276 /// Observe a single instruction while stepping through a block.
1277 void process(MachineInstr &MI, const FuncValueTable *MLiveOuts,
1278 const FuncValueTable *MLiveIns);
1279
1280 /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
1281 /// \returns true if MI was recognized and processed.
1282 bool transferDebugValue(const MachineInstr &MI);
1283
1284 /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
1285 /// \returns true if MI was recognized and processed.
1286 bool transferDebugInstrRef(MachineInstr &MI, const FuncValueTable *MLiveOuts,
1287 const FuncValueTable *MLiveIns);
1288
1289 /// Stores value-information about where this PHI occurred, and what
1290 /// instruction number is associated with it.
1291 /// \returns true if MI was recognized and processed.
1292 bool transferDebugPHI(MachineInstr &MI);
1293
1294 /// Examines whether \p MI is copy instruction, and notifies trackers.
1295 /// \returns true if MI was recognized and processed.
1296 bool transferRegisterCopy(MachineInstr &MI);
1297
1298 /// Examines whether \p MI is stack spill or restore instruction, and
1299 /// notifies trackers. \returns true if MI was recognized and processed.
1300 bool transferSpillOrRestoreInst(MachineInstr &MI);
1301
1302 /// Examines \p MI for any registers that it defines, and notifies trackers.
1303 void transferRegisterDef(MachineInstr &MI);
1304
1305 /// Copy one location to the other, accounting for movement of subregisters
1306 /// too.
1307 void performCopy(Register Src, Register Dst);
1308
1309 void accumulateFragmentMap(MachineInstr &MI);
1310
1311 /// Determine the machine value number referred to by (potentially several)
1312 /// DBG_PHI instructions. Block duplication and tail folding can duplicate
1313 /// DBG_PHIs, shifting the position where values in registers merge, and
1314 /// forming another mini-ssa problem to solve.
1315 /// \p Here the position of a DBG_INSTR_REF seeking a machine value number
1316 /// \p InstrNum Debug instruction number defined by DBG_PHI instructions.
1317 /// \returns The machine value number at position Here, or std::nullopt.
1318 std::optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF,
1319 const FuncValueTable &MLiveOuts,
1320 const FuncValueTable &MLiveIns,
1321 MachineInstr &Here,
1322 uint64_t InstrNum);
1323
1324 std::optional<ValueIDNum> resolveDbgPHIsImpl(MachineFunction &MF,
1325 const FuncValueTable &MLiveOuts,
1326 const FuncValueTable &MLiveIns,
1327 MachineInstr &Here,
1328 uint64_t InstrNum);
1329
1330 /// Step through the function, recording register definitions and movements
1331 /// in an MLocTracker. Convert the observations into a per-block transfer
1332 /// function in \p MLocTransfer, suitable for using with the machine value
1333 /// location dataflow problem.
1334 LLVM_ABI_FOR_TEST void
1335 produceMLocTransferFunction(MachineFunction &MF,
1336 SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1337 unsigned MaxNumBlocks);
1338
1339 /// Solve the machine value location dataflow problem. Takes as input the
1340 /// transfer functions in \p MLocTransfer. Writes the output live-in and
1341 /// live-out arrays to the (initialized to zero) multidimensional arrays in
1342 /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
1343 /// number, the inner by LocIdx.
1344 LLVM_ABI_FOR_TEST void
1345 buildMLocValueMap(MachineFunction &MF, FuncValueTable &MInLocs,
1346 FuncValueTable &MOutLocs,
1347 SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1348
1349 /// Examine the stack indexes (i.e. offsets within the stack) to find the
1350 /// basic units of interference -- like reg units, but for the stack.
1351 void findStackIndexInterference(SmallVectorImpl<unsigned> &Slots);
1352
1353 /// Install PHI values into the live-in array for each block, according to
1354 /// the IDF of each register.
1355 LLVM_ABI_FOR_TEST void placeMLocPHIs(
1356 MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1357 FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1358
1359 /// Propagate variable values to blocks in the common case where there's
1360 /// only one value assigned to the variable. This function has better
1361 /// performance as it doesn't have to find the dominance frontier between
1362 /// different assignments.
1363 void placePHIsForSingleVarDefinition(
1364 const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
1365 MachineBasicBlock *MBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
1366 DebugVariableID Var, LiveInsT &Output);
1367
1368 /// Calculate the iterated-dominance-frontier for a set of defs, using the
1369 /// existing LLVM facilities for this. Works for a single "value" or
1370 /// machine/variable location.
1371 /// \p AllBlocks Set of blocks where we might consume the value.
1372 /// \p DefBlocks Set of blocks where the value/location is defined.
1373 /// \p PHIBlocks Output set of blocks where PHIs must be placed.
1374 void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1375 const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
1376 SmallVectorImpl<MachineBasicBlock *> &PHIBlocks);
1377
1378 /// Perform a control flow join (lattice value meet) of the values in machine
1379 /// locations at \p MBB. Follows the algorithm described in the file-comment,
1380 /// reading live-outs of predecessors from \p OutLocs, the current live ins
1381 /// from \p InLocs, and assigning the newly computed live ins back into
1382 /// \p InLocs. \returns two bools -- the first indicates whether a change
1383 /// was made, the second whether a lattice downgrade occurred. If the latter
1384 /// is true, revisiting this block is necessary.
1385 bool mlocJoin(MachineBasicBlock &MBB,
1386 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1387 FuncValueTable &OutLocs, ValueTable &InLocs);
1388
1389 /// Produce a set of blocks that are in the current lexical scope. This means
1390 /// those blocks that contain instructions "in" the scope, blocks where
1391 /// assignments to variables in scope occur, and artificial blocks that are
1392 /// successors to any of the earlier blocks. See https://llvm.org/PR48091 for
1393 /// more commentry on what "in scope" means.
1394 /// \p DILoc A location in the scope that we're fetching blocks for.
1395 /// \p Output Set to put in-scope-blocks into.
1396 /// \p AssignBlocks Blocks known to contain assignments of variables in scope.
1397 void
1398 getBlocksForScope(const DILocation *DILoc,
1399 SmallPtrSetImpl<const MachineBasicBlock *> &Output,
1400 const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks);
1401
1402 /// Solve the variable value dataflow problem, for a single lexical scope.
1403 /// Uses the algorithm from the file comment to resolve control flow joins
1404 /// using PHI placement and value propagation. Reads the locations of machine
1405 /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap)
1406 /// and reads the variable values transfer function from \p AllTheVlocs.
1407 /// Live-in and Live-out variable values are stored locally, with the live-ins
1408 /// permanently stored to \p Output once a fixedpoint is reached.
1409 /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
1410 /// that we should be tracking.
1411 /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's
1412 /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks
1413 /// locations through.
1414 LLVM_ABI_FOR_TEST void
1415 buildVLocValueMap(const DILocation *DILoc,
1416 const SmallSet<DebugVariableID, 4> &VarsWeCareAbout,
1417 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
1418 LiveInsT &Output, FuncValueTable &MOutLocs,
1419 FuncValueTable &MInLocs,
1420 SmallVectorImpl<VLocTracker> &AllTheVLocs);
1421
1422 /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the
1423 /// live-in values coming from predecessors live-outs, and replaces any PHIs
1424 /// already present in this blocks live-ins with a live-through value if the
1425 /// PHI isn't needed.
1426 /// \p LiveIn Old live-in value, overwritten with new one if live-in changes.
1427 /// \returns true if any live-ins change value, either from value propagation
1428 /// or PHI elimination.
1429 LLVM_ABI_FOR_TEST bool
1430 vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
1431 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
1432 DbgValue &LiveIn);
1433
1434 /// For the given block and live-outs feeding into it, try to find
1435 /// machine locations for each debug operand where all the values feeding
1436 /// into that operand join together.
1437 /// \returns true if a joined location was found for every value that needed
1438 /// to be joined.
1439 LLVM_ABI_FOR_TEST bool
1440 pickVPHILoc(SmallVectorImpl<DbgOpID> &OutValues, const MachineBasicBlock &MBB,
1441 const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
1442 const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
1443
1444 std::optional<ValueIDNum> pickOperandPHILoc(
1445 unsigned DbgOpIdx, const MachineBasicBlock &MBB, const LiveIdxT &LiveOuts,
1446 FuncValueTable &MOutLocs,
1447 const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
1448
1449 /// Take collections of DBG_VALUE instructions stored in TTracker, and
1450 /// install them into their output blocks.
1451 bool emitTransfers();
1452
1453 /// Boilerplate computation of some initial sets, artifical blocks and
1454 /// RPOT block ordering.
1455 LLVM_ABI_FOR_TEST void initialSetup(MachineFunction &MF);
1456
1457 /// Produce a map of the last lexical scope that uses a block, using the
1458 /// scopes DFSOut number. Mapping is block-number to DFSOut.
1459 /// \p EjectionMap Pre-allocated vector in which to install the built ma.
1460 /// \p ScopeToDILocation Mapping of LexicalScopes to their DILocations.
1461 /// \p AssignBlocks Map of blocks where assignments happen for a scope.
1462 void makeDepthFirstEjectionMap(SmallVectorImpl<unsigned> &EjectionMap,
1463 const ScopeToDILocT &ScopeToDILocation,
1464 ScopeToAssignBlocksT &AssignBlocks);
1465
1466 /// When determining per-block variable values and emitting to DBG_VALUEs,
1467 /// this function explores by lexical scope depth. Doing so means that per
1468 /// block information can be fully computed before exploration finishes,
1469 /// allowing us to emit it and free data structures earlier than otherwise.
1470 /// It's also good for locality.
1471 bool depthFirstVLocAndEmit(
1472 unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
1473 const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToBlocks,
1474 LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
1475 SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
1476 bool ShouldEmitDebugEntryValues);
1477
1478 bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
1479 bool ShouldEmitDebugEntryValues, unsigned InputBBLimit,
1480 unsigned InputDbgValLimit) override;
1481
1482public:
1483 /// Default construct and initialize the pass.
1484 LLVM_ABI_FOR_TEST InstrRefBasedLDV();
1485
1486 LLVM_DUMP_METHOD
1487 void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1488
1489 bool isCalleeSaved(LocIdx L) const;
1490 bool isCalleeSavedReg(Register R) const;
1491
1492 bool hasFoldedStackStore(const MachineInstr &MI) {
1493 // Instruction must have a memory operand that's a stack slot, and isn't
1494 // aliased, meaning it's a spill from regalloc instead of a variable.
1495 // If it's aliased, we can't guarantee its value.
1496 if (!MI.hasOneMemOperand())
1497 return false;
1498 auto *MemOperand = *MI.memoperands_begin();
1499 return MemOperand->isStore() &&
1500 MemOperand->getPseudoValue() &&
1501 MemOperand->getPseudoValue()->kind() == PseudoSourceValue::FixedStack
1502 && !MemOperand->getPseudoValue()->isAliased(MFI);
1503 }
1504
1505 std::optional<LocIdx> findLocationForMemOperand(const MachineInstr &MI);
1506
1507 // Utility for unit testing, don't use directly.
1508 DebugVariableMap &getDVMap() {
1509 return DVMap;
1510 }
1511};
1512
1513} // namespace LiveDebugValues
1514
1515#endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */
1516