1 //===- InstrRefBasedImpl.cpp - 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 /// \file InstrRefBasedImpl.cpp
9 ///
10 /// This is a separate implementation of LiveDebugValues, see
11 /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information.
12 ///
13 /// This pass propagates variable locations between basic blocks, resolving
14 /// control flow conflicts between them. The problem is much like SSA
15 /// construction, where each DBG_VALUE instruction assigns the *value* that
16 /// a variable has, and every instruction where the variable is in scope uses
17 /// that variable. The resulting map of instruction-to-value is then translated
18 /// into a register (or spill) location for each variable over each instruction.
19 ///
20 /// This pass determines which DBG_VALUE dominates which instructions, or if
21 /// none do, where values must be merged (like PHI nodes). The added
22 /// complication is that because codegen has already finished, a PHI node may
23 /// be needed for a variable location to be correct, but no register or spill
24 /// slot merges the necessary values. In these circumstances, the variable
25 /// location is dropped.
26 ///
27 /// What makes this analysis non-trivial is loops: we cannot tell in advance
28 /// whether a variable location is live throughout a loop, or whether its
29 /// location is clobbered (or redefined by another DBG_VALUE), without
30 /// exploring all the way through.
31 ///
32 /// To make this simpler we perform two kinds of analysis. First, we identify
33 /// every value defined by every instruction (ignoring those that only move
34 /// another value), then compute a map of which values are available for each
35 /// instruction. This is stronger than a reaching-def analysis, as we create
36 /// PHI values where other values merge.
37 ///
38 /// Secondly, for each variable, we effectively re-construct SSA using each
39 /// DBG_VALUE as a def. The DBG_VALUEs read a value-number computed by the
40 /// first analysis from the location they refer to. We can then compute the
41 /// dominance frontiers of where a variable has a value, and create PHI nodes
42 /// where they merge.
43 /// This isn't precisely SSA-construction though, because the function shape
44 /// is pre-defined. If a variable location requires a PHI node, but no
45 /// PHI for the relevant values is present in the function (as computed by the
46 /// first analysis), the location must be dropped.
47 ///
48 /// Once both are complete, we can pass back over all instructions knowing:
49 ///  * What _value_ each variable should contain, either defined by an
50 ///    instruction or where control flow merges
51 ///  * What the location of that value is (if any).
52 /// Allowing us to create appropriate live-in DBG_VALUEs, and DBG_VALUEs when
53 /// a value moves location. After this pass runs, all variable locations within
54 /// a block should be specified by DBG_VALUEs within that block, allowing
55 /// DbgEntityHistoryCalculator to focus on individual blocks.
56 ///
57 /// This pass is able to go fast because the size of the first
58 /// reaching-definition analysis is proportional to the working-set size of
59 /// the function, which the compiler tries to keep small. (It's also
60 /// proportional to the number of blocks). Additionally, we repeatedly perform
61 /// the second reaching-definition analysis with only the variables and blocks
62 /// in a single lexical scope, exploiting their locality.
63 ///
64 /// Determining where PHIs happen is trickier with this approach, and it comes
65 /// to a head in the major problem for LiveDebugValues: is a value live-through
66 /// a loop, or not? Your garden-variety dataflow analysis aims to build a set of
67 /// facts about a function, however this analysis needs to generate new value
68 /// numbers at joins.
69 ///
70 /// To do this, consider a lattice of all definition values, from instructions
71 /// and from PHIs. Each PHI is characterised by the RPO number of the block it
72 /// occurs in. Each value pair A, B can be ordered by RPO(A) < RPO(B):
73 /// with non-PHI values at the top, and any PHI value in the last block (by RPO
74 /// order) at the bottom.
75 ///
76 /// (Awkwardly: lower-down-the _lattice_ means a greater RPO _number_. Below,
77 /// "rank" always refers to the former).
78 ///
79 /// At any join, for each register, we consider:
80 ///  * All incoming values, and
81 ///  * The PREVIOUS live-in value at this join.
82 /// If all incoming values agree: that's the live-in value. If they do not, the
83 /// incoming values are ranked according to the partial order, and the NEXT
84 /// LOWEST rank after the PREVIOUS live-in value is picked (multiple values of
85 /// the same rank are ignored as conflicting). If there are no candidate values,
86 /// or if the rank of the live-in would be lower than the rank of the current
87 /// blocks PHIs, create a new PHI value.
88 ///
89 /// Intuitively: if it's not immediately obvious what value a join should result
90 /// in, we iteratively descend from instruction-definitions down through PHI
91 /// values, getting closer to the current block each time. If the current block
92 /// is a loop head, this ordering is effectively searching outer levels of
93 /// loops, to find a value that's live-through the current loop.
94 ///
95 /// If there is no value that's live-through this loop, a PHI is created for
96 /// this location instead. We can't use a lower-ranked PHI because by definition
97 /// it doesn't dominate the current block. We can't create a PHI value any
98 /// earlier, because we risk creating a PHI value at a location where values do
99 /// not in fact merge, thus misrepresenting the truth, and not making the true
100 /// live-through value for variable locations.
101 ///
102 /// This algorithm applies to both calculating the availability of values in
103 /// the first analysis, and the location of variables in the second. However
104 /// for the second we add an extra dimension of pain: creating a variable
105 /// location PHI is only valid if, for each incoming edge,
106 ///  * There is a value for the variable on the incoming edge, and
107 ///  * All the edges have that value in the same register.
108 /// Or put another way: we can only create a variable-location PHI if there is
109 /// a matching machine-location PHI, each input to which is the variables value
110 /// in the predecessor block.
111 ///
112 /// To accommodate this difference, each point on the lattice is split in
113 /// two: a "proposed" PHI and "definite" PHI. Any PHI that can immediately
114 /// have a location determined are "definite" PHIs, and no further work is
115 /// needed. Otherwise, a location that all non-backedge predecessors agree
116 /// on is picked and propagated as a "proposed" PHI value. If that PHI value
117 /// is truly live-through, it'll appear on the loop backedges on the next
118 /// dataflow iteration, after which the block live-in moves to be a "definite"
119 /// PHI. If it's not truly live-through, the variable value will be downgraded
120 /// further as we explore the lattice, or remains "proposed" and is considered
121 /// invalid once dataflow completes.
122 ///
123 /// ### Terminology
124 ///
125 /// A machine location is a register or spill slot, a value is something that's
126 /// defined by an instruction or PHI node, while a variable value is the value
127 /// assigned to a variable. A variable location is a machine location, that must
128 /// contain the appropriate variable value. A value that is a PHI node is
129 /// occasionally called an mphi.
130 ///
131 /// The first dataflow problem is the "machine value location" problem,
132 /// because we're determining which machine locations contain which values.
133 /// The "locations" are constant: what's unknown is what value they contain.
134 ///
135 /// The second dataflow problem (the one for variables) is the "variable value
136 /// problem", because it's determining what values a variable has, rather than
137 /// what location those values are placed in. Unfortunately, it's not that
138 /// simple, because producing a PHI value always involves picking a location.
139 /// This is an imperfection that we just have to accept, at least for now.
140 ///
141 /// TODO:
142 ///   Overlapping fragments
143 ///   Entry values
144 ///   Add back DEBUG statements for debugging this
145 ///   Collect statistics
146 ///
147 //===----------------------------------------------------------------------===//
148 
149 #include "llvm/ADT/DenseMap.h"
150 #include "llvm/ADT/PostOrderIterator.h"
151 #include "llvm/ADT/SmallPtrSet.h"
152 #include "llvm/ADT/SmallSet.h"
153 #include "llvm/ADT/SmallVector.h"
154 #include "llvm/ADT/Statistic.h"
155 #include "llvm/ADT/UniqueVector.h"
156 #include "llvm/CodeGen/LexicalScopes.h"
157 #include "llvm/CodeGen/MachineBasicBlock.h"
158 #include "llvm/CodeGen/MachineFrameInfo.h"
159 #include "llvm/CodeGen/MachineFunction.h"
160 #include "llvm/CodeGen/MachineFunctionPass.h"
161 #include "llvm/CodeGen/MachineInstr.h"
162 #include "llvm/CodeGen/MachineInstrBuilder.h"
163 #include "llvm/CodeGen/MachineMemOperand.h"
164 #include "llvm/CodeGen/MachineOperand.h"
165 #include "llvm/CodeGen/PseudoSourceValue.h"
166 #include "llvm/CodeGen/RegisterScavenging.h"
167 #include "llvm/CodeGen/TargetFrameLowering.h"
168 #include "llvm/CodeGen/TargetInstrInfo.h"
169 #include "llvm/CodeGen/TargetLowering.h"
170 #include "llvm/CodeGen/TargetPassConfig.h"
171 #include "llvm/CodeGen/TargetRegisterInfo.h"
172 #include "llvm/CodeGen/TargetSubtargetInfo.h"
173 #include "llvm/Config/llvm-config.h"
174 #include "llvm/IR/DIBuilder.h"
175 #include "llvm/IR/DebugInfoMetadata.h"
176 #include "llvm/IR/DebugLoc.h"
177 #include "llvm/IR/Function.h"
178 #include "llvm/IR/Module.h"
179 #include "llvm/InitializePasses.h"
180 #include "llvm/MC/MCRegisterInfo.h"
181 #include "llvm/Pass.h"
182 #include "llvm/Support/Casting.h"
183 #include "llvm/Support/Compiler.h"
184 #include "llvm/Support/Debug.h"
185 #include "llvm/Support/TypeSize.h"
186 #include "llvm/Support/raw_ostream.h"
187 #include <algorithm>
188 #include <cassert>
189 #include <cstdint>
190 #include <functional>
191 #include <queue>
192 #include <tuple>
193 #include <utility>
194 #include <vector>
195 #include <limits.h>
196 #include <limits>
197 
198 #include "LiveDebugValues.h"
199 
200 using namespace llvm;
201 
202 #define DEBUG_TYPE "livedebugvalues"
203 
204 STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
205 STATISTIC(NumRemoved, "Number of DBG_VALUE instructions removed");
206 
207 // Act more like the VarLoc implementation, by propagating some locations too
208 // far and ignoring some transfers.
209 static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
210                                    cl::desc("Act like old LiveDebugValues did"),
211                                    cl::init(false));
212 
213 // Rely on isStoreToStackSlotPostFE and similar to observe all stack spills.
214 static cl::opt<bool>
215     ObserveAllStackops("observe-all-stack-ops", cl::Hidden,
216                        cl::desc("Allow non-kill spill and restores"),
217                        cl::init(false));
218 
219 namespace {
220 
221 // The location at which a spilled value resides. It consists of a register and
222 // an offset.
223 struct SpillLoc {
224   unsigned SpillBase;
225   StackOffset SpillOffset;
226   bool operator==(const SpillLoc &Other) const {
227     return std::make_pair(SpillBase, SpillOffset) ==
228            std::make_pair(Other.SpillBase, Other.SpillOffset);
229   }
230   bool operator<(const SpillLoc &Other) const {
231     return std::make_tuple(SpillBase, SpillOffset.getFixed(),
232                     SpillOffset.getScalable()) <
233            std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(),
234                     Other.SpillOffset.getScalable());
235   }
236 };
237 
238 class LocIdx {
239   unsigned Location;
240 
241   // Default constructor is private, initializing to an illegal location number.
242   // Use only for "not an entry" elements in IndexedMaps.
243   LocIdx() : Location(UINT_MAX) { }
244 
245 public:
246   #define NUM_LOC_BITS 24
247   LocIdx(unsigned L) : Location(L) {
248     assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
249   }
250 
251   static LocIdx MakeIllegalLoc() {
252     return LocIdx();
253   }
254 
255   bool isIllegal() const {
256     return Location == UINT_MAX;
257   }
258 
259   uint64_t asU64() const {
260     return Location;
261   }
262 
263   bool operator==(unsigned L) const {
264     return Location == L;
265   }
266 
267   bool operator==(const LocIdx &L) const {
268     return Location == L.Location;
269   }
270 
271   bool operator!=(unsigned L) const {
272     return !(*this == L);
273   }
274 
275   bool operator!=(const LocIdx &L) const {
276     return !(*this == L);
277   }
278 
279   bool operator<(const LocIdx &Other) const {
280     return Location < Other.Location;
281   }
282 };
283 
284 class LocIdxToIndexFunctor {
285 public:
286   using argument_type = LocIdx;
287   unsigned operator()(const LocIdx &L) const {
288     return L.asU64();
289   }
290 };
291 
292 /// Unique identifier for a value defined by an instruction, as a value type.
293 /// Casts back and forth to a uint64_t. Probably replacable with something less
294 /// bit-constrained. Each value identifies the instruction and machine location
295 /// where the value is defined, although there may be no corresponding machine
296 /// operand for it (ex: regmasks clobbering values). The instructions are
297 /// one-based, and definitions that are PHIs have instruction number zero.
298 ///
299 /// The obvious limits of a 1M block function or 1M instruction blocks are
300 /// problematic; but by that point we should probably have bailed out of
301 /// trying to analyse the function.
302 class ValueIDNum {
303   uint64_t BlockNo : 20;         /// The block where the def happens.
304   uint64_t InstNo : 20;          /// The Instruction where the def happens.
305                                  /// One based, is distance from start of block.
306   uint64_t LocNo : NUM_LOC_BITS; /// The machine location where the def happens.
307 
308 public:
309   // XXX -- temporarily enabled while the live-in / live-out tables are moved
310   // to something more type-y
311   ValueIDNum() : BlockNo(0xFFFFF),
312                  InstNo(0xFFFFF),
313                  LocNo(0xFFFFFF) { }
314 
315   ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc)
316     : BlockNo(Block), InstNo(Inst), LocNo(Loc) { }
317 
318   ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc)
319     : BlockNo(Block), InstNo(Inst), LocNo(Loc.asU64()) { }
320 
321   uint64_t getBlock() const { return BlockNo; }
322   uint64_t getInst() const { return InstNo; }
323   uint64_t getLoc() const { return LocNo; }
324   bool isPHI() const { return InstNo == 0; }
325 
326   uint64_t asU64() const {
327     uint64_t TmpBlock = BlockNo;
328     uint64_t TmpInst = InstNo;
329     return TmpBlock << 44ull | TmpInst << NUM_LOC_BITS | LocNo;
330   }
331 
332   static ValueIDNum fromU64(uint64_t v) {
333     uint64_t L = (v & 0x3FFF);
334     return {v >> 44ull, ((v >> NUM_LOC_BITS) & 0xFFFFF), L};
335   }
336 
337   bool operator<(const ValueIDNum &Other) const {
338     return asU64() < Other.asU64();
339   }
340 
341   bool operator==(const ValueIDNum &Other) const {
342     return std::tie(BlockNo, InstNo, LocNo) ==
343            std::tie(Other.BlockNo, Other.InstNo, Other.LocNo);
344   }
345 
346   bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
347 
348   std::string asString(const std::string &mlocname) const {
349     return Twine("Value{bb: ")
350         .concat(Twine(BlockNo).concat(
351             Twine(", inst: ")
352                 .concat((InstNo ? Twine(InstNo) : Twine("live-in"))
353                             .concat(Twine(", loc: ").concat(Twine(mlocname)))
354                             .concat(Twine("}")))))
355         .str();
356   }
357 
358   static ValueIDNum EmptyValue;
359 };
360 
361 } // end anonymous namespace
362 
363 namespace {
364 
365 /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
366 /// the the value, and Boolean of whether or not it's indirect.
367 class DbgValueProperties {
368 public:
369   DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
370       : DIExpr(DIExpr), Indirect(Indirect) {}
371 
372   /// Extract properties from an existing DBG_VALUE instruction.
373   DbgValueProperties(const MachineInstr &MI) {
374     assert(MI.isDebugValue());
375     DIExpr = MI.getDebugExpression();
376     Indirect = MI.getOperand(1).isImm();
377   }
378 
379   bool operator==(const DbgValueProperties &Other) const {
380     return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
381   }
382 
383   bool operator!=(const DbgValueProperties &Other) const {
384     return !(*this == Other);
385   }
386 
387   const DIExpression *DIExpr;
388   bool Indirect;
389 };
390 
391 /// Tracker for what values are in machine locations. Listens to the Things
392 /// being Done by various instructions, and maintains a table of what machine
393 /// locations have what values (as defined by a ValueIDNum).
394 ///
395 /// There are potentially a much larger number of machine locations on the
396 /// target machine than the actual working-set size of the function. On x86 for
397 /// example, we're extremely unlikely to want to track values through control
398 /// or debug registers. To avoid doing so, MLocTracker has several layers of
399 /// indirection going on, with two kinds of ``location'':
400 ///  * A LocID uniquely identifies a register or spill location, with a
401 ///    predictable value.
402 ///  * A LocIdx is a key (in the database sense) for a LocID and a ValueIDNum.
403 /// Whenever a location is def'd or used by a MachineInstr, we automagically
404 /// create a new LocIdx for a location, but not otherwise. This ensures we only
405 /// account for locations that are actually used or defined. The cost is another
406 /// vector lookup (of LocID -> LocIdx) over any other implementation. This is
407 /// fairly cheap, and the compiler tries to reduce the working-set at any one
408 /// time in the function anyway.
409 ///
410 /// Register mask operands completely blow this out of the water; I've just
411 /// piled hacks on top of hacks to get around that.
412 class MLocTracker {
413 public:
414   MachineFunction &MF;
415   const TargetInstrInfo &TII;
416   const TargetRegisterInfo &TRI;
417   const TargetLowering &TLI;
418 
419   /// IndexedMap type, mapping from LocIdx to ValueIDNum.
420   using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
421 
422   /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
423   /// packed, entries only exist for locations that are being tracked.
424   LocToValueType LocIdxToIDNum;
425 
426   /// "Map" of machine location IDs (i.e., raw register or spill number) to the
427   /// LocIdx key / number for that location. There are always at least as many
428   /// as the number of registers on the target -- if the value in the register
429   /// is not being tracked, then the LocIdx value will be zero. New entries are
430   /// appended if a new spill slot begins being tracked.
431   /// This, and the corresponding reverse map persist for the analysis of the
432   /// whole function, and is necessarying for decoding various vectors of
433   /// values.
434   std::vector<LocIdx> LocIDToLocIdx;
435 
436   /// Inverse map of LocIDToLocIdx.
437   IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
438 
439   /// Unique-ification of spill slots. Used to number them -- their LocID
440   /// number is the index in SpillLocs minus one plus NumRegs.
441   UniqueVector<SpillLoc> SpillLocs;
442 
443   // If we discover a new machine location, assign it an mphi with this
444   // block number.
445   unsigned CurBB;
446 
447   /// Cached local copy of the number of registers the target has.
448   unsigned NumRegs;
449 
450   /// Collection of register mask operands that have been observed. Second part
451   /// of pair indicates the instruction that they happened in. Used to
452   /// reconstruct where defs happened if we start tracking a location later
453   /// on.
454   SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
455 
456   /// Iterator for locations and the values they contain. Dereferencing
457   /// produces a struct/pair containing the LocIdx key for this location,
458   /// and a reference to the value currently stored. Simplifies the process
459   /// of seeking a particular location.
460   class MLocIterator {
461     LocToValueType &ValueMap;
462     LocIdx Idx;
463 
464   public:
465     class value_type {
466       public:
467       value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) { }
468       const LocIdx Idx;  /// Read-only index of this location.
469       ValueIDNum &Value; /// Reference to the stored value at this location.
470     };
471 
472     MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
473       : ValueMap(ValueMap), Idx(Idx) { }
474 
475     bool operator==(const MLocIterator &Other) const {
476       assert(&ValueMap == &Other.ValueMap);
477       return Idx == Other.Idx;
478     }
479 
480     bool operator!=(const MLocIterator &Other) const {
481       return !(*this == Other);
482     }
483 
484     void operator++() {
485       Idx = LocIdx(Idx.asU64() + 1);
486     }
487 
488     value_type operator*() {
489       return value_type(Idx, ValueMap[LocIdx(Idx)]);
490     }
491   };
492 
493   MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
494               const TargetRegisterInfo &TRI, const TargetLowering &TLI)
495       : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
496         LocIdxToIDNum(ValueIDNum::EmptyValue),
497         LocIdxToLocID(0) {
498     NumRegs = TRI.getNumRegs();
499     reset();
500     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
501     assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
502 
503     // Always track SP. This avoids the implicit clobbering caused by regmasks
504     // from affectings its values. (LiveDebugValues disbelieves calls and
505     // regmasks that claim to clobber SP).
506     Register SP = TLI.getStackPointerRegisterToSaveRestore();
507     if (SP) {
508       unsigned ID = getLocID(SP, false);
509       (void)lookupOrTrackRegister(ID);
510     }
511   }
512 
513   /// Produce location ID number for indexing LocIDToLocIdx. Takes the register
514   /// or spill number, and flag for whether it's a spill or not.
515   unsigned getLocID(Register RegOrSpill, bool isSpill) {
516     return (isSpill) ? RegOrSpill.id() + NumRegs - 1 : RegOrSpill.id();
517   }
518 
519   /// Accessor for reading the value at Idx.
520   ValueIDNum getNumAtPos(LocIdx Idx) const {
521     assert(Idx.asU64() < LocIdxToIDNum.size());
522     return LocIdxToIDNum[Idx];
523   }
524 
525   unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); }
526 
527   /// Reset all locations to contain a PHI value at the designated block. Used
528   /// sometimes for actual PHI values, othertimes to indicate the block entry
529   /// value (before any more information is known).
530   void setMPhis(unsigned NewCurBB) {
531     CurBB = NewCurBB;
532     for (auto Location : locations())
533       Location.Value = {CurBB, 0, Location.Idx};
534   }
535 
536   /// Load values for each location from array of ValueIDNums. Take current
537   /// bbnum just in case we read a value from a hitherto untouched register.
538   void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) {
539     CurBB = NewCurBB;
540     // Iterate over all tracked locations, and load each locations live-in
541     // value into our local index.
542     for (auto Location : locations())
543       Location.Value = Locs[Location.Idx.asU64()];
544   }
545 
546   /// Wipe any un-necessary location records after traversing a block.
547   void reset(void) {
548     // We could reset all the location values too; however either loadFromArray
549     // or setMPhis should be called before this object is re-used. Just
550     // clear Masks, they're definitely not needed.
551     Masks.clear();
552   }
553 
554   /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
555   /// the information in this pass uninterpretable.
556   void clear(void) {
557     reset();
558     LocIDToLocIdx.clear();
559     LocIdxToLocID.clear();
560     LocIdxToIDNum.clear();
561     //SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from 0
562     SpillLocs = decltype(SpillLocs)();
563 
564     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
565   }
566 
567   /// Set a locaiton to a certain value.
568   void setMLoc(LocIdx L, ValueIDNum Num) {
569     assert(L.asU64() < LocIdxToIDNum.size());
570     LocIdxToIDNum[L] = Num;
571   }
572 
573   /// Create a LocIdx for an untracked register ID. Initialize it to either an
574   /// mphi value representing a live-in, or a recent register mask clobber.
575   LocIdx trackRegister(unsigned ID) {
576     assert(ID != 0);
577     LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
578     LocIdxToIDNum.grow(NewIdx);
579     LocIdxToLocID.grow(NewIdx);
580 
581     // Default: it's an mphi.
582     ValueIDNum ValNum = {CurBB, 0, NewIdx};
583     // Was this reg ever touched by a regmask?
584     for (const auto &MaskPair : reverse(Masks)) {
585       if (MaskPair.first->clobbersPhysReg(ID)) {
586         // There was an earlier def we skipped.
587         ValNum = {CurBB, MaskPair.second, NewIdx};
588         break;
589       }
590     }
591 
592     LocIdxToIDNum[NewIdx] = ValNum;
593     LocIdxToLocID[NewIdx] = ID;
594     return NewIdx;
595   }
596 
597   LocIdx lookupOrTrackRegister(unsigned ID) {
598     LocIdx &Index = LocIDToLocIdx[ID];
599     if (Index.isIllegal())
600       Index = trackRegister(ID);
601     return Index;
602   }
603 
604   /// Record a definition of the specified register at the given block / inst.
605   /// This doesn't take a ValueIDNum, because the definition and its location
606   /// are synonymous.
607   void defReg(Register R, unsigned BB, unsigned Inst) {
608     unsigned ID = getLocID(R, false);
609     LocIdx Idx = lookupOrTrackRegister(ID);
610     ValueIDNum ValueID = {BB, Inst, Idx};
611     LocIdxToIDNum[Idx] = ValueID;
612   }
613 
614   /// Set a register to a value number. To be used if the value number is
615   /// known in advance.
616   void setReg(Register R, ValueIDNum ValueID) {
617     unsigned ID = getLocID(R, false);
618     LocIdx Idx = lookupOrTrackRegister(ID);
619     LocIdxToIDNum[Idx] = ValueID;
620   }
621 
622   ValueIDNum readReg(Register R) {
623     unsigned ID = getLocID(R, false);
624     LocIdx Idx = lookupOrTrackRegister(ID);
625     return LocIdxToIDNum[Idx];
626   }
627 
628   /// Reset a register value to zero / empty. Needed to replicate the
629   /// VarLoc implementation where a copy to/from a register effectively
630   /// clears the contents of the source register. (Values can only have one
631   ///  machine location in VarLocBasedImpl).
632   void wipeRegister(Register R) {
633     unsigned ID = getLocID(R, false);
634     LocIdx Idx = LocIDToLocIdx[ID];
635     LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
636   }
637 
638   /// Determine the LocIdx of an existing register.
639   LocIdx getRegMLoc(Register R) {
640     unsigned ID = getLocID(R, false);
641     return LocIDToLocIdx[ID];
642   }
643 
644   /// Record a RegMask operand being executed. Defs any register we currently
645   /// track, stores a pointer to the mask in case we have to account for it
646   /// later.
647   void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID) {
648     // Ensure SP exists, so that we don't override it later.
649     Register SP = TLI.getStackPointerRegisterToSaveRestore();
650 
651     // Def any register we track have that isn't preserved. The regmask
652     // terminates the liveness of a register, meaning its value can't be
653     // relied upon -- we represent this by giving it a new value.
654     for (auto Location : locations()) {
655       unsigned ID = LocIdxToLocID[Location.Idx];
656       // Don't clobber SP, even if the mask says it's clobbered.
657       if (ID < NumRegs && ID != SP && MO->clobbersPhysReg(ID))
658         defReg(ID, CurBB, InstID);
659     }
660     Masks.push_back(std::make_pair(MO, InstID));
661   }
662 
663   /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
664   LocIdx getOrTrackSpillLoc(SpillLoc L) {
665     unsigned SpillID = SpillLocs.idFor(L);
666     if (SpillID == 0) {
667       SpillID = SpillLocs.insert(L);
668       unsigned L = getLocID(SpillID, true);
669       LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
670       LocIdxToIDNum.grow(Idx);
671       LocIdxToLocID.grow(Idx);
672       LocIDToLocIdx.push_back(Idx);
673       LocIdxToLocID[Idx] = L;
674       return Idx;
675     } else {
676       unsigned L = getLocID(SpillID, true);
677       LocIdx Idx = LocIDToLocIdx[L];
678       return Idx;
679     }
680   }
681 
682   /// Set the value stored in a spill slot.
683   void setSpill(SpillLoc L, ValueIDNum ValueID) {
684     LocIdx Idx = getOrTrackSpillLoc(L);
685     LocIdxToIDNum[Idx] = ValueID;
686   }
687 
688   /// Read whatever value is in a spill slot, or None if it isn't tracked.
689   Optional<ValueIDNum> readSpill(SpillLoc L) {
690     unsigned SpillID = SpillLocs.idFor(L);
691     if (SpillID == 0)
692       return None;
693 
694     unsigned LocID = getLocID(SpillID, true);
695     LocIdx Idx = LocIDToLocIdx[LocID];
696     return LocIdxToIDNum[Idx];
697   }
698 
699   /// Determine the LocIdx of a spill slot. Return None if it previously
700   /// hasn't had a value assigned.
701   Optional<LocIdx> getSpillMLoc(SpillLoc L) {
702     unsigned SpillID = SpillLocs.idFor(L);
703     if (SpillID == 0)
704       return None;
705     unsigned LocNo = getLocID(SpillID, true);
706     return LocIDToLocIdx[LocNo];
707   }
708 
709   /// Return true if Idx is a spill machine location.
710   bool isSpill(LocIdx Idx) const {
711     return LocIdxToLocID[Idx] >= NumRegs;
712   }
713 
714   MLocIterator begin() {
715     return MLocIterator(LocIdxToIDNum, 0);
716   }
717 
718   MLocIterator end() {
719     return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
720   }
721 
722   /// Return a range over all locations currently tracked.
723   iterator_range<MLocIterator> locations() {
724     return llvm::make_range(begin(), end());
725   }
726 
727   std::string LocIdxToName(LocIdx Idx) const {
728     unsigned ID = LocIdxToLocID[Idx];
729     if (ID >= NumRegs)
730       return Twine("slot ").concat(Twine(ID - NumRegs)).str();
731     else
732       return TRI.getRegAsmName(ID).str();
733   }
734 
735   std::string IDAsString(const ValueIDNum &Num) const {
736     std::string DefName = LocIdxToName(Num.getLoc());
737     return Num.asString(DefName);
738   }
739 
740   LLVM_DUMP_METHOD
741   void dump() {
742     for (auto Location : locations()) {
743       std::string MLocName = LocIdxToName(Location.Value.getLoc());
744       std::string DefName = Location.Value.asString(MLocName);
745       dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
746     }
747   }
748 
749   LLVM_DUMP_METHOD
750   void dump_mloc_map() {
751     for (auto Location : locations()) {
752       std::string foo = LocIdxToName(Location.Idx);
753       dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
754     }
755   }
756 
757   /// Create a DBG_VALUE based on  machine location \p MLoc. Qualify it with the
758   /// information in \pProperties, for variable Var. Don't insert it anywhere,
759   /// just return the builder for it.
760   MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
761                               const DbgValueProperties &Properties) {
762     DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
763                                   Var.getVariable()->getScope(),
764                                   const_cast<DILocation *>(Var.getInlinedAt()));
765     auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE));
766 
767     const DIExpression *Expr = Properties.DIExpr;
768     if (!MLoc) {
769       // No location -> DBG_VALUE $noreg
770       MIB.addReg(0, RegState::Debug);
771       MIB.addReg(0, RegState::Debug);
772     } else if (LocIdxToLocID[*MLoc] >= NumRegs) {
773       unsigned LocID = LocIdxToLocID[*MLoc];
774       const SpillLoc &Spill = SpillLocs[LocID - NumRegs + 1];
775 
776       auto *TRI = MF.getSubtarget().getRegisterInfo();
777       Expr = TRI->prependOffsetExpression(Expr, DIExpression::ApplyOffset,
778                                           Spill.SpillOffset);
779       unsigned Base = Spill.SpillBase;
780       MIB.addReg(Base, RegState::Debug);
781       MIB.addImm(0);
782     } else {
783       unsigned LocID = LocIdxToLocID[*MLoc];
784       MIB.addReg(LocID, RegState::Debug);
785       if (Properties.Indirect)
786         MIB.addImm(0);
787       else
788         MIB.addReg(0, RegState::Debug);
789     }
790 
791     MIB.addMetadata(Var.getVariable());
792     MIB.addMetadata(Expr);
793     return MIB;
794   }
795 };
796 
797 /// Class recording the (high level) _value_ of a variable. Identifies either
798 /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
799 /// This class also stores meta-information about how the value is qualified.
800 /// Used to reason about variable values when performing the second
801 /// (DebugVariable specific) dataflow analysis.
802 class DbgValue {
803 public:
804   union {
805     /// If Kind is Def, the value number that this value is based on.
806     ValueIDNum ID;
807     /// If Kind is Const, the MachineOperand defining this value.
808     MachineOperand MO;
809     /// For a NoVal DbgValue, which block it was generated in.
810     unsigned BlockNo;
811   };
812   /// Qualifiers for the ValueIDNum above.
813   DbgValueProperties Properties;
814 
815   typedef enum {
816     Undef,     // Represents a DBG_VALUE $noreg in the transfer function only.
817     Def,       // This value is defined by an inst, or is a PHI value.
818     Const,     // A constant value contained in the MachineOperand field.
819     Proposed,  // This is a tentative PHI value, which may be confirmed or
820                // invalidated later.
821     NoVal      // Empty DbgValue, generated during dataflow. BlockNo stores
822                // which block this was generated in.
823    } KindT;
824   /// Discriminator for whether this is a constant or an in-program value.
825   KindT Kind;
826 
827   DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
828     : ID(Val), Properties(Prop), Kind(Kind) {
829     assert(Kind == Def || Kind == Proposed);
830   }
831 
832   DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
833     : BlockNo(BlockNo), Properties(Prop), Kind(Kind) {
834     assert(Kind == NoVal);
835   }
836 
837   DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
838     : MO(MO), Properties(Prop), Kind(Kind) {
839     assert(Kind == Const);
840   }
841 
842   DbgValue(const DbgValueProperties &Prop, KindT Kind)
843     : Properties(Prop), Kind(Kind) {
844     assert(Kind == Undef &&
845            "Empty DbgValue constructor must pass in Undef kind");
846   }
847 
848   void dump(const MLocTracker *MTrack) const {
849     if (Kind == Const) {
850       MO.dump();
851     } else if (Kind == NoVal) {
852       dbgs() << "NoVal(" << BlockNo << ")";
853     } else if (Kind == Proposed) {
854       dbgs() << "VPHI(" << MTrack->IDAsString(ID) << ")";
855     } else {
856       assert(Kind == Def);
857       dbgs() << MTrack->IDAsString(ID);
858     }
859     if (Properties.Indirect)
860       dbgs() << " indir";
861     if (Properties.DIExpr)
862       dbgs() << " " << *Properties.DIExpr;
863   }
864 
865   bool operator==(const DbgValue &Other) const {
866     if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
867       return false;
868     else if (Kind == Proposed && ID != Other.ID)
869       return false;
870     else if (Kind == Def && ID != Other.ID)
871       return false;
872     else if (Kind == NoVal && BlockNo != Other.BlockNo)
873       return false;
874     else if (Kind == Const)
875       return MO.isIdenticalTo(Other.MO);
876 
877     return true;
878   }
879 
880   bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
881 };
882 
883 /// Types for recording sets of variable fragments that overlap. For a given
884 /// local variable, we record all other fragments of that variable that could
885 /// overlap it, to reduce search time.
886 using FragmentOfVar =
887     std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
888 using OverlapMap =
889     DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
890 
891 /// Collection of DBG_VALUEs observed when traversing a block. Records each
892 /// variable and the value the DBG_VALUE refers to. Requires the machine value
893 /// location dataflow algorithm to have run already, so that values can be
894 /// identified.
895 class VLocTracker {
896 public:
897   /// Map DebugVariable to the latest Value it's defined to have.
898   /// Needs to be a MapVector because we determine order-in-the-input-MIR from
899   /// the order in this container.
900   /// We only retain the last DbgValue in each block for each variable, to
901   /// determine the blocks live-out variable value. The Vars container forms the
902   /// transfer function for this block, as part of the dataflow analysis. The
903   /// movement of values between locations inside of a block is handled at a
904   /// much later stage, in the TransferTracker class.
905   MapVector<DebugVariable, DbgValue> Vars;
906   DenseMap<DebugVariable, const DILocation *> Scopes;
907   MachineBasicBlock *MBB;
908 
909 public:
910   VLocTracker() {}
911 
912   void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
913               Optional<ValueIDNum> ID) {
914     assert(MI.isDebugValue() || MI.isDebugRef());
915     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
916                       MI.getDebugLoc()->getInlinedAt());
917     DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
918                         : DbgValue(Properties, DbgValue::Undef);
919 
920     // Attempt insertion; overwrite if it's already mapped.
921     auto Result = Vars.insert(std::make_pair(Var, Rec));
922     if (!Result.second)
923       Result.first->second = Rec;
924     Scopes[Var] = MI.getDebugLoc().get();
925   }
926 
927   void defVar(const MachineInstr &MI, const MachineOperand &MO) {
928     // Only DBG_VALUEs can define constant-valued variables.
929     assert(MI.isDebugValue());
930     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
931                       MI.getDebugLoc()->getInlinedAt());
932     DbgValueProperties Properties(MI);
933     DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
934 
935     // Attempt insertion; overwrite if it's already mapped.
936     auto Result = Vars.insert(std::make_pair(Var, Rec));
937     if (!Result.second)
938       Result.first->second = Rec;
939     Scopes[Var] = MI.getDebugLoc().get();
940   }
941 };
942 
943 /// Tracker for converting machine value locations and variable values into
944 /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
945 /// specifying block live-in locations and transfers within blocks.
946 ///
947 /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
948 /// and must be initialized with the set of variable values that are live-in to
949 /// the block. The caller then repeatedly calls process(). TransferTracker picks
950 /// out variable locations for the live-in variable values (if there _is_ a
951 /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
952 /// stepped through, transfers of values between machine locations are
953 /// identified and if profitable, a DBG_VALUE created.
954 ///
955 /// This is where debug use-before-defs would be resolved: a variable with an
956 /// unavailable value could materialize in the middle of a block, when the
957 /// value becomes available. Or, we could detect clobbers and re-specify the
958 /// variable in a backup location. (XXX these are unimplemented).
959 class TransferTracker {
960 public:
961   const TargetInstrInfo *TII;
962   /// This machine location tracker is assumed to always contain the up-to-date
963   /// value mapping for all machine locations. TransferTracker only reads
964   /// information from it. (XXX make it const?)
965   MLocTracker *MTracker;
966   MachineFunction &MF;
967 
968   /// Record of all changes in variable locations at a block position. Awkwardly
969   /// we allow inserting either before or after the point: MBB != nullptr
970   /// indicates it's before, otherwise after.
971   struct Transfer {
972     MachineBasicBlock::iterator Pos; /// Position to insert DBG_VALUes
973     MachineBasicBlock *MBB;          /// non-null if we should insert after.
974     SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
975   };
976 
977   typedef struct {
978     LocIdx Loc;
979     DbgValueProperties Properties;
980   } LocAndProperties;
981 
982   /// Collection of transfers (DBG_VALUEs) to be inserted.
983   SmallVector<Transfer, 32> Transfers;
984 
985   /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
986   /// between TransferTrackers view of variable locations and MLocTrackers. For
987   /// example, MLocTracker observes all clobbers, but TransferTracker lazily
988   /// does not.
989   std::vector<ValueIDNum> VarLocs;
990 
991   /// Map from LocIdxes to which DebugVariables are based that location.
992   /// Mantained while stepping through the block. Not accurate if
993   /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
994   std::map<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
995 
996   /// Map from DebugVariable to it's current location and qualifying meta
997   /// information. To be used in conjunction with ActiveMLocs to construct
998   /// enough information for the DBG_VALUEs for a particular LocIdx.
999   DenseMap<DebugVariable, LocAndProperties> ActiveVLocs;
1000 
1001   /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
1002   SmallVector<MachineInstr *, 4> PendingDbgValues;
1003 
1004   /// Record of a use-before-def: created when a value that's live-in to the
1005   /// current block isn't available in any machine location, but it will be
1006   /// defined in this block.
1007   struct UseBeforeDef {
1008     /// Value of this variable, def'd in block.
1009     ValueIDNum ID;
1010     /// Identity of this variable.
1011     DebugVariable Var;
1012     /// Additional variable properties.
1013     DbgValueProperties Properties;
1014   };
1015 
1016   /// Map from instruction index (within the block) to the set of UseBeforeDefs
1017   /// that become defined at that instruction.
1018   DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
1019 
1020   /// The set of variables that are in UseBeforeDefs and can become a location
1021   /// once the relevant value is defined. An element being erased from this
1022   /// collection prevents the use-before-def materializing.
1023   DenseSet<DebugVariable> UseBeforeDefVariables;
1024 
1025   const TargetRegisterInfo &TRI;
1026   const BitVector &CalleeSavedRegs;
1027 
1028   TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
1029                   MachineFunction &MF, const TargetRegisterInfo &TRI,
1030                   const BitVector &CalleeSavedRegs)
1031       : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
1032         CalleeSavedRegs(CalleeSavedRegs) {}
1033 
1034   /// Load object with live-in variable values. \p mlocs contains the live-in
1035   /// values in each machine location, while \p vlocs the live-in variable
1036   /// values. This method picks variable locations for the live-in variables,
1037   /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
1038   /// object fields to track variable locations as we step through the block.
1039   /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
1040   void loadInlocs(MachineBasicBlock &MBB, ValueIDNum *MLocs,
1041                   SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
1042                   unsigned NumLocs) {
1043     ActiveMLocs.clear();
1044     ActiveVLocs.clear();
1045     VarLocs.clear();
1046     VarLocs.reserve(NumLocs);
1047     UseBeforeDefs.clear();
1048     UseBeforeDefVariables.clear();
1049 
1050     auto isCalleeSaved = [&](LocIdx L) {
1051       unsigned Reg = MTracker->LocIdxToLocID[L];
1052       if (Reg >= MTracker->NumRegs)
1053         return false;
1054       for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
1055         if (CalleeSavedRegs.test(*RAI))
1056           return true;
1057       return false;
1058     };
1059 
1060     // Map of the preferred location for each value.
1061     std::map<ValueIDNum, LocIdx> ValueToLoc;
1062 
1063     // Produce a map of value numbers to the current machine locs they live
1064     // in. When emulating VarLocBasedImpl, there should only be one
1065     // location; when not, we get to pick.
1066     for (auto Location : MTracker->locations()) {
1067       LocIdx Idx = Location.Idx;
1068       ValueIDNum &VNum = MLocs[Idx.asU64()];
1069       VarLocs.push_back(VNum);
1070       auto it = ValueToLoc.find(VNum);
1071       // In order of preference, pick:
1072       //  * Callee saved registers,
1073       //  * Other registers,
1074       //  * Spill slots.
1075       if (it == ValueToLoc.end() || MTracker->isSpill(it->second) ||
1076           (!isCalleeSaved(it->second) && isCalleeSaved(Idx.asU64()))) {
1077         // Insert, or overwrite if insertion failed.
1078         auto PrefLocRes = ValueToLoc.insert(std::make_pair(VNum, Idx));
1079         if (!PrefLocRes.second)
1080           PrefLocRes.first->second = Idx;
1081       }
1082     }
1083 
1084     // Now map variables to their picked LocIdxes.
1085     for (auto Var : VLocs) {
1086       if (Var.second.Kind == DbgValue::Const) {
1087         PendingDbgValues.push_back(
1088             emitMOLoc(Var.second.MO, Var.first, Var.second.Properties));
1089         continue;
1090       }
1091 
1092       // If the value has no location, we can't make a variable location.
1093       const ValueIDNum &Num = Var.second.ID;
1094       auto ValuesPreferredLoc = ValueToLoc.find(Num);
1095       if (ValuesPreferredLoc == ValueToLoc.end()) {
1096         // If it's a def that occurs in this block, register it as a
1097         // use-before-def to be resolved as we step through the block.
1098         if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI())
1099           addUseBeforeDef(Var.first, Var.second.Properties, Num);
1100         continue;
1101       }
1102 
1103       LocIdx M = ValuesPreferredLoc->second;
1104       auto NewValue = LocAndProperties{M, Var.second.Properties};
1105       auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue));
1106       if (!Result.second)
1107         Result.first->second = NewValue;
1108       ActiveMLocs[M].insert(Var.first);
1109       PendingDbgValues.push_back(
1110           MTracker->emitLoc(M, Var.first, Var.second.Properties));
1111     }
1112     flushDbgValues(MBB.begin(), &MBB);
1113   }
1114 
1115   /// Record that \p Var has value \p ID, a value that becomes available
1116   /// later in the function.
1117   void addUseBeforeDef(const DebugVariable &Var,
1118                        const DbgValueProperties &Properties, ValueIDNum ID) {
1119     UseBeforeDef UBD = {ID, Var, Properties};
1120     UseBeforeDefs[ID.getInst()].push_back(UBD);
1121     UseBeforeDefVariables.insert(Var);
1122   }
1123 
1124   /// After the instruction at index \p Inst and position \p pos has been
1125   /// processed, check whether it defines a variable value in a use-before-def.
1126   /// If so, and the variable value hasn't changed since the start of the
1127   /// block, create a DBG_VALUE.
1128   void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
1129     auto MIt = UseBeforeDefs.find(Inst);
1130     if (MIt == UseBeforeDefs.end())
1131       return;
1132 
1133     for (auto &Use : MIt->second) {
1134       LocIdx L = Use.ID.getLoc();
1135 
1136       // If something goes very wrong, we might end up labelling a COPY
1137       // instruction or similar with an instruction number, where it doesn't
1138       // actually define a new value, instead it moves a value. In case this
1139       // happens, discard.
1140       if (MTracker->LocIdxToIDNum[L] != Use.ID)
1141         continue;
1142 
1143       // If a different debug instruction defined the variable value / location
1144       // since the start of the block, don't materialize this use-before-def.
1145       if (!UseBeforeDefVariables.count(Use.Var))
1146         continue;
1147 
1148       PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties));
1149     }
1150     flushDbgValues(pos, nullptr);
1151   }
1152 
1153   /// Helper to move created DBG_VALUEs into Transfers collection.
1154   void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
1155     if (PendingDbgValues.size() > 0) {
1156       Transfers.push_back({Pos, MBB, PendingDbgValues});
1157       PendingDbgValues.clear();
1158     }
1159   }
1160 
1161   /// Change a variable value after encountering a DBG_VALUE inside a block.
1162   void redefVar(const MachineInstr &MI) {
1163     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1164                       MI.getDebugLoc()->getInlinedAt());
1165     DbgValueProperties Properties(MI);
1166 
1167     const MachineOperand &MO = MI.getOperand(0);
1168 
1169     // Ignore non-register locations, we don't transfer those.
1170     if (!MO.isReg() || MO.getReg() == 0) {
1171       auto It = ActiveVLocs.find(Var);
1172       if (It != ActiveVLocs.end()) {
1173         ActiveMLocs[It->second.Loc].erase(Var);
1174         ActiveVLocs.erase(It);
1175      }
1176       // Any use-before-defs no longer apply.
1177       UseBeforeDefVariables.erase(Var);
1178       return;
1179     }
1180 
1181     Register Reg = MO.getReg();
1182     LocIdx NewLoc = MTracker->getRegMLoc(Reg);
1183     redefVar(MI, Properties, NewLoc);
1184   }
1185 
1186   /// Handle a change in variable location within a block. Terminate the
1187   /// variables current location, and record the value it now refers to, so
1188   /// that we can detect location transfers later on.
1189   void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
1190                 Optional<LocIdx> OptNewLoc) {
1191     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1192                       MI.getDebugLoc()->getInlinedAt());
1193     // Any use-before-defs no longer apply.
1194     UseBeforeDefVariables.erase(Var);
1195 
1196     // Erase any previous location,
1197     auto It = ActiveVLocs.find(Var);
1198     if (It != ActiveVLocs.end())
1199       ActiveMLocs[It->second.Loc].erase(Var);
1200 
1201     // If there _is_ no new location, all we had to do was erase.
1202     if (!OptNewLoc)
1203       return;
1204     LocIdx NewLoc = *OptNewLoc;
1205 
1206     // Check whether our local copy of values-by-location in #VarLocs is out of
1207     // date. Wipe old tracking data for the location if it's been clobbered in
1208     // the meantime.
1209     if (MTracker->getNumAtPos(NewLoc) != VarLocs[NewLoc.asU64()]) {
1210       for (auto &P : ActiveMLocs[NewLoc]) {
1211         ActiveVLocs.erase(P);
1212       }
1213       ActiveMLocs[NewLoc.asU64()].clear();
1214       VarLocs[NewLoc.asU64()] = MTracker->getNumAtPos(NewLoc);
1215     }
1216 
1217     ActiveMLocs[NewLoc].insert(Var);
1218     if (It == ActiveVLocs.end()) {
1219       ActiveVLocs.insert(
1220           std::make_pair(Var, LocAndProperties{NewLoc, Properties}));
1221     } else {
1222       It->second.Loc = NewLoc;
1223       It->second.Properties = Properties;
1224     }
1225   }
1226 
1227   /// Explicitly terminate variable locations based on \p mloc. Creates undef
1228   /// DBG_VALUEs for any variables that were located there, and clears
1229   /// #ActiveMLoc / #ActiveVLoc tracking information for that location.
1230   void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos) {
1231     assert(MTracker->isSpill(MLoc));
1232     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
1233     if (ActiveMLocIt == ActiveMLocs.end())
1234       return;
1235 
1236     VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
1237 
1238     for (auto &Var : ActiveMLocIt->second) {
1239       auto ActiveVLocIt = ActiveVLocs.find(Var);
1240       // Create an undef. We can't feed in a nullptr DIExpression alas,
1241       // so use the variables last expression. Pass None as the location.
1242       const DIExpression *Expr = ActiveVLocIt->second.Properties.DIExpr;
1243       DbgValueProperties Properties(Expr, false);
1244       PendingDbgValues.push_back(MTracker->emitLoc(None, Var, Properties));
1245       ActiveVLocs.erase(ActiveVLocIt);
1246     }
1247     flushDbgValues(Pos, nullptr);
1248 
1249     ActiveMLocIt->second.clear();
1250   }
1251 
1252   /// Transfer variables based on \p Src to be based on \p Dst. This handles
1253   /// both register copies as well as spills and restores. Creates DBG_VALUEs
1254   /// describing the movement.
1255   void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
1256     // Does Src still contain the value num we expect? If not, it's been
1257     // clobbered in the meantime, and our variable locations are stale.
1258     if (VarLocs[Src.asU64()] != MTracker->getNumAtPos(Src))
1259       return;
1260 
1261     // assert(ActiveMLocs[Dst].size() == 0);
1262     //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
1263     ActiveMLocs[Dst] = ActiveMLocs[Src];
1264     VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
1265 
1266     // For each variable based on Src; create a location at Dst.
1267     for (auto &Var : ActiveMLocs[Src]) {
1268       auto ActiveVLocIt = ActiveVLocs.find(Var);
1269       assert(ActiveVLocIt != ActiveVLocs.end());
1270       ActiveVLocIt->second.Loc = Dst;
1271 
1272       assert(Dst != 0);
1273       MachineInstr *MI =
1274           MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties);
1275       PendingDbgValues.push_back(MI);
1276     }
1277     ActiveMLocs[Src].clear();
1278     flushDbgValues(Pos, nullptr);
1279 
1280     // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
1281     // about the old location.
1282     if (EmulateOldLDV)
1283       VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
1284   }
1285 
1286   MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
1287                                 const DebugVariable &Var,
1288                                 const DbgValueProperties &Properties) {
1289     DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
1290                                   Var.getVariable()->getScope(),
1291                                   const_cast<DILocation *>(Var.getInlinedAt()));
1292     auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
1293     MIB.add(MO);
1294     if (Properties.Indirect)
1295       MIB.addImm(0);
1296     else
1297       MIB.addReg(0);
1298     MIB.addMetadata(Var.getVariable());
1299     MIB.addMetadata(Properties.DIExpr);
1300     return MIB;
1301   }
1302 };
1303 
1304 class InstrRefBasedLDV : public LDVImpl {
1305 private:
1306   using FragmentInfo = DIExpression::FragmentInfo;
1307   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
1308 
1309   // Helper while building OverlapMap, a map of all fragments seen for a given
1310   // DILocalVariable.
1311   using VarToFragments =
1312       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
1313 
1314   /// Machine location/value transfer function, a mapping of which locations
1315   /// are assigned which new values.
1316   using MLocTransferMap = std::map<LocIdx, ValueIDNum>;
1317 
1318   /// Live in/out structure for the variable values: a per-block map of
1319   /// variables to their values. XXX, better name?
1320   using LiveIdxT =
1321       DenseMap<const MachineBasicBlock *, DenseMap<DebugVariable, DbgValue> *>;
1322 
1323   using VarAndLoc = std::pair<DebugVariable, DbgValue>;
1324 
1325   /// Type for a live-in value: the predecessor block, and its value.
1326   using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
1327 
1328   /// Vector (per block) of a collection (inner smallvector) of live-ins.
1329   /// Used as the result type for the variable value dataflow problem.
1330   using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
1331 
1332   const TargetRegisterInfo *TRI;
1333   const TargetInstrInfo *TII;
1334   const TargetFrameLowering *TFI;
1335   BitVector CalleeSavedRegs;
1336   LexicalScopes LS;
1337   TargetPassConfig *TPC;
1338 
1339   /// Object to track machine locations as we step through a block. Could
1340   /// probably be a field rather than a pointer, as it's always used.
1341   MLocTracker *MTracker;
1342 
1343   /// Number of the current block LiveDebugValues is stepping through.
1344   unsigned CurBB;
1345 
1346   /// Number of the current instruction LiveDebugValues is evaluating.
1347   unsigned CurInst;
1348 
1349   /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
1350   /// steps through a block. Reads the values at each location from the
1351   /// MLocTracker object.
1352   VLocTracker *VTracker;
1353 
1354   /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
1355   /// between locations during stepping, creates new DBG_VALUEs when values move
1356   /// location.
1357   TransferTracker *TTracker;
1358 
1359   /// Blocks which are artificial, i.e. blocks which exclusively contain
1360   /// instructions without DebugLocs, or with line 0 locations.
1361   SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1362 
1363   // Mapping of blocks to and from their RPOT order.
1364   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1365   DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1366   DenseMap<unsigned, unsigned> BBNumToRPO;
1367 
1368   /// Pair of MachineInstr, and its 1-based offset into the containing block.
1369   using InstAndNum = std::pair<const MachineInstr *, unsigned>;
1370   /// Map from debug instruction number to the MachineInstr labelled with that
1371   /// number, and its location within the function. Used to transform
1372   /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
1373   std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
1374 
1375   // Map of overlapping variable fragments.
1376   OverlapMap OverlapFragments;
1377   VarToFragments SeenFragments;
1378 
1379   /// Tests whether this instruction is a spill to a stack slot.
1380   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
1381 
1382   /// Decide if @MI is a spill instruction and return true if it is. We use 2
1383   /// criteria to make this decision:
1384   /// - Is this instruction a store to a spill slot?
1385   /// - Is there a register operand that is both used and killed?
1386   /// TODO: Store optimization can fold spills into other stores (including
1387   /// other spills). We do not handle this yet (more than one memory operand).
1388   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
1389                        unsigned &Reg);
1390 
1391   /// If a given instruction is identified as a spill, return the spill slot
1392   /// and set \p Reg to the spilled register.
1393   Optional<SpillLoc> isRestoreInstruction(const MachineInstr &MI,
1394                                           MachineFunction *MF, unsigned &Reg);
1395 
1396   /// Given a spill instruction, extract the register and offset used to
1397   /// address the spill slot in a target independent way.
1398   SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
1399 
1400   /// Observe a single instruction while stepping through a block.
1401   void process(MachineInstr &MI);
1402 
1403   /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
1404   /// \returns true if MI was recognized and processed.
1405   bool transferDebugValue(const MachineInstr &MI);
1406 
1407   /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
1408   /// \returns true if MI was recognized and processed.
1409   bool transferDebugInstrRef(MachineInstr &MI);
1410 
1411   /// Examines whether \p MI is copy instruction, and notifies trackers.
1412   /// \returns true if MI was recognized and processed.
1413   bool transferRegisterCopy(MachineInstr &MI);
1414 
1415   /// Examines whether \p MI is stack spill or restore  instruction, and
1416   /// notifies trackers. \returns true if MI was recognized and processed.
1417   bool transferSpillOrRestoreInst(MachineInstr &MI);
1418 
1419   /// Examines \p MI for any registers that it defines, and notifies trackers.
1420   void transferRegisterDef(MachineInstr &MI);
1421 
1422   /// Copy one location to the other, accounting for movement of subregisters
1423   /// too.
1424   void performCopy(Register Src, Register Dst);
1425 
1426   void accumulateFragmentMap(MachineInstr &MI);
1427 
1428   /// Step through the function, recording register definitions and movements
1429   /// in an MLocTracker. Convert the observations into a per-block transfer
1430   /// function in \p MLocTransfer, suitable for using with the machine value
1431   /// location dataflow problem.
1432   void
1433   produceMLocTransferFunction(MachineFunction &MF,
1434                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1435                               unsigned MaxNumBlocks);
1436 
1437   /// Solve the machine value location dataflow problem. Takes as input the
1438   /// transfer functions in \p MLocTransfer. Writes the output live-in and
1439   /// live-out arrays to the (initialized to zero) multidimensional arrays in
1440   /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
1441   /// number, the inner by LocIdx.
1442   void mlocDataflow(ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
1443                     SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1444 
1445   /// Perform a control flow join (lattice value meet) of the values in machine
1446   /// locations at \p MBB. Follows the algorithm described in the file-comment,
1447   /// reading live-outs of predecessors from \p OutLocs, the current live ins
1448   /// from \p InLocs, and assigning the newly computed live ins back into
1449   /// \p InLocs. \returns two bools -- the first indicates whether a change
1450   /// was made, the second whether a lattice downgrade occurred. If the latter
1451   /// is true, revisiting this block is necessary.
1452   std::tuple<bool, bool>
1453   mlocJoin(MachineBasicBlock &MBB,
1454            SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1455            ValueIDNum **OutLocs, ValueIDNum *InLocs);
1456 
1457   /// Solve the variable value dataflow problem, for a single lexical scope.
1458   /// Uses the algorithm from the file comment to resolve control flow joins,
1459   /// although there are extra hacks, see vlocJoin. Reads the
1460   /// locations of values from the \p MInLocs and \p MOutLocs arrays (see
1461   /// mlocDataflow) and reads the variable values transfer function from
1462   /// \p AllTheVlocs. Live-in and Live-out variable values are stored locally,
1463   /// with the live-ins permanently stored to \p Output once the fixedpoint is
1464   /// reached.
1465   /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
1466   /// that we should be tracking.
1467   /// \p AssignBlocks contains the set of blocks that aren't in \p Scope, but
1468   /// which do contain DBG_VALUEs, which VarLocBasedImpl tracks locations
1469   /// through.
1470   void vlocDataflow(const LexicalScope *Scope, const DILocation *DILoc,
1471                     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
1472                     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
1473                     LiveInsT &Output, ValueIDNum **MOutLocs,
1474                     ValueIDNum **MInLocs,
1475                     SmallVectorImpl<VLocTracker> &AllTheVLocs);
1476 
1477   /// Compute the live-ins to a block, considering control flow merges according
1478   /// to the method in the file comment. Live out and live in variable values
1479   /// are stored in \p VLOCOutLocs and \p VLOCInLocs. The live-ins for \p MBB
1480   /// are computed and stored into \p VLOCInLocs. \returns true if the live-ins
1481   /// are modified.
1482   /// \p InLocsT Output argument, storage for calculated live-ins.
1483   /// \returns two bools -- the first indicates whether a change
1484   /// was made, the second whether a lattice downgrade occurred. If the latter
1485   /// is true, revisiting this block is necessary.
1486   std::tuple<bool, bool>
1487   vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs,
1488            SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited,
1489            unsigned BBNum, const SmallSet<DebugVariable, 4> &AllVars,
1490            ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
1491            SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks,
1492            SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
1493            DenseMap<DebugVariable, DbgValue> &InLocsT);
1494 
1495   /// Continue exploration of the variable-value lattice, as explained in the
1496   /// file-level comment. \p OldLiveInLocation contains the current
1497   /// exploration position, from which we need to descend further. \p Values
1498   /// contains the set of live-in values, \p CurBlockRPONum the RPO number of
1499   /// the current block, and \p CandidateLocations a set of locations that
1500   /// should be considered as PHI locations, if we reach the bottom of the
1501   /// lattice. \returns true if we should downgrade; the value is the agreeing
1502   /// value number in a non-backedge predecessor.
1503   bool vlocDowngradeLattice(const MachineBasicBlock &MBB,
1504                             const DbgValue &OldLiveInLocation,
1505                             const SmallVectorImpl<InValueT> &Values,
1506                             unsigned CurBlockRPONum);
1507 
1508   /// For the given block and live-outs feeding into it, try to find a
1509   /// machine location where they all join. If a solution for all predecessors
1510   /// can't be found, a location where all non-backedge-predecessors join
1511   /// will be returned instead. While this method finds a join location, this
1512   /// says nothing as to whether it should be used.
1513   /// \returns Pair of value ID if found, and true when the correct value
1514   /// is available on all predecessor edges, or false if it's only available
1515   /// for non-backedge predecessors.
1516   std::tuple<Optional<ValueIDNum>, bool>
1517   pickVPHILoc(MachineBasicBlock &MBB, const DebugVariable &Var,
1518               const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
1519               ValueIDNum **MInLocs,
1520               const SmallVectorImpl<MachineBasicBlock *> &BlockOrders);
1521 
1522   /// Given the solutions to the two dataflow problems, machine value locations
1523   /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the
1524   /// TransferTracker class over the function to produce live-in and transfer
1525   /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the
1526   /// order given by AllVarsNumbering -- this could be any stable order, but
1527   /// right now "order of appearence in function, when explored in RPO", so
1528   /// that we can compare explictly against VarLocBasedImpl.
1529   void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns,
1530                      ValueIDNum **MInLocs,
1531                      DenseMap<DebugVariable, unsigned> &AllVarsNumbering);
1532 
1533   /// Boilerplate computation of some initial sets, artifical blocks and
1534   /// RPOT block ordering.
1535   void initialSetup(MachineFunction &MF);
1536 
1537   bool ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) override;
1538 
1539 public:
1540   /// Default construct and initialize the pass.
1541   InstrRefBasedLDV();
1542 
1543   LLVM_DUMP_METHOD
1544   void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1545 
1546   bool isCalleeSaved(LocIdx L) {
1547     unsigned Reg = MTracker->LocIdxToLocID[L];
1548     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1549       if (CalleeSavedRegs.test(*RAI))
1550         return true;
1551     return false;
1552   }
1553 };
1554 
1555 } // end anonymous namespace
1556 
1557 //===----------------------------------------------------------------------===//
1558 //            Implementation
1559 //===----------------------------------------------------------------------===//
1560 
1561 ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
1562 
1563 /// Default construct and initialize the pass.
1564 InstrRefBasedLDV::InstrRefBasedLDV() {}
1565 
1566 //===----------------------------------------------------------------------===//
1567 //            Debug Range Extension Implementation
1568 //===----------------------------------------------------------------------===//
1569 
1570 #ifndef NDEBUG
1571 // Something to restore in the future.
1572 // void InstrRefBasedLDV::printVarLocInMBB(..)
1573 #endif
1574 
1575 SpillLoc
1576 InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1577   assert(MI.hasOneMemOperand() &&
1578          "Spill instruction does not have exactly one memory operand?");
1579   auto MMOI = MI.memoperands_begin();
1580   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1581   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1582          "Inconsistent memory operand in spill instruction");
1583   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1584   const MachineBasicBlock *MBB = MI.getParent();
1585   Register Reg;
1586   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1587   return {Reg, Offset};
1588 }
1589 
1590 /// End all previous ranges related to @MI and start a new range from @MI
1591 /// if it is a DBG_VALUE instr.
1592 bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
1593   if (!MI.isDebugValue())
1594     return false;
1595 
1596   const DILocalVariable *Var = MI.getDebugVariable();
1597   const DIExpression *Expr = MI.getDebugExpression();
1598   const DILocation *DebugLoc = MI.getDebugLoc();
1599   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1600   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1601          "Expected inlined-at fields to agree");
1602 
1603   DebugVariable V(Var, Expr, InlinedAt);
1604   DbgValueProperties Properties(MI);
1605 
1606   // If there are no instructions in this lexical scope, do no location tracking
1607   // at all, this variable shouldn't get a legitimate location range.
1608   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1609   if (Scope == nullptr)
1610     return true; // handled it; by doing nothing
1611 
1612   const MachineOperand &MO = MI.getOperand(0);
1613 
1614   // MLocTracker needs to know that this register is read, even if it's only
1615   // read by a debug inst.
1616   if (MO.isReg() && MO.getReg() != 0)
1617     (void)MTracker->readReg(MO.getReg());
1618 
1619   // If we're preparing for the second analysis (variables), the machine value
1620   // locations are already solved, and we report this DBG_VALUE and the value
1621   // it refers to to VLocTracker.
1622   if (VTracker) {
1623     if (MO.isReg()) {
1624       // Feed defVar the new variable location, or if this is a
1625       // DBG_VALUE $noreg, feed defVar None.
1626       if (MO.getReg())
1627         VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg()));
1628       else
1629         VTracker->defVar(MI, Properties, None);
1630     } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() ||
1631                MI.getOperand(0).isCImm()) {
1632       VTracker->defVar(MI, MI.getOperand(0));
1633     }
1634   }
1635 
1636   // If performing final tracking of transfers, report this variable definition
1637   // to the TransferTracker too.
1638   if (TTracker)
1639     TTracker->redefVar(MI);
1640   return true;
1641 }
1642 
1643 bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI) {
1644   if (!MI.isDebugRef())
1645     return false;
1646 
1647   // Only handle this instruction when we are building the variable value
1648   // transfer function.
1649   if (!VTracker)
1650     return false;
1651 
1652   unsigned InstNo = MI.getOperand(0).getImm();
1653   unsigned OpNo = MI.getOperand(1).getImm();
1654 
1655   const DILocalVariable *Var = MI.getDebugVariable();
1656   const DIExpression *Expr = MI.getDebugExpression();
1657   const DILocation *DebugLoc = MI.getDebugLoc();
1658   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1659   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1660          "Expected inlined-at fields to agree");
1661 
1662   DebugVariable V(Var, Expr, InlinedAt);
1663 
1664   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1665   if (Scope == nullptr)
1666     return true; // Handled by doing nothing. This variable is never in scope.
1667 
1668   const MachineFunction &MF = *MI.getParent()->getParent();
1669 
1670   // Various optimizations may have happened to the value during codegen,
1671   // recorded in the value substitution table. Apply any substitutions to
1672   // the instruction / operand number in this DBG_INSTR_REF.
1673   auto Sub = MF.DebugValueSubstitutions.find(std::make_pair(InstNo, OpNo));
1674   while (Sub != MF.DebugValueSubstitutions.end()) {
1675     InstNo = Sub->second.first;
1676     OpNo = Sub->second.second;
1677     Sub = MF.DebugValueSubstitutions.find(std::make_pair(InstNo, OpNo));
1678   }
1679 
1680   // Default machine value number is <None> -- if no instruction defines
1681   // the corresponding value, it must have been optimized out.
1682   Optional<ValueIDNum> NewID = None;
1683 
1684   // Try to lookup the instruction number, and find the machine value number
1685   // that it defines.
1686   auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1687   if (InstrIt != DebugInstrNumToInstr.end()) {
1688     const MachineInstr &TargetInstr = *InstrIt->second.first;
1689     uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1690 
1691     // Pick out the designated operand.
1692     assert(OpNo < TargetInstr.getNumOperands());
1693     const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1694 
1695     // Today, this can only be a register.
1696     assert(MO.isReg() && MO.isDef());
1697 
1698     unsigned LocID = MTracker->getLocID(MO.getReg(), false);
1699     LocIdx L = MTracker->LocIDToLocIdx[LocID];
1700     NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1701   }
1702 
1703   // We, we have a value number or None. Tell the variable value tracker about
1704   // it. The rest of this LiveDebugValues implementation acts exactly the same
1705   // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that
1706   // aren't immediately available).
1707   DbgValueProperties Properties(Expr, false);
1708   VTracker->defVar(MI, Properties, NewID);
1709 
1710   // If we're on the final pass through the function, decompose this INSTR_REF
1711   // into a plain DBG_VALUE.
1712   if (!TTracker)
1713     return true;
1714 
1715   // Pick a location for the machine value number, if such a location exists.
1716   // (This information could be stored in TransferTracker to make it faster).
1717   Optional<LocIdx> FoundLoc = None;
1718   for (auto Location : MTracker->locations()) {
1719     LocIdx CurL = Location.Idx;
1720     ValueIDNum ID = MTracker->LocIdxToIDNum[CurL];
1721     if (NewID && ID == NewID) {
1722       // If this is the first location with that value, pick it. Otherwise,
1723       // consider whether it's a "longer term" location.
1724       if (!FoundLoc) {
1725         FoundLoc = CurL;
1726         continue;
1727       }
1728 
1729       if (MTracker->isSpill(CurL))
1730         FoundLoc = CurL; // Spills are a longer term location.
1731       else if (!MTracker->isSpill(*FoundLoc) &&
1732                !MTracker->isSpill(CurL) &&
1733                !isCalleeSaved(*FoundLoc) &&
1734                isCalleeSaved(CurL))
1735         FoundLoc = CurL; // Callee saved regs are longer term than normal.
1736     }
1737   }
1738 
1739   // Tell transfer tracker that the variable value has changed.
1740   TTracker->redefVar(MI, Properties, FoundLoc);
1741 
1742   // If there was a value with no location; but the value is defined in a
1743   // later instruction in this block, this is a block-local use-before-def.
1744   if (!FoundLoc && NewID && NewID->getBlock() == CurBB &&
1745       NewID->getInst() > CurInst)
1746     TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID);
1747 
1748   // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1749   // This DBG_VALUE is potentially a $noreg / undefined location, if
1750   // FoundLoc is None.
1751   // (XXX -- could morph the DBG_INSTR_REF in the future).
1752   MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties);
1753   TTracker->PendingDbgValues.push_back(DbgMI);
1754   TTracker->flushDbgValues(MI.getIterator(), nullptr);
1755 
1756   return true;
1757 }
1758 
1759 void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1760   // Meta Instructions do not affect the debug liveness of any register they
1761   // define.
1762   if (MI.isImplicitDef()) {
1763     // Except when there's an implicit def, and the location it's defining has
1764     // no value number. The whole point of an implicit def is to announce that
1765     // the register is live, without be specific about it's value. So define
1766     // a value if there isn't one already.
1767     ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1768     // Has a legitimate value -> ignore the implicit def.
1769     if (Num.getLoc() != 0)
1770       return;
1771     // Otherwise, def it here.
1772   } else if (MI.isMetaInstruction())
1773     return;
1774 
1775   MachineFunction *MF = MI.getMF();
1776   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1777   Register SP = TLI->getStackPointerRegisterToSaveRestore();
1778 
1779   // Find the regs killed by MI, and find regmasks of preserved regs.
1780   // Max out the number of statically allocated elements in `DeadRegs`, as this
1781   // prevents fallback to std::set::count() operations.
1782   SmallSet<uint32_t, 32> DeadRegs;
1783   SmallVector<const uint32_t *, 4> RegMasks;
1784   SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1785   for (const MachineOperand &MO : MI.operands()) {
1786     // Determine whether the operand is a register def.
1787     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1788         Register::isPhysicalRegister(MO.getReg()) &&
1789         !(MI.isCall() && MO.getReg() == SP)) {
1790       // Remove ranges of all aliased registers.
1791       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1792         // FIXME: Can we break out of this loop early if no insertion occurs?
1793         DeadRegs.insert(*RAI);
1794     } else if (MO.isRegMask()) {
1795       RegMasks.push_back(MO.getRegMask());
1796       RegMaskPtrs.push_back(&MO);
1797     }
1798   }
1799 
1800   // Tell MLocTracker about all definitions, of regmasks and otherwise.
1801   for (uint32_t DeadReg : DeadRegs)
1802     MTracker->defReg(DeadReg, CurBB, CurInst);
1803 
1804   for (auto *MO : RegMaskPtrs)
1805     MTracker->writeRegMask(MO, CurBB, CurInst);
1806 }
1807 
1808 void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1809   ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1810 
1811   MTracker->setReg(DstRegNum, SrcValue);
1812 
1813   // In all circumstances, re-def the super registers. It's definitely a new
1814   // value now. This doesn't uniquely identify the composition of subregs, for
1815   // example, two identical values in subregisters composed in different
1816   // places would not get equal value numbers.
1817   for (MCSuperRegIterator SRI(DstRegNum, TRI); SRI.isValid(); ++SRI)
1818     MTracker->defReg(*SRI, CurBB, CurInst);
1819 
1820   // If we're emulating VarLocBasedImpl, just define all the subregisters.
1821   // DBG_VALUEs of them will expect to be tracked from the DBG_VALUE, not
1822   // through prior copies.
1823   if (EmulateOldLDV) {
1824     for (MCSubRegIndexIterator DRI(DstRegNum, TRI); DRI.isValid(); ++DRI)
1825       MTracker->defReg(DRI.getSubReg(), CurBB, CurInst);
1826     return;
1827   }
1828 
1829   // Otherwise, actually copy subregisters from one location to another.
1830   // XXX: in addition, any subregisters of DstRegNum that don't line up with
1831   // the source register should be def'd.
1832   for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1833     unsigned SrcSubReg = SRI.getSubReg();
1834     unsigned SubRegIdx = SRI.getSubRegIndex();
1835     unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1836     if (!DstSubReg)
1837       continue;
1838 
1839     // Do copy. There are two matching subregisters, the source value should
1840     // have been def'd when the super-reg was, the latter might not be tracked
1841     // yet.
1842     // This will force SrcSubReg to be tracked, if it isn't yet.
1843     (void)MTracker->readReg(SrcSubReg);
1844     LocIdx SrcL = MTracker->getRegMLoc(SrcSubReg);
1845     assert(SrcL.asU64());
1846     (void)MTracker->readReg(DstSubReg);
1847     LocIdx DstL = MTracker->getRegMLoc(DstSubReg);
1848     assert(DstL.asU64());
1849     (void)DstL;
1850     ValueIDNum CpyValue = {SrcValue.getBlock(), SrcValue.getInst(), SrcL};
1851 
1852     MTracker->setReg(DstSubReg, CpyValue);
1853   }
1854 }
1855 
1856 bool InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1857                                           MachineFunction *MF) {
1858   // TODO: Handle multiple stores folded into one.
1859   if (!MI.hasOneMemOperand())
1860     return false;
1861 
1862   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1863     return false; // This is not a spill instruction, since no valid size was
1864                   // returned from either function.
1865 
1866   return true;
1867 }
1868 
1869 bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
1870                                        MachineFunction *MF, unsigned &Reg) {
1871   if (!isSpillInstruction(MI, MF))
1872     return false;
1873 
1874   // XXX FIXME: On x86, isStoreToStackSlotPostFE returns '1' instead of an
1875   // actual register number.
1876   if (ObserveAllStackops) {
1877     int FI;
1878     Reg = TII->isStoreToStackSlotPostFE(MI, FI);
1879     return Reg != 0;
1880   }
1881 
1882   auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
1883     if (!MO.isReg() || !MO.isUse()) {
1884       Reg = 0;
1885       return false;
1886     }
1887     Reg = MO.getReg();
1888     return MO.isKill();
1889   };
1890 
1891   for (const MachineOperand &MO : MI.operands()) {
1892     // In a spill instruction generated by the InlineSpiller the spilled
1893     // register has its kill flag set.
1894     if (isKilledReg(MO, Reg))
1895       return true;
1896     if (Reg != 0) {
1897       // Check whether next instruction kills the spilled register.
1898       // FIXME: Current solution does not cover search for killed register in
1899       // bundles and instructions further down the chain.
1900       auto NextI = std::next(MI.getIterator());
1901       // Skip next instruction that points to basic block end iterator.
1902       if (MI.getParent()->end() == NextI)
1903         continue;
1904       unsigned RegNext;
1905       for (const MachineOperand &MONext : NextI->operands()) {
1906         // Return true if we came across the register from the
1907         // previous spill instruction that is killed in NextI.
1908         if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1909           return true;
1910       }
1911     }
1912   }
1913   // Return false if we didn't find spilled register.
1914   return false;
1915 }
1916 
1917 Optional<SpillLoc>
1918 InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1919                                        MachineFunction *MF, unsigned &Reg) {
1920   if (!MI.hasOneMemOperand())
1921     return None;
1922 
1923   // FIXME: Handle folded restore instructions with more than one memory
1924   // operand.
1925   if (MI.getRestoreSize(TII)) {
1926     Reg = MI.getOperand(0).getReg();
1927     return extractSpillBaseRegAndOffset(MI);
1928   }
1929   return None;
1930 }
1931 
1932 bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
1933   // XXX -- it's too difficult to implement VarLocBasedImpl's  stack location
1934   // limitations under the new model. Therefore, when comparing them, compare
1935   // versions that don't attempt spills or restores at all.
1936   if (EmulateOldLDV)
1937     return false;
1938 
1939   MachineFunction *MF = MI.getMF();
1940   unsigned Reg;
1941   Optional<SpillLoc> Loc;
1942 
1943   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1944 
1945   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1946   // written to, terminate that variable location. The value in memory
1947   // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
1948   if (isSpillInstruction(MI, MF)) {
1949     Loc = extractSpillBaseRegAndOffset(MI);
1950 
1951     if (TTracker) {
1952       Optional<LocIdx> MLoc = MTracker->getSpillMLoc(*Loc);
1953       if (MLoc)
1954         TTracker->clobberMloc(*MLoc, MI.getIterator());
1955     }
1956   }
1957 
1958   // Try to recognise spill and restore instructions that may transfer a value.
1959   if (isLocationSpill(MI, MF, Reg)) {
1960     Loc = extractSpillBaseRegAndOffset(MI);
1961     auto ValueID = MTracker->readReg(Reg);
1962 
1963     // If the location is empty, produce a phi, signify it's the live-in value.
1964     if (ValueID.getLoc() == 0)
1965       ValueID = {CurBB, 0, MTracker->getRegMLoc(Reg)};
1966 
1967     MTracker->setSpill(*Loc, ValueID);
1968     auto OptSpillLocIdx = MTracker->getSpillMLoc(*Loc);
1969     assert(OptSpillLocIdx && "Spill slot set but has no LocIdx?");
1970     LocIdx SpillLocIdx = *OptSpillLocIdx;
1971 
1972     // Tell TransferTracker about this spill, produce DBG_VALUEs for it.
1973     if (TTracker)
1974       TTracker->transferMlocs(MTracker->getRegMLoc(Reg), SpillLocIdx,
1975                               MI.getIterator());
1976   } else {
1977     if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1978       return false;
1979 
1980     // Is there a value to be restored?
1981     auto OptValueID = MTracker->readSpill(*Loc);
1982     if (OptValueID) {
1983       ValueIDNum ValueID = *OptValueID;
1984       LocIdx SpillLocIdx = *MTracker->getSpillMLoc(*Loc);
1985       // XXX -- can we recover sub-registers of this value? Until we can, first
1986       // overwrite all defs of the register being restored to.
1987       for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1988         MTracker->defReg(*RAI, CurBB, CurInst);
1989 
1990       // Now override the reg we're restoring to.
1991       MTracker->setReg(Reg, ValueID);
1992 
1993       // Report this restore to the transfer tracker too.
1994       if (TTracker)
1995         TTracker->transferMlocs(SpillLocIdx, MTracker->getRegMLoc(Reg),
1996                                 MI.getIterator());
1997     } else {
1998       // There isn't anything in the location; not clear if this is a code path
1999       // that still runs. Def this register anyway just in case.
2000       for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2001         MTracker->defReg(*RAI, CurBB, CurInst);
2002 
2003       // Force the spill slot to be tracked.
2004       LocIdx L = MTracker->getOrTrackSpillLoc(*Loc);
2005 
2006       // Set the restored value to be a machine phi number, signifying that it's
2007       // whatever the spills live-in value is in this block. Definitely has
2008       // a LocIdx due to the setSpill above.
2009       ValueIDNum ValueID = {CurBB, 0, L};
2010       MTracker->setReg(Reg, ValueID);
2011       MTracker->setSpill(*Loc, ValueID);
2012     }
2013   }
2014   return true;
2015 }
2016 
2017 bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
2018   auto DestSrc = TII->isCopyInstr(MI);
2019   if (!DestSrc)
2020     return false;
2021 
2022   const MachineOperand *DestRegOp = DestSrc->Destination;
2023   const MachineOperand *SrcRegOp = DestSrc->Source;
2024 
2025   auto isCalleeSavedReg = [&](unsigned Reg) {
2026     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2027       if (CalleeSavedRegs.test(*RAI))
2028         return true;
2029     return false;
2030   };
2031 
2032   Register SrcReg = SrcRegOp->getReg();
2033   Register DestReg = DestRegOp->getReg();
2034 
2035   // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
2036   if (SrcReg == DestReg)
2037     return true;
2038 
2039   // For emulating VarLocBasedImpl:
2040   // We want to recognize instructions where destination register is callee
2041   // saved register. If register that could be clobbered by the call is
2042   // included, there would be a great chance that it is going to be clobbered
2043   // soon. It is more likely that previous register, which is callee saved, is
2044   // going to stay unclobbered longer, even if it is killed.
2045   //
2046   // For InstrRefBasedImpl, we can track multiple locations per value, so
2047   // ignore this condition.
2048   if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
2049     return false;
2050 
2051   // InstrRefBasedImpl only followed killing copies.
2052   if (EmulateOldLDV && !SrcRegOp->isKill())
2053     return false;
2054 
2055   // Copy MTracker info, including subregs if available.
2056   InstrRefBasedLDV::performCopy(SrcReg, DestReg);
2057 
2058   // Only produce a transfer of DBG_VALUE within a block where old LDV
2059   // would have. We might make use of the additional value tracking in some
2060   // other way, later.
2061   if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
2062     TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
2063                             MTracker->getRegMLoc(DestReg), MI.getIterator());
2064 
2065   // VarLocBasedImpl would quit tracking the old location after copying.
2066   if (EmulateOldLDV && SrcReg != DestReg)
2067     MTracker->defReg(SrcReg, CurBB, CurInst);
2068 
2069   return true;
2070 }
2071 
2072 /// Accumulate a mapping between each DILocalVariable fragment and other
2073 /// fragments of that DILocalVariable which overlap. This reduces work during
2074 /// the data-flow stage from "Find any overlapping fragments" to "Check if the
2075 /// known-to-overlap fragments are present".
2076 /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
2077 ///           fragment usage.
2078 void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
2079   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
2080                       MI.getDebugLoc()->getInlinedAt());
2081   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
2082 
2083   // If this is the first sighting of this variable, then we are guaranteed
2084   // there are currently no overlapping fragments either. Initialize the set
2085   // of seen fragments, record no overlaps for the current one, and return.
2086   auto SeenIt = SeenFragments.find(MIVar.getVariable());
2087   if (SeenIt == SeenFragments.end()) {
2088     SmallSet<FragmentInfo, 4> OneFragment;
2089     OneFragment.insert(ThisFragment);
2090     SeenFragments.insert({MIVar.getVariable(), OneFragment});
2091 
2092     OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2093     return;
2094   }
2095 
2096   // If this particular Variable/Fragment pair already exists in the overlap
2097   // map, it has already been accounted for.
2098   auto IsInOLapMap =
2099       OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2100   if (!IsInOLapMap.second)
2101     return;
2102 
2103   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
2104   auto &AllSeenFragments = SeenIt->second;
2105 
2106   // Otherwise, examine all other seen fragments for this variable, with "this"
2107   // fragment being a previously unseen fragment. Record any pair of
2108   // overlapping fragments.
2109   for (auto &ASeenFragment : AllSeenFragments) {
2110     // Does this previously seen fragment overlap?
2111     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
2112       // Yes: Mark the current fragment as being overlapped.
2113       ThisFragmentsOverlaps.push_back(ASeenFragment);
2114       // Mark the previously seen fragment as being overlapped by the current
2115       // one.
2116       auto ASeenFragmentsOverlaps =
2117           OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
2118       assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
2119              "Previously seen var fragment has no vector of overlaps");
2120       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
2121     }
2122   }
2123 
2124   AllSeenFragments.insert(ThisFragment);
2125 }
2126 
2127 void InstrRefBasedLDV::process(MachineInstr &MI) {
2128   // Try to interpret an MI as a debug or transfer instruction. Only if it's
2129   // none of these should we interpret it's register defs as new value
2130   // definitions.
2131   if (transferDebugValue(MI))
2132     return;
2133   if (transferDebugInstrRef(MI))
2134     return;
2135   if (transferRegisterCopy(MI))
2136     return;
2137   if (transferSpillOrRestoreInst(MI))
2138     return;
2139   transferRegisterDef(MI);
2140 }
2141 
2142 void InstrRefBasedLDV::produceMLocTransferFunction(
2143     MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
2144     unsigned MaxNumBlocks) {
2145   // Because we try to optimize around register mask operands by ignoring regs
2146   // that aren't currently tracked, we set up something ugly for later: RegMask
2147   // operands that are seen earlier than the first use of a register, still need
2148   // to clobber that register in the transfer function. But this information
2149   // isn't actively recorded. Instead, we track each RegMask used in each block,
2150   // and accumulated the clobbered but untracked registers in each block into
2151   // the following bitvector. Later, if new values are tracked, we can add
2152   // appropriate clobbers.
2153   SmallVector<BitVector, 32> BlockMasks;
2154   BlockMasks.resize(MaxNumBlocks);
2155 
2156   // Reserve one bit per register for the masks described above.
2157   unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
2158   for (auto &BV : BlockMasks)
2159     BV.resize(TRI->getNumRegs(), true);
2160 
2161   // Step through all instructions and inhale the transfer function.
2162   for (auto &MBB : MF) {
2163     // Object fields that are read by trackers to know where we are in the
2164     // function.
2165     CurBB = MBB.getNumber();
2166     CurInst = 1;
2167 
2168     // Set all machine locations to a PHI value. For transfer function
2169     // production only, this signifies the live-in value to the block.
2170     MTracker->reset();
2171     MTracker->setMPhis(CurBB);
2172 
2173     // Step through each instruction in this block.
2174     for (auto &MI : MBB) {
2175       process(MI);
2176       // Also accumulate fragment map.
2177       if (MI.isDebugValue())
2178         accumulateFragmentMap(MI);
2179 
2180       // Create a map from the instruction number (if present) to the
2181       // MachineInstr and its position.
2182       if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
2183         auto InstrAndPos = std::make_pair(&MI, CurInst);
2184         auto InsertResult =
2185             DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
2186 
2187         // There should never be duplicate instruction numbers.
2188         assert(InsertResult.second);
2189         (void)InsertResult;
2190       }
2191 
2192       ++CurInst;
2193     }
2194 
2195     // Produce the transfer function, a map of machine location to new value. If
2196     // any machine location has the live-in phi value from the start of the
2197     // block, it's live-through and doesn't need recording in the transfer
2198     // function.
2199     for (auto Location : MTracker->locations()) {
2200       LocIdx Idx = Location.Idx;
2201       ValueIDNum &P = Location.Value;
2202       if (P.isPHI() && P.getLoc() == Idx.asU64())
2203         continue;
2204 
2205       // Insert-or-update.
2206       auto &TransferMap = MLocTransfer[CurBB];
2207       auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
2208       if (!Result.second)
2209         Result.first->second = P;
2210     }
2211 
2212     // Accumulate any bitmask operands into the clobberred reg mask for this
2213     // block.
2214     for (auto &P : MTracker->Masks) {
2215       BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
2216     }
2217   }
2218 
2219   // Compute a bitvector of all the registers that are tracked in this block.
2220   const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
2221   Register SP = TLI->getStackPointerRegisterToSaveRestore();
2222   BitVector UsedRegs(TRI->getNumRegs());
2223   for (auto Location : MTracker->locations()) {
2224     unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
2225     if (ID >= TRI->getNumRegs() || ID == SP)
2226       continue;
2227     UsedRegs.set(ID);
2228   }
2229 
2230   // Check that any regmask-clobber of a register that gets tracked, is not
2231   // live-through in the transfer function. It needs to be clobbered at the
2232   // very least.
2233   for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
2234     BitVector &BV = BlockMasks[I];
2235     BV.flip();
2236     BV &= UsedRegs;
2237     // This produces all the bits that we clobber, but also use. Check that
2238     // they're all clobbered or at least set in the designated transfer
2239     // elem.
2240     for (unsigned Bit : BV.set_bits()) {
2241       unsigned ID = MTracker->getLocID(Bit, false);
2242       LocIdx Idx = MTracker->LocIDToLocIdx[ID];
2243       auto &TransferMap = MLocTransfer[I];
2244 
2245       // Install a value representing the fact that this location is effectively
2246       // written to in this block. As there's no reserved value, instead use
2247       // a value number that is never generated. Pick the value number for the
2248       // first instruction in the block, def'ing this location, which we know
2249       // this block never used anyway.
2250       ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
2251       auto Result =
2252         TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
2253       if (!Result.second) {
2254         ValueIDNum &ValueID = Result.first->second;
2255         if (ValueID.getBlock() == I && ValueID.isPHI())
2256           // It was left as live-through. Set it to clobbered.
2257           ValueID = NotGeneratedNum;
2258       }
2259     }
2260   }
2261 }
2262 
2263 std::tuple<bool, bool>
2264 InstrRefBasedLDV::mlocJoin(MachineBasicBlock &MBB,
2265                            SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
2266                            ValueIDNum **OutLocs, ValueIDNum *InLocs) {
2267   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2268   bool Changed = false;
2269   bool DowngradeOccurred = false;
2270 
2271   // Collect predecessors that have been visited. Anything that hasn't been
2272   // visited yet is a backedge on the first iteration, and the meet of it's
2273   // lattice value for all locations will be unaffected.
2274   SmallVector<const MachineBasicBlock *, 8> BlockOrders;
2275   for (auto Pred : MBB.predecessors()) {
2276     if (Visited.count(Pred)) {
2277       BlockOrders.push_back(Pred);
2278     }
2279   }
2280 
2281   // Visit predecessors in RPOT order.
2282   auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
2283     return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
2284   };
2285   llvm::sort(BlockOrders, Cmp);
2286 
2287   // Skip entry block.
2288   if (BlockOrders.size() == 0)
2289     return std::tuple<bool, bool>(false, false);
2290 
2291   // Step through all machine locations, then look at each predecessor and
2292   // detect disagreements.
2293   unsigned ThisBlockRPO = BBToOrder.find(&MBB)->second;
2294   for (auto Location : MTracker->locations()) {
2295     LocIdx Idx = Location.Idx;
2296     // Pick out the first predecessors live-out value for this location. It's
2297     // guaranteed to be not a backedge, as we order by RPO.
2298     ValueIDNum BaseVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()];
2299 
2300     // Some flags for whether there's a disagreement, and whether it's a
2301     // disagreement with a backedge or not.
2302     bool Disagree = false;
2303     bool NonBackEdgeDisagree = false;
2304 
2305     // Loop around everything that wasn't 'base'.
2306     for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
2307       auto *MBB = BlockOrders[I];
2308       if (BaseVal != OutLocs[MBB->getNumber()][Idx.asU64()]) {
2309         // Live-out of a predecessor disagrees with the first predecessor.
2310         Disagree = true;
2311 
2312         // Test whether it's a disagreemnt in the backedges or not.
2313         if (BBToOrder.find(MBB)->second < ThisBlockRPO) // might be self b/e
2314           NonBackEdgeDisagree = true;
2315       }
2316     }
2317 
2318     bool OverRide = false;
2319     if (Disagree && !NonBackEdgeDisagree) {
2320       // Only the backedges disagree. Consider demoting the livein
2321       // lattice value, as per the file level comment. The value we consider
2322       // demoting to is the value that the non-backedge predecessors agree on.
2323       // The order of values is that non-PHIs are \top, a PHI at this block
2324       // \bot, and phis between the two are ordered by their RPO number.
2325       // If there's no agreement, or we've already demoted to this PHI value
2326       // before, replace with a PHI value at this block.
2327 
2328       // Calculate order numbers: zero means normal def, nonzero means RPO
2329       // number.
2330       unsigned BaseBlockRPONum = BBNumToRPO[BaseVal.getBlock()] + 1;
2331       if (!BaseVal.isPHI())
2332         BaseBlockRPONum = 0;
2333 
2334       ValueIDNum &InLocID = InLocs[Idx.asU64()];
2335       unsigned InLocRPONum = BBNumToRPO[InLocID.getBlock()] + 1;
2336       if (!InLocID.isPHI())
2337         InLocRPONum = 0;
2338 
2339       // Should we ignore the disagreeing backedges, and override with the
2340       // value the other predecessors agree on (in "base")?
2341       unsigned ThisBlockRPONum = BBNumToRPO[MBB.getNumber()] + 1;
2342       if (BaseBlockRPONum > InLocRPONum && BaseBlockRPONum < ThisBlockRPONum) {
2343         // Override.
2344         OverRide = true;
2345         DowngradeOccurred = true;
2346       }
2347     }
2348     // else: if we disagree in the non-backedges, then this is definitely
2349     // a control flow merge where different values merge. Make it a PHI.
2350 
2351     // Generate a phi...
2352     ValueIDNum PHI = {(uint64_t)MBB.getNumber(), 0, Idx};
2353     ValueIDNum NewVal = (Disagree && !OverRide) ? PHI : BaseVal;
2354     if (InLocs[Idx.asU64()] != NewVal) {
2355       Changed |= true;
2356       InLocs[Idx.asU64()] = NewVal;
2357     }
2358   }
2359 
2360   // TODO: Reimplement NumInserted and NumRemoved.
2361   return std::tuple<bool, bool>(Changed, DowngradeOccurred);
2362 }
2363 
2364 void InstrRefBasedLDV::mlocDataflow(
2365     ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
2366     SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2367   std::priority_queue<unsigned int, std::vector<unsigned int>,
2368                       std::greater<unsigned int>>
2369       Worklist, Pending;
2370 
2371   // We track what is on the current and pending worklist to avoid inserting
2372   // the same thing twice. We could avoid this with a custom priority queue,
2373   // but this is probably not worth it.
2374   SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2375 
2376   // Initialize worklist with every block to be visited.
2377   for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2378     Worklist.push(I);
2379     OnWorklist.insert(OrderToBB[I]);
2380   }
2381 
2382   MTracker->reset();
2383 
2384   // Set inlocs for entry block -- each as a PHI at the entry block. Represents
2385   // the incoming value to the function.
2386   MTracker->setMPhis(0);
2387   for (auto Location : MTracker->locations())
2388     MInLocs[0][Location.Idx.asU64()] = Location.Value;
2389 
2390   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2391   while (!Worklist.empty() || !Pending.empty()) {
2392     // Vector for storing the evaluated block transfer function.
2393     SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2394 
2395     while (!Worklist.empty()) {
2396       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2397       CurBB = MBB->getNumber();
2398       Worklist.pop();
2399 
2400       // Join the values in all predecessor blocks.
2401       bool InLocsChanged, DowngradeOccurred;
2402       std::tie(InLocsChanged, DowngradeOccurred) =
2403           mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
2404       InLocsChanged |= Visited.insert(MBB).second;
2405 
2406       // If a downgrade occurred, book us in for re-examination on the next
2407       // iteration.
2408       if (DowngradeOccurred && OnPending.insert(MBB).second)
2409         Pending.push(BBToOrder[MBB]);
2410 
2411       // Don't examine transfer function if we've visited this loc at least
2412       // once, and inlocs haven't changed.
2413       if (!InLocsChanged)
2414         continue;
2415 
2416       // Load the current set of live-ins into MLocTracker.
2417       MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2418 
2419       // Each element of the transfer function can be a new def, or a read of
2420       // a live-in value. Evaluate each element, and store to "ToRemap".
2421       ToRemap.clear();
2422       for (auto &P : MLocTransfer[CurBB]) {
2423         if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2424           // This is a movement of whatever was live in. Read it.
2425           ValueIDNum NewID = MTracker->getNumAtPos(P.second.getLoc());
2426           ToRemap.push_back(std::make_pair(P.first, NewID));
2427         } else {
2428           // It's a def. Just set it.
2429           assert(P.second.getBlock() == CurBB);
2430           ToRemap.push_back(std::make_pair(P.first, P.second));
2431         }
2432       }
2433 
2434       // Commit the transfer function changes into mloc tracker, which
2435       // transforms the contents of the MLocTracker into the live-outs.
2436       for (auto &P : ToRemap)
2437         MTracker->setMLoc(P.first, P.second);
2438 
2439       // Now copy out-locs from mloc tracker into out-loc vector, checking
2440       // whether changes have occurred. These changes can have come from both
2441       // the transfer function, and mlocJoin.
2442       bool OLChanged = false;
2443       for (auto Location : MTracker->locations()) {
2444         OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
2445         MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
2446       }
2447 
2448       MTracker->reset();
2449 
2450       // No need to examine successors again if out-locs didn't change.
2451       if (!OLChanged)
2452         continue;
2453 
2454       // All successors should be visited: put any back-edges on the pending
2455       // list for the next dataflow iteration, and any other successors to be
2456       // visited this iteration, if they're not going to be already.
2457       for (auto s : MBB->successors()) {
2458         // Does branching to this successor represent a back-edge?
2459         if (BBToOrder[s] > BBToOrder[MBB]) {
2460           // No: visit it during this dataflow iteration.
2461           if (OnWorklist.insert(s).second)
2462             Worklist.push(BBToOrder[s]);
2463         } else {
2464           // Yes: visit it on the next iteration.
2465           if (OnPending.insert(s).second)
2466             Pending.push(BBToOrder[s]);
2467         }
2468       }
2469     }
2470 
2471     Worklist.swap(Pending);
2472     std::swap(OnPending, OnWorklist);
2473     OnPending.clear();
2474     // At this point, pending must be empty, since it was just the empty
2475     // worklist
2476     assert(Pending.empty() && "Pending should be empty");
2477   }
2478 
2479   // Once all the live-ins don't change on mlocJoin(), we've reached a
2480   // fixedpoint.
2481 }
2482 
2483 bool InstrRefBasedLDV::vlocDowngradeLattice(
2484     const MachineBasicBlock &MBB, const DbgValue &OldLiveInLocation,
2485     const SmallVectorImpl<InValueT> &Values, unsigned CurBlockRPONum) {
2486   // Ranking value preference: see file level comment, the highest rank is
2487   // a plain def, followed by PHI values in reverse post-order. Numerically,
2488   // we assign all defs the rank '0', all PHIs their blocks RPO number plus
2489   // one, and consider the lowest value the highest ranked.
2490   int OldLiveInRank = BBNumToRPO[OldLiveInLocation.ID.getBlock()] + 1;
2491   if (!OldLiveInLocation.ID.isPHI())
2492     OldLiveInRank = 0;
2493 
2494   // Allow any unresolvable conflict to be over-ridden.
2495   if (OldLiveInLocation.Kind == DbgValue::NoVal) {
2496     // Although if it was an unresolvable conflict from _this_ block, then
2497     // all other seeking of downgrades and PHIs must have failed before hand.
2498     if (OldLiveInLocation.BlockNo == (unsigned)MBB.getNumber())
2499       return false;
2500     OldLiveInRank = INT_MIN;
2501   }
2502 
2503   auto &InValue = *Values[0].second;
2504 
2505   if (InValue.Kind == DbgValue::Const || InValue.Kind == DbgValue::NoVal)
2506     return false;
2507 
2508   unsigned ThisRPO = BBNumToRPO[InValue.ID.getBlock()];
2509   int ThisRank = ThisRPO + 1;
2510   if (!InValue.ID.isPHI())
2511     ThisRank = 0;
2512 
2513   // Too far down the lattice?
2514   if (ThisRPO >= CurBlockRPONum)
2515     return false;
2516 
2517   // Higher in the lattice than what we've already explored?
2518   if (ThisRank <= OldLiveInRank)
2519     return false;
2520 
2521   return true;
2522 }
2523 
2524 std::tuple<Optional<ValueIDNum>, bool> InstrRefBasedLDV::pickVPHILoc(
2525     MachineBasicBlock &MBB, const DebugVariable &Var, const LiveIdxT &LiveOuts,
2526     ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
2527     const SmallVectorImpl<MachineBasicBlock *> &BlockOrders) {
2528   // Collect a set of locations from predecessor where its live-out value can
2529   // be found.
2530   SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2531   unsigned NumLocs = MTracker->getNumLocs();
2532   unsigned BackEdgesStart = 0;
2533 
2534   for (auto p : BlockOrders) {
2535     // Pick out where backedges start in the list of predecessors. Relies on
2536     // BlockOrders being sorted by RPO.
2537     if (BBToOrder[p] < BBToOrder[&MBB])
2538       ++BackEdgesStart;
2539 
2540     // For each predecessor, create a new set of locations.
2541     Locs.resize(Locs.size() + 1);
2542     unsigned ThisBBNum = p->getNumber();
2543     auto LiveOutMap = LiveOuts.find(p);
2544     if (LiveOutMap == LiveOuts.end())
2545       // This predecessor isn't in scope, it must have no live-in/live-out
2546       // locations.
2547       continue;
2548 
2549     auto It = LiveOutMap->second->find(Var);
2550     if (It == LiveOutMap->second->end())
2551       // There's no value recorded for this variable in this predecessor,
2552       // leave an empty set of locations.
2553       continue;
2554 
2555     const DbgValue &OutVal = It->second;
2556 
2557     if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal)
2558       // Consts and no-values cannot have locations we can join on.
2559       continue;
2560 
2561     assert(OutVal.Kind == DbgValue::Proposed || OutVal.Kind == DbgValue::Def);
2562     ValueIDNum ValToLookFor = OutVal.ID;
2563 
2564     // Search the live-outs of the predecessor for the specified value.
2565     for (unsigned int I = 0; I < NumLocs; ++I) {
2566       if (MOutLocs[ThisBBNum][I] == ValToLookFor)
2567         Locs.back().push_back(LocIdx(I));
2568     }
2569   }
2570 
2571   // If there were no locations at all, return an empty result.
2572   if (Locs.empty())
2573     return std::tuple<Optional<ValueIDNum>, bool>(None, false);
2574 
2575   // Lambda for seeking a common location within a range of location-sets.
2576   using LocsIt = SmallVector<SmallVector<LocIdx, 4>, 8>::iterator;
2577   auto SeekLocation =
2578       [&Locs](llvm::iterator_range<LocsIt> SearchRange) -> Optional<LocIdx> {
2579     // Starting with the first set of locations, take the intersection with
2580     // subsequent sets.
2581     SmallVector<LocIdx, 4> base = Locs[0];
2582     for (auto &S : SearchRange) {
2583       SmallVector<LocIdx, 4> new_base;
2584       std::set_intersection(base.begin(), base.end(), S.begin(), S.end(),
2585                             std::inserter(new_base, new_base.begin()));
2586       base = new_base;
2587     }
2588     if (base.empty())
2589       return None;
2590 
2591     // We now have a set of LocIdxes that contain the right output value in
2592     // each of the predecessors. Pick the lowest; if there's a register loc,
2593     // that'll be it.
2594     return *base.begin();
2595   };
2596 
2597   // Search for a common location for all predecessors. If we can't, then fall
2598   // back to only finding a common location between non-backedge predecessors.
2599   bool ValidForAllLocs = true;
2600   auto TheLoc = SeekLocation(Locs);
2601   if (!TheLoc) {
2602     ValidForAllLocs = false;
2603     TheLoc =
2604         SeekLocation(make_range(Locs.begin(), Locs.begin() + BackEdgesStart));
2605   }
2606 
2607   if (!TheLoc)
2608     return std::tuple<Optional<ValueIDNum>, bool>(None, false);
2609 
2610   // Return a PHI-value-number for the found location.
2611   LocIdx L = *TheLoc;
2612   ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2613   return std::tuple<Optional<ValueIDNum>, bool>(PHIVal, ValidForAllLocs);
2614 }
2615 
2616 std::tuple<bool, bool> InstrRefBasedLDV::vlocJoin(
2617     MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs,
2618     SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited, unsigned BBNum,
2619     const SmallSet<DebugVariable, 4> &AllVars, ValueIDNum **MOutLocs,
2620     ValueIDNum **MInLocs,
2621     SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks,
2622     SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2623     DenseMap<DebugVariable, DbgValue> &InLocsT) {
2624   bool DowngradeOccurred = false;
2625 
2626   // To emulate VarLocBasedImpl, process this block if it's not in scope but
2627   // _does_ assign a variable value. No live-ins for this scope are transferred
2628   // in though, so we can return immediately.
2629   if (InScopeBlocks.count(&MBB) == 0 && !ArtificialBlocks.count(&MBB)) {
2630     if (VLOCVisited)
2631       return std::tuple<bool, bool>(true, false);
2632     return std::tuple<bool, bool>(false, false);
2633   }
2634 
2635   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2636   bool Changed = false;
2637 
2638   // Find any live-ins computed in a prior iteration.
2639   auto ILSIt = VLOCInLocs.find(&MBB);
2640   assert(ILSIt != VLOCInLocs.end());
2641   auto &ILS = *ILSIt->second;
2642 
2643   // Order predecessors by RPOT order, for exploring them in that order.
2644   SmallVector<MachineBasicBlock *, 8> BlockOrders;
2645   for (auto p : MBB.predecessors())
2646     BlockOrders.push_back(p);
2647 
2648   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2649     return BBToOrder[A] < BBToOrder[B];
2650   };
2651 
2652   llvm::sort(BlockOrders, Cmp);
2653 
2654   unsigned CurBlockRPONum = BBToOrder[&MBB];
2655 
2656   // Force a re-visit to loop heads in the first dataflow iteration.
2657   // FIXME: if we could "propose" Const values this wouldn't be needed,
2658   // because they'd need to be confirmed before being emitted.
2659   if (!BlockOrders.empty() &&
2660       BBToOrder[BlockOrders[BlockOrders.size() - 1]] >= CurBlockRPONum &&
2661       VLOCVisited)
2662     DowngradeOccurred = true;
2663 
2664   auto ConfirmValue = [&InLocsT](const DebugVariable &DV, DbgValue VR) {
2665     auto Result = InLocsT.insert(std::make_pair(DV, VR));
2666     (void)Result;
2667     assert(Result.second);
2668   };
2669 
2670   auto ConfirmNoVal = [&ConfirmValue, &MBB](const DebugVariable &Var, const DbgValueProperties &Properties) {
2671     DbgValue NoLocPHIVal(MBB.getNumber(), Properties, DbgValue::NoVal);
2672 
2673     ConfirmValue(Var, NoLocPHIVal);
2674   };
2675 
2676   // Attempt to join the values for each variable.
2677   for (auto &Var : AllVars) {
2678     // Collect all the DbgValues for this variable.
2679     SmallVector<InValueT, 8> Values;
2680     bool Bail = false;
2681     unsigned BackEdgesStart = 0;
2682     for (auto p : BlockOrders) {
2683       // If the predecessor isn't in scope / to be explored, we'll never be
2684       // able to join any locations.
2685       if (!BlocksToExplore.contains(p)) {
2686         Bail = true;
2687         break;
2688       }
2689 
2690       // Don't attempt to handle unvisited predecessors: they're implicitly
2691       // "unknown"s in the lattice.
2692       if (VLOCVisited && !VLOCVisited->count(p))
2693         continue;
2694 
2695       // If the predecessors OutLocs is absent, there's not much we can do.
2696       auto OL = VLOCOutLocs.find(p);
2697       if (OL == VLOCOutLocs.end()) {
2698         Bail = true;
2699         break;
2700       }
2701 
2702       // No live-out value for this predecessor also means we can't produce
2703       // a joined value.
2704       auto VIt = OL->second->find(Var);
2705       if (VIt == OL->second->end()) {
2706         Bail = true;
2707         break;
2708       }
2709 
2710       // Keep track of where back-edges begin in the Values vector. Relies on
2711       // BlockOrders being sorted by RPO.
2712       unsigned ThisBBRPONum = BBToOrder[p];
2713       if (ThisBBRPONum < CurBlockRPONum)
2714         ++BackEdgesStart;
2715 
2716       Values.push_back(std::make_pair(p, &VIt->second));
2717     }
2718 
2719     // If there were no values, or one of the predecessors couldn't have a
2720     // value, then give up immediately. It's not safe to produce a live-in
2721     // value.
2722     if (Bail || Values.size() == 0)
2723       continue;
2724 
2725     // Enumeration identifying the current state of the predecessors values.
2726     enum {
2727       Unset = 0,
2728       Agreed,       // All preds agree on the variable value.
2729       PropDisagree, // All preds agree, but the value kind is Proposed in some.
2730       BEDisagree,   // Only back-edges disagree on variable value.
2731       PHINeeded,    // Non-back-edge predecessors have conflicing values.
2732       NoSolution    // Conflicting Value metadata makes solution impossible.
2733     } OurState = Unset;
2734 
2735     // All (non-entry) blocks have at least one non-backedge predecessor.
2736     // Pick the variable value from the first of these, to compare against
2737     // all others.
2738     const DbgValue &FirstVal = *Values[0].second;
2739     const ValueIDNum &FirstID = FirstVal.ID;
2740 
2741     // Scan for variable values that can't be resolved: if they have different
2742     // DIExpressions, different indirectness, or are mixed constants /
2743     // non-constants.
2744     for (auto &V : Values) {
2745       if (V.second->Properties != FirstVal.Properties)
2746         OurState = NoSolution;
2747       if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const)
2748         OurState = NoSolution;
2749     }
2750 
2751     // Flags diagnosing _how_ the values disagree.
2752     bool NonBackEdgeDisagree = false;
2753     bool DisagreeOnPHINess = false;
2754     bool IDDisagree = false;
2755     bool Disagree = false;
2756     if (OurState == Unset) {
2757       for (auto &V : Values) {
2758         if (*V.second == FirstVal)
2759           continue; // No disagreement.
2760 
2761         Disagree = true;
2762 
2763         // Flag whether the value number actually diagrees.
2764         if (V.second->ID != FirstID)
2765           IDDisagree = true;
2766 
2767         // Distinguish whether disagreement happens in backedges or not.
2768         // Relies on Values (and BlockOrders) being sorted by RPO.
2769         unsigned ThisBBRPONum = BBToOrder[V.first];
2770         if (ThisBBRPONum < CurBlockRPONum)
2771           NonBackEdgeDisagree = true;
2772 
2773         // Is there a difference in whether the value is definite or only
2774         // proposed?
2775         if (V.second->Kind != FirstVal.Kind &&
2776             (V.second->Kind == DbgValue::Proposed ||
2777              V.second->Kind == DbgValue::Def) &&
2778             (FirstVal.Kind == DbgValue::Proposed ||
2779              FirstVal.Kind == DbgValue::Def))
2780           DisagreeOnPHINess = true;
2781       }
2782 
2783       // Collect those flags together and determine an overall state for
2784       // what extend the predecessors agree on a live-in value.
2785       if (!Disagree)
2786         OurState = Agreed;
2787       else if (!IDDisagree && DisagreeOnPHINess)
2788         OurState = PropDisagree;
2789       else if (!NonBackEdgeDisagree)
2790         OurState = BEDisagree;
2791       else
2792         OurState = PHINeeded;
2793     }
2794 
2795     // An extra indicator: if we only disagree on whether the value is a
2796     // Def, or proposed, then also flag whether that disagreement happens
2797     // in backedges only.
2798     bool PropOnlyInBEs = Disagree && !IDDisagree && DisagreeOnPHINess &&
2799                          !NonBackEdgeDisagree && FirstVal.Kind == DbgValue::Def;
2800 
2801     const auto &Properties = FirstVal.Properties;
2802 
2803     auto OldLiveInIt = ILS.find(Var);
2804     const DbgValue *OldLiveInLocation =
2805         (OldLiveInIt != ILS.end()) ? &OldLiveInIt->second : nullptr;
2806 
2807     bool OverRide = false;
2808     if (OurState == BEDisagree && OldLiveInLocation) {
2809       // Only backedges disagree: we can consider downgrading. If there was a
2810       // previous live-in value, use it to work out whether the current
2811       // incoming value represents a lattice downgrade or not.
2812       OverRide =
2813           vlocDowngradeLattice(MBB, *OldLiveInLocation, Values, CurBlockRPONum);
2814     }
2815 
2816     // Use the current state of predecessor agreement and other flags to work
2817     // out what to do next. Possibilities include:
2818     //  * Accept a value all predecessors agree on, or accept one that
2819     //    represents a step down the exploration lattice,
2820     //  * Use a PHI value number, if one can be found,
2821     //  * Propose a PHI value number, and see if it gets confirmed later,
2822     //  * Emit a 'NoVal' value, indicating we couldn't resolve anything.
2823     if (OurState == Agreed) {
2824       // Easiest solution: all predecessors agree on the variable value.
2825       ConfirmValue(Var, FirstVal);
2826     } else if (OurState == BEDisagree && OverRide) {
2827       // Only backedges disagree, and the other predecessors have produced
2828       // a new live-in value further down the exploration lattice.
2829       DowngradeOccurred = true;
2830       ConfirmValue(Var, FirstVal);
2831     } else if (OurState == PropDisagree) {
2832       // Predecessors agree on value, but some say it's only a proposed value.
2833       // Propagate it as proposed: unless it was proposed in this block, in
2834       // which case we're able to confirm the value.
2835       if (FirstID.getBlock() == (uint64_t)MBB.getNumber() && FirstID.isPHI()) {
2836         ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Def));
2837       } else if (PropOnlyInBEs) {
2838         // If only backedges disagree, a higher (in RPO) block confirmed this
2839         // location, and we need to propagate it into this loop.
2840         ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Def));
2841       } else {
2842         // Otherwise; a Def meeting a Proposed is still a Proposed.
2843         ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Proposed));
2844       }
2845     } else if ((OurState == PHINeeded || OurState == BEDisagree)) {
2846       // Predecessors disagree and can't be downgraded: this can only be
2847       // solved with a PHI. Use pickVPHILoc to go look for one.
2848       Optional<ValueIDNum> VPHI;
2849       bool AllEdgesVPHI = false;
2850       std::tie(VPHI, AllEdgesVPHI) =
2851           pickVPHILoc(MBB, Var, VLOCOutLocs, MOutLocs, MInLocs, BlockOrders);
2852 
2853       if (VPHI && AllEdgesVPHI) {
2854         // There's a PHI value that's valid for all predecessors -- we can use
2855         // it. If any of the non-backedge predecessors have proposed values
2856         // though, this PHI is also only proposed, until the predecessors are
2857         // confirmed.
2858         DbgValue::KindT K = DbgValue::Def;
2859         for (unsigned int I = 0; I < BackEdgesStart; ++I)
2860           if (Values[I].second->Kind == DbgValue::Proposed)
2861             K = DbgValue::Proposed;
2862 
2863         ConfirmValue(Var, DbgValue(*VPHI, Properties, K));
2864       } else if (VPHI) {
2865         // There's a PHI value, but it's only legal for backedges. Leave this
2866         // as a proposed PHI value: it might come back on the backedges,
2867         // and allow us to confirm it in the future.
2868         DbgValue NoBEValue = DbgValue(*VPHI, Properties, DbgValue::Proposed);
2869         ConfirmValue(Var, NoBEValue);
2870       } else {
2871         ConfirmNoVal(Var, Properties);
2872       }
2873     } else {
2874       // Otherwise: we don't know. Emit a "phi but no real loc" phi.
2875       ConfirmNoVal(Var, Properties);
2876     }
2877   }
2878 
2879   // Store newly calculated in-locs into VLOCInLocs, if they've changed.
2880   Changed = ILS != InLocsT;
2881   if (Changed)
2882     ILS = InLocsT;
2883 
2884   return std::tuple<bool, bool>(Changed, DowngradeOccurred);
2885 }
2886 
2887 void InstrRefBasedLDV::vlocDataflow(
2888     const LexicalScope *Scope, const DILocation *DILoc,
2889     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
2890     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
2891     ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
2892     SmallVectorImpl<VLocTracker> &AllTheVLocs) {
2893   // This method is much like mlocDataflow: but focuses on a single
2894   // LexicalScope at a time. Pick out a set of blocks and variables that are
2895   // to have their value assignments solved, then run our dataflow algorithm
2896   // until a fixedpoint is reached.
2897   std::priority_queue<unsigned int, std::vector<unsigned int>,
2898                       std::greater<unsigned int>>
2899       Worklist, Pending;
2900   SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
2901 
2902   // The set of blocks we'll be examining.
2903   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2904 
2905   // The order in which to examine them (RPO).
2906   SmallVector<MachineBasicBlock *, 8> BlockOrders;
2907 
2908   // RPO ordering function.
2909   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2910     return BBToOrder[A] < BBToOrder[B];
2911   };
2912 
2913   LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
2914 
2915   // A separate container to distinguish "blocks we're exploring" versus
2916   // "blocks that are potentially in scope. See comment at start of vlocJoin.
2917   SmallPtrSet<const MachineBasicBlock *, 8> InScopeBlocks = BlocksToExplore;
2918 
2919   // Old LiveDebugValues tracks variable locations that come out of blocks
2920   // not in scope, where DBG_VALUEs occur. This is something we could
2921   // legitimately ignore, but lets allow it for now.
2922   if (EmulateOldLDV)
2923     BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
2924 
2925   // We also need to propagate variable values through any artificial blocks
2926   // that immediately follow blocks in scope.
2927   DenseSet<const MachineBasicBlock *> ToAdd;
2928 
2929   // Helper lambda: For a given block in scope, perform a depth first search
2930   // of all the artificial successors, adding them to the ToAdd collection.
2931   auto AccumulateArtificialBlocks =
2932       [this, &ToAdd, &BlocksToExplore,
2933        &InScopeBlocks](const MachineBasicBlock *MBB) {
2934         // Depth-first-search state: each node is a block and which successor
2935         // we're currently exploring.
2936         SmallVector<std::pair<const MachineBasicBlock *,
2937                               MachineBasicBlock::const_succ_iterator>,
2938                     8>
2939             DFS;
2940 
2941         // Find any artificial successors not already tracked.
2942         for (auto *succ : MBB->successors()) {
2943           if (BlocksToExplore.count(succ) || InScopeBlocks.count(succ))
2944             continue;
2945           if (!ArtificialBlocks.count(succ))
2946             continue;
2947           DFS.push_back(std::make_pair(succ, succ->succ_begin()));
2948           ToAdd.insert(succ);
2949         }
2950 
2951         // Search all those blocks, depth first.
2952         while (!DFS.empty()) {
2953           const MachineBasicBlock *CurBB = DFS.back().first;
2954           MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
2955           // Walk back if we've explored this blocks successors to the end.
2956           if (CurSucc == CurBB->succ_end()) {
2957             DFS.pop_back();
2958             continue;
2959           }
2960 
2961           // If the current successor is artificial and unexplored, descend into
2962           // it.
2963           if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
2964             DFS.push_back(std::make_pair(*CurSucc, (*CurSucc)->succ_begin()));
2965             ToAdd.insert(*CurSucc);
2966             continue;
2967           }
2968 
2969           ++CurSucc;
2970         }
2971       };
2972 
2973   // Search in-scope blocks and those containing a DBG_VALUE from this scope
2974   // for artificial successors.
2975   for (auto *MBB : BlocksToExplore)
2976     AccumulateArtificialBlocks(MBB);
2977   for (auto *MBB : InScopeBlocks)
2978     AccumulateArtificialBlocks(MBB);
2979 
2980   BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
2981   InScopeBlocks.insert(ToAdd.begin(), ToAdd.end());
2982 
2983   // Single block scope: not interesting! No propagation at all. Note that
2984   // this could probably go above ArtificialBlocks without damage, but
2985   // that then produces output differences from original-live-debug-values,
2986   // which propagates from a single block into many artificial ones.
2987   if (BlocksToExplore.size() == 1)
2988     return;
2989 
2990   // Picks out relevants blocks RPO order and sort them.
2991   for (auto *MBB : BlocksToExplore)
2992     BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
2993 
2994   llvm::sort(BlockOrders, Cmp);
2995   unsigned NumBlocks = BlockOrders.size();
2996 
2997   // Allocate some vectors for storing the live ins and live outs. Large.
2998   SmallVector<DenseMap<DebugVariable, DbgValue>, 32> LiveIns, LiveOuts;
2999   LiveIns.resize(NumBlocks);
3000   LiveOuts.resize(NumBlocks);
3001 
3002   // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
3003   // vlocJoin.
3004   LiveIdxT LiveOutIdx, LiveInIdx;
3005   LiveOutIdx.reserve(NumBlocks);
3006   LiveInIdx.reserve(NumBlocks);
3007   for (unsigned I = 0; I < NumBlocks; ++I) {
3008     LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
3009     LiveInIdx[BlockOrders[I]] = &LiveIns[I];
3010   }
3011 
3012   for (auto *MBB : BlockOrders) {
3013     Worklist.push(BBToOrder[MBB]);
3014     OnWorklist.insert(MBB);
3015   }
3016 
3017   // Iterate over all the blocks we selected, propagating variable values.
3018   bool FirstTrip = true;
3019   SmallPtrSet<const MachineBasicBlock *, 16> VLOCVisited;
3020   while (!Worklist.empty() || !Pending.empty()) {
3021     while (!Worklist.empty()) {
3022       auto *MBB = OrderToBB[Worklist.top()];
3023       CurBB = MBB->getNumber();
3024       Worklist.pop();
3025 
3026       DenseMap<DebugVariable, DbgValue> JoinedInLocs;
3027 
3028       // Join values from predecessors. Updates LiveInIdx, and writes output
3029       // into JoinedInLocs.
3030       bool InLocsChanged, DowngradeOccurred;
3031       std::tie(InLocsChanged, DowngradeOccurred) = vlocJoin(
3032           *MBB, LiveOutIdx, LiveInIdx, (FirstTrip) ? &VLOCVisited : nullptr,
3033           CurBB, VarsWeCareAbout, MOutLocs, MInLocs, InScopeBlocks,
3034           BlocksToExplore, JoinedInLocs);
3035 
3036       bool FirstVisit = VLOCVisited.insert(MBB).second;
3037 
3038       // Always explore transfer function if inlocs changed, or if we've not
3039       // visited this block before.
3040       InLocsChanged |= FirstVisit;
3041 
3042       // If a downgrade occurred, book us in for re-examination on the next
3043       // iteration.
3044       if (DowngradeOccurred && OnPending.insert(MBB).second)
3045         Pending.push(BBToOrder[MBB]);
3046 
3047       if (!InLocsChanged)
3048         continue;
3049 
3050       // Do transfer function.
3051       auto &VTracker = AllTheVLocs[MBB->getNumber()];
3052       for (auto &Transfer : VTracker.Vars) {
3053         // Is this var we're mangling in this scope?
3054         if (VarsWeCareAbout.count(Transfer.first)) {
3055           // Erase on empty transfer (DBG_VALUE $noreg).
3056           if (Transfer.second.Kind == DbgValue::Undef) {
3057             JoinedInLocs.erase(Transfer.first);
3058           } else {
3059             // Insert new variable value; or overwrite.
3060             auto NewValuePair = std::make_pair(Transfer.first, Transfer.second);
3061             auto Result = JoinedInLocs.insert(NewValuePair);
3062             if (!Result.second)
3063               Result.first->second = Transfer.second;
3064           }
3065         }
3066       }
3067 
3068       // Did the live-out locations change?
3069       bool OLChanged = JoinedInLocs != *LiveOutIdx[MBB];
3070 
3071       // If they haven't changed, there's no need to explore further.
3072       if (!OLChanged)
3073         continue;
3074 
3075       // Commit to the live-out record.
3076       *LiveOutIdx[MBB] = JoinedInLocs;
3077 
3078       // We should visit all successors. Ensure we'll visit any non-backedge
3079       // successors during this dataflow iteration; book backedge successors
3080       // to be visited next time around.
3081       for (auto s : MBB->successors()) {
3082         // Ignore out of scope / not-to-be-explored successors.
3083         if (LiveInIdx.find(s) == LiveInIdx.end())
3084           continue;
3085 
3086         if (BBToOrder[s] > BBToOrder[MBB]) {
3087           if (OnWorklist.insert(s).second)
3088             Worklist.push(BBToOrder[s]);
3089         } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
3090           Pending.push(BBToOrder[s]);
3091         }
3092       }
3093     }
3094     Worklist.swap(Pending);
3095     std::swap(OnWorklist, OnPending);
3096     OnPending.clear();
3097     assert(Pending.empty());
3098     FirstTrip = false;
3099   }
3100 
3101   // Dataflow done. Now what? Save live-ins. Ignore any that are still marked
3102   // as being variable-PHIs, because those did not have their machine-PHI
3103   // value confirmed. Such variable values are places that could have been
3104   // PHIs, but are not.
3105   for (auto *MBB : BlockOrders) {
3106     auto &VarMap = *LiveInIdx[MBB];
3107     for (auto &P : VarMap) {
3108       if (P.second.Kind == DbgValue::Proposed ||
3109           P.second.Kind == DbgValue::NoVal)
3110         continue;
3111       Output[MBB->getNumber()].push_back(P);
3112     }
3113   }
3114 
3115   BlockOrders.clear();
3116   BlocksToExplore.clear();
3117 }
3118 
3119 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3120 void InstrRefBasedLDV::dump_mloc_transfer(
3121     const MLocTransferMap &mloc_transfer) const {
3122   for (auto &P : mloc_transfer) {
3123     std::string foo = MTracker->LocIdxToName(P.first);
3124     std::string bar = MTracker->IDAsString(P.second);
3125     dbgs() << "Loc " << foo << " --> " << bar << "\n";
3126   }
3127 }
3128 #endif
3129 
3130 void InstrRefBasedLDV::emitLocations(
3131     MachineFunction &MF, LiveInsT SavedLiveIns, ValueIDNum **MInLocs,
3132     DenseMap<DebugVariable, unsigned> &AllVarsNumbering) {
3133   TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs);
3134   unsigned NumLocs = MTracker->getNumLocs();
3135 
3136   // For each block, load in the machine value locations and variable value
3137   // live-ins, then step through each instruction in the block. New DBG_VALUEs
3138   // to be inserted will be created along the way.
3139   for (MachineBasicBlock &MBB : MF) {
3140     unsigned bbnum = MBB.getNumber();
3141     MTracker->reset();
3142     MTracker->loadFromArray(MInLocs[bbnum], bbnum);
3143     TTracker->loadInlocs(MBB, MInLocs[bbnum], SavedLiveIns[MBB.getNumber()],
3144                          NumLocs);
3145 
3146     CurBB = bbnum;
3147     CurInst = 1;
3148     for (auto &MI : MBB) {
3149       process(MI);
3150       TTracker->checkInstForNewValues(CurInst, MI.getIterator());
3151       ++CurInst;
3152     }
3153   }
3154 
3155   // We have to insert DBG_VALUEs in a consistent order, otherwise they appeaer
3156   // in DWARF in different orders. Use the order that they appear when walking
3157   // through each block / each instruction, stored in AllVarsNumbering.
3158   auto OrderDbgValues = [&](const MachineInstr *A,
3159                             const MachineInstr *B) -> bool {
3160     DebugVariable VarA(A->getDebugVariable(), A->getDebugExpression(),
3161                        A->getDebugLoc()->getInlinedAt());
3162     DebugVariable VarB(B->getDebugVariable(), B->getDebugExpression(),
3163                        B->getDebugLoc()->getInlinedAt());
3164     return AllVarsNumbering.find(VarA)->second <
3165            AllVarsNumbering.find(VarB)->second;
3166   };
3167 
3168   // Go through all the transfers recorded in the TransferTracker -- this is
3169   // both the live-ins to a block, and any movements of values that happen
3170   // in the middle.
3171   for (auto &P : TTracker->Transfers) {
3172     // Sort them according to appearance order.
3173     llvm::sort(P.Insts, OrderDbgValues);
3174     // Insert either before or after the designated point...
3175     if (P.MBB) {
3176       MachineBasicBlock &MBB = *P.MBB;
3177       for (auto *MI : P.Insts) {
3178         MBB.insert(P.Pos, MI);
3179       }
3180     } else {
3181       MachineBasicBlock &MBB = *P.Pos->getParent();
3182       for (auto *MI : P.Insts) {
3183         MBB.insertAfter(P.Pos, MI);
3184       }
3185     }
3186   }
3187 }
3188 
3189 void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
3190   // Build some useful data structures.
3191   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
3192     if (const DebugLoc &DL = MI.getDebugLoc())
3193       return DL.getLine() != 0;
3194     return false;
3195   };
3196   // Collect a set of all the artificial blocks.
3197   for (auto &MBB : MF)
3198     if (none_of(MBB.instrs(), hasNonArtificialLocation))
3199       ArtificialBlocks.insert(&MBB);
3200 
3201   // Compute mappings of block <=> RPO order.
3202   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
3203   unsigned int RPONumber = 0;
3204   for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
3205     OrderToBB[RPONumber] = *RI;
3206     BBToOrder[*RI] = RPONumber;
3207     BBNumToRPO[(*RI)->getNumber()] = RPONumber;
3208     ++RPONumber;
3209   }
3210 }
3211 
3212 /// Calculate the liveness information for the given machine function and
3213 /// extend ranges across basic blocks.
3214 bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
3215                                     TargetPassConfig *TPC) {
3216   // No subprogram means this function contains no debuginfo.
3217   if (!MF.getFunction().getSubprogram())
3218     return false;
3219 
3220   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
3221   this->TPC = TPC;
3222 
3223   TRI = MF.getSubtarget().getRegisterInfo();
3224   TII = MF.getSubtarget().getInstrInfo();
3225   TFI = MF.getSubtarget().getFrameLowering();
3226   TFI->getCalleeSaves(MF, CalleeSavedRegs);
3227   LS.initialize(MF);
3228 
3229   MTracker =
3230       new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
3231   VTracker = nullptr;
3232   TTracker = nullptr;
3233 
3234   SmallVector<MLocTransferMap, 32> MLocTransfer;
3235   SmallVector<VLocTracker, 8> vlocs;
3236   LiveInsT SavedLiveIns;
3237 
3238   int MaxNumBlocks = -1;
3239   for (auto &MBB : MF)
3240     MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
3241   assert(MaxNumBlocks >= 0);
3242   ++MaxNumBlocks;
3243 
3244   MLocTransfer.resize(MaxNumBlocks);
3245   vlocs.resize(MaxNumBlocks);
3246   SavedLiveIns.resize(MaxNumBlocks);
3247 
3248   initialSetup(MF);
3249 
3250   produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
3251 
3252   // Allocate and initialize two array-of-arrays for the live-in and live-out
3253   // machine values. The outer dimension is the block number; while the inner
3254   // dimension is a LocIdx from MLocTracker.
3255   ValueIDNum **MOutLocs = new ValueIDNum *[MaxNumBlocks];
3256   ValueIDNum **MInLocs = new ValueIDNum *[MaxNumBlocks];
3257   unsigned NumLocs = MTracker->getNumLocs();
3258   for (int i = 0; i < MaxNumBlocks; ++i) {
3259     MOutLocs[i] = new ValueIDNum[NumLocs];
3260     MInLocs[i] = new ValueIDNum[NumLocs];
3261   }
3262 
3263   // Solve the machine value dataflow problem using the MLocTransfer function,
3264   // storing the computed live-ins / live-outs into the array-of-arrays. We use
3265   // both live-ins and live-outs for decision making in the variable value
3266   // dataflow problem.
3267   mlocDataflow(MInLocs, MOutLocs, MLocTransfer);
3268 
3269   // Walk back through each block / instruction, collecting DBG_VALUE
3270   // instructions and recording what machine value their operands refer to.
3271   for (auto &OrderPair : OrderToBB) {
3272     MachineBasicBlock &MBB = *OrderPair.second;
3273     CurBB = MBB.getNumber();
3274     VTracker = &vlocs[CurBB];
3275     VTracker->MBB = &MBB;
3276     MTracker->loadFromArray(MInLocs[CurBB], CurBB);
3277     CurInst = 1;
3278     for (auto &MI : MBB) {
3279       process(MI);
3280       ++CurInst;
3281     }
3282     MTracker->reset();
3283   }
3284 
3285   // Number all variables in the order that they appear, to be used as a stable
3286   // insertion order later.
3287   DenseMap<DebugVariable, unsigned> AllVarsNumbering;
3288 
3289   // Map from one LexicalScope to all the variables in that scope.
3290   DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>> ScopeToVars;
3291 
3292   // Map from One lexical scope to all blocks in that scope.
3293   DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>
3294       ScopeToBlocks;
3295 
3296   // Store a DILocation that describes a scope.
3297   DenseMap<const LexicalScope *, const DILocation *> ScopeToDILocation;
3298 
3299   // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3300   // the order is unimportant, it just has to be stable.
3301   for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3302     auto *MBB = OrderToBB[I];
3303     auto *VTracker = &vlocs[MBB->getNumber()];
3304     // Collect each variable with a DBG_VALUE in this block.
3305     for (auto &idx : VTracker->Vars) {
3306       const auto &Var = idx.first;
3307       const DILocation *ScopeLoc = VTracker->Scopes[Var];
3308       assert(ScopeLoc != nullptr);
3309       auto *Scope = LS.findLexicalScope(ScopeLoc);
3310 
3311       // No insts in scope -> shouldn't have been recorded.
3312       assert(Scope != nullptr);
3313 
3314       AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
3315       ScopeToVars[Scope].insert(Var);
3316       ScopeToBlocks[Scope].insert(VTracker->MBB);
3317       ScopeToDILocation[Scope] = ScopeLoc;
3318     }
3319   }
3320 
3321   // OK. Iterate over scopes: there might be something to be said for
3322   // ordering them by size/locality, but that's for the future. For each scope,
3323   // solve the variable value problem, producing a map of variables to values
3324   // in SavedLiveIns.
3325   for (auto &P : ScopeToVars) {
3326     vlocDataflow(P.first, ScopeToDILocation[P.first], P.second,
3327                  ScopeToBlocks[P.first], SavedLiveIns, MOutLocs, MInLocs,
3328                  vlocs);
3329   }
3330 
3331   // Using the computed value locations and variable values for each block,
3332   // create the DBG_VALUE instructions representing the extended variable
3333   // locations.
3334   emitLocations(MF, SavedLiveIns, MInLocs, AllVarsNumbering);
3335 
3336   for (int Idx = 0; Idx < MaxNumBlocks; ++Idx) {
3337     delete[] MOutLocs[Idx];
3338     delete[] MInLocs[Idx];
3339   }
3340   delete[] MOutLocs;
3341   delete[] MInLocs;
3342 
3343   // Did we actually make any changes? If we created any DBG_VALUEs, then yes.
3344   bool Changed = TTracker->Transfers.size() != 0;
3345 
3346   delete MTracker;
3347   delete TTracker;
3348   MTracker = nullptr;
3349   VTracker = nullptr;
3350   TTracker = nullptr;
3351 
3352   ArtificialBlocks.clear();
3353   OrderToBB.clear();
3354   BBToOrder.clear();
3355   BBNumToRPO.clear();
3356   DebugInstrNumToInstr.clear();
3357 
3358   return Changed;
3359 }
3360 
3361 LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3362   return new InstrRefBasedLDV();
3363 }
3364