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 
23 #include "LiveDebugValues.h"
24 
25 class TransferTracker;
26 
27 // Forward dec of unit test class, so that we can peer into the LDV object.
28 class InstrRefLDVTest;
29 
30 namespace LiveDebugValues {
31 
32 class MLocTracker;
33 
34 using namespace llvm;
35 
36 /// Handle-class for a particular "location". This value-type uniquely
37 /// symbolises a register or stack location, allowing manipulation of locations
38 /// without concern for where that location is. Practically, this allows us to
39 /// treat the state of the machine at a particular point as an array of values,
40 /// rather than a map of values.
41 class LocIdx {
42   unsigned Location;
43 
44   // Default constructor is private, initializing to an illegal location number.
45   // Use only for "not an entry" elements in IndexedMaps.
46   LocIdx() : Location(UINT_MAX) {}
47 
48 public:
49 #define NUM_LOC_BITS 24
50   LocIdx(unsigned L) : Location(L) {
51     assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
52   }
53 
54   static LocIdx MakeIllegalLoc() { return LocIdx(); }
55   static LocIdx MakeTombstoneLoc() {
56     LocIdx L = LocIdx();
57     --L.Location;
58     return L;
59   }
60 
61   bool isIllegal() const { return Location == UINT_MAX; }
62 
63   uint64_t asU64() const { return Location; }
64 
65   bool operator==(unsigned L) const { return Location == L; }
66 
67   bool operator==(const LocIdx &L) const { return Location == L.Location; }
68 
69   bool operator!=(unsigned L) const { return !(*this == L); }
70 
71   bool operator!=(const LocIdx &L) const { return !(*this == L); }
72 
73   bool operator<(const LocIdx &Other) const {
74     return Location < Other.Location;
75   }
76 };
77 
78 // The location at which a spilled value resides. It consists of a register and
79 // an offset.
80 struct SpillLoc {
81   unsigned SpillBase;
82   StackOffset SpillOffset;
83   bool operator==(const SpillLoc &Other) const {
84     return std::make_pair(SpillBase, SpillOffset) ==
85            std::make_pair(Other.SpillBase, Other.SpillOffset);
86   }
87   bool operator<(const SpillLoc &Other) const {
88     return std::make_tuple(SpillBase, SpillOffset.getFixed(),
89                            SpillOffset.getScalable()) <
90            std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(),
91                            Other.SpillOffset.getScalable());
92   }
93 };
94 
95 /// Unique identifier for a value defined by an instruction, as a value type.
96 /// Casts back and forth to a uint64_t. Probably replacable with something less
97 /// bit-constrained. Each value identifies the instruction and machine location
98 /// where the value is defined, although there may be no corresponding machine
99 /// operand for it (ex: regmasks clobbering values). The instructions are
100 /// one-based, and definitions that are PHIs have instruction number zero.
101 ///
102 /// The obvious limits of a 1M block function or 1M instruction blocks are
103 /// problematic; but by that point we should probably have bailed out of
104 /// trying to analyse the function.
105 class ValueIDNum {
106   union {
107     struct {
108       uint64_t BlockNo : 20; /// The block where the def happens.
109       uint64_t InstNo : 20;  /// The Instruction where the def happens.
110                              /// One based, is distance from start of block.
111       uint64_t LocNo
112           : NUM_LOC_BITS; /// The machine location where the def happens.
113     } s;
114     uint64_t Value;
115   } u;
116 
117   static_assert(sizeof(u) == 8, "Badly packed ValueIDNum?");
118 
119 public:
120   // Default-initialize to EmptyValue. This is necessary to make IndexedMaps
121   // of values to work.
122   ValueIDNum() { u.Value = EmptyValue.asU64(); }
123 
124   ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) {
125     u.s = {Block, Inst, Loc};
126   }
127 
128   ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) {
129     u.s = {Block, Inst, Loc.asU64()};
130   }
131 
132   uint64_t getBlock() const { return u.s.BlockNo; }
133   uint64_t getInst() const { return u.s.InstNo; }
134   uint64_t getLoc() const { return u.s.LocNo; }
135   bool isPHI() const { return u.s.InstNo == 0; }
136 
137   uint64_t asU64() const { return u.Value; }
138 
139   static ValueIDNum fromU64(uint64_t v) {
140     ValueIDNum Val;
141     Val.u.Value = v;
142     return Val;
143   }
144 
145   bool operator<(const ValueIDNum &Other) const {
146     return asU64() < Other.asU64();
147   }
148 
149   bool operator==(const ValueIDNum &Other) const {
150     return u.Value == Other.u.Value;
151   }
152 
153   bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
154 
155   std::string asString(const std::string &mlocname) const {
156     return Twine("Value{bb: ")
157         .concat(Twine(u.s.BlockNo)
158                     .concat(Twine(", inst: ")
159                                 .concat((u.s.InstNo ? Twine(u.s.InstNo)
160                                                     : Twine("live-in"))
161                                             .concat(Twine(", loc: ").concat(
162                                                 Twine(mlocname)))
163                                             .concat(Twine("}")))))
164         .str();
165   }
166 
167   static ValueIDNum EmptyValue;
168   static ValueIDNum TombstoneValue;
169 };
170 
171 /// Type for a table of values in a block.
172 using ValueTable = std::unique_ptr<ValueIDNum[]>;
173 
174 /// Type for a table-of-table-of-values, i.e., the collection of either
175 /// live-in or live-out values for each block in the function.
176 using FuncValueTable = std::unique_ptr<ValueTable[]>;
177 
178 /// Thin wrapper around an integer -- designed to give more type safety to
179 /// spill location numbers.
180 class SpillLocationNo {
181 public:
182   explicit SpillLocationNo(unsigned SpillNo) : SpillNo(SpillNo) {}
183   unsigned SpillNo;
184   unsigned id() const { return SpillNo; }
185 
186   bool operator<(const SpillLocationNo &Other) const {
187     return SpillNo < Other.SpillNo;
188   }
189 
190   bool operator==(const SpillLocationNo &Other) const {
191     return SpillNo == Other.SpillNo;
192   }
193   bool operator!=(const SpillLocationNo &Other) const {
194     return !(*this == Other);
195   }
196 };
197 
198 /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
199 /// the the value, and Boolean of whether or not it's indirect.
200 class DbgValueProperties {
201 public:
202   DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
203       : DIExpr(DIExpr), Indirect(Indirect) {}
204 
205   /// Extract properties from an existing DBG_VALUE instruction.
206   DbgValueProperties(const MachineInstr &MI) {
207     assert(MI.isDebugValue());
208     DIExpr = MI.getDebugExpression();
209     Indirect = MI.getOperand(1).isImm();
210   }
211 
212   bool operator==(const DbgValueProperties &Other) const {
213     return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
214   }
215 
216   bool operator!=(const DbgValueProperties &Other) const {
217     return !(*this == Other);
218   }
219 
220   const DIExpression *DIExpr;
221   bool Indirect;
222 };
223 
224 /// Class recording the (high level) _value_ of a variable. Identifies either
225 /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
226 /// This class also stores meta-information about how the value is qualified.
227 /// Used to reason about variable values when performing the second
228 /// (DebugVariable specific) dataflow analysis.
229 class DbgValue {
230 public:
231   /// If Kind is Def, the value number that this value is based on. VPHIs set
232   /// this field to EmptyValue if there is no machine-value for this VPHI, or
233   /// the corresponding machine-value if there is one.
234   ValueIDNum ID;
235   /// If Kind is Const, the MachineOperand defining this value.
236   Optional<MachineOperand> MO;
237   /// For a NoVal or VPHI DbgValue, which block it was generated in.
238   int BlockNo;
239 
240   /// Qualifiers for the ValueIDNum above.
241   DbgValueProperties Properties;
242 
243   typedef enum {
244     Undef, // Represents a DBG_VALUE $noreg in the transfer function only.
245     Def,   // This value is defined by an inst, or is a PHI value.
246     Const, // A constant value contained in the MachineOperand field.
247     VPHI,  // Incoming values to BlockNo differ, those values must be joined by
248            // a PHI in this block.
249     NoVal, // Empty DbgValue indicating an unknown value. Used as initializer,
250            // before dominating blocks values are propagated in.
251   } KindT;
252   /// Discriminator for whether this is a constant or an in-program value.
253   KindT Kind;
254 
255   DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
256       : ID(Val), MO(None), BlockNo(0), Properties(Prop), Kind(Kind) {
257     assert(Kind == Def);
258   }
259 
260   DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
261       : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(BlockNo),
262         Properties(Prop), Kind(Kind) {
263     assert(Kind == NoVal || Kind == VPHI);
264   }
265 
266   DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
267       : ID(ValueIDNum::EmptyValue), MO(MO), BlockNo(0), Properties(Prop),
268         Kind(Kind) {
269     assert(Kind == Const);
270   }
271 
272   DbgValue(const DbgValueProperties &Prop, KindT Kind)
273     : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(0), Properties(Prop),
274       Kind(Kind) {
275     assert(Kind == Undef &&
276            "Empty DbgValue constructor must pass in Undef kind");
277   }
278 
279 #ifndef NDEBUG
280   void dump(const MLocTracker *MTrack) const;
281 #endif
282 
283   bool operator==(const DbgValue &Other) const {
284     if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
285       return false;
286     else if (Kind == Def && ID != Other.ID)
287       return false;
288     else if (Kind == NoVal && BlockNo != Other.BlockNo)
289       return false;
290     else if (Kind == Const)
291       return MO->isIdenticalTo(*Other.MO);
292     else if (Kind == VPHI && BlockNo != Other.BlockNo)
293       return false;
294     else if (Kind == VPHI && ID != Other.ID)
295       return false;
296 
297     return true;
298   }
299 
300   bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
301 };
302 
303 class LocIdxToIndexFunctor {
304 public:
305   using argument_type = LocIdx;
306   unsigned operator()(const LocIdx &L) const { return L.asU64(); }
307 };
308 
309 /// Tracker for what values are in machine locations. Listens to the Things
310 /// being Done by various instructions, and maintains a table of what machine
311 /// locations have what values (as defined by a ValueIDNum).
312 ///
313 /// There are potentially a much larger number of machine locations on the
314 /// target machine than the actual working-set size of the function. On x86 for
315 /// example, we're extremely unlikely to want to track values through control
316 /// or debug registers. To avoid doing so, MLocTracker has several layers of
317 /// indirection going on, described below, to avoid unnecessarily tracking
318 /// any location.
319 ///
320 /// Here's a sort of diagram of the indexes, read from the bottom up:
321 ///
322 ///           Size on stack   Offset on stack
323 ///                 \              /
324 ///          Stack Idx (Where in slot is this?)
325 ///                         /
326 ///                        /
327 /// Slot Num (%stack.0)   /
328 /// FrameIdx => SpillNum /
329 ///              \      /
330 ///           SpillID (int)              Register number (int)
331 ///                      \                  /
332 ///                      LocationID => LocIdx
333 ///                                |
334 ///                       LocIdx => ValueIDNum
335 ///
336 /// The aim here is that the LocIdx => ValueIDNum vector is just an array of
337 /// values in numbered locations, so that later analyses can ignore whether the
338 /// location is a register or otherwise. To map a register / spill location to
339 /// a LocIdx, you have to use the (sparse) LocationID => LocIdx map. And to
340 /// build a LocationID for a stack slot, you need to combine identifiers for
341 /// which stack slot it is and where within that slot is being described.
342 ///
343 /// Register mask operands cause trouble by technically defining every register;
344 /// various hacks are used to avoid tracking registers that are never read and
345 /// only written by regmasks.
346 class MLocTracker {
347 public:
348   MachineFunction &MF;
349   const TargetInstrInfo &TII;
350   const TargetRegisterInfo &TRI;
351   const TargetLowering &TLI;
352 
353   /// IndexedMap type, mapping from LocIdx to ValueIDNum.
354   using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
355 
356   /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
357   /// packed, entries only exist for locations that are being tracked.
358   LocToValueType LocIdxToIDNum;
359 
360   /// "Map" of machine location IDs (i.e., raw register or spill number) to the
361   /// LocIdx key / number for that location. There are always at least as many
362   /// as the number of registers on the target -- if the value in the register
363   /// is not being tracked, then the LocIdx value will be zero. New entries are
364   /// appended if a new spill slot begins being tracked.
365   /// This, and the corresponding reverse map persist for the analysis of the
366   /// whole function, and is necessarying for decoding various vectors of
367   /// values.
368   std::vector<LocIdx> LocIDToLocIdx;
369 
370   /// Inverse map of LocIDToLocIdx.
371   IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
372 
373   /// When clobbering register masks, we chose to not believe the machine model
374   /// and don't clobber SP. Do the same for SP aliases, and for efficiency,
375   /// keep a set of them here.
376   SmallSet<Register, 8> SPAliases;
377 
378   /// Unique-ification of spill. Used to number them -- their LocID number is
379   /// the index in SpillLocs minus one plus NumRegs.
380   UniqueVector<SpillLoc> SpillLocs;
381 
382   // If we discover a new machine location, assign it an mphi with this
383   // block number.
384   unsigned CurBB;
385 
386   /// Cached local copy of the number of registers the target has.
387   unsigned NumRegs;
388 
389   /// Number of slot indexes the target has -- distinct segments of a stack
390   /// slot that can take on the value of a subregister, when a super-register
391   /// is written to the stack.
392   unsigned NumSlotIdxes;
393 
394   /// Collection of register mask operands that have been observed. Second part
395   /// of pair indicates the instruction that they happened in. Used to
396   /// reconstruct where defs happened if we start tracking a location later
397   /// on.
398   SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
399 
400   /// Pair for describing a position within a stack slot -- first the size in
401   /// bits, then the offset.
402   typedef std::pair<unsigned short, unsigned short> StackSlotPos;
403 
404   /// Map from a size/offset pair describing a position in a stack slot, to a
405   /// numeric identifier for that position. Allows easier identification of
406   /// individual positions.
407   DenseMap<StackSlotPos, unsigned> StackSlotIdxes;
408 
409   /// Inverse of StackSlotIdxes.
410   DenseMap<unsigned, StackSlotPos> StackIdxesToPos;
411 
412   /// Iterator for locations and the values they contain. Dereferencing
413   /// produces a struct/pair containing the LocIdx key for this location,
414   /// and a reference to the value currently stored. Simplifies the process
415   /// of seeking a particular location.
416   class MLocIterator {
417     LocToValueType &ValueMap;
418     LocIdx Idx;
419 
420   public:
421     class value_type {
422     public:
423       value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {}
424       const LocIdx Idx;  /// Read-only index of this location.
425       ValueIDNum &Value; /// Reference to the stored value at this location.
426     };
427 
428     MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
429         : ValueMap(ValueMap), Idx(Idx) {}
430 
431     bool operator==(const MLocIterator &Other) const {
432       assert(&ValueMap == &Other.ValueMap);
433       return Idx == Other.Idx;
434     }
435 
436     bool operator!=(const MLocIterator &Other) const {
437       return !(*this == Other);
438     }
439 
440     void operator++() { Idx = LocIdx(Idx.asU64() + 1); }
441 
442     value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); }
443   };
444 
445   MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
446               const TargetRegisterInfo &TRI, const TargetLowering &TLI);
447 
448   /// Produce location ID number for a Register. Provides some small amount of
449   /// type safety.
450   /// \param Reg The register we're looking up.
451   unsigned getLocID(Register Reg) { return Reg.id(); }
452 
453   /// Produce location ID number for a spill position.
454   /// \param Spill The number of the spill we're fetching the location for.
455   /// \param SpillSubReg Subregister within the spill we're addressing.
456   unsigned getLocID(SpillLocationNo Spill, unsigned SpillSubReg) {
457     unsigned short Size = TRI.getSubRegIdxSize(SpillSubReg);
458     unsigned short Offs = TRI.getSubRegIdxOffset(SpillSubReg);
459     return getLocID(Spill, {Size, Offs});
460   }
461 
462   /// Produce location ID number for a spill position.
463   /// \param Spill The number of the spill we're fetching the location for.
464   /// \apram SpillIdx size/offset within the spill slot to be addressed.
465   unsigned getLocID(SpillLocationNo Spill, StackSlotPos Idx) {
466     unsigned SlotNo = Spill.id() - 1;
467     SlotNo *= NumSlotIdxes;
468     assert(StackSlotIdxes.find(Idx) != StackSlotIdxes.end());
469     SlotNo += StackSlotIdxes[Idx];
470     SlotNo += NumRegs;
471     return SlotNo;
472   }
473 
474   /// Given a spill number, and a slot within the spill, calculate the ID number
475   /// for that location.
476   unsigned getSpillIDWithIdx(SpillLocationNo Spill, unsigned Idx) {
477     unsigned SlotNo = Spill.id() - 1;
478     SlotNo *= NumSlotIdxes;
479     SlotNo += Idx;
480     SlotNo += NumRegs;
481     return SlotNo;
482   }
483 
484   /// Return the spill number that a location ID corresponds to.
485   SpillLocationNo locIDToSpill(unsigned ID) const {
486     assert(ID >= NumRegs);
487     ID -= NumRegs;
488     // Truncate away the index part, leaving only the spill number.
489     ID /= NumSlotIdxes;
490     return SpillLocationNo(ID + 1); // The UniqueVector is one-based.
491   }
492 
493   /// Returns the spill-slot size/offs that a location ID corresponds to.
494   StackSlotPos locIDToSpillIdx(unsigned ID) const {
495     assert(ID >= NumRegs);
496     ID -= NumRegs;
497     unsigned Idx = ID % NumSlotIdxes;
498     return StackIdxesToPos.find(Idx)->second;
499   }
500 
501   unsigned getNumLocs() const { return LocIdxToIDNum.size(); }
502 
503   /// Reset all locations to contain a PHI value at the designated block. Used
504   /// sometimes for actual PHI values, othertimes to indicate the block entry
505   /// value (before any more information is known).
506   void setMPhis(unsigned NewCurBB) {
507     CurBB = NewCurBB;
508     for (auto Location : locations())
509       Location.Value = {CurBB, 0, Location.Idx};
510   }
511 
512   /// Load values for each location from array of ValueIDNums. Take current
513   /// bbnum just in case we read a value from a hitherto untouched register.
514   void loadFromArray(ValueTable &Locs, unsigned NewCurBB) {
515     CurBB = NewCurBB;
516     // Iterate over all tracked locations, and load each locations live-in
517     // value into our local index.
518     for (auto Location : locations())
519       Location.Value = Locs[Location.Idx.asU64()];
520   }
521 
522   /// Wipe any un-necessary location records after traversing a block.
523   void reset() {
524     // We could reset all the location values too; however either loadFromArray
525     // or setMPhis should be called before this object is re-used. Just
526     // clear Masks, they're definitely not needed.
527     Masks.clear();
528   }
529 
530   /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
531   /// the information in this pass uninterpretable.
532   void clear() {
533     reset();
534     LocIDToLocIdx.clear();
535     LocIdxToLocID.clear();
536     LocIdxToIDNum.clear();
537     // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from
538     // 0
539     SpillLocs = decltype(SpillLocs)();
540     StackSlotIdxes.clear();
541     StackIdxesToPos.clear();
542 
543     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
544   }
545 
546   /// Set a locaiton to a certain value.
547   void setMLoc(LocIdx L, ValueIDNum Num) {
548     assert(L.asU64() < LocIdxToIDNum.size());
549     LocIdxToIDNum[L] = Num;
550   }
551 
552   /// Read the value of a particular location
553   ValueIDNum readMLoc(LocIdx L) {
554     assert(L.asU64() < LocIdxToIDNum.size());
555     return LocIdxToIDNum[L];
556   }
557 
558   /// Create a LocIdx for an untracked register ID. Initialize it to either an
559   /// mphi value representing a live-in, or a recent register mask clobber.
560   LocIdx trackRegister(unsigned ID);
561 
562   LocIdx lookupOrTrackRegister(unsigned ID) {
563     LocIdx &Index = LocIDToLocIdx[ID];
564     if (Index.isIllegal())
565       Index = trackRegister(ID);
566     return Index;
567   }
568 
569   /// Is register R currently tracked by MLocTracker?
570   bool isRegisterTracked(Register R) {
571     LocIdx &Index = LocIDToLocIdx[R];
572     return !Index.isIllegal();
573   }
574 
575   /// Record a definition of the specified register at the given block / inst.
576   /// This doesn't take a ValueIDNum, because the definition and its location
577   /// are synonymous.
578   void defReg(Register R, unsigned BB, unsigned Inst) {
579     unsigned ID = getLocID(R);
580     LocIdx Idx = lookupOrTrackRegister(ID);
581     ValueIDNum ValueID = {BB, Inst, Idx};
582     LocIdxToIDNum[Idx] = ValueID;
583   }
584 
585   /// Set a register to a value number. To be used if the value number is
586   /// known in advance.
587   void setReg(Register R, ValueIDNum ValueID) {
588     unsigned ID = getLocID(R);
589     LocIdx Idx = lookupOrTrackRegister(ID);
590     LocIdxToIDNum[Idx] = ValueID;
591   }
592 
593   ValueIDNum readReg(Register R) {
594     unsigned ID = getLocID(R);
595     LocIdx Idx = lookupOrTrackRegister(ID);
596     return LocIdxToIDNum[Idx];
597   }
598 
599   /// Reset a register value to zero / empty. Needed to replicate the
600   /// VarLoc implementation where a copy to/from a register effectively
601   /// clears the contents of the source register. (Values can only have one
602   ///  machine location in VarLocBasedImpl).
603   void wipeRegister(Register R) {
604     unsigned ID = getLocID(R);
605     LocIdx Idx = LocIDToLocIdx[ID];
606     LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
607   }
608 
609   /// Determine the LocIdx of an existing register.
610   LocIdx getRegMLoc(Register R) {
611     unsigned ID = getLocID(R);
612     assert(ID < LocIDToLocIdx.size());
613     assert(LocIDToLocIdx[ID] != UINT_MAX); // Sentinal for IndexedMap.
614     return LocIDToLocIdx[ID];
615   }
616 
617   /// Record a RegMask operand being executed. Defs any register we currently
618   /// track, stores a pointer to the mask in case we have to account for it
619   /// later.
620   void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID);
621 
622   /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
623   /// Returns None when in scenarios where a spill slot could be tracked, but
624   /// we would likely run into resource limitations.
625   Optional<SpillLocationNo> getOrTrackSpillLoc(SpillLoc L);
626 
627   // Get LocIdx of a spill ID.
628   LocIdx getSpillMLoc(unsigned SpillID) {
629     assert(LocIDToLocIdx[SpillID] != UINT_MAX); // Sentinal for IndexedMap.
630     return LocIDToLocIdx[SpillID];
631   }
632 
633   /// Return true if Idx is a spill machine location.
634   bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; }
635 
636   MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); }
637 
638   MLocIterator end() {
639     return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
640   }
641 
642   /// Return a range over all locations currently tracked.
643   iterator_range<MLocIterator> locations() {
644     return llvm::make_range(begin(), end());
645   }
646 
647   std::string LocIdxToName(LocIdx Idx) const;
648 
649   std::string IDAsString(const ValueIDNum &Num) const;
650 
651 #ifndef NDEBUG
652   LLVM_DUMP_METHOD void dump();
653 
654   LLVM_DUMP_METHOD void dump_mloc_map();
655 #endif
656 
657   /// Create a DBG_VALUE based on  machine location \p MLoc. Qualify it with the
658   /// information in \pProperties, for variable Var. Don't insert it anywhere,
659   /// just return the builder for it.
660   MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
661                               const DbgValueProperties &Properties);
662 };
663 
664 /// Types for recording sets of variable fragments that overlap. For a given
665 /// local variable, we record all other fragments of that variable that could
666 /// overlap it, to reduce search time.
667 using FragmentOfVar =
668     std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
669 using OverlapMap =
670     DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
671 
672 /// Collection of DBG_VALUEs observed when traversing a block. Records each
673 /// variable and the value the DBG_VALUE refers to. Requires the machine value
674 /// location dataflow algorithm to have run already, so that values can be
675 /// identified.
676 class VLocTracker {
677 public:
678   /// Map DebugVariable to the latest Value it's defined to have.
679   /// Needs to be a MapVector because we determine order-in-the-input-MIR from
680   /// the order in this container.
681   /// We only retain the last DbgValue in each block for each variable, to
682   /// determine the blocks live-out variable value. The Vars container forms the
683   /// transfer function for this block, as part of the dataflow analysis. The
684   /// movement of values between locations inside of a block is handled at a
685   /// much later stage, in the TransferTracker class.
686   MapVector<DebugVariable, DbgValue> Vars;
687   SmallDenseMap<DebugVariable, const DILocation *, 8> Scopes;
688   MachineBasicBlock *MBB = nullptr;
689   const OverlapMap &OverlappingFragments;
690   DbgValueProperties EmptyProperties;
691 
692 public:
693   VLocTracker(const OverlapMap &O, const DIExpression *EmptyExpr)
694       : OverlappingFragments(O), EmptyProperties(EmptyExpr, false) {}
695 
696   void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
697               Optional<ValueIDNum> ID) {
698     assert(MI.isDebugValue() || MI.isDebugRef());
699     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
700                       MI.getDebugLoc()->getInlinedAt());
701     DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
702                         : DbgValue(Properties, DbgValue::Undef);
703 
704     // Attempt insertion; overwrite if it's already mapped.
705     auto Result = Vars.insert(std::make_pair(Var, Rec));
706     if (!Result.second)
707       Result.first->second = Rec;
708     Scopes[Var] = MI.getDebugLoc().get();
709 
710     considerOverlaps(Var, MI.getDebugLoc().get());
711   }
712 
713   void defVar(const MachineInstr &MI, const MachineOperand &MO) {
714     // Only DBG_VALUEs can define constant-valued variables.
715     assert(MI.isDebugValue());
716     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
717                       MI.getDebugLoc()->getInlinedAt());
718     DbgValueProperties Properties(MI);
719     DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
720 
721     // Attempt insertion; overwrite if it's already mapped.
722     auto Result = Vars.insert(std::make_pair(Var, Rec));
723     if (!Result.second)
724       Result.first->second = Rec;
725     Scopes[Var] = MI.getDebugLoc().get();
726 
727     considerOverlaps(Var, MI.getDebugLoc().get());
728   }
729 
730   void considerOverlaps(const DebugVariable &Var, const DILocation *Loc) {
731     auto Overlaps = OverlappingFragments.find(
732         {Var.getVariable(), Var.getFragmentOrDefault()});
733     if (Overlaps == OverlappingFragments.end())
734       return;
735 
736     // Otherwise: terminate any overlapped variable locations.
737     for (auto FragmentInfo : Overlaps->second) {
738       // The "empty" fragment is stored as DebugVariable::DefaultFragment, so
739       // that it overlaps with everything, however its cannonical representation
740       // in a DebugVariable is as "None".
741       Optional<DIExpression::FragmentInfo> OptFragmentInfo = FragmentInfo;
742       if (DebugVariable::isDefaultFragment(FragmentInfo))
743         OptFragmentInfo = None;
744 
745       DebugVariable Overlapped(Var.getVariable(), OptFragmentInfo,
746                                Var.getInlinedAt());
747       DbgValue Rec = DbgValue(EmptyProperties, DbgValue::Undef);
748 
749       // Attempt insertion; overwrite if it's already mapped.
750       auto Result = Vars.insert(std::make_pair(Overlapped, Rec));
751       if (!Result.second)
752         Result.first->second = Rec;
753       Scopes[Overlapped] = Loc;
754     }
755   }
756 
757   void clear() {
758     Vars.clear();
759     Scopes.clear();
760   }
761 };
762 
763 // XXX XXX docs
764 class InstrRefBasedLDV : public LDVImpl {
765 public:
766   friend class ::InstrRefLDVTest;
767 
768   using FragmentInfo = DIExpression::FragmentInfo;
769   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
770 
771   // Helper while building OverlapMap, a map of all fragments seen for a given
772   // DILocalVariable.
773   using VarToFragments =
774       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
775 
776   /// Machine location/value transfer function, a mapping of which locations
777   /// are assigned which new values.
778   using MLocTransferMap = SmallDenseMap<LocIdx, ValueIDNum>;
779 
780   /// Live in/out structure for the variable values: a per-block map of
781   /// variables to their values.
782   using LiveIdxT = DenseMap<const MachineBasicBlock *, DbgValue *>;
783 
784   using VarAndLoc = std::pair<DebugVariable, DbgValue>;
785 
786   /// Type for a live-in value: the predecessor block, and its value.
787   using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
788 
789   /// Vector (per block) of a collection (inner smallvector) of live-ins.
790   /// Used as the result type for the variable value dataflow problem.
791   using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
792 
793   /// Mapping from lexical scopes to a DILocation in that scope.
794   using ScopeToDILocT = DenseMap<const LexicalScope *, const DILocation *>;
795 
796   /// Mapping from lexical scopes to variables in that scope.
797   using ScopeToVarsT = DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>>;
798 
799   /// Mapping from lexical scopes to blocks where variables in that scope are
800   /// assigned. Such blocks aren't necessarily "in" the lexical scope, it's
801   /// just a block where an assignment happens.
802   using ScopeToAssignBlocksT = DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>;
803 
804 private:
805   MachineDominatorTree *DomTree;
806   const TargetRegisterInfo *TRI;
807   const MachineRegisterInfo *MRI;
808   const TargetInstrInfo *TII;
809   const TargetFrameLowering *TFI;
810   const MachineFrameInfo *MFI;
811   BitVector CalleeSavedRegs;
812   LexicalScopes LS;
813   TargetPassConfig *TPC;
814 
815   // An empty DIExpression. Used default / placeholder DbgValueProperties
816   // objects, as we can't have null expressions.
817   const DIExpression *EmptyExpr;
818 
819   /// Object to track machine locations as we step through a block. Could
820   /// probably be a field rather than a pointer, as it's always used.
821   MLocTracker *MTracker = nullptr;
822 
823   /// Number of the current block LiveDebugValues is stepping through.
824   unsigned CurBB;
825 
826   /// Number of the current instruction LiveDebugValues is evaluating.
827   unsigned CurInst;
828 
829   /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
830   /// steps through a block. Reads the values at each location from the
831   /// MLocTracker object.
832   VLocTracker *VTracker = nullptr;
833 
834   /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
835   /// between locations during stepping, creates new DBG_VALUEs when values move
836   /// location.
837   TransferTracker *TTracker = nullptr;
838 
839   /// Blocks which are artificial, i.e. blocks which exclusively contain
840   /// instructions without DebugLocs, or with line 0 locations.
841   SmallPtrSet<MachineBasicBlock *, 16> ArtificialBlocks;
842 
843   // Mapping of blocks to and from their RPOT order.
844   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
845   DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder;
846   DenseMap<unsigned, unsigned> BBNumToRPO;
847 
848   /// Pair of MachineInstr, and its 1-based offset into the containing block.
849   using InstAndNum = std::pair<const MachineInstr *, unsigned>;
850   /// Map from debug instruction number to the MachineInstr labelled with that
851   /// number, and its location within the function. Used to transform
852   /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
853   std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
854 
855   /// Record of where we observed a DBG_PHI instruction.
856   class DebugPHIRecord {
857   public:
858     /// Instruction number of this DBG_PHI.
859     uint64_t InstrNum;
860     /// Block where DBG_PHI occurred.
861     MachineBasicBlock *MBB;
862     /// The value number read by the DBG_PHI -- or None if it didn't refer to
863     /// a value.
864     Optional<ValueIDNum> ValueRead;
865     /// Register/Stack location the DBG_PHI reads -- or None if it referred to
866     /// something unexpected.
867     Optional<LocIdx> ReadLoc;
868 
869     operator unsigned() const { return InstrNum; }
870   };
871 
872   /// Map from instruction numbers defined by DBG_PHIs to a record of what that
873   /// DBG_PHI read and where. Populated and edited during the machine value
874   /// location problem -- we use LLVMs SSA Updater to fix changes by
875   /// optimizations that destroy PHI instructions.
876   SmallVector<DebugPHIRecord, 32> DebugPHINumToValue;
877 
878   // Map of overlapping variable fragments.
879   OverlapMap OverlapFragments;
880   VarToFragments SeenFragments;
881 
882   /// Mapping of DBG_INSTR_REF instructions to their values, for those
883   /// DBG_INSTR_REFs that call resolveDbgPHIs. These variable references solve
884   /// a mini SSA problem caused by DBG_PHIs being cloned, this collection caches
885   /// the result.
886   DenseMap<MachineInstr *, Optional<ValueIDNum>> SeenDbgPHIs;
887 
888   /// True if we need to examine call instructions for stack clobbers. We
889   /// normally assume that they don't clobber SP, but stack probes on Windows
890   /// do.
891   bool AdjustsStackInCalls = false;
892 
893   /// If AdjustsStackInCalls is true, this holds the name of the target's stack
894   /// probe function, which is the function we expect will alter the stack
895   /// pointer.
896   StringRef StackProbeSymbolName;
897 
898   /// Tests whether this instruction is a spill to a stack slot.
899   Optional<SpillLocationNo> isSpillInstruction(const MachineInstr &MI,
900                                                MachineFunction *MF);
901 
902   /// Decide if @MI is a spill instruction and return true if it is. We use 2
903   /// criteria to make this decision:
904   /// - Is this instruction a store to a spill slot?
905   /// - Is there a register operand that is both used and killed?
906   /// TODO: Store optimization can fold spills into other stores (including
907   /// other spills). We do not handle this yet (more than one memory operand).
908   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
909                        unsigned &Reg);
910 
911   /// If a given instruction is identified as a spill, return the spill slot
912   /// and set \p Reg to the spilled register.
913   Optional<SpillLocationNo> isRestoreInstruction(const MachineInstr &MI,
914                                           MachineFunction *MF, unsigned &Reg);
915 
916   /// Given a spill instruction, extract the spill slot information, ensure it's
917   /// tracked, and return the spill number.
918   Optional<SpillLocationNo>
919   extractSpillBaseRegAndOffset(const MachineInstr &MI);
920 
921   /// Observe a single instruction while stepping through a block.
922   void process(MachineInstr &MI, const ValueTable *MLiveOuts,
923                const ValueTable *MLiveIns);
924 
925   /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
926   /// \returns true if MI was recognized and processed.
927   bool transferDebugValue(const MachineInstr &MI);
928 
929   /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
930   /// \returns true if MI was recognized and processed.
931   bool transferDebugInstrRef(MachineInstr &MI, const ValueTable *MLiveOuts,
932                              const ValueTable *MLiveIns);
933 
934   /// Stores value-information about where this PHI occurred, and what
935   /// instruction number is associated with it.
936   /// \returns true if MI was recognized and processed.
937   bool transferDebugPHI(MachineInstr &MI);
938 
939   /// Examines whether \p MI is copy instruction, and notifies trackers.
940   /// \returns true if MI was recognized and processed.
941   bool transferRegisterCopy(MachineInstr &MI);
942 
943   /// Examines whether \p MI is stack spill or restore  instruction, and
944   /// notifies trackers. \returns true if MI was recognized and processed.
945   bool transferSpillOrRestoreInst(MachineInstr &MI);
946 
947   /// Examines \p MI for any registers that it defines, and notifies trackers.
948   void transferRegisterDef(MachineInstr &MI);
949 
950   /// Copy one location to the other, accounting for movement of subregisters
951   /// too.
952   void performCopy(Register Src, Register Dst);
953 
954   void accumulateFragmentMap(MachineInstr &MI);
955 
956   /// Determine the machine value number referred to by (potentially several)
957   /// DBG_PHI instructions. Block duplication and tail folding can duplicate
958   /// DBG_PHIs, shifting the position where values in registers merge, and
959   /// forming another mini-ssa problem to solve.
960   /// \p Here the position of a DBG_INSTR_REF seeking a machine value number
961   /// \p InstrNum Debug instruction number defined by DBG_PHI instructions.
962   /// \returns The machine value number at position Here, or None.
963   Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF,
964                                       const ValueTable *MLiveOuts,
965                                       const ValueTable *MLiveIns,
966                                       MachineInstr &Here, uint64_t InstrNum);
967 
968   Optional<ValueIDNum> resolveDbgPHIsImpl(MachineFunction &MF,
969                                           const ValueTable *MLiveOuts,
970                                           const ValueTable *MLiveIns,
971                                           MachineInstr &Here,
972                                           uint64_t InstrNum);
973 
974   /// Step through the function, recording register definitions and movements
975   /// in an MLocTracker. Convert the observations into a per-block transfer
976   /// function in \p MLocTransfer, suitable for using with the machine value
977   /// location dataflow problem.
978   void
979   produceMLocTransferFunction(MachineFunction &MF,
980                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
981                               unsigned MaxNumBlocks);
982 
983   /// Solve the machine value location dataflow problem. Takes as input the
984   /// transfer functions in \p MLocTransfer. Writes the output live-in and
985   /// live-out arrays to the (initialized to zero) multidimensional arrays in
986   /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
987   /// number, the inner by LocIdx.
988   void buildMLocValueMap(MachineFunction &MF, FuncValueTable &MInLocs,
989                          FuncValueTable &MOutLocs,
990                          SmallVectorImpl<MLocTransferMap> &MLocTransfer);
991 
992   /// Examine the stack indexes (i.e. offsets within the stack) to find the
993   /// basic units of interference -- like reg units, but for the stack.
994   void findStackIndexInterference(SmallVectorImpl<unsigned> &Slots);
995 
996   /// Install PHI values into the live-in array for each block, according to
997   /// the IDF of each register.
998   void placeMLocPHIs(MachineFunction &MF,
999                      SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1000                      FuncValueTable &MInLocs,
1001                      SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1002 
1003   /// Propagate variable values to blocks in the common case where there's
1004   /// only one value assigned to the variable. This function has better
1005   /// performance as it doesn't have to find the dominance frontier between
1006   /// different assignments.
1007   void placePHIsForSingleVarDefinition(
1008           const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
1009           MachineBasicBlock *MBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
1010           const DebugVariable &Var, LiveInsT &Output);
1011 
1012   /// Calculate the iterated-dominance-frontier for a set of defs, using the
1013   /// existing LLVM facilities for this. Works for a single "value" or
1014   /// machine/variable location.
1015   /// \p AllBlocks Set of blocks where we might consume the value.
1016   /// \p DefBlocks Set of blocks where the value/location is defined.
1017   /// \p PHIBlocks Output set of blocks where PHIs must be placed.
1018   void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1019                          const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
1020                          SmallVectorImpl<MachineBasicBlock *> &PHIBlocks);
1021 
1022   /// Perform a control flow join (lattice value meet) of the values in machine
1023   /// locations at \p MBB. Follows the algorithm described in the file-comment,
1024   /// reading live-outs of predecessors from \p OutLocs, the current live ins
1025   /// from \p InLocs, and assigning the newly computed live ins back into
1026   /// \p InLocs. \returns two bools -- the first indicates whether a change
1027   /// was made, the second whether a lattice downgrade occurred. If the latter
1028   /// is true, revisiting this block is necessary.
1029   bool mlocJoin(MachineBasicBlock &MBB,
1030                 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1031                 FuncValueTable &OutLocs, ValueTable &InLocs);
1032 
1033   /// Produce a set of blocks that are in the current lexical scope. This means
1034   /// those blocks that contain instructions "in" the scope, blocks where
1035   /// assignments to variables in scope occur, and artificial blocks that are
1036   /// successors to any of the earlier blocks. See https://llvm.org/PR48091 for
1037   /// more commentry on what "in scope" means.
1038   /// \p DILoc A location in the scope that we're fetching blocks for.
1039   /// \p Output Set to put in-scope-blocks into.
1040   /// \p AssignBlocks Blocks known to contain assignments of variables in scope.
1041   void
1042   getBlocksForScope(const DILocation *DILoc,
1043                     SmallPtrSetImpl<const MachineBasicBlock *> &Output,
1044                     const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks);
1045 
1046   /// Solve the variable value dataflow problem, for a single lexical scope.
1047   /// Uses the algorithm from the file comment to resolve control flow joins
1048   /// using PHI placement and value propagation. Reads the locations of machine
1049   /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap)
1050   /// and reads the variable values transfer function from \p AllTheVlocs.
1051   /// Live-in and Live-out variable values are stored locally, with the live-ins
1052   /// permanently stored to \p Output once a fixedpoint is reached.
1053   /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
1054   /// that we should be tracking.
1055   /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's
1056   /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks
1057   /// locations through.
1058   void buildVLocValueMap(const DILocation *DILoc,
1059                          const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
1060                          SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
1061                          LiveInsT &Output, FuncValueTable &MOutLocs,
1062                          FuncValueTable &MInLocs,
1063                          SmallVectorImpl<VLocTracker> &AllTheVLocs);
1064 
1065   /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the
1066   /// live-in values coming from predecessors live-outs, and replaces any PHIs
1067   /// already present in this blocks live-ins with a live-through value if the
1068   /// PHI isn't needed.
1069   /// \p LiveIn Old live-in value, overwritten with new one if live-in changes.
1070   /// \returns true if any live-ins change value, either from value propagation
1071   ///          or PHI elimination.
1072   bool vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
1073                 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
1074                 DbgValue &LiveIn);
1075 
1076   /// For the given block and live-outs feeding into it, try to find a
1077   /// machine location where all the variable values join together.
1078   /// \returns Value ID of a machine PHI if an appropriate one is available.
1079   Optional<ValueIDNum>
1080   pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var,
1081               const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
1082               const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
1083 
1084   /// Take collections of DBG_VALUE instructions stored in TTracker, and
1085   /// install them into their output blocks. Preserves a stable order of
1086   /// DBG_VALUEs produced (which would otherwise cause nondeterminism) through
1087   /// the AllVarsNumbering order.
1088   bool emitTransfers(DenseMap<DebugVariable, unsigned> &AllVarsNumbering);
1089 
1090   /// Boilerplate computation of some initial sets, artifical blocks and
1091   /// RPOT block ordering.
1092   void initialSetup(MachineFunction &MF);
1093 
1094   /// Produce a map of the last lexical scope that uses a block, using the
1095   /// scopes DFSOut number. Mapping is block-number to DFSOut.
1096   /// \p EjectionMap Pre-allocated vector in which to install the built ma.
1097   /// \p ScopeToDILocation Mapping of LexicalScopes to their DILocations.
1098   /// \p AssignBlocks Map of blocks where assignments happen for a scope.
1099   void makeDepthFirstEjectionMap(SmallVectorImpl<unsigned> &EjectionMap,
1100                                  const ScopeToDILocT &ScopeToDILocation,
1101                                  ScopeToAssignBlocksT &AssignBlocks);
1102 
1103   /// When determining per-block variable values and emitting to DBG_VALUEs,
1104   /// this function explores by lexical scope depth. Doing so means that per
1105   /// block information can be fully computed before exploration finishes,
1106   /// allowing us to emit it and free data structures earlier than otherwise.
1107   /// It's also good for locality.
1108   bool depthFirstVLocAndEmit(
1109       unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
1110       const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToBlocks,
1111       LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
1112       SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
1113       DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
1114       const TargetPassConfig &TPC);
1115 
1116   bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
1117                     TargetPassConfig *TPC, unsigned InputBBLimit,
1118                     unsigned InputDbgValLimit) override;
1119 
1120 public:
1121   /// Default construct and initialize the pass.
1122   InstrRefBasedLDV();
1123 
1124   LLVM_DUMP_METHOD
1125   void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1126 
1127   bool isCalleeSaved(LocIdx L) const;
1128 
1129   bool hasFoldedStackStore(const MachineInstr &MI) {
1130     // Instruction must have a memory operand that's a stack slot, and isn't
1131     // aliased, meaning it's a spill from regalloc instead of a variable.
1132     // If it's aliased, we can't guarantee its value.
1133     if (!MI.hasOneMemOperand())
1134       return false;
1135     auto *MemOperand = *MI.memoperands_begin();
1136     return MemOperand->isStore() &&
1137            MemOperand->getPseudoValue() &&
1138            MemOperand->getPseudoValue()->kind() == PseudoSourceValue::FixedStack
1139            && !MemOperand->getPseudoValue()->isAliased(MFI);
1140   }
1141 
1142   Optional<LocIdx> findLocationForMemOperand(const MachineInstr &MI);
1143 };
1144 
1145 } // namespace LiveDebugValues
1146 
1147 namespace llvm {
1148 using namespace LiveDebugValues;
1149 
1150 template <> struct DenseMapInfo<LocIdx> {
1151   static inline LocIdx getEmptyKey() { return LocIdx::MakeIllegalLoc(); }
1152   static inline LocIdx getTombstoneKey() { return LocIdx::MakeTombstoneLoc(); }
1153 
1154   static unsigned getHashValue(const LocIdx &Loc) { return Loc.asU64(); }
1155 
1156   static bool isEqual(const LocIdx &A, const LocIdx &B) { return A == B; }
1157 };
1158 
1159 template <> struct DenseMapInfo<ValueIDNum> {
1160   static inline ValueIDNum getEmptyKey() { return ValueIDNum::EmptyValue; }
1161   static inline ValueIDNum getTombstoneKey() {
1162     return ValueIDNum::TombstoneValue;
1163   }
1164 
1165   static unsigned getHashValue(const ValueIDNum &Val) {
1166     return hash_value(Val.asU64());
1167   }
1168 
1169   static bool isEqual(const ValueIDNum &A, const ValueIDNum &B) {
1170     return A == B;
1171   }
1172 };
1173 
1174 } // end namespace llvm
1175 
1176 #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */
1177