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