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/raw_ostream.h"
186 #include <algorithm>
187 #include <cassert>
188 #include <cstdint>
189 #include <functional>
190 #include <queue>
191 #include <tuple>
192 #include <utility>
193 #include <vector>
194 #include <limits.h>
195 #include <limits>
196 
197 #include "LiveDebugValues.h"
198 
199 using namespace llvm;
200 
201 #define DEBUG_TYPE "livedebugvalues"
202 
203 STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
204 STATISTIC(NumRemoved, "Number of DBG_VALUE instructions removed");
205 
206 // Act more like the VarLoc implementation, by propagating some locations too
207 // far and ignoring some transfers.
208 static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
209                                    cl::desc("Act like old LiveDebugValues did"),
210                                    cl::init(false));
211 
212 // Rely on isStoreToStackSlotPostFE and similar to observe all stack spills.
213 static cl::opt<bool>
214     ObserveAllStackops("observe-all-stack-ops", cl::Hidden,
215                        cl::desc("Allow non-kill spill and restores"),
216                        cl::init(false));
217 
218 namespace {
219 
220 // The location at which a spilled value resides. It consists of a register and
221 // an offset.
222 struct SpillLoc {
223   unsigned SpillBase;
224   int SpillOffset;
225   bool operator==(const SpillLoc &Other) const {
226     return std::tie(SpillBase, SpillOffset) ==
227            std::tie(Other.SpillBase, Other.SpillOffset);
228   }
229   bool operator<(const SpillLoc &Other) const {
230     return std::tie(SpillBase, SpillOffset) <
231            std::tie(Other.SpillBase, Other.SpillOffset);
232   }
233 };
234 
235 class LocIdx {
236   unsigned Location;
237 
238   // Default constructor is private, initializing to an illegal location number.
239   // Use only for "not an entry" elements in IndexedMaps.
240   LocIdx() : Location(UINT_MAX) { }
241 
242 public:
243   #define NUM_LOC_BITS 24
244   LocIdx(unsigned L) : Location(L) {
245     assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
246   }
247 
248   static LocIdx MakeIllegalLoc() {
249     return LocIdx();
250   }
251 
252   bool isIllegal() const {
253     return Location == UINT_MAX;
254   }
255 
256   uint64_t asU64() const {
257     return Location;
258   }
259 
260   bool operator==(unsigned L) const {
261     return Location == L;
262   }
263 
264   bool operator==(const LocIdx &L) const {
265     return Location == L.Location;
266   }
267 
268   bool operator!=(unsigned L) const {
269     return !(*this == L);
270   }
271 
272   bool operator!=(const LocIdx &L) const {
273     return !(*this == L);
274   }
275 
276   bool operator<(const LocIdx &Other) const {
277     return Location < Other.Location;
278   }
279 };
280 
281 class LocIdxToIndexFunctor {
282 public:
283   using argument_type = LocIdx;
284   unsigned operator()(const LocIdx &L) const {
285     return L.asU64();
286   }
287 };
288 
289 /// Unique identifier for a value defined by an instruction, as a value type.
290 /// Casts back and forth to a uint64_t. Probably replacable with something less
291 /// bit-constrained. Each value identifies the instruction and machine location
292 /// where the value is defined, although there may be no corresponding machine
293 /// operand for it (ex: regmasks clobbering values). The instructions are
294 /// one-based, and definitions that are PHIs have instruction number zero.
295 ///
296 /// The obvious limits of a 1M block function or 1M instruction blocks are
297 /// problematic; but by that point we should probably have bailed out of
298 /// trying to analyse the function.
299 class ValueIDNum {
300   uint64_t BlockNo : 20;         /// The block where the def happens.
301   uint64_t InstNo : 20;          /// The Instruction where the def happens.
302                                  /// One based, is distance from start of block.
303   uint64_t LocNo : NUM_LOC_BITS; /// The machine location where the def happens.
304 
305 public:
306   // XXX -- temporarily enabled while the live-in / live-out tables are moved
307   // to something more type-y
308   ValueIDNum() : BlockNo(0xFFFFF),
309                  InstNo(0xFFFFF),
310                  LocNo(0xFFFFFF) { }
311 
312   ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc)
313     : BlockNo(Block), InstNo(Inst), LocNo(Loc) { }
314 
315   ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc)
316     : BlockNo(Block), InstNo(Inst), LocNo(Loc.asU64()) { }
317 
318   uint64_t getBlock() const { return BlockNo; }
319   uint64_t getInst() const { return InstNo; }
320   uint64_t getLoc() const { return LocNo; }
321   bool isPHI() const { return InstNo == 0; }
322 
323   uint64_t asU64() const {
324     uint64_t TmpBlock = BlockNo;
325     uint64_t TmpInst = InstNo;
326     return TmpBlock << 44ull | TmpInst << NUM_LOC_BITS | LocNo;
327   }
328 
329   static ValueIDNum fromU64(uint64_t v) {
330     uint64_t L = (v & 0x3FFF);
331     return {v >> 44ull, ((v >> NUM_LOC_BITS) & 0xFFFFF), L};
332   }
333 
334   bool operator<(const ValueIDNum &Other) const {
335     return asU64() < Other.asU64();
336   }
337 
338   bool operator==(const ValueIDNum &Other) const {
339     return std::tie(BlockNo, InstNo, LocNo) ==
340            std::tie(Other.BlockNo, Other.InstNo, Other.LocNo);
341   }
342 
343   bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
344 
345   std::string asString(const std::string &mlocname) const {
346     return Twine("Value{bb: ")
347         .concat(Twine(BlockNo).concat(
348             Twine(", inst: ")
349                 .concat((InstNo ? Twine(InstNo) : Twine("live-in"))
350                             .concat(Twine(", loc: ").concat(Twine(mlocname)))
351                             .concat(Twine("}")))))
352         .str();
353   }
354 
355   static ValueIDNum EmptyValue;
356 };
357 
358 } // end anonymous namespace
359 
360 namespace {
361 
362 /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
363 /// the the value, and Boolean of whether or not it's indirect.
364 class DbgValueProperties {
365 public:
366   DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
367       : DIExpr(DIExpr), Indirect(Indirect) {}
368 
369   /// Extract properties from an existing DBG_VALUE instruction.
370   DbgValueProperties(const MachineInstr &MI) {
371     assert(MI.isDebugValue());
372     DIExpr = MI.getDebugExpression();
373     Indirect = MI.getOperand(1).isImm();
374   }
375 
376   bool operator==(const DbgValueProperties &Other) const {
377     return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
378   }
379 
380   bool operator!=(const DbgValueProperties &Other) const {
381     return !(*this == Other);
382   }
383 
384   const DIExpression *DIExpr;
385   bool Indirect;
386 };
387 
388 /// Tracker for what values are in machine locations. Listens to the Things
389 /// being Done by various instructions, and maintains a table of what machine
390 /// locations have what values (as defined by a ValueIDNum).
391 ///
392 /// There are potentially a much larger number of machine locations on the
393 /// target machine than the actual working-set size of the function. On x86 for
394 /// example, we're extremely unlikely to want to track values through control
395 /// or debug registers. To avoid doing so, MLocTracker has several layers of
396 /// indirection going on, with two kinds of ``location'':
397 ///  * A LocID uniquely identifies a register or spill location, with a
398 ///    predictable value.
399 ///  * A LocIdx is a key (in the database sense) for a LocID and a ValueIDNum.
400 /// Whenever a location is def'd or used by a MachineInstr, we automagically
401 /// create a new LocIdx for a location, but not otherwise. This ensures we only
402 /// account for locations that are actually used or defined. The cost is another
403 /// vector lookup (of LocID -> LocIdx) over any other implementation. This is
404 /// fairly cheap, and the compiler tries to reduce the working-set at any one
405 /// time in the function anyway.
406 ///
407 /// Register mask operands completely blow this out of the water; I've just
408 /// piled hacks on top of hacks to get around that.
409 class MLocTracker {
410 public:
411   MachineFunction &MF;
412   const TargetInstrInfo &TII;
413   const TargetRegisterInfo &TRI;
414   const TargetLowering &TLI;
415 
416   /// IndexedMap type, mapping from LocIdx to ValueIDNum.
417   using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
418 
419   /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
420   /// packed, entries only exist for locations that are being tracked.
421   LocToValueType LocIdxToIDNum;
422 
423   /// "Map" of machine location IDs (i.e., raw register or spill number) to the
424   /// LocIdx key / number for that location. There are always at least as many
425   /// as the number of registers on the target -- if the value in the register
426   /// is not being tracked, then the LocIdx value will be zero. New entries are
427   /// appended if a new spill slot begins being tracked.
428   /// This, and the corresponding reverse map persist for the analysis of the
429   /// whole function, and is necessarying for decoding various vectors of
430   /// values.
431   std::vector<LocIdx> LocIDToLocIdx;
432 
433   /// Inverse map of LocIDToLocIdx.
434   IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
435 
436   /// Unique-ification of spill slots. Used to number them -- their LocID
437   /// number is the index in SpillLocs minus one plus NumRegs.
438   UniqueVector<SpillLoc> SpillLocs;
439 
440   // If we discover a new machine location, assign it an mphi with this
441   // block number.
442   unsigned CurBB;
443 
444   /// Cached local copy of the number of registers the target has.
445   unsigned NumRegs;
446 
447   /// Collection of register mask operands that have been observed. Second part
448   /// of pair indicates the instruction that they happened in. Used to
449   /// reconstruct where defs happened if we start tracking a location later
450   /// on.
451   SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
452 
453   /// Iterator for locations and the values they contain. Dereferencing
454   /// produces a struct/pair containing the LocIdx key for this location,
455   /// and a reference to the value currently stored. Simplifies the process
456   /// of seeking a particular location.
457   class MLocIterator {
458     LocToValueType &ValueMap;
459     LocIdx Idx;
460 
461   public:
462     class value_type {
463       public:
464       value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) { }
465       const LocIdx Idx;  /// Read-only index of this location.
466       ValueIDNum &Value; /// Reference to the stored value at this location.
467     };
468 
469     MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
470       : ValueMap(ValueMap), Idx(Idx) { }
471 
472     bool operator==(const MLocIterator &Other) const {
473       assert(&ValueMap == &Other.ValueMap);
474       return Idx == Other.Idx;
475     }
476 
477     bool operator!=(const MLocIterator &Other) const {
478       return !(*this == Other);
479     }
480 
481     void operator++() {
482       Idx = LocIdx(Idx.asU64() + 1);
483     }
484 
485     value_type operator*() {
486       return value_type(Idx, ValueMap[LocIdx(Idx)]);
487     }
488   };
489 
490   MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
491               const TargetRegisterInfo &TRI, const TargetLowering &TLI)
492       : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
493         LocIdxToIDNum(ValueIDNum::EmptyValue),
494         LocIdxToLocID(0) {
495     NumRegs = TRI.getNumRegs();
496     reset();
497     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
498     assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
499 
500     // Always track SP. This avoids the implicit clobbering caused by regmasks
501     // from affectings its values. (LiveDebugValues disbelieves calls and
502     // regmasks that claim to clobber SP).
503     Register SP = TLI.getStackPointerRegisterToSaveRestore();
504     if (SP) {
505       unsigned ID = getLocID(SP, false);
506       (void)lookupOrTrackRegister(ID);
507     }
508   }
509 
510   /// Produce location ID number for indexing LocIDToLocIdx. Takes the register
511   /// or spill number, and flag for whether it's a spill or not.
512   unsigned getLocID(Register RegOrSpill, bool isSpill) {
513     return (isSpill) ? RegOrSpill.id() + NumRegs - 1 : RegOrSpill.id();
514   }
515 
516   /// Accessor for reading the value at Idx.
517   ValueIDNum getNumAtPos(LocIdx Idx) const {
518     assert(Idx.asU64() < LocIdxToIDNum.size());
519     return LocIdxToIDNum[Idx];
520   }
521 
522   unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); }
523 
524   /// Reset all locations to contain a PHI value at the designated block. Used
525   /// sometimes for actual PHI values, othertimes to indicate the block entry
526   /// value (before any more information is known).
527   void setMPhis(unsigned NewCurBB) {
528     CurBB = NewCurBB;
529     for (auto Location : locations())
530       Location.Value = {CurBB, 0, Location.Idx};
531   }
532 
533   /// Load values for each location from array of ValueIDNums. Take current
534   /// bbnum just in case we read a value from a hitherto untouched register.
535   void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) {
536     CurBB = NewCurBB;
537     // Iterate over all tracked locations, and load each locations live-in
538     // value into our local index.
539     for (auto Location : locations())
540       Location.Value = Locs[Location.Idx.asU64()];
541   }
542 
543   /// Wipe any un-necessary location records after traversing a block.
544   void reset(void) {
545     // We could reset all the location values too; however either loadFromArray
546     // or setMPhis should be called before this object is re-used. Just
547     // clear Masks, they're definitely not needed.
548     Masks.clear();
549   }
550 
551   /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
552   /// the information in this pass uninterpretable.
553   void clear(void) {
554     reset();
555     LocIDToLocIdx.clear();
556     LocIdxToLocID.clear();
557     LocIdxToIDNum.clear();
558     //SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from 0
559     SpillLocs = decltype(SpillLocs)();
560 
561     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
562   }
563 
564   /// Set a locaiton to a certain value.
565   void setMLoc(LocIdx L, ValueIDNum Num) {
566     assert(L.asU64() < LocIdxToIDNum.size());
567     LocIdxToIDNum[L] = Num;
568   }
569 
570   /// Create a LocIdx for an untracked register ID. Initialize it to either an
571   /// mphi value representing a live-in, or a recent register mask clobber.
572   LocIdx trackRegister(unsigned ID) {
573     assert(ID != 0);
574     LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
575     LocIdxToIDNum.grow(NewIdx);
576     LocIdxToLocID.grow(NewIdx);
577 
578     // Default: it's an mphi.
579     ValueIDNum ValNum = {CurBB, 0, NewIdx};
580     // Was this reg ever touched by a regmask?
581     for (const auto &MaskPair : reverse(Masks)) {
582       if (MaskPair.first->clobbersPhysReg(ID)) {
583         // There was an earlier def we skipped.
584         ValNum = {CurBB, MaskPair.second, NewIdx};
585         break;
586       }
587     }
588 
589     LocIdxToIDNum[NewIdx] = ValNum;
590     LocIdxToLocID[NewIdx] = ID;
591     return NewIdx;
592   }
593 
594   LocIdx lookupOrTrackRegister(unsigned ID) {
595     LocIdx &Index = LocIDToLocIdx[ID];
596     if (Index.isIllegal())
597       Index = trackRegister(ID);
598     return Index;
599   }
600 
601   /// Record a definition of the specified register at the given block / inst.
602   /// This doesn't take a ValueIDNum, because the definition and its location
603   /// are synonymous.
604   void defReg(Register R, unsigned BB, unsigned Inst) {
605     unsigned ID = getLocID(R, false);
606     LocIdx Idx = lookupOrTrackRegister(ID);
607     ValueIDNum ValueID = {BB, Inst, Idx};
608     LocIdxToIDNum[Idx] = ValueID;
609   }
610 
611   /// Set a register to a value number. To be used if the value number is
612   /// known in advance.
613   void setReg(Register R, ValueIDNum ValueID) {
614     unsigned ID = getLocID(R, false);
615     LocIdx Idx = lookupOrTrackRegister(ID);
616     LocIdxToIDNum[Idx] = ValueID;
617   }
618 
619   ValueIDNum readReg(Register R) {
620     unsigned ID = getLocID(R, false);
621     LocIdx Idx = lookupOrTrackRegister(ID);
622     return LocIdxToIDNum[Idx];
623   }
624 
625   /// Reset a register value to zero / empty. Needed to replicate the
626   /// VarLoc implementation where a copy to/from a register effectively
627   /// clears the contents of the source register. (Values can only have one
628   ///  machine location in VarLocBasedImpl).
629   void wipeRegister(Register R) {
630     unsigned ID = getLocID(R, false);
631     LocIdx Idx = LocIDToLocIdx[ID];
632     LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
633   }
634 
635   /// Determine the LocIdx of an existing register.
636   LocIdx getRegMLoc(Register R) {
637     unsigned ID = getLocID(R, false);
638     return LocIDToLocIdx[ID];
639   }
640 
641   /// Record a RegMask operand being executed. Defs any register we currently
642   /// track, stores a pointer to the mask in case we have to account for it
643   /// later.
644   void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID) {
645     // Ensure SP exists, so that we don't override it later.
646     Register SP = TLI.getStackPointerRegisterToSaveRestore();
647 
648     // Def any register we track have that isn't preserved. The regmask
649     // terminates the liveness of a register, meaning its value can't be
650     // relied upon -- we represent this by giving it a new value.
651     for (auto Location : locations()) {
652       unsigned ID = LocIdxToLocID[Location.Idx];
653       // Don't clobber SP, even if the mask says it's clobbered.
654       if (ID < NumRegs && ID != SP && MO->clobbersPhysReg(ID))
655         defReg(ID, CurBB, InstID);
656     }
657     Masks.push_back(std::make_pair(MO, InstID));
658   }
659 
660   /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
661   LocIdx getOrTrackSpillLoc(SpillLoc L) {
662     unsigned SpillID = SpillLocs.idFor(L);
663     if (SpillID == 0) {
664       SpillID = SpillLocs.insert(L);
665       unsigned L = getLocID(SpillID, true);
666       LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
667       LocIdxToIDNum.grow(Idx);
668       LocIdxToLocID.grow(Idx);
669       LocIDToLocIdx.push_back(Idx);
670       LocIdxToLocID[Idx] = L;
671       return Idx;
672     } else {
673       unsigned L = getLocID(SpillID, true);
674       LocIdx Idx = LocIDToLocIdx[L];
675       return Idx;
676     }
677   }
678 
679   /// Set the value stored in a spill slot.
680   void setSpill(SpillLoc L, ValueIDNum ValueID) {
681     LocIdx Idx = getOrTrackSpillLoc(L);
682     LocIdxToIDNum[Idx] = ValueID;
683   }
684 
685   /// Read whatever value is in a spill slot, or None if it isn't tracked.
686   Optional<ValueIDNum> readSpill(SpillLoc L) {
687     unsigned SpillID = SpillLocs.idFor(L);
688     if (SpillID == 0)
689       return None;
690 
691     unsigned LocID = getLocID(SpillID, true);
692     LocIdx Idx = LocIDToLocIdx[LocID];
693     return LocIdxToIDNum[Idx];
694   }
695 
696   /// Determine the LocIdx of a spill slot. Return None if it previously
697   /// hasn't had a value assigned.
698   Optional<LocIdx> getSpillMLoc(SpillLoc L) {
699     unsigned SpillID = SpillLocs.idFor(L);
700     if (SpillID == 0)
701       return None;
702     unsigned LocNo = getLocID(SpillID, true);
703     return LocIDToLocIdx[LocNo];
704   }
705 
706   /// Return true if Idx is a spill machine location.
707   bool isSpill(LocIdx Idx) const {
708     return LocIdxToLocID[Idx] >= NumRegs;
709   }
710 
711   MLocIterator begin() {
712     return MLocIterator(LocIdxToIDNum, 0);
713   }
714 
715   MLocIterator end() {
716     return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
717   }
718 
719   /// Return a range over all locations currently tracked.
720   iterator_range<MLocIterator> locations() {
721     return llvm::make_range(begin(), end());
722   }
723 
724   std::string LocIdxToName(LocIdx Idx) const {
725     unsigned ID = LocIdxToLocID[Idx];
726     if (ID >= NumRegs)
727       return Twine("slot ").concat(Twine(ID - NumRegs)).str();
728     else
729       return TRI.getRegAsmName(ID).str();
730   }
731 
732   std::string IDAsString(const ValueIDNum &Num) const {
733     std::string DefName = LocIdxToName(Num.getLoc());
734     return Num.asString(DefName);
735   }
736 
737   LLVM_DUMP_METHOD
738   void dump() {
739     for (auto Location : locations()) {
740       std::string MLocName = LocIdxToName(Location.Value.getLoc());
741       std::string DefName = Location.Value.asString(MLocName);
742       dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
743     }
744   }
745 
746   LLVM_DUMP_METHOD
747   void dump_mloc_map() {
748     for (auto Location : locations()) {
749       std::string foo = LocIdxToName(Location.Idx);
750       dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
751     }
752   }
753 
754   /// Create a DBG_VALUE based on  machine location \p MLoc. Qualify it with the
755   /// information in \pProperties, for variable Var. Don't insert it anywhere,
756   /// just return the builder for it.
757   MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
758                               const DbgValueProperties &Properties) {
759     DebugLoc DL =
760         DebugLoc::get(0, 0, Var.getVariable()->getScope(), Var.getInlinedAt());
761     auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE));
762 
763     const DIExpression *Expr = Properties.DIExpr;
764     if (!MLoc) {
765       // No location -> DBG_VALUE $noreg
766       MIB.addReg(0, RegState::Debug);
767       MIB.addReg(0, RegState::Debug);
768     } else if (LocIdxToLocID[*MLoc] >= NumRegs) {
769       unsigned LocID = LocIdxToLocID[*MLoc];
770       const SpillLoc &Spill = SpillLocs[LocID - NumRegs + 1];
771       Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset,
772                                    Spill.SpillOffset);
773       unsigned Base = Spill.SpillBase;
774       MIB.addReg(Base, RegState::Debug);
775       MIB.addImm(0);
776     } else {
777       unsigned LocID = LocIdxToLocID[*MLoc];
778       MIB.addReg(LocID, RegState::Debug);
779       if (Properties.Indirect)
780         MIB.addImm(0);
781       else
782         MIB.addReg(0, RegState::Debug);
783     }
784 
785     MIB.addMetadata(Var.getVariable());
786     MIB.addMetadata(Expr);
787     return MIB;
788   }
789 };
790 
791 /// Class recording the (high level) _value_ of a variable. Identifies either
792 /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
793 /// This class also stores meta-information about how the value is qualified.
794 /// Used to reason about variable values when performing the second
795 /// (DebugVariable specific) dataflow analysis.
796 class DbgValue {
797 public:
798   union {
799     /// If Kind is Def, the value number that this value is based on.
800     ValueIDNum ID;
801     /// If Kind is Const, the MachineOperand defining this value.
802     MachineOperand MO;
803     /// For a NoVal DbgValue, which block it was generated in.
804     unsigned BlockNo;
805   };
806   /// Qualifiers for the ValueIDNum above.
807   DbgValueProperties Properties;
808 
809   typedef enum {
810     Undef,     // Represents a DBG_VALUE $noreg in the transfer function only.
811     Def,       // This value is defined by an inst, or is a PHI value.
812     Const,     // A constant value contained in the MachineOperand field.
813     Proposed,  // This is a tentative PHI value, which may be confirmed or
814                // invalidated later.
815     NoVal      // Empty DbgValue, generated during dataflow. BlockNo stores
816                // which block this was generated in.
817    } KindT;
818   /// Discriminator for whether this is a constant or an in-program value.
819   KindT Kind;
820 
821   DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
822     : ID(Val), Properties(Prop), Kind(Kind) {
823     assert(Kind == Def || Kind == Proposed);
824   }
825 
826   DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
827     : BlockNo(BlockNo), Properties(Prop), Kind(Kind) {
828     assert(Kind == NoVal);
829   }
830 
831   DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
832     : MO(MO), Properties(Prop), Kind(Kind) {
833     assert(Kind == Const);
834   }
835 
836   DbgValue(const DbgValueProperties &Prop, KindT Kind)
837     : Properties(Prop), Kind(Kind) {
838     assert(Kind == Undef &&
839            "Empty DbgValue constructor must pass in Undef kind");
840   }
841 
842   void dump(const MLocTracker *MTrack) const {
843     if (Kind == Const) {
844       MO.dump();
845     } else if (Kind == NoVal) {
846       dbgs() << "NoVal(" << BlockNo << ")";
847     } else if (Kind == Proposed) {
848       dbgs() << "VPHI(" << MTrack->IDAsString(ID) << ")";
849     } else {
850       assert(Kind == Def);
851       dbgs() << MTrack->IDAsString(ID);
852     }
853     if (Properties.Indirect)
854       dbgs() << " indir";
855     if (Properties.DIExpr)
856       dbgs() << " " << *Properties.DIExpr;
857   }
858 
859   bool operator==(const DbgValue &Other) const {
860     if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
861       return false;
862     else if (Kind == Proposed && ID != Other.ID)
863       return false;
864     else if (Kind == Def && ID != Other.ID)
865       return false;
866     else if (Kind == NoVal && BlockNo != Other.BlockNo)
867       return false;
868     else if (Kind == Const)
869       return MO.isIdenticalTo(Other.MO);
870 
871     return true;
872   }
873 
874   bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
875 };
876 
877 /// Types for recording sets of variable fragments that overlap. For a given
878 /// local variable, we record all other fragments of that variable that could
879 /// overlap it, to reduce search time.
880 using FragmentOfVar =
881     std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
882 using OverlapMap =
883     DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
884 
885 /// Collection of DBG_VALUEs observed when traversing a block. Records each
886 /// variable and the value the DBG_VALUE refers to. Requires the machine value
887 /// location dataflow algorithm to have run already, so that values can be
888 /// identified.
889 class VLocTracker {
890 public:
891   /// Map DebugVariable to the latest Value it's defined to have.
892   /// Needs to be a MapVector because we determine order-in-the-input-MIR from
893   /// the order in this container.
894   /// We only retain the last DbgValue in each block for each variable, to
895   /// determine the blocks live-out variable value. The Vars container forms the
896   /// transfer function for this block, as part of the dataflow analysis. The
897   /// movement of values between locations inside of a block is handled at a
898   /// much later stage, in the TransferTracker class.
899   MapVector<DebugVariable, DbgValue> Vars;
900   DenseMap<DebugVariable, const DILocation *> Scopes;
901   MachineBasicBlock *MBB;
902 
903 public:
904   VLocTracker() {}
905 
906   void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
907               Optional<ValueIDNum> ID) {
908     assert(MI.isDebugValue() || MI.isDebugRef());
909     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
910                       MI.getDebugLoc()->getInlinedAt());
911     DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
912                         : DbgValue(Properties, DbgValue::Undef);
913 
914     // Attempt insertion; overwrite if it's already mapped.
915     auto Result = Vars.insert(std::make_pair(Var, Rec));
916     if (!Result.second)
917       Result.first->second = Rec;
918     Scopes[Var] = MI.getDebugLoc().get();
919   }
920 
921   void defVar(const MachineInstr &MI, const MachineOperand &MO) {
922     // Only DBG_VALUEs can define constant-valued variables.
923     assert(MI.isDebugValue());
924     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
925                       MI.getDebugLoc()->getInlinedAt());
926     DbgValueProperties Properties(MI);
927     DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
928 
929     // Attempt insertion; overwrite if it's already mapped.
930     auto Result = Vars.insert(std::make_pair(Var, Rec));
931     if (!Result.second)
932       Result.first->second = Rec;
933     Scopes[Var] = MI.getDebugLoc().get();
934   }
935 };
936 
937 /// Tracker for converting machine value locations and variable values into
938 /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
939 /// specifying block live-in locations and transfers within blocks.
940 ///
941 /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
942 /// and must be initialized with the set of variable values that are live-in to
943 /// the block. The caller then repeatedly calls process(). TransferTracker picks
944 /// out variable locations for the live-in variable values (if there _is_ a
945 /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
946 /// stepped through, transfers of values between machine locations are
947 /// identified and if profitable, a DBG_VALUE created.
948 ///
949 /// This is where debug use-before-defs would be resolved: a variable with an
950 /// unavailable value could materialize in the middle of a block, when the
951 /// value becomes available. Or, we could detect clobbers and re-specify the
952 /// variable in a backup location. (XXX these are unimplemented).
953 class TransferTracker {
954 public:
955   const TargetInstrInfo *TII;
956   /// This machine location tracker is assumed to always contain the up-to-date
957   /// value mapping for all machine locations. TransferTracker only reads
958   /// information from it. (XXX make it const?)
959   MLocTracker *MTracker;
960   MachineFunction &MF;
961 
962   /// Record of all changes in variable locations at a block position. Awkwardly
963   /// we allow inserting either before or after the point: MBB != nullptr
964   /// indicates it's before, otherwise after.
965   struct Transfer {
966     MachineBasicBlock::iterator Pos; /// Position to insert DBG_VALUes
967     MachineBasicBlock *MBB;          /// non-null if we should insert after.
968     SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
969   };
970 
971   typedef struct {
972     LocIdx Loc;
973     DbgValueProperties Properties;
974   } LocAndProperties;
975 
976   /// Collection of transfers (DBG_VALUEs) to be inserted.
977   SmallVector<Transfer, 32> Transfers;
978 
979   /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
980   /// between TransferTrackers view of variable locations and MLocTrackers. For
981   /// example, MLocTracker observes all clobbers, but TransferTracker lazily
982   /// does not.
983   std::vector<ValueIDNum> VarLocs;
984 
985   /// Map from LocIdxes to which DebugVariables are based that location.
986   /// Mantained while stepping through the block. Not accurate if
987   /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
988   std::map<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
989 
990   /// Map from DebugVariable to it's current location and qualifying meta
991   /// information. To be used in conjunction with ActiveMLocs to construct
992   /// enough information for the DBG_VALUEs for a particular LocIdx.
993   DenseMap<DebugVariable, LocAndProperties> ActiveVLocs;
994 
995   /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
996   SmallVector<MachineInstr *, 4> PendingDbgValues;
997 
998   /// Record of a use-before-def: created when a value that's live-in to the
999   /// current block isn't available in any machine location, but it will be
1000   /// defined in this block.
1001   struct UseBeforeDef {
1002     /// Value of this variable, def'd in block.
1003     ValueIDNum ID;
1004     /// Identity of this variable.
1005     DebugVariable Var;
1006     /// Additional variable properties.
1007     DbgValueProperties Properties;
1008   };
1009 
1010   /// Map from instruction index (within the block) to the set of UseBeforeDefs
1011   /// that become defined at that instruction.
1012   DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
1013 
1014   /// The set of variables that are in UseBeforeDefs and can become a location
1015   /// once the relevant value is defined. An element being erased from this
1016   /// collection prevents the use-before-def materializing.
1017   DenseSet<DebugVariable> UseBeforeDefVariables;
1018 
1019   const TargetRegisterInfo &TRI;
1020   const BitVector &CalleeSavedRegs;
1021 
1022   TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
1023                   MachineFunction &MF, const TargetRegisterInfo &TRI,
1024                   const BitVector &CalleeSavedRegs)
1025       : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
1026         CalleeSavedRegs(CalleeSavedRegs) {}
1027 
1028   /// Load object with live-in variable values. \p mlocs contains the live-in
1029   /// values in each machine location, while \p vlocs the live-in variable
1030   /// values. This method picks variable locations for the live-in variables,
1031   /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
1032   /// object fields to track variable locations as we step through the block.
1033   /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
1034   void loadInlocs(MachineBasicBlock &MBB, ValueIDNum *MLocs,
1035                   SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
1036                   unsigned NumLocs) {
1037     ActiveMLocs.clear();
1038     ActiveVLocs.clear();
1039     VarLocs.clear();
1040     VarLocs.reserve(NumLocs);
1041     UseBeforeDefs.clear();
1042     UseBeforeDefVariables.clear();
1043 
1044     auto isCalleeSaved = [&](LocIdx L) {
1045       unsigned Reg = MTracker->LocIdxToLocID[L];
1046       if (Reg >= MTracker->NumRegs)
1047         return false;
1048       for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
1049         if (CalleeSavedRegs.test(*RAI))
1050           return true;
1051       return false;
1052     };
1053 
1054     // Map of the preferred location for each value.
1055     std::map<ValueIDNum, LocIdx> ValueToLoc;
1056 
1057     // Produce a map of value numbers to the current machine locs they live
1058     // in. When emulating VarLocBasedImpl, there should only be one
1059     // location; when not, we get to pick.
1060     for (auto Location : MTracker->locations()) {
1061       LocIdx Idx = Location.Idx;
1062       ValueIDNum &VNum = MLocs[Idx.asU64()];
1063       VarLocs.push_back(VNum);
1064       auto it = ValueToLoc.find(VNum);
1065       // In order of preference, pick:
1066       //  * Callee saved registers,
1067       //  * Other registers,
1068       //  * Spill slots.
1069       if (it == ValueToLoc.end() || MTracker->isSpill(it->second) ||
1070           (!isCalleeSaved(it->second) && isCalleeSaved(Idx.asU64()))) {
1071         // Insert, or overwrite if insertion failed.
1072         auto PrefLocRes = ValueToLoc.insert(std::make_pair(VNum, Idx));
1073         if (!PrefLocRes.second)
1074           PrefLocRes.first->second = Idx;
1075       }
1076     }
1077 
1078     // Now map variables to their picked LocIdxes.
1079     for (auto Var : VLocs) {
1080       if (Var.second.Kind == DbgValue::Const) {
1081         PendingDbgValues.push_back(
1082             emitMOLoc(Var.second.MO, Var.first, Var.second.Properties));
1083         continue;
1084       }
1085 
1086       // If the value has no location, we can't make a variable location.
1087       const ValueIDNum &Num = Var.second.ID;
1088       auto ValuesPreferredLoc = ValueToLoc.find(Num);
1089       if (ValuesPreferredLoc == ValueToLoc.end()) {
1090         // If it's a def that occurs in this block, register it as a
1091         // use-before-def to be resolved as we step through the block.
1092         if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI())
1093           addUseBeforeDef(Var.first, Var.second.Properties, Num);
1094         continue;
1095       }
1096 
1097       LocIdx M = ValuesPreferredLoc->second;
1098       auto NewValue = LocAndProperties{M, Var.second.Properties};
1099       auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue));
1100       if (!Result.second)
1101         Result.first->second = NewValue;
1102       ActiveMLocs[M].insert(Var.first);
1103       PendingDbgValues.push_back(
1104           MTracker->emitLoc(M, Var.first, Var.second.Properties));
1105     }
1106     flushDbgValues(MBB.begin(), &MBB);
1107   }
1108 
1109   /// Record that \p Var has value \p ID, a value that becomes available
1110   /// later in the function.
1111   void addUseBeforeDef(const DebugVariable &Var,
1112                        const DbgValueProperties &Properties, ValueIDNum ID) {
1113     UseBeforeDef UBD = {ID, Var, Properties};
1114     UseBeforeDefs[ID.getInst()].push_back(UBD);
1115     UseBeforeDefVariables.insert(Var);
1116   }
1117 
1118   /// After the instruction at index \p Inst and position \p pos has been
1119   /// processed, check whether it defines a variable value in a use-before-def.
1120   /// If so, and the variable value hasn't changed since the start of the
1121   /// block, create a DBG_VALUE.
1122   void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
1123     auto MIt = UseBeforeDefs.find(Inst);
1124     if (MIt == UseBeforeDefs.end())
1125       return;
1126 
1127     for (auto &Use : MIt->second) {
1128       LocIdx L = Use.ID.getLoc();
1129 
1130       // If something goes very wrong, we might end up labelling a COPY
1131       // instruction or similar with an instruction number, where it doesn't
1132       // actually define a new value, instead it moves a value. In case this
1133       // happens, discard.
1134       if (MTracker->LocIdxToIDNum[L] != Use.ID)
1135         continue;
1136 
1137       // If a different debug instruction defined the variable value / location
1138       // since the start of the block, don't materialize this use-before-def.
1139       if (!UseBeforeDefVariables.count(Use.Var))
1140         continue;
1141 
1142       PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties));
1143     }
1144     flushDbgValues(pos, nullptr);
1145   }
1146 
1147   /// Helper to move created DBG_VALUEs into Transfers collection.
1148   void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
1149     if (PendingDbgValues.size() > 0) {
1150       Transfers.push_back({Pos, MBB, PendingDbgValues});
1151       PendingDbgValues.clear();
1152     }
1153   }
1154 
1155   /// Change a variable value after encountering a DBG_VALUE inside a block.
1156   void redefVar(const MachineInstr &MI) {
1157     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1158                       MI.getDebugLoc()->getInlinedAt());
1159     DbgValueProperties Properties(MI);
1160 
1161     const MachineOperand &MO = MI.getOperand(0);
1162 
1163     // Ignore non-register locations, we don't transfer those.
1164     if (!MO.isReg() || MO.getReg() == 0) {
1165       auto It = ActiveVLocs.find(Var);
1166       if (It != ActiveVLocs.end()) {
1167         ActiveMLocs[It->second.Loc].erase(Var);
1168         ActiveVLocs.erase(It);
1169      }
1170       // Any use-before-defs no longer apply.
1171       UseBeforeDefVariables.erase(Var);
1172       return;
1173     }
1174 
1175     Register Reg = MO.getReg();
1176     LocIdx NewLoc = MTracker->getRegMLoc(Reg);
1177     redefVar(MI, Properties, NewLoc);
1178   }
1179 
1180   /// Handle a change in variable location within a block. Terminate the
1181   /// variables current location, and record the value it now refers to, so
1182   /// that we can detect location transfers later on.
1183   void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
1184                 Optional<LocIdx> OptNewLoc) {
1185     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1186                       MI.getDebugLoc()->getInlinedAt());
1187     // Any use-before-defs no longer apply.
1188     UseBeforeDefVariables.erase(Var);
1189 
1190     // Erase any previous location,
1191     auto It = ActiveVLocs.find(Var);
1192     if (It != ActiveVLocs.end())
1193       ActiveMLocs[It->second.Loc].erase(Var);
1194 
1195     // If there _is_ no new location, all we had to do was erase.
1196     if (!OptNewLoc)
1197       return;
1198     LocIdx NewLoc = *OptNewLoc;
1199 
1200     // Check whether our local copy of values-by-location in #VarLocs is out of
1201     // date. Wipe old tracking data for the location if it's been clobbered in
1202     // the meantime.
1203     if (MTracker->getNumAtPos(NewLoc) != VarLocs[NewLoc.asU64()]) {
1204       for (auto &P : ActiveMLocs[NewLoc]) {
1205         ActiveVLocs.erase(P);
1206       }
1207       ActiveMLocs[NewLoc.asU64()].clear();
1208       VarLocs[NewLoc.asU64()] = MTracker->getNumAtPos(NewLoc);
1209     }
1210 
1211     ActiveMLocs[NewLoc].insert(Var);
1212     if (It == ActiveVLocs.end()) {
1213       ActiveVLocs.insert(
1214           std::make_pair(Var, LocAndProperties{NewLoc, Properties}));
1215     } else {
1216       It->second.Loc = NewLoc;
1217       It->second.Properties = Properties;
1218     }
1219   }
1220 
1221   /// Explicitly terminate variable locations based on \p mloc. Creates undef
1222   /// DBG_VALUEs for any variables that were located there, and clears
1223   /// #ActiveMLoc / #ActiveVLoc tracking information for that location.
1224   void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos) {
1225     assert(MTracker->isSpill(MLoc));
1226     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
1227     if (ActiveMLocIt == ActiveMLocs.end())
1228       return;
1229 
1230     VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
1231 
1232     for (auto &Var : ActiveMLocIt->second) {
1233       auto ActiveVLocIt = ActiveVLocs.find(Var);
1234       // Create an undef. We can't feed in a nullptr DIExpression alas,
1235       // so use the variables last expression. Pass None as the location.
1236       const DIExpression *Expr = ActiveVLocIt->second.Properties.DIExpr;
1237       DbgValueProperties Properties(Expr, false);
1238       PendingDbgValues.push_back(MTracker->emitLoc(None, Var, Properties));
1239       ActiveVLocs.erase(ActiveVLocIt);
1240     }
1241     flushDbgValues(Pos, nullptr);
1242 
1243     ActiveMLocIt->second.clear();
1244   }
1245 
1246   /// Transfer variables based on \p Src to be based on \p Dst. This handles
1247   /// both register copies as well as spills and restores. Creates DBG_VALUEs
1248   /// describing the movement.
1249   void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
1250     // Does Src still contain the value num we expect? If not, it's been
1251     // clobbered in the meantime, and our variable locations are stale.
1252     if (VarLocs[Src.asU64()] != MTracker->getNumAtPos(Src))
1253       return;
1254 
1255     // assert(ActiveMLocs[Dst].size() == 0);
1256     //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
1257     ActiveMLocs[Dst] = ActiveMLocs[Src];
1258     VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
1259 
1260     // For each variable based on Src; create a location at Dst.
1261     for (auto &Var : ActiveMLocs[Src]) {
1262       auto ActiveVLocIt = ActiveVLocs.find(Var);
1263       assert(ActiveVLocIt != ActiveVLocs.end());
1264       ActiveVLocIt->second.Loc = Dst;
1265 
1266       assert(Dst != 0);
1267       MachineInstr *MI =
1268           MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties);
1269       PendingDbgValues.push_back(MI);
1270     }
1271     ActiveMLocs[Src].clear();
1272     flushDbgValues(Pos, nullptr);
1273 
1274     // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
1275     // about the old location.
1276     if (EmulateOldLDV)
1277       VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
1278   }
1279 
1280   MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
1281                                 const DebugVariable &Var,
1282                                 const DbgValueProperties &Properties) {
1283     DebugLoc DL =
1284         DebugLoc::get(0, 0, Var.getVariable()->getScope(), Var.getInlinedAt());
1285     auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
1286     MIB.add(MO);
1287     if (Properties.Indirect)
1288       MIB.addImm(0);
1289     else
1290       MIB.addReg(0);
1291     MIB.addMetadata(Var.getVariable());
1292     MIB.addMetadata(Properties.DIExpr);
1293     return MIB;
1294   }
1295 };
1296 
1297 class InstrRefBasedLDV : public LDVImpl {
1298 private:
1299   using FragmentInfo = DIExpression::FragmentInfo;
1300   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
1301 
1302   // Helper while building OverlapMap, a map of all fragments seen for a given
1303   // DILocalVariable.
1304   using VarToFragments =
1305       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
1306 
1307   /// Machine location/value transfer function, a mapping of which locations
1308   /// are assigned which new values.
1309   using MLocTransferMap = std::map<LocIdx, ValueIDNum>;
1310 
1311   /// Live in/out structure for the variable values: a per-block map of
1312   /// variables to their values. XXX, better name?
1313   using LiveIdxT =
1314       DenseMap<const MachineBasicBlock *, DenseMap<DebugVariable, DbgValue> *>;
1315 
1316   using VarAndLoc = std::pair<DebugVariable, DbgValue>;
1317 
1318   /// Type for a live-in value: the predecessor block, and its value.
1319   using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
1320 
1321   /// Vector (per block) of a collection (inner smallvector) of live-ins.
1322   /// Used as the result type for the variable value dataflow problem.
1323   using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
1324 
1325   const TargetRegisterInfo *TRI;
1326   const TargetInstrInfo *TII;
1327   const TargetFrameLowering *TFI;
1328   BitVector CalleeSavedRegs;
1329   LexicalScopes LS;
1330   TargetPassConfig *TPC;
1331 
1332   /// Object to track machine locations as we step through a block. Could
1333   /// probably be a field rather than a pointer, as it's always used.
1334   MLocTracker *MTracker;
1335 
1336   /// Number of the current block LiveDebugValues is stepping through.
1337   unsigned CurBB;
1338 
1339   /// Number of the current instruction LiveDebugValues is evaluating.
1340   unsigned CurInst;
1341 
1342   /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
1343   /// steps through a block. Reads the values at each location from the
1344   /// MLocTracker object.
1345   VLocTracker *VTracker;
1346 
1347   /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
1348   /// between locations during stepping, creates new DBG_VALUEs when values move
1349   /// location.
1350   TransferTracker *TTracker;
1351 
1352   /// Blocks which are artificial, i.e. blocks which exclusively contain
1353   /// instructions without DebugLocs, or with line 0 locations.
1354   SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1355 
1356   // Mapping of blocks to and from their RPOT order.
1357   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1358   DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1359   DenseMap<unsigned, unsigned> BBNumToRPO;
1360 
1361   /// Pair of MachineInstr, and its 1-based offset into the containing block.
1362   using InstAndNum = std::pair<const MachineInstr *, unsigned>;
1363   /// Map from debug instruction number to the MachineInstr labelled with that
1364   /// number, and its location within the function. Used to transform
1365   /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
1366   std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
1367 
1368   // Map of overlapping variable fragments.
1369   OverlapMap OverlapFragments;
1370   VarToFragments SeenFragments;
1371 
1372   /// Tests whether this instruction is a spill to a stack slot.
1373   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
1374 
1375   /// Decide if @MI is a spill instruction and return true if it is. We use 2
1376   /// criteria to make this decision:
1377   /// - Is this instruction a store to a spill slot?
1378   /// - Is there a register operand that is both used and killed?
1379   /// TODO: Store optimization can fold spills into other stores (including
1380   /// other spills). We do not handle this yet (more than one memory operand).
1381   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
1382                        unsigned &Reg);
1383 
1384   /// If a given instruction is identified as a spill, return the spill slot
1385   /// and set \p Reg to the spilled register.
1386   Optional<SpillLoc> isRestoreInstruction(const MachineInstr &MI,
1387                                           MachineFunction *MF, unsigned &Reg);
1388 
1389   /// Given a spill instruction, extract the register and offset used to
1390   /// address the spill slot in a target independent way.
1391   SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
1392 
1393   /// Observe a single instruction while stepping through a block.
1394   void process(MachineInstr &MI);
1395 
1396   /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
1397   /// \returns true if MI was recognized and processed.
1398   bool transferDebugValue(const MachineInstr &MI);
1399 
1400   /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
1401   /// \returns true if MI was recognized and processed.
1402   bool transferDebugInstrRef(MachineInstr &MI);
1403 
1404   /// Examines whether \p MI is copy instruction, and notifies trackers.
1405   /// \returns true if MI was recognized and processed.
1406   bool transferRegisterCopy(MachineInstr &MI);
1407 
1408   /// Examines whether \p MI is stack spill or restore  instruction, and
1409   /// notifies trackers. \returns true if MI was recognized and processed.
1410   bool transferSpillOrRestoreInst(MachineInstr &MI);
1411 
1412   /// Examines \p MI for any registers that it defines, and notifies trackers.
1413   void transferRegisterDef(MachineInstr &MI);
1414 
1415   /// Copy one location to the other, accounting for movement of subregisters
1416   /// too.
1417   void performCopy(Register Src, Register Dst);
1418 
1419   void accumulateFragmentMap(MachineInstr &MI);
1420 
1421   /// Step through the function, recording register definitions and movements
1422   /// in an MLocTracker. Convert the observations into a per-block transfer
1423   /// function in \p MLocTransfer, suitable for using with the machine value
1424   /// location dataflow problem.
1425   void
1426   produceMLocTransferFunction(MachineFunction &MF,
1427                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1428                               unsigned MaxNumBlocks);
1429 
1430   /// Solve the machine value location dataflow problem. Takes as input the
1431   /// transfer functions in \p MLocTransfer. Writes the output live-in and
1432   /// live-out arrays to the (initialized to zero) multidimensional arrays in
1433   /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
1434   /// number, the inner by LocIdx.
1435   void mlocDataflow(ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
1436                     SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1437 
1438   /// Perform a control flow join (lattice value meet) of the values in machine
1439   /// locations at \p MBB. Follows the algorithm described in the file-comment,
1440   /// reading live-outs of predecessors from \p OutLocs, the current live ins
1441   /// from \p InLocs, and assigning the newly computed live ins back into
1442   /// \p InLocs. \returns two bools -- the first indicates whether a change
1443   /// was made, the second whether a lattice downgrade occurred. If the latter
1444   /// is true, revisiting this block is necessary.
1445   std::tuple<bool, bool>
1446   mlocJoin(MachineBasicBlock &MBB,
1447            SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1448            ValueIDNum **OutLocs, ValueIDNum *InLocs);
1449 
1450   /// Solve the variable value dataflow problem, for a single lexical scope.
1451   /// Uses the algorithm from the file comment to resolve control flow joins,
1452   /// although there are extra hacks, see vlocJoin. Reads the
1453   /// locations of values from the \p MInLocs and \p MOutLocs arrays (see
1454   /// mlocDataflow) and reads the variable values transfer function from
1455   /// \p AllTheVlocs. Live-in and Live-out variable values are stored locally,
1456   /// with the live-ins permanently stored to \p Output once the fixedpoint is
1457   /// reached.
1458   /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
1459   /// that we should be tracking.
1460   /// \p AssignBlocks contains the set of blocks that aren't in \p Scope, but
1461   /// which do contain DBG_VALUEs, which VarLocBasedImpl tracks locations
1462   /// through.
1463   void vlocDataflow(const LexicalScope *Scope, const DILocation *DILoc,
1464                     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
1465                     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
1466                     LiveInsT &Output, ValueIDNum **MOutLocs,
1467                     ValueIDNum **MInLocs,
1468                     SmallVectorImpl<VLocTracker> &AllTheVLocs);
1469 
1470   /// Compute the live-ins to a block, considering control flow merges according
1471   /// to the method in the file comment. Live out and live in variable values
1472   /// are stored in \p VLOCOutLocs and \p VLOCInLocs. The live-ins for \p MBB
1473   /// are computed and stored into \p VLOCInLocs. \returns true if the live-ins
1474   /// are modified.
1475   /// \p InLocsT Output argument, storage for calculated live-ins.
1476   /// \returns two bools -- the first indicates whether a change
1477   /// was made, the second whether a lattice downgrade occurred. If the latter
1478   /// is true, revisiting this block is necessary.
1479   std::tuple<bool, bool>
1480   vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs,
1481            SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited,
1482            unsigned BBNum, const SmallSet<DebugVariable, 4> &AllVars,
1483            ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
1484            SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks,
1485            SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
1486            DenseMap<DebugVariable, DbgValue> &InLocsT);
1487 
1488   /// Continue exploration of the variable-value lattice, as explained in the
1489   /// file-level comment. \p OldLiveInLocation contains the current
1490   /// exploration position, from which we need to descend further. \p Values
1491   /// contains the set of live-in values, \p CurBlockRPONum the RPO number of
1492   /// the current block, and \p CandidateLocations a set of locations that
1493   /// should be considered as PHI locations, if we reach the bottom of the
1494   /// lattice. \returns true if we should downgrade; the value is the agreeing
1495   /// value number in a non-backedge predecessor.
1496   bool vlocDowngradeLattice(const MachineBasicBlock &MBB,
1497                             const DbgValue &OldLiveInLocation,
1498                             const SmallVectorImpl<InValueT> &Values,
1499                             unsigned CurBlockRPONum);
1500 
1501   /// For the given block and live-outs feeding into it, try to find a
1502   /// machine location where they all join. If a solution for all predecessors
1503   /// can't be found, a location where all non-backedge-predecessors join
1504   /// will be returned instead. While this method finds a join location, this
1505   /// says nothing as to whether it should be used.
1506   /// \returns Pair of value ID if found, and true when the correct value
1507   /// is available on all predecessor edges, or false if it's only available
1508   /// for non-backedge predecessors.
1509   std::tuple<Optional<ValueIDNum>, bool>
1510   pickVPHILoc(MachineBasicBlock &MBB, const DebugVariable &Var,
1511               const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
1512               ValueIDNum **MInLocs,
1513               const SmallVectorImpl<MachineBasicBlock *> &BlockOrders);
1514 
1515   /// Given the solutions to the two dataflow problems, machine value locations
1516   /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the
1517   /// TransferTracker class over the function to produce live-in and transfer
1518   /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the
1519   /// order given by AllVarsNumbering -- this could be any stable order, but
1520   /// right now "order of appearence in function, when explored in RPO", so
1521   /// that we can compare explictly against VarLocBasedImpl.
1522   void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns,
1523                      ValueIDNum **MInLocs,
1524                      DenseMap<DebugVariable, unsigned> &AllVarsNumbering);
1525 
1526   /// Boilerplate computation of some initial sets, artifical blocks and
1527   /// RPOT block ordering.
1528   void initialSetup(MachineFunction &MF);
1529 
1530   bool ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) override;
1531 
1532 public:
1533   /// Default construct and initialize the pass.
1534   InstrRefBasedLDV();
1535 
1536   LLVM_DUMP_METHOD
1537   void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1538 
1539   bool isCalleeSaved(LocIdx L) {
1540     unsigned Reg = MTracker->LocIdxToLocID[L];
1541     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1542       if (CalleeSavedRegs.test(*RAI))
1543         return true;
1544     return false;
1545   }
1546 };
1547 
1548 } // end anonymous namespace
1549 
1550 //===----------------------------------------------------------------------===//
1551 //            Implementation
1552 //===----------------------------------------------------------------------===//
1553 
1554 ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
1555 
1556 /// Default construct and initialize the pass.
1557 InstrRefBasedLDV::InstrRefBasedLDV() {}
1558 
1559 //===----------------------------------------------------------------------===//
1560 //            Debug Range Extension Implementation
1561 //===----------------------------------------------------------------------===//
1562 
1563 #ifndef NDEBUG
1564 // Something to restore in the future.
1565 // void InstrRefBasedLDV::printVarLocInMBB(..)
1566 #endif
1567 
1568 SpillLoc
1569 InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1570   assert(MI.hasOneMemOperand() &&
1571          "Spill instruction does not have exactly one memory operand?");
1572   auto MMOI = MI.memoperands_begin();
1573   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1574   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1575          "Inconsistent memory operand in spill instruction");
1576   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1577   const MachineBasicBlock *MBB = MI.getParent();
1578   Register Reg;
1579   int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1580   return {Reg, Offset};
1581 }
1582 
1583 /// End all previous ranges related to @MI and start a new range from @MI
1584 /// if it is a DBG_VALUE instr.
1585 bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
1586   if (!MI.isDebugValue())
1587     return false;
1588 
1589   const DILocalVariable *Var = MI.getDebugVariable();
1590   const DIExpression *Expr = MI.getDebugExpression();
1591   const DILocation *DebugLoc = MI.getDebugLoc();
1592   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1593   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1594          "Expected inlined-at fields to agree");
1595 
1596   DebugVariable V(Var, Expr, InlinedAt);
1597   DbgValueProperties Properties(MI);
1598 
1599   // If there are no instructions in this lexical scope, do no location tracking
1600   // at all, this variable shouldn't get a legitimate location range.
1601   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1602   if (Scope == nullptr)
1603     return true; // handled it; by doing nothing
1604 
1605   const MachineOperand &MO = MI.getOperand(0);
1606 
1607   // MLocTracker needs to know that this register is read, even if it's only
1608   // read by a debug inst.
1609   if (MO.isReg() && MO.getReg() != 0)
1610     (void)MTracker->readReg(MO.getReg());
1611 
1612   // If we're preparing for the second analysis (variables), the machine value
1613   // locations are already solved, and we report this DBG_VALUE and the value
1614   // it refers to to VLocTracker.
1615   if (VTracker) {
1616     if (MO.isReg()) {
1617       // Feed defVar the new variable location, or if this is a
1618       // DBG_VALUE $noreg, feed defVar None.
1619       if (MO.getReg())
1620         VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg()));
1621       else
1622         VTracker->defVar(MI, Properties, None);
1623     } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() ||
1624                MI.getOperand(0).isCImm()) {
1625       VTracker->defVar(MI, MI.getOperand(0));
1626     }
1627   }
1628 
1629   // If performing final tracking of transfers, report this variable definition
1630   // to the TransferTracker too.
1631   if (TTracker)
1632     TTracker->redefVar(MI);
1633   return true;
1634 }
1635 
1636 bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI) {
1637   if (!MI.isDebugRef())
1638     return false;
1639 
1640   // Only handle this instruction when we are building the variable value
1641   // transfer function.
1642   if (!VTracker)
1643     return false;
1644 
1645   unsigned InstNo = MI.getOperand(0).getImm();
1646   unsigned OpNo = MI.getOperand(1).getImm();
1647 
1648   const DILocalVariable *Var = MI.getDebugVariable();
1649   const DIExpression *Expr = MI.getDebugExpression();
1650   const DILocation *DebugLoc = MI.getDebugLoc();
1651   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1652   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1653          "Expected inlined-at fields to agree");
1654 
1655   DebugVariable V(Var, Expr, InlinedAt);
1656 
1657   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1658   if (Scope == nullptr)
1659     return true; // Handled by doing nothing. This variable is never in scope.
1660 
1661   const MachineFunction &MF = *MI.getParent()->getParent();
1662 
1663   // Various optimizations may have happened to the value during codegen,
1664   // recorded in the value substitution table. Apply any substitutions to
1665   // the instruction / operand number in this DBG_INSTR_REF.
1666   auto Sub = MF.DebugValueSubstitutions.find(std::make_pair(InstNo, OpNo));
1667   while (Sub != MF.DebugValueSubstitutions.end()) {
1668     InstNo = Sub->second.first;
1669     OpNo = Sub->second.second;
1670     Sub = MF.DebugValueSubstitutions.find(std::make_pair(InstNo, OpNo));
1671   }
1672 
1673   // Default machine value number is <None> -- if no instruction defines
1674   // the corresponding value, it must have been optimized out.
1675   Optional<ValueIDNum> NewID = None;
1676 
1677   // Try to lookup the instruction number, and find the machine value number
1678   // that it defines.
1679   auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1680   if (InstrIt != DebugInstrNumToInstr.end()) {
1681     const MachineInstr &TargetInstr = *InstrIt->second.first;
1682     uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1683 
1684     // Pick out the designated operand.
1685     assert(OpNo < TargetInstr.getNumOperands());
1686     const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1687 
1688     // Today, this can only be a register.
1689     assert(MO.isReg() && MO.isDef());
1690 
1691     unsigned LocID = MTracker->getLocID(MO.getReg(), false);
1692     LocIdx L = MTracker->LocIDToLocIdx[LocID];
1693     NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1694   }
1695 
1696   // We, we have a value number or None. Tell the variable value tracker about
1697   // it. The rest of this LiveDebugValues implementation acts exactly the same
1698   // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that
1699   // aren't immediately available).
1700   DbgValueProperties Properties(Expr, false);
1701   VTracker->defVar(MI, Properties, NewID);
1702 
1703   // If we're on the final pass through the function, decompose this INSTR_REF
1704   // into a plain DBG_VALUE.
1705   if (!TTracker)
1706     return true;
1707 
1708   // Pick a location for the machine value number, if such a location exists.
1709   // (This information could be stored in TransferTracker to make it faster).
1710   Optional<LocIdx> FoundLoc = None;
1711   for (auto Location : MTracker->locations()) {
1712     LocIdx CurL = Location.Idx;
1713     ValueIDNum ID = MTracker->LocIdxToIDNum[CurL];
1714     if (NewID && ID == NewID) {
1715       // If this is the first location with that value, pick it. Otherwise,
1716       // consider whether it's a "longer term" location.
1717       if (!FoundLoc) {
1718         FoundLoc = CurL;
1719         continue;
1720       }
1721 
1722       if (MTracker->isSpill(CurL))
1723         FoundLoc = CurL; // Spills are a longer term location.
1724       else if (!MTracker->isSpill(*FoundLoc) &&
1725                !MTracker->isSpill(CurL) &&
1726                !isCalleeSaved(*FoundLoc) &&
1727                isCalleeSaved(CurL))
1728         FoundLoc = CurL; // Callee saved regs are longer term than normal.
1729     }
1730   }
1731 
1732   // Tell transfer tracker that the variable value has changed.
1733   TTracker->redefVar(MI, Properties, FoundLoc);
1734 
1735   // If there was a value with no location; but the value is defined in a
1736   // later instruction in this block, this is a block-local use-before-def.
1737   if (!FoundLoc && NewID && NewID->getBlock() == CurBB &&
1738       NewID->getInst() > CurInst)
1739     TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID);
1740 
1741   // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1742   // This DBG_VALUE is potentially a $noreg / undefined location, if
1743   // FoundLoc is None.
1744   // (XXX -- could morph the DBG_INSTR_REF in the future).
1745   MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties);
1746   TTracker->PendingDbgValues.push_back(DbgMI);
1747   TTracker->flushDbgValues(MI.getIterator(), nullptr);
1748 
1749   return true;
1750 }
1751 
1752 void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1753   // Meta Instructions do not affect the debug liveness of any register they
1754   // define.
1755   if (MI.isImplicitDef()) {
1756     // Except when there's an implicit def, and the location it's defining has
1757     // no value number. The whole point of an implicit def is to announce that
1758     // the register is live, without be specific about it's value. So define
1759     // a value if there isn't one already.
1760     ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1761     // Has a legitimate value -> ignore the implicit def.
1762     if (Num.getLoc() != 0)
1763       return;
1764     // Otherwise, def it here.
1765   } else if (MI.isMetaInstruction())
1766     return;
1767 
1768   MachineFunction *MF = MI.getMF();
1769   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1770   Register SP = TLI->getStackPointerRegisterToSaveRestore();
1771 
1772   // Find the regs killed by MI, and find regmasks of preserved regs.
1773   // Max out the number of statically allocated elements in `DeadRegs`, as this
1774   // prevents fallback to std::set::count() operations.
1775   SmallSet<uint32_t, 32> DeadRegs;
1776   SmallVector<const uint32_t *, 4> RegMasks;
1777   SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1778   for (const MachineOperand &MO : MI.operands()) {
1779     // Determine whether the operand is a register def.
1780     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1781         Register::isPhysicalRegister(MO.getReg()) &&
1782         !(MI.isCall() && MO.getReg() == SP)) {
1783       // Remove ranges of all aliased registers.
1784       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1785         // FIXME: Can we break out of this loop early if no insertion occurs?
1786         DeadRegs.insert(*RAI);
1787     } else if (MO.isRegMask()) {
1788       RegMasks.push_back(MO.getRegMask());
1789       RegMaskPtrs.push_back(&MO);
1790     }
1791   }
1792 
1793   // Tell MLocTracker about all definitions, of regmasks and otherwise.
1794   for (uint32_t DeadReg : DeadRegs)
1795     MTracker->defReg(DeadReg, CurBB, CurInst);
1796 
1797   for (auto *MO : RegMaskPtrs)
1798     MTracker->writeRegMask(MO, CurBB, CurInst);
1799 }
1800 
1801 void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1802   ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1803 
1804   MTracker->setReg(DstRegNum, SrcValue);
1805 
1806   // In all circumstances, re-def the super registers. It's definitely a new
1807   // value now. This doesn't uniquely identify the composition of subregs, for
1808   // example, two identical values in subregisters composed in different
1809   // places would not get equal value numbers.
1810   for (MCSuperRegIterator SRI(DstRegNum, TRI); SRI.isValid(); ++SRI)
1811     MTracker->defReg(*SRI, CurBB, CurInst);
1812 
1813   // If we're emulating VarLocBasedImpl, just define all the subregisters.
1814   // DBG_VALUEs of them will expect to be tracked from the DBG_VALUE, not
1815   // through prior copies.
1816   if (EmulateOldLDV) {
1817     for (MCSubRegIndexIterator DRI(DstRegNum, TRI); DRI.isValid(); ++DRI)
1818       MTracker->defReg(DRI.getSubReg(), CurBB, CurInst);
1819     return;
1820   }
1821 
1822   // Otherwise, actually copy subregisters from one location to another.
1823   // XXX: in addition, any subregisters of DstRegNum that don't line up with
1824   // the source register should be def'd.
1825   for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1826     unsigned SrcSubReg = SRI.getSubReg();
1827     unsigned SubRegIdx = SRI.getSubRegIndex();
1828     unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1829     if (!DstSubReg)
1830       continue;
1831 
1832     // Do copy. There are two matching subregisters, the source value should
1833     // have been def'd when the super-reg was, the latter might not be tracked
1834     // yet.
1835     // This will force SrcSubReg to be tracked, if it isn't yet.
1836     (void)MTracker->readReg(SrcSubReg);
1837     LocIdx SrcL = MTracker->getRegMLoc(SrcSubReg);
1838     assert(SrcL.asU64());
1839     (void)MTracker->readReg(DstSubReg);
1840     LocIdx DstL = MTracker->getRegMLoc(DstSubReg);
1841     assert(DstL.asU64());
1842     (void)DstL;
1843     ValueIDNum CpyValue = {SrcValue.getBlock(), SrcValue.getInst(), SrcL};
1844 
1845     MTracker->setReg(DstSubReg, CpyValue);
1846   }
1847 }
1848 
1849 bool InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1850                                           MachineFunction *MF) {
1851   // TODO: Handle multiple stores folded into one.
1852   if (!MI.hasOneMemOperand())
1853     return false;
1854 
1855   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1856     return false; // This is not a spill instruction, since no valid size was
1857                   // returned from either function.
1858 
1859   return true;
1860 }
1861 
1862 bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
1863                                        MachineFunction *MF, unsigned &Reg) {
1864   if (!isSpillInstruction(MI, MF))
1865     return false;
1866 
1867   // XXX FIXME: On x86, isStoreToStackSlotPostFE returns '1' instead of an
1868   // actual register number.
1869   if (ObserveAllStackops) {
1870     int FI;
1871     Reg = TII->isStoreToStackSlotPostFE(MI, FI);
1872     return Reg != 0;
1873   }
1874 
1875   auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
1876     if (!MO.isReg() || !MO.isUse()) {
1877       Reg = 0;
1878       return false;
1879     }
1880     Reg = MO.getReg();
1881     return MO.isKill();
1882   };
1883 
1884   for (const MachineOperand &MO : MI.operands()) {
1885     // In a spill instruction generated by the InlineSpiller the spilled
1886     // register has its kill flag set.
1887     if (isKilledReg(MO, Reg))
1888       return true;
1889     if (Reg != 0) {
1890       // Check whether next instruction kills the spilled register.
1891       // FIXME: Current solution does not cover search for killed register in
1892       // bundles and instructions further down the chain.
1893       auto NextI = std::next(MI.getIterator());
1894       // Skip next instruction that points to basic block end iterator.
1895       if (MI.getParent()->end() == NextI)
1896         continue;
1897       unsigned RegNext;
1898       for (const MachineOperand &MONext : NextI->operands()) {
1899         // Return true if we came across the register from the
1900         // previous spill instruction that is killed in NextI.
1901         if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1902           return true;
1903       }
1904     }
1905   }
1906   // Return false if we didn't find spilled register.
1907   return false;
1908 }
1909 
1910 Optional<SpillLoc>
1911 InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1912                                        MachineFunction *MF, unsigned &Reg) {
1913   if (!MI.hasOneMemOperand())
1914     return None;
1915 
1916   // FIXME: Handle folded restore instructions with more than one memory
1917   // operand.
1918   if (MI.getRestoreSize(TII)) {
1919     Reg = MI.getOperand(0).getReg();
1920     return extractSpillBaseRegAndOffset(MI);
1921   }
1922   return None;
1923 }
1924 
1925 bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
1926   // XXX -- it's too difficult to implement VarLocBasedImpl's  stack location
1927   // limitations under the new model. Therefore, when comparing them, compare
1928   // versions that don't attempt spills or restores at all.
1929   if (EmulateOldLDV)
1930     return false;
1931 
1932   MachineFunction *MF = MI.getMF();
1933   unsigned Reg;
1934   Optional<SpillLoc> Loc;
1935 
1936   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1937 
1938   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1939   // written to, terminate that variable location. The value in memory
1940   // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
1941   if (isSpillInstruction(MI, MF)) {
1942     Loc = extractSpillBaseRegAndOffset(MI);
1943 
1944     if (TTracker) {
1945       Optional<LocIdx> MLoc = MTracker->getSpillMLoc(*Loc);
1946       if (MLoc)
1947         TTracker->clobberMloc(*MLoc, MI.getIterator());
1948     }
1949   }
1950 
1951   // Try to recognise spill and restore instructions that may transfer a value.
1952   if (isLocationSpill(MI, MF, Reg)) {
1953     Loc = extractSpillBaseRegAndOffset(MI);
1954     auto ValueID = MTracker->readReg(Reg);
1955 
1956     // If the location is empty, produce a phi, signify it's the live-in value.
1957     if (ValueID.getLoc() == 0)
1958       ValueID = {CurBB, 0, MTracker->getRegMLoc(Reg)};
1959 
1960     MTracker->setSpill(*Loc, ValueID);
1961     auto OptSpillLocIdx = MTracker->getSpillMLoc(*Loc);
1962     assert(OptSpillLocIdx && "Spill slot set but has no LocIdx?");
1963     LocIdx SpillLocIdx = *OptSpillLocIdx;
1964 
1965     // Tell TransferTracker about this spill, produce DBG_VALUEs for it.
1966     if (TTracker)
1967       TTracker->transferMlocs(MTracker->getRegMLoc(Reg), SpillLocIdx,
1968                               MI.getIterator());
1969 
1970     // VarLocBasedImpl would, at this point, stop tracking the source
1971     // register of the store.
1972     if (EmulateOldLDV) {
1973       for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1974         MTracker->defReg(*RAI, CurBB, CurInst);
1975     }
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.begin(), BlockOrders.end(), 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.begin(), BlockOrders.end(), 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.find(p) == BlocksToExplore.end()) {
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.begin(), BlockOrders.end(), 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.begin(), P.Insts.end(), 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