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