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