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